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 "X86ShuffleDecode.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.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/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/PseudoSourceValue.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/CommandLine.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"
54 using namespace dwarf;
56 STATISTIC(NumTailCalls, "Number of tail calls");
58 // Forward declarations.
59 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
62 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
64 bool is64Bit = TM.getSubtarget<X86Subtarget>().is64Bit();
66 if (TM.getSubtarget<X86Subtarget>().isTargetDarwin()) {
68 return new X8664_MachoTargetObjectFile();
69 return new TargetLoweringObjectFileMachO();
72 if (TM.getSubtarget<X86Subtarget>().isTargetELF() ){
74 return new X8664_ELFTargetObjectFile(TM);
75 return new X8632_ELFTargetObjectFile(TM);
77 if (TM.getSubtarget<X86Subtarget>().isTargetCOFF())
78 return new TargetLoweringObjectFileCOFF();
79 llvm_unreachable("unknown subtarget type");
82 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
83 : TargetLowering(TM, createTLOF(TM)) {
84 Subtarget = &TM.getSubtarget<X86Subtarget>();
85 X86ScalarSSEf64 = Subtarget->hasXMMInt();
86 X86ScalarSSEf32 = Subtarget->hasXMM();
87 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
89 RegInfo = TM.getRegisterInfo();
92 // Set up the TargetLowering object.
93 static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
95 // X86 is weird, it always uses i8 for shift amounts and setcc results.
96 setShiftAmountType(MVT::i8);
97 setBooleanContents(ZeroOrOneBooleanContent);
98 setSchedulingPreference(Sched::RegPressure);
99 setStackPointerRegisterToSaveRestore(X86StackPtr);
101 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
102 // Setup Windows compiler runtime calls.
103 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
104 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
105 setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
106 setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
107 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
108 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
109 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
110 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
113 if (Subtarget->isTargetDarwin()) {
114 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
115 setUseUnderscoreSetJmp(false);
116 setUseUnderscoreLongJmp(false);
117 } else if (Subtarget->isTargetMingw()) {
118 // MS runtime is weird: it exports _setjmp, but longjmp!
119 setUseUnderscoreSetJmp(true);
120 setUseUnderscoreLongJmp(false);
122 setUseUnderscoreSetJmp(true);
123 setUseUnderscoreLongJmp(true);
126 // Set up the register classes.
127 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
128 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
129 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
130 if (Subtarget->is64Bit())
131 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
133 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
135 // We don't accept any truncstore of integer registers.
136 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
137 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
138 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
139 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
140 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
141 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
143 // SETOEQ and SETUNE require checking two conditions.
144 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
145 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
146 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
147 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
148 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
149 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
151 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
153 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
154 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
155 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
157 if (Subtarget->is64Bit()) {
158 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
159 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
160 } else if (!UseSoftFloat) {
161 // We have an algorithm for SSE2->double, and we turn this into a
162 // 64-bit FILD followed by conditional FADD for other targets.
163 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
164 // We have an algorithm for SSE2, and we turn this into a 64-bit
165 // FILD for other targets.
166 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
169 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
171 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
172 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
175 // SSE has no i16 to fp conversion, only i32
176 if (X86ScalarSSEf32) {
177 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
178 // f32 and f64 cases are Legal, f80 case is not
179 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
181 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
182 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
185 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
186 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
189 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
190 // are Legal, f80 is custom lowered.
191 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
192 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
194 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
196 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
197 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
199 if (X86ScalarSSEf32) {
200 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
201 // f32 and f64 cases are Legal, f80 case is not
202 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
204 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
205 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
208 // Handle FP_TO_UINT by promoting the destination to a larger signed
210 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
211 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
212 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
214 if (Subtarget->is64Bit()) {
215 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
216 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
217 } else if (!UseSoftFloat) {
218 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
219 // Expand FP_TO_UINT into a select.
220 // FIXME: We would like to use a Custom expander here eventually to do
221 // the optimal thing for SSE vs. the default expansion in the legalizer.
222 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
224 // With SSE3 we can use fisttpll to convert to a signed i64; without
225 // SSE, we're stuck with a fistpll.
226 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
229 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
230 if (!X86ScalarSSEf64) {
231 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
232 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
233 if (Subtarget->is64Bit()) {
234 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
235 // Without SSE, i64->f64 goes through memory.
236 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
240 // Scalar integer divide and remainder are lowered to use operations that
241 // produce two results, to match the available instructions. This exposes
242 // the two-result form to trivial CSE, which is able to combine x/y and x%y
243 // into a single instruction.
245 // Scalar integer multiply-high is also lowered to use two-result
246 // operations, to match the available instructions. However, plain multiply
247 // (low) operations are left as Legal, as there are single-result
248 // instructions for this in x86. Using the two-result multiply instructions
249 // when both high and low results are needed must be arranged by dagcombine.
250 for (unsigned i = 0, e = 4; i != e; ++i) {
252 setOperationAction(ISD::MULHS, VT, Expand);
253 setOperationAction(ISD::MULHU, VT, Expand);
254 setOperationAction(ISD::SDIV, VT, Expand);
255 setOperationAction(ISD::UDIV, VT, Expand);
256 setOperationAction(ISD::SREM, VT, Expand);
257 setOperationAction(ISD::UREM, VT, Expand);
259 // Add/Sub overflow ops with MVT::Flags are lowered to EFLAGS dependences.
260 setOperationAction(ISD::ADDC, VT, Custom);
261 setOperationAction(ISD::ADDE, VT, Custom);
262 setOperationAction(ISD::SUBC, VT, Custom);
263 setOperationAction(ISD::SUBE, VT, Custom);
266 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
267 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
268 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
269 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
270 if (Subtarget->is64Bit())
271 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
272 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
273 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
274 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
275 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
276 setOperationAction(ISD::FREM , MVT::f32 , Expand);
277 setOperationAction(ISD::FREM , MVT::f64 , Expand);
278 setOperationAction(ISD::FREM , MVT::f80 , Expand);
279 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
281 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
282 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
283 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
284 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
285 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
286 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
287 if (Subtarget->is64Bit()) {
288 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
289 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
292 if (Subtarget->hasPOPCNT()) {
293 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
295 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
296 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
297 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
298 if (Subtarget->is64Bit())
299 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
302 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
303 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
305 // These should be promoted to a larger select which is supported.
306 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
307 // X86 wants to expand cmov itself.
308 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
309 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
310 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
311 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
312 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
313 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
314 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
315 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
316 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
317 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
318 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
319 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
320 if (Subtarget->is64Bit()) {
321 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
322 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
324 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
327 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
328 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
329 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
330 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
331 if (Subtarget->is64Bit())
332 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
333 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
334 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
335 if (Subtarget->is64Bit()) {
336 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
337 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
338 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
339 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
340 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
342 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
343 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
344 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
345 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
346 if (Subtarget->is64Bit()) {
347 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
348 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
349 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
352 if (Subtarget->hasXMM())
353 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
355 // We may not have a libcall for MEMBARRIER so we should lower this.
356 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
358 // On X86 and X86-64, atomic operations are lowered to locked instructions.
359 // Locked instructions, in turn, have implicit fence semantics (all memory
360 // operations are flushed before issuing the locked instruction, and they
361 // are not buffered), so we can fold away the common pattern of
362 // fence-atomic-fence.
363 setShouldFoldAtomicFences(true);
365 // Expand certain atomics
366 for (unsigned i = 0, e = 4; i != e; ++i) {
368 setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
369 setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
372 if (!Subtarget->is64Bit()) {
373 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
374 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
375 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
376 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
377 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
378 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
379 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
382 // FIXME - use subtarget debug flags
383 if (!Subtarget->isTargetDarwin() &&
384 !Subtarget->isTargetELF() &&
385 !Subtarget->isTargetCygMing()) {
386 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
389 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
390 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
391 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
392 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
393 if (Subtarget->is64Bit()) {
394 setExceptionPointerRegister(X86::RAX);
395 setExceptionSelectorRegister(X86::RDX);
397 setExceptionPointerRegister(X86::EAX);
398 setExceptionSelectorRegister(X86::EDX);
400 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
401 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
403 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
405 setOperationAction(ISD::TRAP, MVT::Other, Legal);
407 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
408 setOperationAction(ISD::VASTART , MVT::Other, Custom);
409 setOperationAction(ISD::VAEND , MVT::Other, Expand);
410 if (Subtarget->is64Bit()) {
411 setOperationAction(ISD::VAARG , MVT::Other, Custom);
412 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
414 setOperationAction(ISD::VAARG , MVT::Other, Expand);
415 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
418 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
419 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
420 if (Subtarget->is64Bit())
421 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
422 if (Subtarget->isTargetCygMing() || Subtarget->isTargetWindows())
423 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
425 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
427 if (!UseSoftFloat && X86ScalarSSEf64) {
428 // f32 and f64 use SSE.
429 // Set up the FP register classes.
430 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
431 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
433 // Use ANDPD to simulate FABS.
434 setOperationAction(ISD::FABS , MVT::f64, Custom);
435 setOperationAction(ISD::FABS , MVT::f32, Custom);
437 // Use XORP to simulate FNEG.
438 setOperationAction(ISD::FNEG , MVT::f64, Custom);
439 setOperationAction(ISD::FNEG , MVT::f32, Custom);
441 // Use ANDPD and ORPD to simulate FCOPYSIGN.
442 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
443 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
445 // We don't support sin/cos/fmod
446 setOperationAction(ISD::FSIN , MVT::f64, Expand);
447 setOperationAction(ISD::FCOS , MVT::f64, Expand);
448 setOperationAction(ISD::FSIN , MVT::f32, Expand);
449 setOperationAction(ISD::FCOS , MVT::f32, Expand);
451 // Expand FP immediates into loads from the stack, except for the special
453 addLegalFPImmediate(APFloat(+0.0)); // xorpd
454 addLegalFPImmediate(APFloat(+0.0f)); // xorps
455 } else if (!UseSoftFloat && X86ScalarSSEf32) {
456 // Use SSE for f32, x87 for f64.
457 // Set up the FP register classes.
458 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
459 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
461 // Use ANDPS to simulate FABS.
462 setOperationAction(ISD::FABS , MVT::f32, Custom);
464 // Use XORP to simulate FNEG.
465 setOperationAction(ISD::FNEG , MVT::f32, Custom);
467 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
469 // Use ANDPS and ORPS to simulate FCOPYSIGN.
470 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
471 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
473 // We don't support sin/cos/fmod
474 setOperationAction(ISD::FSIN , MVT::f32, Expand);
475 setOperationAction(ISD::FCOS , MVT::f32, Expand);
477 // Special cases we handle for FP constants.
478 addLegalFPImmediate(APFloat(+0.0f)); // xorps
479 addLegalFPImmediate(APFloat(+0.0)); // FLD0
480 addLegalFPImmediate(APFloat(+1.0)); // FLD1
481 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
482 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
485 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
486 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
488 } else if (!UseSoftFloat) {
489 // f32 and f64 in x87.
490 // Set up the FP register classes.
491 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
492 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
494 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
495 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
496 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
497 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
500 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
501 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
503 addLegalFPImmediate(APFloat(+0.0)); // FLD0
504 addLegalFPImmediate(APFloat(+1.0)); // FLD1
505 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
506 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
507 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
508 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
509 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
510 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
513 // Long double always uses X87.
515 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
516 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
517 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
519 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
520 addLegalFPImmediate(TmpFlt); // FLD0
522 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
525 APFloat TmpFlt2(+1.0);
526 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
528 addLegalFPImmediate(TmpFlt2); // FLD1
529 TmpFlt2.changeSign();
530 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
534 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
535 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
539 // Always use a library call for pow.
540 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
541 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
542 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
544 setOperationAction(ISD::FLOG, MVT::f80, Expand);
545 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
546 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
547 setOperationAction(ISD::FEXP, MVT::f80, Expand);
548 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
550 // First set operation action for all vector types to either promote
551 // (for widening) or expand (for scalarization). Then we will selectively
552 // turn on ones that can be effectively codegen'd.
553 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
554 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
555 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
556 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
557 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
558 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
559 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
560 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
561 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
562 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
563 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
564 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
565 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
566 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
567 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
568 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
569 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
570 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
571 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
572 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
573 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
574 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
575 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
576 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
577 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
578 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
579 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
580 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
581 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
582 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
583 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
584 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
585 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
586 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
587 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
588 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
589 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
590 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
591 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
592 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
593 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
594 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
595 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
596 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
597 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
598 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
599 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
600 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
601 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
602 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
603 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
604 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
605 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
606 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
607 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
608 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
609 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
610 setTruncStoreAction((MVT::SimpleValueType)VT,
611 (MVT::SimpleValueType)InnerVT, Expand);
612 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
613 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
614 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
617 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
618 // with -msoft-float, disable use of MMX as well.
619 if (!UseSoftFloat && Subtarget->hasMMX()) {
620 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
621 // No operations on x86mmx supported, everything uses intrinsics.
624 // MMX-sized vectors (other than x86mmx) are expected to be expanded
625 // into smaller operations.
626 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
627 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
628 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
629 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
630 setOperationAction(ISD::AND, MVT::v8i8, Expand);
631 setOperationAction(ISD::AND, MVT::v4i16, Expand);
632 setOperationAction(ISD::AND, MVT::v2i32, Expand);
633 setOperationAction(ISD::AND, MVT::v1i64, Expand);
634 setOperationAction(ISD::OR, MVT::v8i8, Expand);
635 setOperationAction(ISD::OR, MVT::v4i16, Expand);
636 setOperationAction(ISD::OR, MVT::v2i32, Expand);
637 setOperationAction(ISD::OR, MVT::v1i64, Expand);
638 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
639 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
640 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
641 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
642 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
643 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
644 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
645 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
646 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
647 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
648 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
649 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
650 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
651 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
652 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
653 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
654 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
656 if (!UseSoftFloat && Subtarget->hasXMM()) {
657 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
659 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
660 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
661 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
662 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
663 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
664 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
665 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
666 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
667 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
668 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
669 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
670 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
673 if (!UseSoftFloat && Subtarget->hasXMMInt()) {
674 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
676 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
677 // registers cannot be used even for integer operations.
678 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
679 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
680 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
681 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
683 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
684 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
685 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
686 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
687 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
688 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
689 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
690 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
691 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
692 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
693 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
694 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
695 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
696 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
697 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
698 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
700 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
701 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
702 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
703 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
705 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
706 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
707 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
708 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
709 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
711 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
712 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
713 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
714 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
715 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
717 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
718 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
719 EVT VT = (MVT::SimpleValueType)i;
720 // Do not attempt to custom lower non-power-of-2 vectors
721 if (!isPowerOf2_32(VT.getVectorNumElements()))
723 // Do not attempt to custom lower non-128-bit vectors
724 if (!VT.is128BitVector())
726 setOperationAction(ISD::BUILD_VECTOR,
727 VT.getSimpleVT().SimpleTy, Custom);
728 setOperationAction(ISD::VECTOR_SHUFFLE,
729 VT.getSimpleVT().SimpleTy, Custom);
730 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
731 VT.getSimpleVT().SimpleTy, Custom);
734 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
735 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
736 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
737 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
738 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
739 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
741 if (Subtarget->is64Bit()) {
742 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
743 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
746 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
747 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
748 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
751 // Do not attempt to promote non-128-bit vectors
752 if (!VT.is128BitVector())
755 setOperationAction(ISD::AND, SVT, Promote);
756 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
757 setOperationAction(ISD::OR, SVT, Promote);
758 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
759 setOperationAction(ISD::XOR, SVT, Promote);
760 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
761 setOperationAction(ISD::LOAD, SVT, Promote);
762 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
763 setOperationAction(ISD::SELECT, SVT, Promote);
764 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
767 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
769 // Custom lower v2i64 and v2f64 selects.
770 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
771 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
772 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
773 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
775 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
776 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
779 if (Subtarget->hasSSE41()) {
780 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
781 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
782 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
783 setOperationAction(ISD::FRINT, MVT::f32, Legal);
784 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
785 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
786 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
787 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
788 setOperationAction(ISD::FRINT, MVT::f64, Legal);
789 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
791 // FIXME: Do we need to handle scalar-to-vector here?
792 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
794 // Can turn SHL into an integer multiply.
795 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
796 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
798 // i8 and i16 vectors are custom , because the source register and source
799 // source memory operand types are not the same width. f32 vectors are
800 // custom since the immediate controlling the insert encodes additional
802 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
803 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
804 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
805 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
807 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
808 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
809 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
810 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
812 if (Subtarget->is64Bit()) {
813 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
814 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
818 if (Subtarget->hasSSE42())
819 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
821 if (!UseSoftFloat && Subtarget->hasAVX()) {
822 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
823 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
824 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
825 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
826 addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
828 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
829 setOperationAction(ISD::LOAD, MVT::v8i32, Legal);
830 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
831 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
832 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
833 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
834 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
835 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
836 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
837 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
838 setOperationAction(ISD::BUILD_VECTOR, MVT::v8f32, Custom);
839 //setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Custom);
840 //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
841 //setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
842 //setOperationAction(ISD::VSETCC, MVT::v8f32, Custom);
844 // Operations to consider commented out -v16i16 v32i8
845 //setOperationAction(ISD::ADD, MVT::v16i16, Legal);
846 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
847 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
848 //setOperationAction(ISD::SUB, MVT::v32i8, Legal);
849 //setOperationAction(ISD::SUB, MVT::v16i16, Legal);
850 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
851 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
852 //setOperationAction(ISD::MUL, MVT::v16i16, Legal);
853 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
854 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
855 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
856 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
857 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
858 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
860 setOperationAction(ISD::VSETCC, MVT::v4f64, Custom);
861 // setOperationAction(ISD::VSETCC, MVT::v32i8, Custom);
862 // setOperationAction(ISD::VSETCC, MVT::v16i16, Custom);
863 setOperationAction(ISD::VSETCC, MVT::v8i32, Custom);
865 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v32i8, Custom);
866 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i16, Custom);
867 // setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i16, Custom);
868 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i32, Custom);
869 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8f32, Custom);
871 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
872 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i64, Custom);
873 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f64, Custom);
874 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i64, Custom);
875 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f64, Custom);
876 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
879 // Not sure we want to do this since there are no 256-bit integer
882 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
883 // This includes 256-bit vectors
884 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
885 EVT VT = (MVT::SimpleValueType)i;
887 // Do not attempt to custom lower non-power-of-2 vectors
888 if (!isPowerOf2_32(VT.getVectorNumElements()))
891 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
892 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
893 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
896 if (Subtarget->is64Bit()) {
897 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i64, Custom);
898 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
903 // Not sure we want to do this since there are no 256-bit integer
906 // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
907 // Including 256-bit vectors
908 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
909 EVT VT = (MVT::SimpleValueType)i;
911 if (!VT.is256BitVector()) {
914 setOperationAction(ISD::AND, VT, Promote);
915 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
916 setOperationAction(ISD::OR, VT, Promote);
917 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
918 setOperationAction(ISD::XOR, VT, Promote);
919 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
920 setOperationAction(ISD::LOAD, VT, Promote);
921 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
922 setOperationAction(ISD::SELECT, VT, Promote);
923 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
926 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
930 // We want to custom lower some of our intrinsics.
931 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
934 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
935 // handle type legalization for these operations here.
937 // FIXME: We really should do custom legalization for addition and
938 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
939 // than generic legalization for 64-bit multiplication-with-overflow, though.
940 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
941 // Add/Sub/Mul with overflow operations are custom lowered.
943 setOperationAction(ISD::SADDO, VT, Custom);
944 setOperationAction(ISD::UADDO, VT, Custom);
945 setOperationAction(ISD::SSUBO, VT, Custom);
946 setOperationAction(ISD::USUBO, VT, Custom);
947 setOperationAction(ISD::SMULO, VT, Custom);
948 setOperationAction(ISD::UMULO, VT, Custom);
951 // There are no 8-bit 3-address imul/mul instructions
952 setOperationAction(ISD::SMULO, MVT::i8, Expand);
953 setOperationAction(ISD::UMULO, MVT::i8, Expand);
955 if (!Subtarget->is64Bit()) {
956 // These libcalls are not available in 32-bit.
957 setLibcallName(RTLIB::SHL_I128, 0);
958 setLibcallName(RTLIB::SRL_I128, 0);
959 setLibcallName(RTLIB::SRA_I128, 0);
962 // We have target-specific dag combine patterns for the following nodes:
963 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
964 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
965 setTargetDAGCombine(ISD::BUILD_VECTOR);
966 setTargetDAGCombine(ISD::SELECT);
967 setTargetDAGCombine(ISD::SHL);
968 setTargetDAGCombine(ISD::SRA);
969 setTargetDAGCombine(ISD::SRL);
970 setTargetDAGCombine(ISD::OR);
971 setTargetDAGCombine(ISD::AND);
972 setTargetDAGCombine(ISD::STORE);
973 setTargetDAGCombine(ISD::ZERO_EXTEND);
974 if (Subtarget->is64Bit())
975 setTargetDAGCombine(ISD::MUL);
977 computeRegisterProperties();
979 // FIXME: These should be based on subtarget info. Plus, the values should
980 // be smaller when we are in optimizing for size mode.
981 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
982 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
983 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
984 setPrefLoopAlignment(16);
985 benefitFromCodePlacementOpt = true;
989 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
994 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
995 /// the desired ByVal argument alignment.
996 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
999 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1000 if (VTy->getBitWidth() == 128)
1002 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1003 unsigned EltAlign = 0;
1004 getMaxByValAlign(ATy->getElementType(), EltAlign);
1005 if (EltAlign > MaxAlign)
1006 MaxAlign = EltAlign;
1007 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1008 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1009 unsigned EltAlign = 0;
1010 getMaxByValAlign(STy->getElementType(i), EltAlign);
1011 if (EltAlign > MaxAlign)
1012 MaxAlign = EltAlign;
1020 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1021 /// function arguments in the caller parameter area. For X86, aggregates
1022 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1023 /// are at 4-byte boundaries.
1024 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1025 if (Subtarget->is64Bit()) {
1026 // Max of 8 and alignment of type.
1027 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1034 if (Subtarget->hasXMM())
1035 getMaxByValAlign(Ty, Align);
1039 /// getOptimalMemOpType - Returns the target specific optimal type for load
1040 /// and store operations as a result of memset, memcpy, and memmove
1041 /// lowering. If DstAlign is zero that means it's safe to destination
1042 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1043 /// means there isn't a need to check it against alignment requirement,
1044 /// probably because the source does not need to be loaded. If
1045 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1046 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1047 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1048 /// constant so it does not need to be loaded.
1049 /// It returns EVT::Other if the type should be determined using generic
1050 /// target-independent logic.
1052 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1053 unsigned DstAlign, unsigned SrcAlign,
1054 bool NonScalarIntSafe,
1056 MachineFunction &MF) const {
1057 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1058 // linux. This is because the stack realignment code can't handle certain
1059 // cases like PR2962. This should be removed when PR2962 is fixed.
1060 const Function *F = MF.getFunction();
1061 if (NonScalarIntSafe &&
1062 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1064 (Subtarget->isUnalignedMemAccessFast() ||
1065 ((DstAlign == 0 || DstAlign >= 16) &&
1066 (SrcAlign == 0 || SrcAlign >= 16))) &&
1067 Subtarget->getStackAlignment() >= 16) {
1068 if (Subtarget->hasSSE2())
1070 if (Subtarget->hasSSE1())
1072 } else if (!MemcpyStrSrc && Size >= 8 &&
1073 !Subtarget->is64Bit() &&
1074 Subtarget->getStackAlignment() >= 8 &&
1075 Subtarget->hasXMMInt()) {
1076 // Do not use f64 to lower memcpy if source is string constant. It's
1077 // better to use i32 to avoid the loads.
1081 if (Subtarget->is64Bit() && Size >= 8)
1086 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1087 /// current function. The returned value is a member of the
1088 /// MachineJumpTableInfo::JTEntryKind enum.
1089 unsigned X86TargetLowering::getJumpTableEncoding() const {
1090 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1092 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1093 Subtarget->isPICStyleGOT())
1094 return MachineJumpTableInfo::EK_Custom32;
1096 // Otherwise, use the normal jump table encoding heuristics.
1097 return TargetLowering::getJumpTableEncoding();
1101 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1102 const MachineBasicBlock *MBB,
1103 unsigned uid,MCContext &Ctx) const{
1104 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1105 Subtarget->isPICStyleGOT());
1106 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1108 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1109 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1112 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1114 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1115 SelectionDAG &DAG) const {
1116 if (!Subtarget->is64Bit())
1117 // This doesn't have DebugLoc associated with it, but is not really the
1118 // same as a Register.
1119 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1123 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1124 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1126 const MCExpr *X86TargetLowering::
1127 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1128 MCContext &Ctx) const {
1129 // X86-64 uses RIP relative addressing based on the jump table label.
1130 if (Subtarget->isPICStyleRIPRel())
1131 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1133 // Otherwise, the reference is relative to the PIC base.
1134 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1137 /// getFunctionAlignment - Return the Log2 alignment of this function.
1138 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1139 return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1142 std::pair<const TargetRegisterClass*, uint8_t>
1143 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1144 const TargetRegisterClass *RRC = 0;
1146 switch (VT.getSimpleVT().SimpleTy) {
1148 return TargetLowering::findRepresentativeClass(VT);
1149 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1150 RRC = (Subtarget->is64Bit()
1151 ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1154 RRC = X86::VR64RegisterClass;
1156 case MVT::f32: case MVT::f64:
1157 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1158 case MVT::v4f32: case MVT::v2f64:
1159 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1161 RRC = X86::VR128RegisterClass;
1164 return std::make_pair(RRC, Cost);
1168 X86TargetLowering::getRegPressureLimit(const TargetRegisterClass *RC,
1169 MachineFunction &MF) const {
1170 const TargetFrameInfo *TFI = MF.getTarget().getFrameInfo();
1172 unsigned FPDiff = TFI->hasFP(MF) ? 1 : 0;
1173 switch (RC->getID()) {
1176 case X86::GR32RegClassID:
1178 case X86::GR64RegClassID:
1180 case X86::VR128RegClassID:
1181 return Subtarget->is64Bit() ? 10 : 4;
1182 case X86::VR64RegClassID:
1187 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1188 unsigned &Offset) const {
1189 if (!Subtarget->isTargetLinux())
1192 if (Subtarget->is64Bit()) {
1193 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1195 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1208 //===----------------------------------------------------------------------===//
1209 // Return Value Calling Convention Implementation
1210 //===----------------------------------------------------------------------===//
1212 #include "X86GenCallingConv.inc"
1215 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1216 const SmallVectorImpl<ISD::OutputArg> &Outs,
1217 LLVMContext &Context) const {
1218 SmallVector<CCValAssign, 16> RVLocs;
1219 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1221 return CCInfo.CheckReturn(Outs, RetCC_X86);
1225 X86TargetLowering::LowerReturn(SDValue Chain,
1226 CallingConv::ID CallConv, bool isVarArg,
1227 const SmallVectorImpl<ISD::OutputArg> &Outs,
1228 const SmallVectorImpl<SDValue> &OutVals,
1229 DebugLoc dl, SelectionDAG &DAG) const {
1230 MachineFunction &MF = DAG.getMachineFunction();
1231 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1233 SmallVector<CCValAssign, 16> RVLocs;
1234 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1235 RVLocs, *DAG.getContext());
1236 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1238 // Add the regs to the liveout set for the function.
1239 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1240 for (unsigned i = 0; i != RVLocs.size(); ++i)
1241 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1242 MRI.addLiveOut(RVLocs[i].getLocReg());
1246 SmallVector<SDValue, 6> RetOps;
1247 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1248 // Operand #1 = Bytes To Pop
1249 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1252 // Copy the result values into the output registers.
1253 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1254 CCValAssign &VA = RVLocs[i];
1255 assert(VA.isRegLoc() && "Can only return in registers!");
1256 SDValue ValToCopy = OutVals[i];
1257 EVT ValVT = ValToCopy.getValueType();
1259 // If this is x86-64, and we disabled SSE, we can't return FP values,
1260 // or SSE or MMX vectors.
1261 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1262 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1263 (Subtarget->is64Bit() && !Subtarget->hasXMM())) {
1264 report_fatal_error("SSE register return with SSE disabled");
1266 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1267 // llvm-gcc has never done it right and no one has noticed, so this
1268 // should be OK for now.
1269 if (ValVT == MVT::f64 &&
1270 (Subtarget->is64Bit() && !Subtarget->hasXMMInt()))
1271 report_fatal_error("SSE2 register return with SSE2 disabled");
1273 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1274 // the RET instruction and handled by the FP Stackifier.
1275 if (VA.getLocReg() == X86::ST0 ||
1276 VA.getLocReg() == X86::ST1) {
1277 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1278 // change the value to the FP stack register class.
1279 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1280 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1281 RetOps.push_back(ValToCopy);
1282 // Don't emit a copytoreg.
1286 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1287 // which is returned in RAX / RDX.
1288 if (Subtarget->is64Bit()) {
1289 if (ValVT == MVT::x86mmx) {
1290 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1291 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1292 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1294 // If we don't have SSE2 available, convert to v4f32 so the generated
1295 // register is legal.
1296 if (!Subtarget->hasSSE2())
1297 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1302 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1303 Flag = Chain.getValue(1);
1306 // The x86-64 ABI for returning structs by value requires that we copy
1307 // the sret argument into %rax for the return. We saved the argument into
1308 // a virtual register in the entry block, so now we copy the value out
1310 if (Subtarget->is64Bit() &&
1311 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1312 MachineFunction &MF = DAG.getMachineFunction();
1313 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1314 unsigned Reg = FuncInfo->getSRetReturnReg();
1316 "SRetReturnReg should have been set in LowerFormalArguments().");
1317 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1319 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1320 Flag = Chain.getValue(1);
1322 // RAX now acts like a return value.
1323 MRI.addLiveOut(X86::RAX);
1326 RetOps[0] = Chain; // Update chain.
1328 // Add the flag if we have it.
1330 RetOps.push_back(Flag);
1332 return DAG.getNode(X86ISD::RET_FLAG, dl,
1333 MVT::Other, &RetOps[0], RetOps.size());
1336 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1337 if (N->getNumValues() != 1)
1339 if (!N->hasNUsesOfValue(1, 0))
1342 SDNode *Copy = *N->use_begin();
1343 if (Copy->getOpcode() != ISD::CopyToReg &&
1344 Copy->getOpcode() != ISD::FP_EXTEND)
1347 bool HasRet = false;
1348 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1350 if (UI->getOpcode() != X86ISD::RET_FLAG)
1358 /// LowerCallResult - Lower the result values of a call into the
1359 /// appropriate copies out of appropriate physical registers.
1362 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1363 CallingConv::ID CallConv, bool isVarArg,
1364 const SmallVectorImpl<ISD::InputArg> &Ins,
1365 DebugLoc dl, SelectionDAG &DAG,
1366 SmallVectorImpl<SDValue> &InVals) const {
1368 // Assign locations to each value returned by this call.
1369 SmallVector<CCValAssign, 16> RVLocs;
1370 bool Is64Bit = Subtarget->is64Bit();
1371 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1372 RVLocs, *DAG.getContext());
1373 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1375 // Copy all of the result registers out of their specified physreg.
1376 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1377 CCValAssign &VA = RVLocs[i];
1378 EVT CopyVT = VA.getValVT();
1380 // If this is x86-64, and we disabled SSE, we can't return FP values
1381 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1382 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasXMM())) {
1383 report_fatal_error("SSE register return with SSE disabled");
1388 // If this is a call to a function that returns an fp value on the floating
1389 // point stack, we must guarantee the the value is popped from the stack, so
1390 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1391 // if the return value is not used. We use the FpGET_ST0 instructions
1393 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1394 // If we prefer to use the value in xmm registers, copy it out as f80 and
1395 // use a truncate to move it from fp stack reg to xmm reg.
1396 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1397 bool isST0 = VA.getLocReg() == X86::ST0;
1399 if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1400 if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1401 if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1402 SDValue Ops[] = { Chain, InFlag };
1403 Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Flag,
1405 Val = Chain.getValue(0);
1407 // Round the f80 to the right size, which also moves it to the appropriate
1409 if (CopyVT != VA.getValVT())
1410 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1411 // This truncation won't change the value.
1412 DAG.getIntPtrConstant(1));
1413 } else if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1414 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1415 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1416 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1417 MVT::v2i64, InFlag).getValue(1);
1418 Val = Chain.getValue(0);
1419 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1420 Val, DAG.getConstant(0, MVT::i64));
1422 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1423 MVT::i64, InFlag).getValue(1);
1424 Val = Chain.getValue(0);
1426 Val = DAG.getNode(ISD::BITCAST, dl, CopyVT, Val);
1428 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1429 CopyVT, InFlag).getValue(1);
1430 Val = Chain.getValue(0);
1432 InFlag = Chain.getValue(2);
1433 InVals.push_back(Val);
1440 //===----------------------------------------------------------------------===//
1441 // C & StdCall & Fast Calling Convention implementation
1442 //===----------------------------------------------------------------------===//
1443 // StdCall calling convention seems to be standard for many Windows' API
1444 // routines and around. It differs from C calling convention just a little:
1445 // callee should clean up the stack, not caller. Symbols should be also
1446 // decorated in some fancy way :) It doesn't support any vector arguments.
1447 // For info on fast calling convention see Fast Calling Convention (tail call)
1448 // implementation LowerX86_32FastCCCallTo.
1450 /// CallIsStructReturn - Determines whether a call uses struct return
1452 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1456 return Outs[0].Flags.isSRet();
1459 /// ArgsAreStructReturn - Determines whether a function uses struct
1460 /// return semantics.
1462 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1466 return Ins[0].Flags.isSRet();
1469 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1470 /// by "Src" to address "Dst" with size and alignment information specified by
1471 /// the specific parameter attribute. The copy will be passed as a byval
1472 /// function parameter.
1474 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1475 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1477 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1479 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1480 /*isVolatile*/false, /*AlwaysInline=*/true,
1481 MachinePointerInfo(), MachinePointerInfo());
1484 /// IsTailCallConvention - Return true if the calling convention is one that
1485 /// supports tail call optimization.
1486 static bool IsTailCallConvention(CallingConv::ID CC) {
1487 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1490 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1491 /// a tailcall target by changing its ABI.
1492 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1493 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1497 X86TargetLowering::LowerMemArgument(SDValue Chain,
1498 CallingConv::ID CallConv,
1499 const SmallVectorImpl<ISD::InputArg> &Ins,
1500 DebugLoc dl, SelectionDAG &DAG,
1501 const CCValAssign &VA,
1502 MachineFrameInfo *MFI,
1504 // Create the nodes corresponding to a load from this parameter slot.
1505 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1506 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1507 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1510 // If value is passed by pointer we have address passed instead of the value
1512 if (VA.getLocInfo() == CCValAssign::Indirect)
1513 ValVT = VA.getLocVT();
1515 ValVT = VA.getValVT();
1517 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1518 // changed with more analysis.
1519 // In case of tail call optimization mark all arguments mutable. Since they
1520 // could be overwritten by lowering of arguments in case of a tail call.
1521 if (Flags.isByVal()) {
1522 int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1523 VA.getLocMemOffset(), isImmutable);
1524 return DAG.getFrameIndex(FI, getPointerTy());
1526 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1527 VA.getLocMemOffset(), isImmutable);
1528 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1529 return DAG.getLoad(ValVT, dl, Chain, FIN,
1530 MachinePointerInfo::getFixedStack(FI),
1536 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1537 CallingConv::ID CallConv,
1539 const SmallVectorImpl<ISD::InputArg> &Ins,
1542 SmallVectorImpl<SDValue> &InVals)
1544 MachineFunction &MF = DAG.getMachineFunction();
1545 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1547 const Function* Fn = MF.getFunction();
1548 if (Fn->hasExternalLinkage() &&
1549 Subtarget->isTargetCygMing() &&
1550 Fn->getName() == "main")
1551 FuncInfo->setForceFramePointer(true);
1553 MachineFrameInfo *MFI = MF.getFrameInfo();
1554 bool Is64Bit = Subtarget->is64Bit();
1555 bool IsWin64 = Subtarget->isTargetWin64();
1557 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1558 "Var args not supported with calling convention fastcc or ghc");
1560 // Assign locations to all of the incoming arguments.
1561 SmallVector<CCValAssign, 16> ArgLocs;
1562 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1563 ArgLocs, *DAG.getContext());
1564 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1566 unsigned LastVal = ~0U;
1568 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1569 CCValAssign &VA = ArgLocs[i];
1570 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1572 assert(VA.getValNo() != LastVal &&
1573 "Don't support value assigned to multiple locs yet");
1574 LastVal = VA.getValNo();
1576 if (VA.isRegLoc()) {
1577 EVT RegVT = VA.getLocVT();
1578 TargetRegisterClass *RC = NULL;
1579 if (RegVT == MVT::i32)
1580 RC = X86::GR32RegisterClass;
1581 else if (Is64Bit && RegVT == MVT::i64)
1582 RC = X86::GR64RegisterClass;
1583 else if (RegVT == MVT::f32)
1584 RC = X86::FR32RegisterClass;
1585 else if (RegVT == MVT::f64)
1586 RC = X86::FR64RegisterClass;
1587 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1588 RC = X86::VR256RegisterClass;
1589 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1590 RC = X86::VR128RegisterClass;
1591 else if (RegVT == MVT::x86mmx)
1592 RC = X86::VR64RegisterClass;
1594 llvm_unreachable("Unknown argument type!");
1596 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1597 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1599 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1600 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1602 if (VA.getLocInfo() == CCValAssign::SExt)
1603 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1604 DAG.getValueType(VA.getValVT()));
1605 else if (VA.getLocInfo() == CCValAssign::ZExt)
1606 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1607 DAG.getValueType(VA.getValVT()));
1608 else if (VA.getLocInfo() == CCValAssign::BCvt)
1609 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1611 if (VA.isExtInLoc()) {
1612 // Handle MMX values passed in XMM regs.
1613 if (RegVT.isVector()) {
1614 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1617 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1620 assert(VA.isMemLoc());
1621 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1624 // If value is passed via pointer - do a load.
1625 if (VA.getLocInfo() == CCValAssign::Indirect)
1626 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1627 MachinePointerInfo(), false, false, 0);
1629 InVals.push_back(ArgValue);
1632 // The x86-64 ABI for returning structs by value requires that we copy
1633 // the sret argument into %rax for the return. Save the argument into
1634 // a virtual register so that we can access it from the return points.
1635 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1636 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1637 unsigned Reg = FuncInfo->getSRetReturnReg();
1639 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1640 FuncInfo->setSRetReturnReg(Reg);
1642 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1643 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1646 unsigned StackSize = CCInfo.getNextStackOffset();
1647 // Align stack specially for tail calls.
1648 if (FuncIsMadeTailCallSafe(CallConv))
1649 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1651 // If the function takes variable number of arguments, make a frame index for
1652 // the start of the first vararg value... for expansion of llvm.va_start.
1654 if (!IsWin64 && (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1655 CallConv != CallingConv::X86_ThisCall))) {
1656 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1659 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1661 // FIXME: We should really autogenerate these arrays
1662 static const unsigned GPR64ArgRegsWin64[] = {
1663 X86::RCX, X86::RDX, X86::R8, X86::R9
1665 static const unsigned GPR64ArgRegs64Bit[] = {
1666 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1668 static const unsigned XMMArgRegs64Bit[] = {
1669 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1670 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1672 const unsigned *GPR64ArgRegs;
1673 unsigned NumXMMRegs = 0;
1676 // The XMM registers which might contain var arg parameters are shadowed
1677 // in their paired GPR. So we only need to save the GPR to their home
1679 TotalNumIntRegs = 4;
1680 GPR64ArgRegs = GPR64ArgRegsWin64;
1682 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1683 GPR64ArgRegs = GPR64ArgRegs64Bit;
1685 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1687 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1690 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1691 assert(!(NumXMMRegs && !Subtarget->hasXMM()) &&
1692 "SSE register cannot be used when SSE is disabled!");
1693 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1694 "SSE register cannot be used when SSE is disabled!");
1695 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasXMM())
1696 // Kernel mode asks for SSE to be disabled, so don't push them
1698 TotalNumXMMRegs = 0;
1701 const TargetFrameInfo &TFI = *getTargetMachine().getFrameInfo();
1702 // Get to the caller-allocated home save location. Add 8 to account
1703 // for the return address.
1704 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1705 FuncInfo->setRegSaveFrameIndex(
1706 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1707 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1709 // For X86-64, if there are vararg parameters that are passed via
1710 // registers, then we must store them to their spots on the stack so they
1711 // may be loaded by deferencing the result of va_next.
1712 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1713 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1714 FuncInfo->setRegSaveFrameIndex(
1715 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1719 // Store the integer parameter registers.
1720 SmallVector<SDValue, 8> MemOps;
1721 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1723 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1724 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1725 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1726 DAG.getIntPtrConstant(Offset));
1727 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1728 X86::GR64RegisterClass);
1729 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1731 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1732 MachinePointerInfo::getFixedStack(
1733 FuncInfo->getRegSaveFrameIndex(), Offset),
1735 MemOps.push_back(Store);
1739 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1740 // Now store the XMM (fp + vector) parameter registers.
1741 SmallVector<SDValue, 11> SaveXMMOps;
1742 SaveXMMOps.push_back(Chain);
1744 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1745 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1746 SaveXMMOps.push_back(ALVal);
1748 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1749 FuncInfo->getRegSaveFrameIndex()));
1750 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1751 FuncInfo->getVarArgsFPOffset()));
1753 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1754 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1755 X86::VR128RegisterClass);
1756 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1757 SaveXMMOps.push_back(Val);
1759 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1761 &SaveXMMOps[0], SaveXMMOps.size()));
1764 if (!MemOps.empty())
1765 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1766 &MemOps[0], MemOps.size());
1770 // Some CCs need callee pop.
1771 if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1772 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1774 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1775 // If this is an sret function, the return should pop the hidden pointer.
1776 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1777 FuncInfo->setBytesToPopOnReturn(4);
1781 // RegSaveFrameIndex is X86-64 only.
1782 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1783 if (CallConv == CallingConv::X86_FastCall ||
1784 CallConv == CallingConv::X86_ThisCall)
1785 // fastcc functions can't have varargs.
1786 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1793 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1794 SDValue StackPtr, SDValue Arg,
1795 DebugLoc dl, SelectionDAG &DAG,
1796 const CCValAssign &VA,
1797 ISD::ArgFlagsTy Flags) const {
1798 const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1799 unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1800 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1801 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1802 if (Flags.isByVal())
1803 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1805 return DAG.getStore(Chain, dl, Arg, PtrOff,
1806 MachinePointerInfo::getStack(LocMemOffset),
1810 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1811 /// optimization is performed and it is required.
1813 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1814 SDValue &OutRetAddr, SDValue Chain,
1815 bool IsTailCall, bool Is64Bit,
1816 int FPDiff, DebugLoc dl) const {
1817 // Adjust the Return address stack slot.
1818 EVT VT = getPointerTy();
1819 OutRetAddr = getReturnAddressFrameIndex(DAG);
1821 // Load the "old" Return address.
1822 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1824 return SDValue(OutRetAddr.getNode(), 1);
1827 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1828 /// optimization is performed and it is required (FPDiff!=0).
1830 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1831 SDValue Chain, SDValue RetAddrFrIdx,
1832 bool Is64Bit, int FPDiff, DebugLoc dl) {
1833 // Store the return address to the appropriate stack slot.
1834 if (!FPDiff) return Chain;
1835 // Calculate the new stack slot for the return address.
1836 int SlotSize = Is64Bit ? 8 : 4;
1837 int NewReturnAddrFI =
1838 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1839 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1840 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1841 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1842 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1848 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1849 CallingConv::ID CallConv, bool isVarArg,
1851 const SmallVectorImpl<ISD::OutputArg> &Outs,
1852 const SmallVectorImpl<SDValue> &OutVals,
1853 const SmallVectorImpl<ISD::InputArg> &Ins,
1854 DebugLoc dl, SelectionDAG &DAG,
1855 SmallVectorImpl<SDValue> &InVals) const {
1856 MachineFunction &MF = DAG.getMachineFunction();
1857 bool Is64Bit = Subtarget->is64Bit();
1858 bool IsStructRet = CallIsStructReturn(Outs);
1859 bool IsSibcall = false;
1862 // Check if it's really possible to do a tail call.
1863 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1864 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1865 Outs, OutVals, Ins, DAG);
1867 // Sibcalls are automatically detected tailcalls which do not require
1869 if (!GuaranteedTailCallOpt && isTailCall)
1876 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1877 "Var args not supported with calling convention fastcc or ghc");
1879 // Analyze operands of the call, assigning locations to each operand.
1880 SmallVector<CCValAssign, 16> ArgLocs;
1881 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1882 ArgLocs, *DAG.getContext());
1883 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
1885 // Get a count of how many bytes are to be pushed on the stack.
1886 unsigned NumBytes = CCInfo.getNextStackOffset();
1888 // This is a sibcall. The memory operands are available in caller's
1889 // own caller's stack.
1891 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1892 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1895 if (isTailCall && !IsSibcall) {
1896 // Lower arguments at fp - stackoffset + fpdiff.
1897 unsigned NumBytesCallerPushed =
1898 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1899 FPDiff = NumBytesCallerPushed - NumBytes;
1901 // Set the delta of movement of the returnaddr stackslot.
1902 // But only set if delta is greater than previous delta.
1903 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1904 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1908 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1910 SDValue RetAddrFrIdx;
1911 // Load return adress for tail calls.
1912 if (isTailCall && FPDiff)
1913 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1914 Is64Bit, FPDiff, dl);
1916 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1917 SmallVector<SDValue, 8> MemOpChains;
1920 // Walk the register/memloc assignments, inserting copies/loads. In the case
1921 // of tail call optimization arguments are handle later.
1922 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1923 CCValAssign &VA = ArgLocs[i];
1924 EVT RegVT = VA.getLocVT();
1925 SDValue Arg = OutVals[i];
1926 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1927 bool isByVal = Flags.isByVal();
1929 // Promote the value if needed.
1930 switch (VA.getLocInfo()) {
1931 default: llvm_unreachable("Unknown loc info!");
1932 case CCValAssign::Full: break;
1933 case CCValAssign::SExt:
1934 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1936 case CCValAssign::ZExt:
1937 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1939 case CCValAssign::AExt:
1940 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1941 // Special case: passing MMX values in XMM registers.
1942 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
1943 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1944 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1946 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1948 case CCValAssign::BCvt:
1949 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
1951 case CCValAssign::Indirect: {
1952 // Store the argument.
1953 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1954 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1955 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1956 MachinePointerInfo::getFixedStack(FI),
1963 if (VA.isRegLoc()) {
1964 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1965 if (isVarArg && Subtarget->isTargetWin64()) {
1966 // Win64 ABI requires argument XMM reg to be copied to the corresponding
1967 // shadow reg if callee is a varargs function.
1968 unsigned ShadowReg = 0;
1969 switch (VA.getLocReg()) {
1970 case X86::XMM0: ShadowReg = X86::RCX; break;
1971 case X86::XMM1: ShadowReg = X86::RDX; break;
1972 case X86::XMM2: ShadowReg = X86::R8; break;
1973 case X86::XMM3: ShadowReg = X86::R9; break;
1976 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
1978 } else if (!IsSibcall && (!isTailCall || isByVal)) {
1979 assert(VA.isMemLoc());
1980 if (StackPtr.getNode() == 0)
1981 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1982 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1983 dl, DAG, VA, Flags));
1987 if (!MemOpChains.empty())
1988 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1989 &MemOpChains[0], MemOpChains.size());
1991 // Build a sequence of copy-to-reg nodes chained together with token chain
1992 // and flag operands which copy the outgoing args into registers.
1994 // Tail call byval lowering might overwrite argument registers so in case of
1995 // tail call optimization the copies to registers are lowered later.
1997 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1998 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1999 RegsToPass[i].second, InFlag);
2000 InFlag = Chain.getValue(1);
2003 if (Subtarget->isPICStyleGOT()) {
2004 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2007 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2008 DAG.getNode(X86ISD::GlobalBaseReg,
2009 DebugLoc(), getPointerTy()),
2011 InFlag = Chain.getValue(1);
2013 // If we are tail calling and generating PIC/GOT style code load the
2014 // address of the callee into ECX. The value in ecx is used as target of
2015 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2016 // for tail calls on PIC/GOT architectures. Normally we would just put the
2017 // address of GOT into ebx and then call target@PLT. But for tail calls
2018 // ebx would be restored (since ebx is callee saved) before jumping to the
2021 // Note: The actual moving to ECX is done further down.
2022 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2023 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2024 !G->getGlobal()->hasProtectedVisibility())
2025 Callee = LowerGlobalAddress(Callee, DAG);
2026 else if (isa<ExternalSymbolSDNode>(Callee))
2027 Callee = LowerExternalSymbol(Callee, DAG);
2031 if (Is64Bit && isVarArg && !Subtarget->isTargetWin64()) {
2032 // From AMD64 ABI document:
2033 // For calls that may call functions that use varargs or stdargs
2034 // (prototype-less calls or calls to functions containing ellipsis (...) in
2035 // the declaration) %al is used as hidden argument to specify the number
2036 // of SSE registers used. The contents of %al do not need to match exactly
2037 // the number of registers, but must be an ubound on the number of SSE
2038 // registers used and is in the range 0 - 8 inclusive.
2040 // Count the number of XMM registers allocated.
2041 static const unsigned XMMArgRegs[] = {
2042 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2043 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2045 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2046 assert((Subtarget->hasXMM() || !NumXMMRegs)
2047 && "SSE registers cannot be used when SSE is disabled");
2049 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2050 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2051 InFlag = Chain.getValue(1);
2055 // For tail calls lower the arguments to the 'real' stack slot.
2057 // Force all the incoming stack arguments to be loaded from the stack
2058 // before any new outgoing arguments are stored to the stack, because the
2059 // outgoing stack slots may alias the incoming argument stack slots, and
2060 // the alias isn't otherwise explicit. This is slightly more conservative
2061 // than necessary, because it means that each store effectively depends
2062 // on every argument instead of just those arguments it would clobber.
2063 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2065 SmallVector<SDValue, 8> MemOpChains2;
2068 // Do not flag preceeding copytoreg stuff together with the following stuff.
2070 if (GuaranteedTailCallOpt) {
2071 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2072 CCValAssign &VA = ArgLocs[i];
2075 assert(VA.isMemLoc());
2076 SDValue Arg = OutVals[i];
2077 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2078 // Create frame index.
2079 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2080 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2081 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2082 FIN = DAG.getFrameIndex(FI, getPointerTy());
2084 if (Flags.isByVal()) {
2085 // Copy relative to framepointer.
2086 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2087 if (StackPtr.getNode() == 0)
2088 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2090 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2092 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2096 // Store relative to framepointer.
2097 MemOpChains2.push_back(
2098 DAG.getStore(ArgChain, dl, Arg, FIN,
2099 MachinePointerInfo::getFixedStack(FI),
2105 if (!MemOpChains2.empty())
2106 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2107 &MemOpChains2[0], MemOpChains2.size());
2109 // Copy arguments to their registers.
2110 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2111 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2112 RegsToPass[i].second, InFlag);
2113 InFlag = Chain.getValue(1);
2117 // Store the return address to the appropriate stack slot.
2118 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2122 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2123 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2124 // In the 64-bit large code model, we have to make all calls
2125 // through a register, since the call instruction's 32-bit
2126 // pc-relative offset may not be large enough to hold the whole
2128 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2129 // If the callee is a GlobalAddress node (quite common, every direct call
2130 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2133 // We should use extra load for direct calls to dllimported functions in
2135 const GlobalValue *GV = G->getGlobal();
2136 if (!GV->hasDLLImportLinkage()) {
2137 unsigned char OpFlags = 0;
2139 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2140 // external symbols most go through the PLT in PIC mode. If the symbol
2141 // has hidden or protected visibility, or if it is static or local, then
2142 // we don't need to use the PLT - we can directly call it.
2143 if (Subtarget->isTargetELF() &&
2144 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2145 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2146 OpFlags = X86II::MO_PLT;
2147 } else if (Subtarget->isPICStyleStubAny() &&
2148 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2149 Subtarget->getDarwinVers() < 9) {
2150 // PC-relative references to external symbols should go through $stub,
2151 // unless we're building with the leopard linker or later, which
2152 // automatically synthesizes these stubs.
2153 OpFlags = X86II::MO_DARWIN_STUB;
2156 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2157 G->getOffset(), OpFlags);
2159 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2160 unsigned char OpFlags = 0;
2162 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2163 // external symbols should go through the PLT.
2164 if (Subtarget->isTargetELF() &&
2165 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2166 OpFlags = X86II::MO_PLT;
2167 } else if (Subtarget->isPICStyleStubAny() &&
2168 Subtarget->getDarwinVers() < 9) {
2169 // PC-relative references to external symbols should go through $stub,
2170 // unless we're building with the leopard linker or later, which
2171 // automatically synthesizes these stubs.
2172 OpFlags = X86II::MO_DARWIN_STUB;
2175 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2179 // Returns a chain & a flag for retval copy to use.
2180 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2181 SmallVector<SDValue, 8> Ops;
2183 if (!IsSibcall && isTailCall) {
2184 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2185 DAG.getIntPtrConstant(0, true), InFlag);
2186 InFlag = Chain.getValue(1);
2189 Ops.push_back(Chain);
2190 Ops.push_back(Callee);
2193 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2195 // Add argument registers to the end of the list so that they are known live
2197 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2198 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2199 RegsToPass[i].second.getValueType()));
2201 // Add an implicit use GOT pointer in EBX.
2202 if (!isTailCall && Subtarget->isPICStyleGOT())
2203 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2205 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2206 if (Is64Bit && isVarArg && !Subtarget->isTargetWin64())
2207 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2209 if (InFlag.getNode())
2210 Ops.push_back(InFlag);
2214 //// If this is the first return lowered for this function, add the regs
2215 //// to the liveout set for the function.
2216 // This isn't right, although it's probably harmless on x86; liveouts
2217 // should be computed from returns not tail calls. Consider a void
2218 // function making a tail call to a function returning int.
2219 return DAG.getNode(X86ISD::TC_RETURN, dl,
2220 NodeTys, &Ops[0], Ops.size());
2223 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2224 InFlag = Chain.getValue(1);
2226 // Create the CALLSEQ_END node.
2227 unsigned NumBytesForCalleeToPush;
2228 if (Subtarget->IsCalleePop(isVarArg, CallConv))
2229 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2230 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2231 // If this is a call to a struct-return function, the callee
2232 // pops the hidden struct pointer, so we have to push it back.
2233 // This is common for Darwin/X86, Linux & Mingw32 targets.
2234 NumBytesForCalleeToPush = 4;
2236 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2238 // Returns a flag for retval copy to use.
2240 Chain = DAG.getCALLSEQ_END(Chain,
2241 DAG.getIntPtrConstant(NumBytes, true),
2242 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2245 InFlag = Chain.getValue(1);
2248 // Handle result values, copying them out of physregs into vregs that we
2250 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2251 Ins, dl, DAG, InVals);
2255 //===----------------------------------------------------------------------===//
2256 // Fast Calling Convention (tail call) implementation
2257 //===----------------------------------------------------------------------===//
2259 // Like std call, callee cleans arguments, convention except that ECX is
2260 // reserved for storing the tail called function address. Only 2 registers are
2261 // free for argument passing (inreg). Tail call optimization is performed
2263 // * tailcallopt is enabled
2264 // * caller/callee are fastcc
2265 // On X86_64 architecture with GOT-style position independent code only local
2266 // (within module) calls are supported at the moment.
2267 // To keep the stack aligned according to platform abi the function
2268 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2269 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2270 // If a tail called function callee has more arguments than the caller the
2271 // caller needs to make sure that there is room to move the RETADDR to. This is
2272 // achieved by reserving an area the size of the argument delta right after the
2273 // original REtADDR, but before the saved framepointer or the spilled registers
2274 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2286 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2287 /// for a 16 byte align requirement.
2289 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2290 SelectionDAG& DAG) const {
2291 MachineFunction &MF = DAG.getMachineFunction();
2292 const TargetMachine &TM = MF.getTarget();
2293 const TargetFrameInfo &TFI = *TM.getFrameInfo();
2294 unsigned StackAlignment = TFI.getStackAlignment();
2295 uint64_t AlignMask = StackAlignment - 1;
2296 int64_t Offset = StackSize;
2297 uint64_t SlotSize = TD->getPointerSize();
2298 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2299 // Number smaller than 12 so just add the difference.
2300 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2302 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2303 Offset = ((~AlignMask) & Offset) + StackAlignment +
2304 (StackAlignment-SlotSize);
2309 /// MatchingStackOffset - Return true if the given stack call argument is
2310 /// already available in the same position (relatively) of the caller's
2311 /// incoming argument stack.
2313 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2314 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2315 const X86InstrInfo *TII) {
2316 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2318 if (Arg.getOpcode() == ISD::CopyFromReg) {
2319 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2320 if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2322 MachineInstr *Def = MRI->getVRegDef(VR);
2325 if (!Flags.isByVal()) {
2326 if (!TII->isLoadFromStackSlot(Def, FI))
2329 unsigned Opcode = Def->getOpcode();
2330 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2331 Def->getOperand(1).isFI()) {
2332 FI = Def->getOperand(1).getIndex();
2333 Bytes = Flags.getByValSize();
2337 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2338 if (Flags.isByVal())
2339 // ByVal argument is passed in as a pointer but it's now being
2340 // dereferenced. e.g.
2341 // define @foo(%struct.X* %A) {
2342 // tail call @bar(%struct.X* byval %A)
2345 SDValue Ptr = Ld->getBasePtr();
2346 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2349 FI = FINode->getIndex();
2353 assert(FI != INT_MAX);
2354 if (!MFI->isFixedObjectIndex(FI))
2356 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2359 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2360 /// for tail call optimization. Targets which want to do tail call
2361 /// optimization should implement this function.
2363 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2364 CallingConv::ID CalleeCC,
2366 bool isCalleeStructRet,
2367 bool isCallerStructRet,
2368 const SmallVectorImpl<ISD::OutputArg> &Outs,
2369 const SmallVectorImpl<SDValue> &OutVals,
2370 const SmallVectorImpl<ISD::InputArg> &Ins,
2371 SelectionDAG& DAG) const {
2372 if (!IsTailCallConvention(CalleeCC) &&
2373 CalleeCC != CallingConv::C)
2376 // If -tailcallopt is specified, make fastcc functions tail-callable.
2377 const MachineFunction &MF = DAG.getMachineFunction();
2378 const Function *CallerF = DAG.getMachineFunction().getFunction();
2379 CallingConv::ID CallerCC = CallerF->getCallingConv();
2380 bool CCMatch = CallerCC == CalleeCC;
2382 if (GuaranteedTailCallOpt) {
2383 if (IsTailCallConvention(CalleeCC) && CCMatch)
2388 // Look for obvious safe cases to perform tail call optimization that do not
2389 // require ABI changes. This is what gcc calls sibcall.
2391 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2392 // emit a special epilogue.
2393 if (RegInfo->needsStackRealignment(MF))
2396 // Do not sibcall optimize vararg calls unless the call site is not passing
2398 if (isVarArg && !Outs.empty())
2401 // Also avoid sibcall optimization if either caller or callee uses struct
2402 // return semantics.
2403 if (isCalleeStructRet || isCallerStructRet)
2406 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2407 // Therefore if it's not used by the call it is not safe to optimize this into
2409 bool Unused = false;
2410 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2417 SmallVector<CCValAssign, 16> RVLocs;
2418 CCState CCInfo(CalleeCC, false, getTargetMachine(),
2419 RVLocs, *DAG.getContext());
2420 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2421 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2422 CCValAssign &VA = RVLocs[i];
2423 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2428 // If the calling conventions do not match, then we'd better make sure the
2429 // results are returned in the same way as what the caller expects.
2431 SmallVector<CCValAssign, 16> RVLocs1;
2432 CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2433 RVLocs1, *DAG.getContext());
2434 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2436 SmallVector<CCValAssign, 16> RVLocs2;
2437 CCState CCInfo2(CallerCC, false, getTargetMachine(),
2438 RVLocs2, *DAG.getContext());
2439 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2441 if (RVLocs1.size() != RVLocs2.size())
2443 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2444 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2446 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2448 if (RVLocs1[i].isRegLoc()) {
2449 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2452 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2458 // If the callee takes no arguments then go on to check the results of the
2460 if (!Outs.empty()) {
2461 // Check if stack adjustment is needed. For now, do not do this if any
2462 // argument is passed on the stack.
2463 SmallVector<CCValAssign, 16> ArgLocs;
2464 CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2465 ArgLocs, *DAG.getContext());
2466 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2467 if (CCInfo.getNextStackOffset()) {
2468 MachineFunction &MF = DAG.getMachineFunction();
2469 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2471 if (Subtarget->isTargetWin64())
2472 // Win64 ABI has additional complications.
2475 // Check if the arguments are already laid out in the right way as
2476 // the caller's fixed stack objects.
2477 MachineFrameInfo *MFI = MF.getFrameInfo();
2478 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2479 const X86InstrInfo *TII =
2480 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2481 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2482 CCValAssign &VA = ArgLocs[i];
2483 SDValue Arg = OutVals[i];
2484 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2485 if (VA.getLocInfo() == CCValAssign::Indirect)
2487 if (!VA.isRegLoc()) {
2488 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2495 // If the tailcall address may be in a register, then make sure it's
2496 // possible to register allocate for it. In 32-bit, the call address can
2497 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2498 // callee-saved registers are restored. These happen to be the same
2499 // registers used to pass 'inreg' arguments so watch out for those.
2500 if (!Subtarget->is64Bit() &&
2501 !isa<GlobalAddressSDNode>(Callee) &&
2502 !isa<ExternalSymbolSDNode>(Callee)) {
2503 unsigned NumInRegs = 0;
2504 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2505 CCValAssign &VA = ArgLocs[i];
2508 unsigned Reg = VA.getLocReg();
2511 case X86::EAX: case X86::EDX: case X86::ECX:
2512 if (++NumInRegs == 3)
2520 // An stdcall caller is expected to clean up its arguments; the callee
2521 // isn't going to do that.
2522 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2529 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2530 return X86::createFastISel(funcInfo);
2534 //===----------------------------------------------------------------------===//
2535 // Other Lowering Hooks
2536 //===----------------------------------------------------------------------===//
2538 static bool MayFoldLoad(SDValue Op) {
2539 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2542 static bool MayFoldIntoStore(SDValue Op) {
2543 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2546 static bool isTargetShuffle(unsigned Opcode) {
2548 default: return false;
2549 case X86ISD::PSHUFD:
2550 case X86ISD::PSHUFHW:
2551 case X86ISD::PSHUFLW:
2552 case X86ISD::SHUFPD:
2553 case X86ISD::PALIGN:
2554 case X86ISD::SHUFPS:
2555 case X86ISD::MOVLHPS:
2556 case X86ISD::MOVLHPD:
2557 case X86ISD::MOVHLPS:
2558 case X86ISD::MOVLPS:
2559 case X86ISD::MOVLPD:
2560 case X86ISD::MOVSHDUP:
2561 case X86ISD::MOVSLDUP:
2562 case X86ISD::MOVDDUP:
2565 case X86ISD::UNPCKLPS:
2566 case X86ISD::UNPCKLPD:
2567 case X86ISD::PUNPCKLWD:
2568 case X86ISD::PUNPCKLBW:
2569 case X86ISD::PUNPCKLDQ:
2570 case X86ISD::PUNPCKLQDQ:
2571 case X86ISD::UNPCKHPS:
2572 case X86ISD::UNPCKHPD:
2573 case X86ISD::PUNPCKHWD:
2574 case X86ISD::PUNPCKHBW:
2575 case X86ISD::PUNPCKHDQ:
2576 case X86ISD::PUNPCKHQDQ:
2582 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2583 SDValue V1, SelectionDAG &DAG) {
2585 default: llvm_unreachable("Unknown x86 shuffle node");
2586 case X86ISD::MOVSHDUP:
2587 case X86ISD::MOVSLDUP:
2588 case X86ISD::MOVDDUP:
2589 return DAG.getNode(Opc, dl, VT, V1);
2595 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2596 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2598 default: llvm_unreachable("Unknown x86 shuffle node");
2599 case X86ISD::PSHUFD:
2600 case X86ISD::PSHUFHW:
2601 case X86ISD::PSHUFLW:
2602 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2608 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2609 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2611 default: llvm_unreachable("Unknown x86 shuffle node");
2612 case X86ISD::PALIGN:
2613 case X86ISD::SHUFPD:
2614 case X86ISD::SHUFPS:
2615 return DAG.getNode(Opc, dl, VT, V1, V2,
2616 DAG.getConstant(TargetMask, MVT::i8));
2621 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2622 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2624 default: llvm_unreachable("Unknown x86 shuffle node");
2625 case X86ISD::MOVLHPS:
2626 case X86ISD::MOVLHPD:
2627 case X86ISD::MOVHLPS:
2628 case X86ISD::MOVLPS:
2629 case X86ISD::MOVLPD:
2632 case X86ISD::UNPCKLPS:
2633 case X86ISD::UNPCKLPD:
2634 case X86ISD::PUNPCKLWD:
2635 case X86ISD::PUNPCKLBW:
2636 case X86ISD::PUNPCKLDQ:
2637 case X86ISD::PUNPCKLQDQ:
2638 case X86ISD::UNPCKHPS:
2639 case X86ISD::UNPCKHPD:
2640 case X86ISD::PUNPCKHWD:
2641 case X86ISD::PUNPCKHBW:
2642 case X86ISD::PUNPCKHDQ:
2643 case X86ISD::PUNPCKHQDQ:
2644 return DAG.getNode(Opc, dl, VT, V1, V2);
2649 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2650 MachineFunction &MF = DAG.getMachineFunction();
2651 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2652 int ReturnAddrIndex = FuncInfo->getRAIndex();
2654 if (ReturnAddrIndex == 0) {
2655 // Set up a frame object for the return address.
2656 uint64_t SlotSize = TD->getPointerSize();
2657 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2659 FuncInfo->setRAIndex(ReturnAddrIndex);
2662 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2666 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2667 bool hasSymbolicDisplacement) {
2668 // Offset should fit into 32 bit immediate field.
2669 if (!isInt<32>(Offset))
2672 // If we don't have a symbolic displacement - we don't have any extra
2674 if (!hasSymbolicDisplacement)
2677 // FIXME: Some tweaks might be needed for medium code model.
2678 if (M != CodeModel::Small && M != CodeModel::Kernel)
2681 // For small code model we assume that latest object is 16MB before end of 31
2682 // bits boundary. We may also accept pretty large negative constants knowing
2683 // that all objects are in the positive half of address space.
2684 if (M == CodeModel::Small && Offset < 16*1024*1024)
2687 // For kernel code model we know that all object resist in the negative half
2688 // of 32bits address space. We may not accept negative offsets, since they may
2689 // be just off and we may accept pretty large positive ones.
2690 if (M == CodeModel::Kernel && Offset > 0)
2696 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2697 /// specific condition code, returning the condition code and the LHS/RHS of the
2698 /// comparison to make.
2699 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2700 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2702 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2703 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2704 // X > -1 -> X == 0, jump !sign.
2705 RHS = DAG.getConstant(0, RHS.getValueType());
2706 return X86::COND_NS;
2707 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2708 // X < 0 -> X == 0, jump on sign.
2710 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2712 RHS = DAG.getConstant(0, RHS.getValueType());
2713 return X86::COND_LE;
2717 switch (SetCCOpcode) {
2718 default: llvm_unreachable("Invalid integer condition!");
2719 case ISD::SETEQ: return X86::COND_E;
2720 case ISD::SETGT: return X86::COND_G;
2721 case ISD::SETGE: return X86::COND_GE;
2722 case ISD::SETLT: return X86::COND_L;
2723 case ISD::SETLE: return X86::COND_LE;
2724 case ISD::SETNE: return X86::COND_NE;
2725 case ISD::SETULT: return X86::COND_B;
2726 case ISD::SETUGT: return X86::COND_A;
2727 case ISD::SETULE: return X86::COND_BE;
2728 case ISD::SETUGE: return X86::COND_AE;
2732 // First determine if it is required or is profitable to flip the operands.
2734 // If LHS is a foldable load, but RHS is not, flip the condition.
2735 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2736 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2737 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2738 std::swap(LHS, RHS);
2741 switch (SetCCOpcode) {
2747 std::swap(LHS, RHS);
2751 // On a floating point condition, the flags are set as follows:
2753 // 0 | 0 | 0 | X > Y
2754 // 0 | 0 | 1 | X < Y
2755 // 1 | 0 | 0 | X == Y
2756 // 1 | 1 | 1 | unordered
2757 switch (SetCCOpcode) {
2758 default: llvm_unreachable("Condcode should be pre-legalized away");
2760 case ISD::SETEQ: return X86::COND_E;
2761 case ISD::SETOLT: // flipped
2763 case ISD::SETGT: return X86::COND_A;
2764 case ISD::SETOLE: // flipped
2766 case ISD::SETGE: return X86::COND_AE;
2767 case ISD::SETUGT: // flipped
2769 case ISD::SETLT: return X86::COND_B;
2770 case ISD::SETUGE: // flipped
2772 case ISD::SETLE: return X86::COND_BE;
2774 case ISD::SETNE: return X86::COND_NE;
2775 case ISD::SETUO: return X86::COND_P;
2776 case ISD::SETO: return X86::COND_NP;
2778 case ISD::SETUNE: return X86::COND_INVALID;
2782 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2783 /// code. Current x86 isa includes the following FP cmov instructions:
2784 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2785 static bool hasFPCMov(unsigned X86CC) {
2801 /// isFPImmLegal - Returns true if the target can instruction select the
2802 /// specified FP immediate natively. If false, the legalizer will
2803 /// materialize the FP immediate as a load from a constant pool.
2804 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2805 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2806 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2812 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2813 /// the specified range (L, H].
2814 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2815 return (Val < 0) || (Val >= Low && Val < Hi);
2818 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2819 /// specified value.
2820 static bool isUndefOrEqual(int Val, int CmpVal) {
2821 if (Val < 0 || Val == CmpVal)
2826 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2827 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2828 /// the second operand.
2829 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2830 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
2831 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2832 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2833 return (Mask[0] < 2 && Mask[1] < 2);
2837 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2838 SmallVector<int, 8> M;
2840 return ::isPSHUFDMask(M, N->getValueType(0));
2843 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2844 /// is suitable for input to PSHUFHW.
2845 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2846 if (VT != MVT::v8i16)
2849 // Lower quadword copied in order or undef.
2850 for (int i = 0; i != 4; ++i)
2851 if (Mask[i] >= 0 && Mask[i] != i)
2854 // Upper quadword shuffled.
2855 for (int i = 4; i != 8; ++i)
2856 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2862 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2863 SmallVector<int, 8> M;
2865 return ::isPSHUFHWMask(M, N->getValueType(0));
2868 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2869 /// is suitable for input to PSHUFLW.
2870 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2871 if (VT != MVT::v8i16)
2874 // Upper quadword copied in order.
2875 for (int i = 4; i != 8; ++i)
2876 if (Mask[i] >= 0 && Mask[i] != i)
2879 // Lower quadword shuffled.
2880 for (int i = 0; i != 4; ++i)
2887 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2888 SmallVector<int, 8> M;
2890 return ::isPSHUFLWMask(M, N->getValueType(0));
2893 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2894 /// is suitable for input to PALIGNR.
2895 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2897 int i, e = VT.getVectorNumElements();
2899 // Do not handle v2i64 / v2f64 shuffles with palignr.
2900 if (e < 4 || !hasSSSE3)
2903 for (i = 0; i != e; ++i)
2907 // All undef, not a palignr.
2911 // Determine if it's ok to perform a palignr with only the LHS, since we
2912 // don't have access to the actual shuffle elements to see if RHS is undef.
2913 bool Unary = Mask[i] < (int)e;
2914 bool NeedsUnary = false;
2916 int s = Mask[i] - i;
2918 // Check the rest of the elements to see if they are consecutive.
2919 for (++i; i != e; ++i) {
2924 Unary = Unary && (m < (int)e);
2925 NeedsUnary = NeedsUnary || (m < s);
2927 if (NeedsUnary && !Unary)
2929 if (Unary && m != ((s+i) & (e-1)))
2931 if (!Unary && m != (s+i))
2937 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2938 SmallVector<int, 8> M;
2940 return ::isPALIGNRMask(M, N->getValueType(0), true);
2943 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2944 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2945 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2946 int NumElems = VT.getVectorNumElements();
2947 if (NumElems != 2 && NumElems != 4)
2950 int Half = NumElems / 2;
2951 for (int i = 0; i < Half; ++i)
2952 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2954 for (int i = Half; i < NumElems; ++i)
2955 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2961 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2962 SmallVector<int, 8> M;
2964 return ::isSHUFPMask(M, N->getValueType(0));
2967 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2968 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2969 /// half elements to come from vector 1 (which would equal the dest.) and
2970 /// the upper half to come from vector 2.
2971 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2972 int NumElems = VT.getVectorNumElements();
2974 if (NumElems != 2 && NumElems != 4)
2977 int Half = NumElems / 2;
2978 for (int i = 0; i < Half; ++i)
2979 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2981 for (int i = Half; i < NumElems; ++i)
2982 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2987 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2988 SmallVector<int, 8> M;
2990 return isCommutedSHUFPMask(M, N->getValueType(0));
2993 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2994 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2995 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2996 if (N->getValueType(0).getVectorNumElements() != 4)
2999 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3000 return isUndefOrEqual(N->getMaskElt(0), 6) &&
3001 isUndefOrEqual(N->getMaskElt(1), 7) &&
3002 isUndefOrEqual(N->getMaskElt(2), 2) &&
3003 isUndefOrEqual(N->getMaskElt(3), 3);
3006 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3007 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3009 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3010 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3015 return isUndefOrEqual(N->getMaskElt(0), 2) &&
3016 isUndefOrEqual(N->getMaskElt(1), 3) &&
3017 isUndefOrEqual(N->getMaskElt(2), 2) &&
3018 isUndefOrEqual(N->getMaskElt(3), 3);
3021 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3022 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3023 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3024 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3026 if (NumElems != 2 && NumElems != 4)
3029 for (unsigned i = 0; i < NumElems/2; ++i)
3030 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3033 for (unsigned i = NumElems/2; i < NumElems; ++i)
3034 if (!isUndefOrEqual(N->getMaskElt(i), i))
3040 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3041 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3042 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3043 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3045 if (NumElems != 2 && NumElems != 4)
3048 for (unsigned i = 0; i < NumElems/2; ++i)
3049 if (!isUndefOrEqual(N->getMaskElt(i), i))
3052 for (unsigned i = 0; i < NumElems/2; ++i)
3053 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3059 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3060 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3061 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3062 bool V2IsSplat = false) {
3063 int NumElts = VT.getVectorNumElements();
3064 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3067 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3069 int BitI1 = Mask[i+1];
3070 if (!isUndefOrEqual(BitI, j))
3073 if (!isUndefOrEqual(BitI1, NumElts))
3076 if (!isUndefOrEqual(BitI1, j + NumElts))
3083 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3084 SmallVector<int, 8> M;
3086 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3089 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3090 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3091 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3092 bool V2IsSplat = false) {
3093 int NumElts = VT.getVectorNumElements();
3094 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3097 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3099 int BitI1 = Mask[i+1];
3100 if (!isUndefOrEqual(BitI, j + NumElts/2))
3103 if (isUndefOrEqual(BitI1, NumElts))
3106 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3113 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3114 SmallVector<int, 8> M;
3116 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3119 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3120 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3122 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3123 int NumElems = VT.getVectorNumElements();
3124 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3127 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
3129 int BitI1 = Mask[i+1];
3130 if (!isUndefOrEqual(BitI, j))
3132 if (!isUndefOrEqual(BitI1, j))
3138 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3139 SmallVector<int, 8> M;
3141 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3144 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3145 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3147 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3148 int NumElems = VT.getVectorNumElements();
3149 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3152 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3154 int BitI1 = Mask[i+1];
3155 if (!isUndefOrEqual(BitI, j))
3157 if (!isUndefOrEqual(BitI1, j))
3163 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3164 SmallVector<int, 8> M;
3166 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3169 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3170 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3171 /// MOVSD, and MOVD, i.e. setting the lowest element.
3172 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3173 if (VT.getVectorElementType().getSizeInBits() < 32)
3176 int NumElts = VT.getVectorNumElements();
3178 if (!isUndefOrEqual(Mask[0], NumElts))
3181 for (int i = 1; i < NumElts; ++i)
3182 if (!isUndefOrEqual(Mask[i], i))
3188 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3189 SmallVector<int, 8> M;
3191 return ::isMOVLMask(M, N->getValueType(0));
3194 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3195 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3196 /// element of vector 2 and the other elements to come from vector 1 in order.
3197 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3198 bool V2IsSplat = false, bool V2IsUndef = false) {
3199 int NumOps = VT.getVectorNumElements();
3200 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3203 if (!isUndefOrEqual(Mask[0], 0))
3206 for (int i = 1; i < NumOps; ++i)
3207 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3208 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3209 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3215 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3216 bool V2IsUndef = false) {
3217 SmallVector<int, 8> M;
3219 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3222 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3223 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3224 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3225 if (N->getValueType(0).getVectorNumElements() != 4)
3228 // Expect 1, 1, 3, 3
3229 for (unsigned i = 0; i < 2; ++i) {
3230 int Elt = N->getMaskElt(i);
3231 if (Elt >= 0 && Elt != 1)
3236 for (unsigned i = 2; i < 4; ++i) {
3237 int Elt = N->getMaskElt(i);
3238 if (Elt >= 0 && Elt != 3)
3243 // Don't use movshdup if it can be done with a shufps.
3244 // FIXME: verify that matching u, u, 3, 3 is what we want.
3248 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3249 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3250 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3251 if (N->getValueType(0).getVectorNumElements() != 4)
3254 // Expect 0, 0, 2, 2
3255 for (unsigned i = 0; i < 2; ++i)
3256 if (N->getMaskElt(i) > 0)
3260 for (unsigned i = 2; i < 4; ++i) {
3261 int Elt = N->getMaskElt(i);
3262 if (Elt >= 0 && Elt != 2)
3267 // Don't use movsldup if it can be done with a shufps.
3271 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3272 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3273 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3274 int e = N->getValueType(0).getVectorNumElements() / 2;
3276 for (int i = 0; i < e; ++i)
3277 if (!isUndefOrEqual(N->getMaskElt(i), i))
3279 for (int i = 0; i < e; ++i)
3280 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3285 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3286 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3287 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3288 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3289 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3291 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3293 for (int i = 0; i < NumOperands; ++i) {
3294 int Val = SVOp->getMaskElt(NumOperands-i-1);
3295 if (Val < 0) Val = 0;
3296 if (Val >= NumOperands) Val -= NumOperands;
3298 if (i != NumOperands - 1)
3304 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3305 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3306 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3307 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3309 // 8 nodes, but we only care about the last 4.
3310 for (unsigned i = 7; i >= 4; --i) {
3311 int Val = SVOp->getMaskElt(i);
3320 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3321 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3322 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3323 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3325 // 8 nodes, but we only care about the first 4.
3326 for (int i = 3; i >= 0; --i) {
3327 int Val = SVOp->getMaskElt(i);
3336 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3337 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3338 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3339 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3340 EVT VVT = N->getValueType(0);
3341 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3345 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3346 Val = SVOp->getMaskElt(i);
3350 return (Val - i) * EltSize;
3353 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3355 bool X86::isZeroNode(SDValue Elt) {
3356 return ((isa<ConstantSDNode>(Elt) &&
3357 cast<ConstantSDNode>(Elt)->isNullValue()) ||
3358 (isa<ConstantFPSDNode>(Elt) &&
3359 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3362 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3363 /// their permute mask.
3364 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3365 SelectionDAG &DAG) {
3366 EVT VT = SVOp->getValueType(0);
3367 unsigned NumElems = VT.getVectorNumElements();
3368 SmallVector<int, 8> MaskVec;
3370 for (unsigned i = 0; i != NumElems; ++i) {
3371 int idx = SVOp->getMaskElt(i);
3373 MaskVec.push_back(idx);
3374 else if (idx < (int)NumElems)
3375 MaskVec.push_back(idx + NumElems);
3377 MaskVec.push_back(idx - NumElems);
3379 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3380 SVOp->getOperand(0), &MaskVec[0]);
3383 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3384 /// the two vector operands have swapped position.
3385 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3386 unsigned NumElems = VT.getVectorNumElements();
3387 for (unsigned i = 0; i != NumElems; ++i) {
3391 else if (idx < (int)NumElems)
3392 Mask[i] = idx + NumElems;
3394 Mask[i] = idx - NumElems;
3398 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3399 /// match movhlps. The lower half elements should come from upper half of
3400 /// V1 (and in order), and the upper half elements should come from the upper
3401 /// half of V2 (and in order).
3402 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3403 if (Op->getValueType(0).getVectorNumElements() != 4)
3405 for (unsigned i = 0, e = 2; i != e; ++i)
3406 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3408 for (unsigned i = 2; i != 4; ++i)
3409 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3414 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3415 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3417 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3418 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3420 N = N->getOperand(0).getNode();
3421 if (!ISD::isNON_EXTLoad(N))
3424 *LD = cast<LoadSDNode>(N);
3428 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3429 /// match movlp{s|d}. The lower half elements should come from lower half of
3430 /// V1 (and in order), and the upper half elements should come from the upper
3431 /// half of V2 (and in order). And since V1 will become the source of the
3432 /// MOVLP, it must be either a vector load or a scalar load to vector.
3433 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3434 ShuffleVectorSDNode *Op) {
3435 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3437 // Is V2 is a vector load, don't do this transformation. We will try to use
3438 // load folding shufps op.
3439 if (ISD::isNON_EXTLoad(V2))
3442 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3444 if (NumElems != 2 && NumElems != 4)
3446 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3447 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3449 for (unsigned i = NumElems/2; i != NumElems; ++i)
3450 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3455 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3457 static bool isSplatVector(SDNode *N) {
3458 if (N->getOpcode() != ISD::BUILD_VECTOR)
3461 SDValue SplatValue = N->getOperand(0);
3462 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3463 if (N->getOperand(i) != SplatValue)
3468 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3469 /// to an zero vector.
3470 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3471 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3472 SDValue V1 = N->getOperand(0);
3473 SDValue V2 = N->getOperand(1);
3474 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3475 for (unsigned i = 0; i != NumElems; ++i) {
3476 int Idx = N->getMaskElt(i);
3477 if (Idx >= (int)NumElems) {
3478 unsigned Opc = V2.getOpcode();
3479 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3481 if (Opc != ISD::BUILD_VECTOR ||
3482 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3484 } else if (Idx >= 0) {
3485 unsigned Opc = V1.getOpcode();
3486 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3488 if (Opc != ISD::BUILD_VECTOR ||
3489 !X86::isZeroNode(V1.getOperand(Idx)))
3496 /// getZeroVector - Returns a vector of specified type with all zero elements.
3498 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3500 assert(VT.isVector() && "Expected a vector type");
3502 // Always build SSE zero vectors as <4 x i32> bitcasted
3503 // to their dest type. This ensures they get CSE'd.
3505 if (VT.getSizeInBits() == 128) { // SSE
3506 if (HasSSE2) { // SSE2
3507 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3508 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3510 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3511 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3513 } else if (VT.getSizeInBits() == 256) { // AVX
3514 // 256-bit logic and arithmetic instructions in AVX are
3515 // all floating-point, no support for integer ops. Default
3516 // to emitting fp zeroed vectors then.
3517 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3518 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3519 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3521 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3524 /// getOnesVector - Returns a vector of specified type with all bits set.
3526 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3527 assert(VT.isVector() && "Expected a vector type");
3529 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3530 // type. This ensures they get CSE'd.
3531 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3533 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3534 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3538 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3539 /// that point to V2 points to its first element.
3540 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3541 EVT VT = SVOp->getValueType(0);
3542 unsigned NumElems = VT.getVectorNumElements();
3544 bool Changed = false;
3545 SmallVector<int, 8> MaskVec;
3546 SVOp->getMask(MaskVec);
3548 for (unsigned i = 0; i != NumElems; ++i) {
3549 if (MaskVec[i] > (int)NumElems) {
3550 MaskVec[i] = NumElems;
3555 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3556 SVOp->getOperand(1), &MaskVec[0]);
3557 return SDValue(SVOp, 0);
3560 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3561 /// operation of specified width.
3562 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3564 unsigned NumElems = VT.getVectorNumElements();
3565 SmallVector<int, 8> Mask;
3566 Mask.push_back(NumElems);
3567 for (unsigned i = 1; i != NumElems; ++i)
3569 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3572 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3573 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3575 unsigned NumElems = VT.getVectorNumElements();
3576 SmallVector<int, 8> Mask;
3577 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3579 Mask.push_back(i + NumElems);
3581 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3584 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3585 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3587 unsigned NumElems = VT.getVectorNumElements();
3588 unsigned Half = NumElems/2;
3589 SmallVector<int, 8> Mask;
3590 for (unsigned i = 0; i != Half; ++i) {
3591 Mask.push_back(i + Half);
3592 Mask.push_back(i + NumElems + Half);
3594 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3597 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3598 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3599 EVT PVT = MVT::v4f32;
3600 EVT VT = SV->getValueType(0);
3601 DebugLoc dl = SV->getDebugLoc();
3602 SDValue V1 = SV->getOperand(0);
3603 int NumElems = VT.getVectorNumElements();
3604 int EltNo = SV->getSplatIndex();
3606 // unpack elements to the correct location
3607 while (NumElems > 4) {
3608 if (EltNo < NumElems/2) {
3609 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3611 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3612 EltNo -= NumElems/2;
3617 // Perform the splat.
3618 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3619 V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3620 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3621 return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3624 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3625 /// vector of zero or undef vector. This produces a shuffle where the low
3626 /// element of V2 is swizzled into the zero/undef vector, landing at element
3627 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3628 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3629 bool isZero, bool HasSSE2,
3630 SelectionDAG &DAG) {
3631 EVT VT = V2.getValueType();
3633 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3634 unsigned NumElems = VT.getVectorNumElements();
3635 SmallVector<int, 16> MaskVec;
3636 for (unsigned i = 0; i != NumElems; ++i)
3637 // If this is the insertion idx, put the low elt of V2 here.
3638 MaskVec.push_back(i == Idx ? NumElems : i);
3639 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3642 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3643 /// element of the result of the vector shuffle.
3644 SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3647 return SDValue(); // Limit search depth.
3649 SDValue V = SDValue(N, 0);
3650 EVT VT = V.getValueType();
3651 unsigned Opcode = V.getOpcode();
3653 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3654 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3655 Index = SV->getMaskElt(Index);
3658 return DAG.getUNDEF(VT.getVectorElementType());
3660 int NumElems = VT.getVectorNumElements();
3661 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3662 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3665 // Recurse into target specific vector shuffles to find scalars.
3666 if (isTargetShuffle(Opcode)) {
3667 int NumElems = VT.getVectorNumElements();
3668 SmallVector<unsigned, 16> ShuffleMask;
3672 case X86ISD::SHUFPS:
3673 case X86ISD::SHUFPD:
3674 ImmN = N->getOperand(N->getNumOperands()-1);
3675 DecodeSHUFPSMask(NumElems,
3676 cast<ConstantSDNode>(ImmN)->getZExtValue(),
3679 case X86ISD::PUNPCKHBW:
3680 case X86ISD::PUNPCKHWD:
3681 case X86ISD::PUNPCKHDQ:
3682 case X86ISD::PUNPCKHQDQ:
3683 DecodePUNPCKHMask(NumElems, ShuffleMask);
3685 case X86ISD::UNPCKHPS:
3686 case X86ISD::UNPCKHPD:
3687 DecodeUNPCKHPMask(NumElems, ShuffleMask);
3689 case X86ISD::PUNPCKLBW:
3690 case X86ISD::PUNPCKLWD:
3691 case X86ISD::PUNPCKLDQ:
3692 case X86ISD::PUNPCKLQDQ:
3693 DecodePUNPCKLMask(NumElems, ShuffleMask);
3695 case X86ISD::UNPCKLPS:
3696 case X86ISD::UNPCKLPD:
3697 DecodeUNPCKLPMask(NumElems, ShuffleMask);
3699 case X86ISD::MOVHLPS:
3700 DecodeMOVHLPSMask(NumElems, ShuffleMask);
3702 case X86ISD::MOVLHPS:
3703 DecodeMOVLHPSMask(NumElems, ShuffleMask);
3705 case X86ISD::PSHUFD:
3706 ImmN = N->getOperand(N->getNumOperands()-1);
3707 DecodePSHUFMask(NumElems,
3708 cast<ConstantSDNode>(ImmN)->getZExtValue(),
3711 case X86ISD::PSHUFHW:
3712 ImmN = N->getOperand(N->getNumOperands()-1);
3713 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3716 case X86ISD::PSHUFLW:
3717 ImmN = N->getOperand(N->getNumOperands()-1);
3718 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3722 case X86ISD::MOVSD: {
3723 // The index 0 always comes from the first element of the second source,
3724 // this is why MOVSS and MOVSD are used in the first place. The other
3725 // elements come from the other positions of the first source vector.
3726 unsigned OpNum = (Index == 0) ? 1 : 0;
3727 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
3731 assert("not implemented for target shuffle node");
3735 Index = ShuffleMask[Index];
3737 return DAG.getUNDEF(VT.getVectorElementType());
3739 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
3740 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
3744 // Actual nodes that may contain scalar elements
3745 if (Opcode == ISD::BITCAST) {
3746 V = V.getOperand(0);
3747 EVT SrcVT = V.getValueType();
3748 unsigned NumElems = VT.getVectorNumElements();
3750 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
3754 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
3755 return (Index == 0) ? V.getOperand(0)
3756 : DAG.getUNDEF(VT.getVectorElementType());
3758 if (V.getOpcode() == ISD::BUILD_VECTOR)
3759 return V.getOperand(Index);
3764 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
3765 /// shuffle operation which come from a consecutively from a zero. The
3766 /// search can start in two diferent directions, from left or right.
3768 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
3769 bool ZerosFromLeft, SelectionDAG &DAG) {
3772 while (i < NumElems) {
3773 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
3774 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
3775 if (!(Elt.getNode() &&
3776 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
3784 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
3785 /// MaskE correspond consecutively to elements from one of the vector operands,
3786 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
3788 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
3789 int OpIdx, int NumElems, unsigned &OpNum) {
3790 bool SeenV1 = false;
3791 bool SeenV2 = false;
3793 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
3794 int Idx = SVOp->getMaskElt(i);
3795 // Ignore undef indicies
3804 // Only accept consecutive elements from the same vector
3805 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
3809 OpNum = SeenV1 ? 0 : 1;
3813 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
3814 /// logical left shift of a vector.
3815 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3816 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3817 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3818 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3819 false /* check zeros from right */, DAG);
3825 // Considering the elements in the mask that are not consecutive zeros,
3826 // check if they consecutively come from only one of the source vectors.
3828 // V1 = {X, A, B, C} 0
3830 // vector_shuffle V1, V2 <1, 2, 3, X>
3832 if (!isShuffleMaskConsecutive(SVOp,
3833 0, // Mask Start Index
3834 NumElems-NumZeros-1, // Mask End Index
3835 NumZeros, // Where to start looking in the src vector
3836 NumElems, // Number of elements in vector
3837 OpSrc)) // Which source operand ?
3842 ShVal = SVOp->getOperand(OpSrc);
3846 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
3847 /// logical left shift of a vector.
3848 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3849 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3850 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3851 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3852 true /* check zeros from left */, DAG);
3858 // Considering the elements in the mask that are not consecutive zeros,
3859 // check if they consecutively come from only one of the source vectors.
3861 // 0 { A, B, X, X } = V2
3863 // vector_shuffle V1, V2 <X, X, 4, 5>
3865 if (!isShuffleMaskConsecutive(SVOp,
3866 NumZeros, // Mask Start Index
3867 NumElems-1, // Mask End Index
3868 0, // Where to start looking in the src vector
3869 NumElems, // Number of elements in vector
3870 OpSrc)) // Which source operand ?
3875 ShVal = SVOp->getOperand(OpSrc);
3879 /// isVectorShift - Returns true if the shuffle can be implemented as a
3880 /// logical left or right shift of a vector.
3881 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3882 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3883 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
3884 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
3890 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3892 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3893 unsigned NumNonZero, unsigned NumZero,
3895 const TargetLowering &TLI) {
3899 DebugLoc dl = Op.getDebugLoc();
3902 for (unsigned i = 0; i < 16; ++i) {
3903 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3904 if (ThisIsNonZero && First) {
3906 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3908 V = DAG.getUNDEF(MVT::v8i16);
3913 SDValue ThisElt(0, 0), LastElt(0, 0);
3914 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3915 if (LastIsNonZero) {
3916 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3917 MVT::i16, Op.getOperand(i-1));
3919 if (ThisIsNonZero) {
3920 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3921 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3922 ThisElt, DAG.getConstant(8, MVT::i8));
3924 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3928 if (ThisElt.getNode())
3929 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3930 DAG.getIntPtrConstant(i/2));
3934 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
3937 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3939 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3940 unsigned NumNonZero, unsigned NumZero,
3942 const TargetLowering &TLI) {
3946 DebugLoc dl = Op.getDebugLoc();
3949 for (unsigned i = 0; i < 8; ++i) {
3950 bool isNonZero = (NonZeros & (1 << i)) != 0;
3954 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3956 V = DAG.getUNDEF(MVT::v8i16);
3959 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3960 MVT::v8i16, V, Op.getOperand(i),
3961 DAG.getIntPtrConstant(i));
3968 /// getVShift - Return a vector logical shift node.
3970 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3971 unsigned NumBits, SelectionDAG &DAG,
3972 const TargetLowering &TLI, DebugLoc dl) {
3973 EVT ShVT = MVT::v2i64;
3974 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3975 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
3976 return DAG.getNode(ISD::BITCAST, dl, VT,
3977 DAG.getNode(Opc, dl, ShVT, SrcOp,
3978 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3982 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3983 SelectionDAG &DAG) const {
3985 // Check if the scalar load can be widened into a vector load. And if
3986 // the address is "base + cst" see if the cst can be "absorbed" into
3987 // the shuffle mask.
3988 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3989 SDValue Ptr = LD->getBasePtr();
3990 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3992 EVT PVT = LD->getValueType(0);
3993 if (PVT != MVT::i32 && PVT != MVT::f32)
3998 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3999 FI = FINode->getIndex();
4001 } else if (Ptr.getOpcode() == ISD::ADD &&
4002 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
4003 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4004 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4005 Offset = Ptr.getConstantOperandVal(1);
4006 Ptr = Ptr.getOperand(0);
4011 SDValue Chain = LD->getChain();
4012 // Make sure the stack object alignment is at least 16.
4013 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4014 if (DAG.InferPtrAlignment(Ptr) < 16) {
4015 if (MFI->isFixedObjectIndex(FI)) {
4016 // Can't change the alignment. FIXME: It's possible to compute
4017 // the exact stack offset and reference FI + adjust offset instead.
4018 // If someone *really* cares about this. That's the way to implement it.
4021 MFI->setObjectAlignment(FI, 16);
4025 // (Offset % 16) must be multiple of 4. Then address is then
4026 // Ptr + (Offset & ~15).
4029 if ((Offset % 16) & 3)
4031 int64_t StartOffset = Offset & ~15;
4033 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4034 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4036 int EltNo = (Offset - StartOffset) >> 2;
4037 int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4038 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4039 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4040 LD->getPointerInfo().getWithOffset(StartOffset),
4042 // Canonicalize it to a v4i32 shuffle.
4043 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4044 return DAG.getNode(ISD::BITCAST, dl, VT,
4045 DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4046 DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4052 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4053 /// vector of type 'VT', see if the elements can be replaced by a single large
4054 /// load which has the same value as a build_vector whose operands are 'elts'.
4056 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4058 /// FIXME: we'd also like to handle the case where the last elements are zero
4059 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4060 /// There's even a handy isZeroNode for that purpose.
4061 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4062 DebugLoc &DL, SelectionDAG &DAG) {
4063 EVT EltVT = VT.getVectorElementType();
4064 unsigned NumElems = Elts.size();
4066 LoadSDNode *LDBase = NULL;
4067 unsigned LastLoadedElt = -1U;
4069 // For each element in the initializer, see if we've found a load or an undef.
4070 // If we don't find an initial load element, or later load elements are
4071 // non-consecutive, bail out.
4072 for (unsigned i = 0; i < NumElems; ++i) {
4073 SDValue Elt = Elts[i];
4075 if (!Elt.getNode() ||
4076 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4079 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4081 LDBase = cast<LoadSDNode>(Elt.getNode());
4085 if (Elt.getOpcode() == ISD::UNDEF)
4088 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4089 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4094 // If we have found an entire vector of loads and undefs, then return a large
4095 // load of the entire vector width starting at the base pointer. If we found
4096 // consecutive loads for the low half, generate a vzext_load node.
4097 if (LastLoadedElt == NumElems - 1) {
4098 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4099 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4100 LDBase->getPointerInfo(),
4101 LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4102 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4103 LDBase->getPointerInfo(),
4104 LDBase->isVolatile(), LDBase->isNonTemporal(),
4105 LDBase->getAlignment());
4106 } else if (NumElems == 4 && LastLoadedElt == 1) {
4107 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4108 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4109 SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4111 LDBase->getMemOperand());
4112 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4118 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4119 DebugLoc dl = Op.getDebugLoc();
4120 // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4121 // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4122 // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4123 // is present, so AllOnes is ignored.
4124 if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4125 (Op.getValueType().getSizeInBits() != 256 &&
4126 ISD::isBuildVectorAllOnes(Op.getNode()))) {
4127 // Canonicalize this to <4 x i32> (SSE) to
4128 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4129 // eliminated on x86-32 hosts.
4130 if (Op.getValueType() == MVT::v4i32)
4133 if (ISD::isBuildVectorAllOnes(Op.getNode()))
4134 return getOnesVector(Op.getValueType(), DAG, dl);
4135 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4138 EVT VT = Op.getValueType();
4139 EVT ExtVT = VT.getVectorElementType();
4140 unsigned EVTBits = ExtVT.getSizeInBits();
4142 unsigned NumElems = Op.getNumOperands();
4143 unsigned NumZero = 0;
4144 unsigned NumNonZero = 0;
4145 unsigned NonZeros = 0;
4146 bool IsAllConstants = true;
4147 SmallSet<SDValue, 8> Values;
4148 for (unsigned i = 0; i < NumElems; ++i) {
4149 SDValue Elt = Op.getOperand(i);
4150 if (Elt.getOpcode() == ISD::UNDEF)
4153 if (Elt.getOpcode() != ISD::Constant &&
4154 Elt.getOpcode() != ISD::ConstantFP)
4155 IsAllConstants = false;
4156 if (X86::isZeroNode(Elt))
4159 NonZeros |= (1 << i);
4164 // All undef vector. Return an UNDEF. All zero vectors were handled above.
4165 if (NumNonZero == 0)
4166 return DAG.getUNDEF(VT);
4168 // Special case for single non-zero, non-undef, element.
4169 if (NumNonZero == 1) {
4170 unsigned Idx = CountTrailingZeros_32(NonZeros);
4171 SDValue Item = Op.getOperand(Idx);
4173 // If this is an insertion of an i64 value on x86-32, and if the top bits of
4174 // the value are obviously zero, truncate the value to i32 and do the
4175 // insertion that way. Only do this if the value is non-constant or if the
4176 // value is a constant being inserted into element 0. It is cheaper to do
4177 // a constant pool load than it is to do a movd + shuffle.
4178 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4179 (!IsAllConstants || Idx == 0)) {
4180 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4182 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4183 EVT VecVT = MVT::v4i32;
4184 unsigned VecElts = 4;
4186 // Truncate the value (which may itself be a constant) to i32, and
4187 // convert it to a vector with movd (S2V+shuffle to zero extend).
4188 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4189 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4190 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4191 Subtarget->hasSSE2(), DAG);
4193 // Now we have our 32-bit value zero extended in the low element of
4194 // a vector. If Idx != 0, swizzle it into place.
4196 SmallVector<int, 4> Mask;
4197 Mask.push_back(Idx);
4198 for (unsigned i = 1; i != VecElts; ++i)
4200 Item = DAG.getVectorShuffle(VecVT, dl, Item,
4201 DAG.getUNDEF(Item.getValueType()),
4204 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4208 // If we have a constant or non-constant insertion into the low element of
4209 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4210 // the rest of the elements. This will be matched as movd/movq/movss/movsd
4211 // depending on what the source datatype is.
4214 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4215 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4216 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4217 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4218 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4219 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4221 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4222 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4223 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4224 EVT MiddleVT = MVT::v4i32;
4225 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4226 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4227 Subtarget->hasSSE2(), DAG);
4228 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4232 // Is it a vector logical left shift?
4233 if (NumElems == 2 && Idx == 1 &&
4234 X86::isZeroNode(Op.getOperand(0)) &&
4235 !X86::isZeroNode(Op.getOperand(1))) {
4236 unsigned NumBits = VT.getSizeInBits();
4237 return getVShift(true, VT,
4238 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4239 VT, Op.getOperand(1)),
4240 NumBits/2, DAG, *this, dl);
4243 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4246 // Otherwise, if this is a vector with i32 or f32 elements, and the element
4247 // is a non-constant being inserted into an element other than the low one,
4248 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
4249 // movd/movss) to move this into the low element, then shuffle it into
4251 if (EVTBits == 32) {
4252 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4254 // Turn it into a shuffle of zero and zero-extended scalar to vector.
4255 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4256 Subtarget->hasSSE2(), DAG);
4257 SmallVector<int, 8> MaskVec;
4258 for (unsigned i = 0; i < NumElems; i++)
4259 MaskVec.push_back(i == Idx ? 0 : 1);
4260 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4264 // Splat is obviously ok. Let legalizer expand it to a shuffle.
4265 if (Values.size() == 1) {
4266 if (EVTBits == 32) {
4267 // Instead of a shuffle like this:
4268 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4269 // Check if it's possible to issue this instead.
4270 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4271 unsigned Idx = CountTrailingZeros_32(NonZeros);
4272 SDValue Item = Op.getOperand(Idx);
4273 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4274 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4279 // A vector full of immediates; various special cases are already
4280 // handled, so this is best done with a single constant-pool load.
4284 // Let legalizer expand 2-wide build_vectors.
4285 if (EVTBits == 64) {
4286 if (NumNonZero == 1) {
4287 // One half is zero or undef.
4288 unsigned Idx = CountTrailingZeros_32(NonZeros);
4289 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4290 Op.getOperand(Idx));
4291 return getShuffleVectorZeroOrUndef(V2, Idx, true,
4292 Subtarget->hasSSE2(), DAG);
4297 // If element VT is < 32 bits, convert it to inserts into a zero vector.
4298 if (EVTBits == 8 && NumElems == 16) {
4299 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4301 if (V.getNode()) return V;
4304 if (EVTBits == 16 && NumElems == 8) {
4305 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4307 if (V.getNode()) return V;
4310 // If element VT is == 32 bits, turn it into a number of shuffles.
4311 SmallVector<SDValue, 8> V;
4313 if (NumElems == 4 && NumZero > 0) {
4314 for (unsigned i = 0; i < 4; ++i) {
4315 bool isZero = !(NonZeros & (1 << i));
4317 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4319 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4322 for (unsigned i = 0; i < 2; ++i) {
4323 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4326 V[i] = V[i*2]; // Must be a zero vector.
4329 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4332 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4335 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4340 SmallVector<int, 8> MaskVec;
4341 bool Reverse = (NonZeros & 0x3) == 2;
4342 for (unsigned i = 0; i < 2; ++i)
4343 MaskVec.push_back(Reverse ? 1-i : i);
4344 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4345 for (unsigned i = 0; i < 2; ++i)
4346 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4347 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4350 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4351 // Check for a build vector of consecutive loads.
4352 for (unsigned i = 0; i < NumElems; ++i)
4353 V[i] = Op.getOperand(i);
4355 // Check for elements which are consecutive loads.
4356 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4360 // For SSE 4.1, use insertps to put the high elements into the low element.
4361 if (getSubtarget()->hasSSE41()) {
4363 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4364 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4366 Result = DAG.getUNDEF(VT);
4368 for (unsigned i = 1; i < NumElems; ++i) {
4369 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4370 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4371 Op.getOperand(i), DAG.getIntPtrConstant(i));
4376 // Otherwise, expand into a number of unpckl*, start by extending each of
4377 // our (non-undef) elements to the full vector width with the element in the
4378 // bottom slot of the vector (which generates no code for SSE).
4379 for (unsigned i = 0; i < NumElems; ++i) {
4380 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4381 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4383 V[i] = DAG.getUNDEF(VT);
4386 // Next, we iteratively mix elements, e.g. for v4f32:
4387 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4388 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4389 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
4390 unsigned EltStride = NumElems >> 1;
4391 while (EltStride != 0) {
4392 for (unsigned i = 0; i < EltStride; ++i) {
4393 // If V[i+EltStride] is undef and this is the first round of mixing,
4394 // then it is safe to just drop this shuffle: V[i] is already in the
4395 // right place, the one element (since it's the first round) being
4396 // inserted as undef can be dropped. This isn't safe for successive
4397 // rounds because they will permute elements within both vectors.
4398 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4399 EltStride == NumElems/2)
4402 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4412 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4413 // We support concatenate two MMX registers and place them in a MMX
4414 // register. This is better than doing a stack convert.
4415 DebugLoc dl = Op.getDebugLoc();
4416 EVT ResVT = Op.getValueType();
4417 assert(Op.getNumOperands() == 2);
4418 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4419 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4421 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4422 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4423 InVec = Op.getOperand(1);
4424 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4425 unsigned NumElts = ResVT.getVectorNumElements();
4426 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4427 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4428 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4430 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4431 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4432 Mask[0] = 0; Mask[1] = 2;
4433 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4435 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4438 // v8i16 shuffles - Prefer shuffles in the following order:
4439 // 1. [all] pshuflw, pshufhw, optional move
4440 // 2. [ssse3] 1 x pshufb
4441 // 3. [ssse3] 2 x pshufb + 1 x por
4442 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4444 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4445 SelectionDAG &DAG) const {
4446 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4447 SDValue V1 = SVOp->getOperand(0);
4448 SDValue V2 = SVOp->getOperand(1);
4449 DebugLoc dl = SVOp->getDebugLoc();
4450 SmallVector<int, 8> MaskVals;
4452 // Determine if more than 1 of the words in each of the low and high quadwords
4453 // of the result come from the same quadword of one of the two inputs. Undef
4454 // mask values count as coming from any quadword, for better codegen.
4455 SmallVector<unsigned, 4> LoQuad(4);
4456 SmallVector<unsigned, 4> HiQuad(4);
4457 BitVector InputQuads(4);
4458 for (unsigned i = 0; i < 8; ++i) {
4459 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4460 int EltIdx = SVOp->getMaskElt(i);
4461 MaskVals.push_back(EltIdx);
4470 InputQuads.set(EltIdx / 4);
4473 int BestLoQuad = -1;
4474 unsigned MaxQuad = 1;
4475 for (unsigned i = 0; i < 4; ++i) {
4476 if (LoQuad[i] > MaxQuad) {
4478 MaxQuad = LoQuad[i];
4482 int BestHiQuad = -1;
4484 for (unsigned i = 0; i < 4; ++i) {
4485 if (HiQuad[i] > MaxQuad) {
4487 MaxQuad = HiQuad[i];
4491 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4492 // of the two input vectors, shuffle them into one input vector so only a
4493 // single pshufb instruction is necessary. If There are more than 2 input
4494 // quads, disable the next transformation since it does not help SSSE3.
4495 bool V1Used = InputQuads[0] || InputQuads[1];
4496 bool V2Used = InputQuads[2] || InputQuads[3];
4497 if (Subtarget->hasSSSE3()) {
4498 if (InputQuads.count() == 2 && V1Used && V2Used) {
4499 BestLoQuad = InputQuads.find_first();
4500 BestHiQuad = InputQuads.find_next(BestLoQuad);
4502 if (InputQuads.count() > 2) {
4508 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4509 // the shuffle mask. If a quad is scored as -1, that means that it contains
4510 // words from all 4 input quadwords.
4512 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4513 SmallVector<int, 8> MaskV;
4514 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4515 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4516 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4517 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4518 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4519 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4521 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4522 // source words for the shuffle, to aid later transformations.
4523 bool AllWordsInNewV = true;
4524 bool InOrder[2] = { true, true };
4525 for (unsigned i = 0; i != 8; ++i) {
4526 int idx = MaskVals[i];
4528 InOrder[i/4] = false;
4529 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4531 AllWordsInNewV = false;
4535 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4536 if (AllWordsInNewV) {
4537 for (int i = 0; i != 8; ++i) {
4538 int idx = MaskVals[i];
4541 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4542 if ((idx != i) && idx < 4)
4544 if ((idx != i) && idx > 3)
4553 // If we've eliminated the use of V2, and the new mask is a pshuflw or
4554 // pshufhw, that's as cheap as it gets. Return the new shuffle.
4555 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4556 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4557 unsigned TargetMask = 0;
4558 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4559 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4560 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4561 X86::getShufflePSHUFLWImmediate(NewV.getNode());
4562 V1 = NewV.getOperand(0);
4563 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4567 // If we have SSSE3, and all words of the result are from 1 input vector,
4568 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
4569 // is present, fall back to case 4.
4570 if (Subtarget->hasSSSE3()) {
4571 SmallVector<SDValue,16> pshufbMask;
4573 // If we have elements from both input vectors, set the high bit of the
4574 // shuffle mask element to zero out elements that come from V2 in the V1
4575 // mask, and elements that come from V1 in the V2 mask, so that the two
4576 // results can be OR'd together.
4577 bool TwoInputs = V1Used && V2Used;
4578 for (unsigned i = 0; i != 8; ++i) {
4579 int EltIdx = MaskVals[i] * 2;
4580 if (TwoInputs && (EltIdx >= 16)) {
4581 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4582 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4585 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4586 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4588 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4589 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4590 DAG.getNode(ISD::BUILD_VECTOR, dl,
4591 MVT::v16i8, &pshufbMask[0], 16));
4593 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4595 // Calculate the shuffle mask for the second input, shuffle it, and
4596 // OR it with the first shuffled input.
4598 for (unsigned i = 0; i != 8; ++i) {
4599 int EltIdx = MaskVals[i] * 2;
4601 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4602 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4605 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4606 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4608 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4609 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4610 DAG.getNode(ISD::BUILD_VECTOR, dl,
4611 MVT::v16i8, &pshufbMask[0], 16));
4612 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4613 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4616 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4617 // and update MaskVals with new element order.
4618 BitVector InOrder(8);
4619 if (BestLoQuad >= 0) {
4620 SmallVector<int, 8> MaskV;
4621 for (int i = 0; i != 4; ++i) {
4622 int idx = MaskVals[i];
4624 MaskV.push_back(-1);
4626 } else if ((idx / 4) == BestLoQuad) {
4627 MaskV.push_back(idx & 3);
4630 MaskV.push_back(-1);
4633 for (unsigned i = 4; i != 8; ++i)
4635 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4638 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4639 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4641 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4645 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4646 // and update MaskVals with the new element order.
4647 if (BestHiQuad >= 0) {
4648 SmallVector<int, 8> MaskV;
4649 for (unsigned i = 0; i != 4; ++i)
4651 for (unsigned i = 4; i != 8; ++i) {
4652 int idx = MaskVals[i];
4654 MaskV.push_back(-1);
4656 } else if ((idx / 4) == BestHiQuad) {
4657 MaskV.push_back((idx & 3) + 4);
4660 MaskV.push_back(-1);
4663 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4666 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4667 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
4669 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
4673 // In case BestHi & BestLo were both -1, which means each quadword has a word
4674 // from each of the four input quadwords, calculate the InOrder bitvector now
4675 // before falling through to the insert/extract cleanup.
4676 if (BestLoQuad == -1 && BestHiQuad == -1) {
4678 for (int i = 0; i != 8; ++i)
4679 if (MaskVals[i] < 0 || MaskVals[i] == i)
4683 // The other elements are put in the right place using pextrw and pinsrw.
4684 for (unsigned i = 0; i != 8; ++i) {
4687 int EltIdx = MaskVals[i];
4690 SDValue ExtOp = (EltIdx < 8)
4691 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4692 DAG.getIntPtrConstant(EltIdx))
4693 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4694 DAG.getIntPtrConstant(EltIdx - 8));
4695 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4696 DAG.getIntPtrConstant(i));
4701 // v16i8 shuffles - Prefer shuffles in the following order:
4702 // 1. [ssse3] 1 x pshufb
4703 // 2. [ssse3] 2 x pshufb + 1 x por
4704 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
4706 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4708 const X86TargetLowering &TLI) {
4709 SDValue V1 = SVOp->getOperand(0);
4710 SDValue V2 = SVOp->getOperand(1);
4711 DebugLoc dl = SVOp->getDebugLoc();
4712 SmallVector<int, 16> MaskVals;
4713 SVOp->getMask(MaskVals);
4715 // If we have SSSE3, case 1 is generated when all result bytes come from
4716 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
4717 // present, fall back to case 3.
4718 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4721 for (unsigned i = 0; i < 16; ++i) {
4722 int EltIdx = MaskVals[i];
4731 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4732 if (TLI.getSubtarget()->hasSSSE3()) {
4733 SmallVector<SDValue,16> pshufbMask;
4735 // If all result elements are from one input vector, then only translate
4736 // undef mask values to 0x80 (zero out result) in the pshufb mask.
4738 // Otherwise, we have elements from both input vectors, and must zero out
4739 // elements that come from V2 in the first mask, and V1 in the second mask
4740 // so that we can OR them together.
4741 bool TwoInputs = !(V1Only || V2Only);
4742 for (unsigned i = 0; i != 16; ++i) {
4743 int EltIdx = MaskVals[i];
4744 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4745 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4748 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4750 // If all the elements are from V2, assign it to V1 and return after
4751 // building the first pshufb.
4754 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4755 DAG.getNode(ISD::BUILD_VECTOR, dl,
4756 MVT::v16i8, &pshufbMask[0], 16));
4760 // Calculate the shuffle mask for the second input, shuffle it, and
4761 // OR it with the first shuffled input.
4763 for (unsigned i = 0; i != 16; ++i) {
4764 int EltIdx = MaskVals[i];
4766 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4769 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4771 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4772 DAG.getNode(ISD::BUILD_VECTOR, dl,
4773 MVT::v16i8, &pshufbMask[0], 16));
4774 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4777 // No SSSE3 - Calculate in place words and then fix all out of place words
4778 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
4779 // the 16 different words that comprise the two doublequadword input vectors.
4780 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4781 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
4782 SDValue NewV = V2Only ? V2 : V1;
4783 for (int i = 0; i != 8; ++i) {
4784 int Elt0 = MaskVals[i*2];
4785 int Elt1 = MaskVals[i*2+1];
4787 // This word of the result is all undef, skip it.
4788 if (Elt0 < 0 && Elt1 < 0)
4791 // This word of the result is already in the correct place, skip it.
4792 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4794 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4797 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4798 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4801 // If Elt0 and Elt1 are defined, are consecutive, and can be load
4802 // using a single extract together, load it and store it.
4803 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4804 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4805 DAG.getIntPtrConstant(Elt1 / 2));
4806 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4807 DAG.getIntPtrConstant(i));
4811 // If Elt1 is defined, extract it from the appropriate source. If the
4812 // source byte is not also odd, shift the extracted word left 8 bits
4813 // otherwise clear the bottom 8 bits if we need to do an or.
4815 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4816 DAG.getIntPtrConstant(Elt1 / 2));
4817 if ((Elt1 & 1) == 0)
4818 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4819 DAG.getConstant(8, TLI.getShiftAmountTy()));
4821 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4822 DAG.getConstant(0xFF00, MVT::i16));
4824 // If Elt0 is defined, extract it from the appropriate source. If the
4825 // source byte is not also even, shift the extracted word right 8 bits. If
4826 // Elt1 was also defined, OR the extracted values together before
4827 // inserting them in the result.
4829 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4830 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4831 if ((Elt0 & 1) != 0)
4832 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4833 DAG.getConstant(8, TLI.getShiftAmountTy()));
4835 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4836 DAG.getConstant(0x00FF, MVT::i16));
4837 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4840 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4841 DAG.getIntPtrConstant(i));
4843 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
4846 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4847 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
4848 /// done when every pair / quad of shuffle mask elements point to elements in
4849 /// the right sequence. e.g.
4850 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
4852 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4853 SelectionDAG &DAG, DebugLoc dl) {
4854 EVT VT = SVOp->getValueType(0);
4855 SDValue V1 = SVOp->getOperand(0);
4856 SDValue V2 = SVOp->getOperand(1);
4857 unsigned NumElems = VT.getVectorNumElements();
4858 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4860 switch (VT.getSimpleVT().SimpleTy) {
4861 default: assert(false && "Unexpected!");
4862 case MVT::v4f32: NewVT = MVT::v2f64; break;
4863 case MVT::v4i32: NewVT = MVT::v2i64; break;
4864 case MVT::v8i16: NewVT = MVT::v4i32; break;
4865 case MVT::v16i8: NewVT = MVT::v4i32; break;
4868 int Scale = NumElems / NewWidth;
4869 SmallVector<int, 8> MaskVec;
4870 for (unsigned i = 0; i < NumElems; i += Scale) {
4872 for (int j = 0; j < Scale; ++j) {
4873 int EltIdx = SVOp->getMaskElt(i+j);
4877 StartIdx = EltIdx - (EltIdx % Scale);
4878 if (EltIdx != StartIdx + j)
4882 MaskVec.push_back(-1);
4884 MaskVec.push_back(StartIdx / Scale);
4887 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
4888 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
4889 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4892 /// getVZextMovL - Return a zero-extending vector move low node.
4894 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4895 SDValue SrcOp, SelectionDAG &DAG,
4896 const X86Subtarget *Subtarget, DebugLoc dl) {
4897 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4898 LoadSDNode *LD = NULL;
4899 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4900 LD = dyn_cast<LoadSDNode>(SrcOp);
4902 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4904 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4905 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
4906 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4907 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
4908 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4910 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4911 return DAG.getNode(ISD::BITCAST, dl, VT,
4912 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4913 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4921 return DAG.getNode(ISD::BITCAST, dl, VT,
4922 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4923 DAG.getNode(ISD::BITCAST, dl,
4927 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4930 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4931 SDValue V1 = SVOp->getOperand(0);
4932 SDValue V2 = SVOp->getOperand(1);
4933 DebugLoc dl = SVOp->getDebugLoc();
4934 EVT VT = SVOp->getValueType(0);
4936 SmallVector<std::pair<int, int>, 8> Locs;
4938 SmallVector<int, 8> Mask1(4U, -1);
4939 SmallVector<int, 8> PermMask;
4940 SVOp->getMask(PermMask);
4944 for (unsigned i = 0; i != 4; ++i) {
4945 int Idx = PermMask[i];
4947 Locs[i] = std::make_pair(-1, -1);
4949 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4951 Locs[i] = std::make_pair(0, NumLo);
4955 Locs[i] = std::make_pair(1, NumHi);
4957 Mask1[2+NumHi] = Idx;
4963 if (NumLo <= 2 && NumHi <= 2) {
4964 // If no more than two elements come from either vector. This can be
4965 // implemented with two shuffles. First shuffle gather the elements.
4966 // The second shuffle, which takes the first shuffle as both of its
4967 // vector operands, put the elements into the right order.
4968 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4970 SmallVector<int, 8> Mask2(4U, -1);
4972 for (unsigned i = 0; i != 4; ++i) {
4973 if (Locs[i].first == -1)
4976 unsigned Idx = (i < 2) ? 0 : 4;
4977 Idx += Locs[i].first * 2 + Locs[i].second;
4982 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4983 } else if (NumLo == 3 || NumHi == 3) {
4984 // Otherwise, we must have three elements from one vector, call it X, and
4985 // one element from the other, call it Y. First, use a shufps to build an
4986 // intermediate vector with the one element from Y and the element from X
4987 // that will be in the same half in the final destination (the indexes don't
4988 // matter). Then, use a shufps to build the final vector, taking the half
4989 // containing the element from Y from the intermediate, and the other half
4992 // Normalize it so the 3 elements come from V1.
4993 CommuteVectorShuffleMask(PermMask, VT);
4997 // Find the element from V2.
4999 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5000 int Val = PermMask[HiIndex];
5007 Mask1[0] = PermMask[HiIndex];
5009 Mask1[2] = PermMask[HiIndex^1];
5011 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5014 Mask1[0] = PermMask[0];
5015 Mask1[1] = PermMask[1];
5016 Mask1[2] = HiIndex & 1 ? 6 : 4;
5017 Mask1[3] = HiIndex & 1 ? 4 : 6;
5018 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5020 Mask1[0] = HiIndex & 1 ? 2 : 0;
5021 Mask1[1] = HiIndex & 1 ? 0 : 2;
5022 Mask1[2] = PermMask[2];
5023 Mask1[3] = PermMask[3];
5028 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5032 // Break it into (shuffle shuffle_hi, shuffle_lo).
5034 SmallVector<int,8> LoMask(4U, -1);
5035 SmallVector<int,8> HiMask(4U, -1);
5037 SmallVector<int,8> *MaskPtr = &LoMask;
5038 unsigned MaskIdx = 0;
5041 for (unsigned i = 0; i != 4; ++i) {
5048 int Idx = PermMask[i];
5050 Locs[i] = std::make_pair(-1, -1);
5051 } else if (Idx < 4) {
5052 Locs[i] = std::make_pair(MaskIdx, LoIdx);
5053 (*MaskPtr)[LoIdx] = Idx;
5056 Locs[i] = std::make_pair(MaskIdx, HiIdx);
5057 (*MaskPtr)[HiIdx] = Idx;
5062 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5063 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5064 SmallVector<int, 8> MaskOps;
5065 for (unsigned i = 0; i != 4; ++i) {
5066 if (Locs[i].first == -1) {
5067 MaskOps.push_back(-1);
5069 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5070 MaskOps.push_back(Idx);
5073 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5076 static bool MayFoldVectorLoad(SDValue V) {
5077 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5078 V = V.getOperand(0);
5079 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5080 V = V.getOperand(0);
5086 // FIXME: the version above should always be used. Since there's
5087 // a bug where several vector shuffles can't be folded because the
5088 // DAG is not updated during lowering and a node claims to have two
5089 // uses while it only has one, use this version, and let isel match
5090 // another instruction if the load really happens to have more than
5091 // one use. Remove this version after this bug get fixed.
5092 // rdar://8434668, PR8156
5093 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5094 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5095 V = V.getOperand(0);
5096 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5097 V = V.getOperand(0);
5098 if (ISD::isNormalLoad(V.getNode()))
5103 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5104 /// a vector extract, and if both can be later optimized into a single load.
5105 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5106 /// here because otherwise a target specific shuffle node is going to be
5107 /// emitted for this shuffle, and the optimization not done.
5108 /// FIXME: This is probably not the best approach, but fix the problem
5109 /// until the right path is decided.
5111 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5112 const TargetLowering &TLI) {
5113 EVT VT = V.getValueType();
5114 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5116 // Be sure that the vector shuffle is present in a pattern like this:
5117 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5121 SDNode *N = *V.getNode()->use_begin();
5122 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5125 SDValue EltNo = N->getOperand(1);
5126 if (!isa<ConstantSDNode>(EltNo))
5129 // If the bit convert changed the number of elements, it is unsafe
5130 // to examine the mask.
5131 bool HasShuffleIntoBitcast = false;
5132 if (V.getOpcode() == ISD::BITCAST) {
5133 EVT SrcVT = V.getOperand(0).getValueType();
5134 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5136 V = V.getOperand(0);
5137 HasShuffleIntoBitcast = true;
5140 // Select the input vector, guarding against out of range extract vector.
5141 unsigned NumElems = VT.getVectorNumElements();
5142 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5143 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5144 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5146 // Skip one more bit_convert if necessary
5147 if (V.getOpcode() == ISD::BITCAST)
5148 V = V.getOperand(0);
5150 if (ISD::isNormalLoad(V.getNode())) {
5151 // Is the original load suitable?
5152 LoadSDNode *LN0 = cast<LoadSDNode>(V);
5154 // FIXME: avoid the multi-use bug that is preventing lots of
5155 // of foldings to be detected, this is still wrong of course, but
5156 // give the temporary desired behavior, and if it happens that
5157 // the load has real more uses, during isel it will not fold, and
5158 // will generate poor code.
5159 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5162 if (!HasShuffleIntoBitcast)
5165 // If there's a bitcast before the shuffle, check if the load type and
5166 // alignment is valid.
5167 unsigned Align = LN0->getAlignment();
5169 TLI.getTargetData()->getABITypeAlignment(
5170 VT.getTypeForEVT(*DAG.getContext()));
5172 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5180 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5181 EVT VT = Op.getValueType();
5183 // Canonizalize to v2f64.
5184 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5185 return DAG.getNode(ISD::BITCAST, dl, VT,
5186 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5191 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5193 SDValue V1 = Op.getOperand(0);
5194 SDValue V2 = Op.getOperand(1);
5195 EVT VT = Op.getValueType();
5197 assert(VT != MVT::v2i64 && "unsupported shuffle type");
5199 if (HasSSE2 && VT == MVT::v2f64)
5200 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5203 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5207 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5208 SDValue V1 = Op.getOperand(0);
5209 SDValue V2 = Op.getOperand(1);
5210 EVT VT = Op.getValueType();
5212 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5213 "unsupported shuffle type");
5215 if (V2.getOpcode() == ISD::UNDEF)
5219 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5223 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5224 SDValue V1 = Op.getOperand(0);
5225 SDValue V2 = Op.getOperand(1);
5226 EVT VT = Op.getValueType();
5227 unsigned NumElems = VT.getVectorNumElements();
5229 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5230 // operand of these instructions is only memory, so check if there's a
5231 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5233 bool CanFoldLoad = false;
5235 // Trivial case, when V2 comes from a load.
5236 if (MayFoldVectorLoad(V2))
5239 // When V1 is a load, it can be folded later into a store in isel, example:
5240 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5242 // (MOVLPSmr addr:$src1, VR128:$src2)
5243 // So, recognize this potential and also use MOVLPS or MOVLPD
5244 if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5248 if (HasSSE2 && NumElems == 2)
5249 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5252 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5255 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5256 // movl and movlp will both match v2i64, but v2i64 is never matched by
5257 // movl earlier because we make it strict to avoid messing with the movlp load
5258 // folding logic (see the code above getMOVLP call). Match it here then,
5259 // this is horrible, but will stay like this until we move all shuffle
5260 // matching to x86 specific nodes. Note that for the 1st condition all
5261 // types are matched with movsd.
5262 if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5263 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5265 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5268 assert(VT != MVT::v4i32 && "unsupported shuffle type");
5270 // Invert the operand order and use SHUFPS to match it.
5271 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5272 X86::getShuffleSHUFImmediate(SVOp), DAG);
5275 static inline unsigned getUNPCKLOpcode(EVT VT) {
5276 switch(VT.getSimpleVT().SimpleTy) {
5277 case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5278 case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5279 case MVT::v4f32: return X86ISD::UNPCKLPS;
5280 case MVT::v2f64: return X86ISD::UNPCKLPD;
5281 case MVT::v16i8: return X86ISD::PUNPCKLBW;
5282 case MVT::v8i16: return X86ISD::PUNPCKLWD;
5284 llvm_unreachable("Unknow type for unpckl");
5289 static inline unsigned getUNPCKHOpcode(EVT VT) {
5290 switch(VT.getSimpleVT().SimpleTy) {
5291 case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5292 case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5293 case MVT::v4f32: return X86ISD::UNPCKHPS;
5294 case MVT::v2f64: return X86ISD::UNPCKHPD;
5295 case MVT::v16i8: return X86ISD::PUNPCKHBW;
5296 case MVT::v8i16: return X86ISD::PUNPCKHWD;
5298 llvm_unreachable("Unknow type for unpckh");
5304 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5305 const TargetLowering &TLI,
5306 const X86Subtarget *Subtarget) {
5307 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5308 EVT VT = Op.getValueType();
5309 DebugLoc dl = Op.getDebugLoc();
5310 SDValue V1 = Op.getOperand(0);
5311 SDValue V2 = Op.getOperand(1);
5313 if (isZeroShuffle(SVOp))
5314 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5316 // Handle splat operations
5317 if (SVOp->isSplat()) {
5318 // Special case, this is the only place now where it's
5319 // allowed to return a vector_shuffle operation without
5320 // using a target specific node, because *hopefully* it
5321 // will be optimized away by the dag combiner.
5322 if (VT.getVectorNumElements() <= 4 &&
5323 CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5326 // Handle splats by matching through known masks
5327 if (VT.getVectorNumElements() <= 4)
5330 // Canonicalize all of the remaining to v4f32.
5331 return PromoteSplat(SVOp, DAG);
5334 // If the shuffle can be profitably rewritten as a narrower shuffle, then
5336 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5337 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5338 if (NewOp.getNode())
5339 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5340 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5341 // FIXME: Figure out a cleaner way to do this.
5342 // Try to make use of movq to zero out the top part.
5343 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5344 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5345 if (NewOp.getNode()) {
5346 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5347 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5348 DAG, Subtarget, dl);
5350 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5351 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5352 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5353 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5354 DAG, Subtarget, dl);
5361 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5362 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5363 SDValue V1 = Op.getOperand(0);
5364 SDValue V2 = Op.getOperand(1);
5365 EVT VT = Op.getValueType();
5366 DebugLoc dl = Op.getDebugLoc();
5367 unsigned NumElems = VT.getVectorNumElements();
5368 bool isMMX = VT.getSizeInBits() == 64;
5369 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5370 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5371 bool V1IsSplat = false;
5372 bool V2IsSplat = false;
5373 bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5374 bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5375 bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5376 MachineFunction &MF = DAG.getMachineFunction();
5377 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5379 // Shuffle operations on MMX not supported.
5383 // Vector shuffle lowering takes 3 steps:
5385 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5386 // narrowing and commutation of operands should be handled.
5387 // 2) Matching of shuffles with known shuffle masks to x86 target specific
5389 // 3) Rewriting of unmatched masks into new generic shuffle operations,
5390 // so the shuffle can be broken into other shuffles and the legalizer can
5391 // try the lowering again.
5393 // The general ideia is that no vector_shuffle operation should be left to
5394 // be matched during isel, all of them must be converted to a target specific
5397 // Normalize the input vectors. Here splats, zeroed vectors, profitable
5398 // narrowing and commutation of operands should be handled. The actual code
5399 // doesn't include all of those, work in progress...
5400 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5401 if (NewOp.getNode())
5404 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5405 // unpckh_undef). Only use pshufd if speed is more important than size.
5406 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5407 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5408 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5409 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5410 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5411 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5413 if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5414 RelaxedMayFoldVectorLoad(V1))
5415 return getMOVDDup(Op, dl, V1, DAG);
5417 if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5418 return getMOVHighToLow(Op, dl, DAG);
5420 // Use to match splats
5421 if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5422 (VT == MVT::v2f64 || VT == MVT::v2i64))
5423 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5425 if (X86::isPSHUFDMask(SVOp)) {
5426 // The actual implementation will match the mask in the if above and then
5427 // during isel it can match several different instructions, not only pshufd
5428 // as its name says, sad but true, emulate the behavior for now...
5429 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5430 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5432 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5434 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5435 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5437 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5438 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5441 if (VT == MVT::v4f32)
5442 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5446 // Check if this can be converted into a logical shift.
5447 bool isLeft = false;
5450 bool isShift = getSubtarget()->hasSSE2() &&
5451 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5452 if (isShift && ShVal.hasOneUse()) {
5453 // If the shifted value has multiple uses, it may be cheaper to use
5454 // v_set0 + movlhps or movhlps, etc.
5455 EVT EltVT = VT.getVectorElementType();
5456 ShAmt *= EltVT.getSizeInBits();
5457 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5460 if (X86::isMOVLMask(SVOp)) {
5463 if (ISD::isBuildVectorAllZeros(V1.getNode()))
5464 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5465 if (!X86::isMOVLPMask(SVOp)) {
5466 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5467 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5469 if (VT == MVT::v4i32 || VT == MVT::v4f32)
5470 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5474 // FIXME: fold these into legal mask.
5475 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5476 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5478 if (X86::isMOVHLPSMask(SVOp))
5479 return getMOVHighToLow(Op, dl, DAG);
5481 if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5482 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5484 if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5485 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5487 if (X86::isMOVLPMask(SVOp))
5488 return getMOVLP(Op, dl, DAG, HasSSE2);
5490 if (ShouldXformToMOVHLPS(SVOp) ||
5491 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5492 return CommuteVectorShuffle(SVOp, DAG);
5495 // No better options. Use a vshl / vsrl.
5496 EVT EltVT = VT.getVectorElementType();
5497 ShAmt *= EltVT.getSizeInBits();
5498 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5501 bool Commuted = false;
5502 // FIXME: This should also accept a bitcast of a splat? Be careful, not
5503 // 1,1,1,1 -> v8i16 though.
5504 V1IsSplat = isSplatVector(V1.getNode());
5505 V2IsSplat = isSplatVector(V2.getNode());
5507 // Canonicalize the splat or undef, if present, to be on the RHS.
5508 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5509 Op = CommuteVectorShuffle(SVOp, DAG);
5510 SVOp = cast<ShuffleVectorSDNode>(Op);
5511 V1 = SVOp->getOperand(0);
5512 V2 = SVOp->getOperand(1);
5513 std::swap(V1IsSplat, V2IsSplat);
5514 std::swap(V1IsUndef, V2IsUndef);
5518 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5519 // Shuffling low element of v1 into undef, just return v1.
5522 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5523 // the instruction selector will not match, so get a canonical MOVL with
5524 // swapped operands to undo the commute.
5525 return getMOVL(DAG, dl, VT, V2, V1);
5528 if (X86::isUNPCKLMask(SVOp))
5529 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
5531 if (X86::isUNPCKHMask(SVOp))
5532 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5535 // Normalize mask so all entries that point to V2 points to its first
5536 // element then try to match unpck{h|l} again. If match, return a
5537 // new vector_shuffle with the corrected mask.
5538 SDValue NewMask = NormalizeMask(SVOp, DAG);
5539 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5540 if (NSVOp != SVOp) {
5541 if (X86::isUNPCKLMask(NSVOp, true)) {
5543 } else if (X86::isUNPCKHMask(NSVOp, true)) {
5550 // Commute is back and try unpck* again.
5551 // FIXME: this seems wrong.
5552 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5553 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5555 if (X86::isUNPCKLMask(NewSVOp))
5556 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
5558 if (X86::isUNPCKHMask(NewSVOp))
5559 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5562 // Normalize the node to match x86 shuffle ops if needed
5563 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5564 return CommuteVectorShuffle(SVOp, DAG);
5566 // The checks below are all present in isShuffleMaskLegal, but they are
5567 // inlined here right now to enable us to directly emit target specific
5568 // nodes, and remove one by one until they don't return Op anymore.
5569 SmallVector<int, 16> M;
5572 if (isPALIGNRMask(M, VT, HasSSSE3))
5573 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5574 X86::getShufflePALIGNRImmediate(SVOp),
5577 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5578 SVOp->getSplatIndex() == 0 && V2IsUndef) {
5579 if (VT == MVT::v2f64)
5580 return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
5581 if (VT == MVT::v2i64)
5582 return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5585 if (isPSHUFHWMask(M, VT))
5586 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5587 X86::getShufflePSHUFHWImmediate(SVOp),
5590 if (isPSHUFLWMask(M, VT))
5591 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5592 X86::getShufflePSHUFLWImmediate(SVOp),
5595 if (isSHUFPMask(M, VT)) {
5596 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5597 if (VT == MVT::v4f32 || VT == MVT::v4i32)
5598 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5600 if (VT == MVT::v2f64 || VT == MVT::v2i64)
5601 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5605 if (X86::isUNPCKL_v_undef_Mask(SVOp))
5606 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5607 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5608 if (X86::isUNPCKH_v_undef_Mask(SVOp))
5609 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5610 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5612 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5613 if (VT == MVT::v8i16) {
5614 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5615 if (NewOp.getNode())
5619 if (VT == MVT::v16i8) {
5620 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5621 if (NewOp.getNode())
5625 // Handle all 4 wide cases with a number of shuffles.
5627 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5633 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5634 SelectionDAG &DAG) const {
5635 EVT VT = Op.getValueType();
5636 DebugLoc dl = Op.getDebugLoc();
5637 if (VT.getSizeInBits() == 8) {
5638 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5639 Op.getOperand(0), Op.getOperand(1));
5640 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5641 DAG.getValueType(VT));
5642 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5643 } else if (VT.getSizeInBits() == 16) {
5644 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5645 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
5647 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5648 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5649 DAG.getNode(ISD::BITCAST, dl,
5653 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
5654 Op.getOperand(0), Op.getOperand(1));
5655 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5656 DAG.getValueType(VT));
5657 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5658 } else if (VT == MVT::f32) {
5659 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
5660 // the result back to FR32 register. It's only worth matching if the
5661 // result has a single use which is a store or a bitcast to i32. And in
5662 // the case of a store, it's not worth it if the index is a constant 0,
5663 // because a MOVSSmr can be used instead, which is smaller and faster.
5664 if (!Op.hasOneUse())
5666 SDNode *User = *Op.getNode()->use_begin();
5667 if ((User->getOpcode() != ISD::STORE ||
5668 (isa<ConstantSDNode>(Op.getOperand(1)) &&
5669 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
5670 (User->getOpcode() != ISD::BITCAST ||
5671 User->getValueType(0) != MVT::i32))
5673 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5674 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
5677 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
5678 } else if (VT == MVT::i32) {
5679 // ExtractPS works with constant index.
5680 if (isa<ConstantSDNode>(Op.getOperand(1)))
5688 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5689 SelectionDAG &DAG) const {
5690 if (!isa<ConstantSDNode>(Op.getOperand(1)))
5693 if (Subtarget->hasSSE41()) {
5694 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
5699 EVT VT = Op.getValueType();
5700 DebugLoc dl = Op.getDebugLoc();
5701 // TODO: handle v16i8.
5702 if (VT.getSizeInBits() == 16) {
5703 SDValue Vec = Op.getOperand(0);
5704 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5706 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5707 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5708 DAG.getNode(ISD::BITCAST, dl,
5711 // Transform it so it match pextrw which produces a 32-bit result.
5712 EVT EltVT = MVT::i32;
5713 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
5714 Op.getOperand(0), Op.getOperand(1));
5715 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
5716 DAG.getValueType(VT));
5717 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5718 } else if (VT.getSizeInBits() == 32) {
5719 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5723 // SHUFPS the element to the lowest double word, then movss.
5724 int Mask[4] = { Idx, -1, -1, -1 };
5725 EVT VVT = Op.getOperand(0).getValueType();
5726 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5727 DAG.getUNDEF(VVT), Mask);
5728 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5729 DAG.getIntPtrConstant(0));
5730 } else if (VT.getSizeInBits() == 64) {
5731 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
5732 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
5733 // to match extract_elt for f64.
5734 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5738 // UNPCKHPD the element to the lowest double word, then movsd.
5739 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
5740 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
5741 int Mask[2] = { 1, -1 };
5742 EVT VVT = Op.getOperand(0).getValueType();
5743 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5744 DAG.getUNDEF(VVT), Mask);
5745 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5746 DAG.getIntPtrConstant(0));
5753 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
5754 SelectionDAG &DAG) const {
5755 EVT VT = Op.getValueType();
5756 EVT EltVT = VT.getVectorElementType();
5757 DebugLoc dl = Op.getDebugLoc();
5759 SDValue N0 = Op.getOperand(0);
5760 SDValue N1 = Op.getOperand(1);
5761 SDValue N2 = Op.getOperand(2);
5763 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
5764 isa<ConstantSDNode>(N2)) {
5766 if (VT == MVT::v8i16)
5767 Opc = X86ISD::PINSRW;
5768 else if (VT == MVT::v16i8)
5769 Opc = X86ISD::PINSRB;
5771 Opc = X86ISD::PINSRB;
5773 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
5775 if (N1.getValueType() != MVT::i32)
5776 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5777 if (N2.getValueType() != MVT::i32)
5778 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5779 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
5780 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
5781 // Bits [7:6] of the constant are the source select. This will always be
5782 // zero here. The DAG Combiner may combine an extract_elt index into these
5783 // bits. For example (insert (extract, 3), 2) could be matched by putting
5784 // the '3' into bits [7:6] of X86ISD::INSERTPS.
5785 // Bits [5:4] of the constant are the destination select. This is the
5786 // value of the incoming immediate.
5787 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
5788 // combine either bitwise AND or insert of float 0.0 to set these bits.
5789 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
5790 // Create this as a scalar to vector..
5791 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
5792 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
5793 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
5794 // PINSR* works with constant index.
5801 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
5802 EVT VT = Op.getValueType();
5803 EVT EltVT = VT.getVectorElementType();
5805 if (Subtarget->hasSSE41())
5806 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
5808 if (EltVT == MVT::i8)
5811 DebugLoc dl = Op.getDebugLoc();
5812 SDValue N0 = Op.getOperand(0);
5813 SDValue N1 = Op.getOperand(1);
5814 SDValue N2 = Op.getOperand(2);
5816 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
5817 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
5818 // as its second argument.
5819 if (N1.getValueType() != MVT::i32)
5820 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5821 if (N2.getValueType() != MVT::i32)
5822 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5823 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
5829 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5830 DebugLoc dl = Op.getDebugLoc();
5832 if (Op.getValueType() == MVT::v1i64 &&
5833 Op.getOperand(0).getValueType() == MVT::i64)
5834 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5836 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5837 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
5838 "Expected an SSE type!");
5839 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
5840 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
5843 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5844 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5845 // one of the above mentioned nodes. It has to be wrapped because otherwise
5846 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5847 // be used to form addressing mode. These wrapped nodes will be selected
5850 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
5851 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5853 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5855 unsigned char OpFlag = 0;
5856 unsigned WrapperKind = X86ISD::Wrapper;
5857 CodeModel::Model M = getTargetMachine().getCodeModel();
5859 if (Subtarget->isPICStyleRIPRel() &&
5860 (M == CodeModel::Small || M == CodeModel::Kernel))
5861 WrapperKind = X86ISD::WrapperRIP;
5862 else if (Subtarget->isPICStyleGOT())
5863 OpFlag = X86II::MO_GOTOFF;
5864 else if (Subtarget->isPICStyleStubPIC())
5865 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5867 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5869 CP->getOffset(), OpFlag);
5870 DebugLoc DL = CP->getDebugLoc();
5871 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5872 // With PIC, the address is actually $g + Offset.
5874 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5875 DAG.getNode(X86ISD::GlobalBaseReg,
5876 DebugLoc(), getPointerTy()),
5883 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
5884 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5886 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5888 unsigned char OpFlag = 0;
5889 unsigned WrapperKind = X86ISD::Wrapper;
5890 CodeModel::Model M = getTargetMachine().getCodeModel();
5892 if (Subtarget->isPICStyleRIPRel() &&
5893 (M == CodeModel::Small || M == CodeModel::Kernel))
5894 WrapperKind = X86ISD::WrapperRIP;
5895 else if (Subtarget->isPICStyleGOT())
5896 OpFlag = X86II::MO_GOTOFF;
5897 else if (Subtarget->isPICStyleStubPIC())
5898 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5900 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5902 DebugLoc DL = JT->getDebugLoc();
5903 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5905 // With PIC, the address is actually $g + Offset.
5907 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5908 DAG.getNode(X86ISD::GlobalBaseReg,
5909 DebugLoc(), getPointerTy()),
5916 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
5917 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5919 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5921 unsigned char OpFlag = 0;
5922 unsigned WrapperKind = X86ISD::Wrapper;
5923 CodeModel::Model M = getTargetMachine().getCodeModel();
5925 if (Subtarget->isPICStyleRIPRel() &&
5926 (M == CodeModel::Small || M == CodeModel::Kernel))
5927 WrapperKind = X86ISD::WrapperRIP;
5928 else if (Subtarget->isPICStyleGOT())
5929 OpFlag = X86II::MO_GOTOFF;
5930 else if (Subtarget->isPICStyleStubPIC())
5931 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5933 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5935 DebugLoc DL = Op.getDebugLoc();
5936 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5939 // With PIC, the address is actually $g + Offset.
5940 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
5941 !Subtarget->is64Bit()) {
5942 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5943 DAG.getNode(X86ISD::GlobalBaseReg,
5944 DebugLoc(), getPointerTy()),
5952 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
5953 // Create the TargetBlockAddressAddress node.
5954 unsigned char OpFlags =
5955 Subtarget->ClassifyBlockAddressReference();
5956 CodeModel::Model M = getTargetMachine().getCodeModel();
5957 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5958 DebugLoc dl = Op.getDebugLoc();
5959 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5960 /*isTarget=*/true, OpFlags);
5962 if (Subtarget->isPICStyleRIPRel() &&
5963 (M == CodeModel::Small || M == CodeModel::Kernel))
5964 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5966 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5968 // With PIC, the address is actually $g + Offset.
5969 if (isGlobalRelativeToPICBase(OpFlags)) {
5970 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5971 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5979 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
5981 SelectionDAG &DAG) const {
5982 // Create the TargetGlobalAddress node, folding in the constant
5983 // offset if it is legal.
5984 unsigned char OpFlags =
5985 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5986 CodeModel::Model M = getTargetMachine().getCodeModel();
5988 if (OpFlags == X86II::MO_NO_FLAG &&
5989 X86::isOffsetSuitableForCodeModel(Offset, M)) {
5990 // A direct static reference to a global.
5991 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
5994 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
5997 if (Subtarget->isPICStyleRIPRel() &&
5998 (M == CodeModel::Small || M == CodeModel::Kernel))
5999 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6001 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6003 // With PIC, the address is actually $g + Offset.
6004 if (isGlobalRelativeToPICBase(OpFlags)) {
6005 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6006 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6010 // For globals that require a load from a stub to get the address, emit the
6012 if (isGlobalStubReference(OpFlags))
6013 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6014 MachinePointerInfo::getGOT(), false, false, 0);
6016 // If there was a non-zero offset that we didn't fold, create an explicit
6019 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6020 DAG.getConstant(Offset, getPointerTy()));
6026 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6027 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6028 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6029 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6033 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6034 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6035 unsigned char OperandFlags) {
6036 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6037 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6038 DebugLoc dl = GA->getDebugLoc();
6039 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6040 GA->getValueType(0),
6044 SDValue Ops[] = { Chain, TGA, *InFlag };
6045 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6047 SDValue Ops[] = { Chain, TGA };
6048 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6051 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6052 MFI->setAdjustsStack(true);
6054 SDValue Flag = Chain.getValue(1);
6055 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6058 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6060 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6063 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
6064 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6065 DAG.getNode(X86ISD::GlobalBaseReg,
6066 DebugLoc(), PtrVT), InFlag);
6067 InFlag = Chain.getValue(1);
6069 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6072 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6074 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6076 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6077 X86::RAX, X86II::MO_TLSGD);
6080 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6081 // "local exec" model.
6082 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6083 const EVT PtrVT, TLSModel::Model model,
6085 DebugLoc dl = GA->getDebugLoc();
6087 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6088 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6089 is64Bit ? 257 : 256));
6091 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6092 DAG.getIntPtrConstant(0),
6093 MachinePointerInfo(Ptr), false, false, 0);
6095 unsigned char OperandFlags = 0;
6096 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
6098 unsigned WrapperKind = X86ISD::Wrapper;
6099 if (model == TLSModel::LocalExec) {
6100 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6101 } else if (is64Bit) {
6102 assert(model == TLSModel::InitialExec);
6103 OperandFlags = X86II::MO_GOTTPOFF;
6104 WrapperKind = X86ISD::WrapperRIP;
6106 assert(model == TLSModel::InitialExec);
6107 OperandFlags = X86II::MO_INDNTPOFF;
6110 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6112 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6113 GA->getValueType(0),
6114 GA->getOffset(), OperandFlags);
6115 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6117 if (model == TLSModel::InitialExec)
6118 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6119 MachinePointerInfo::getGOT(), false, false, 0);
6121 // The address of the thread local variable is the add of the thread
6122 // pointer with the offset of the variable.
6123 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6127 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6129 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6130 const GlobalValue *GV = GA->getGlobal();
6132 if (Subtarget->isTargetELF()) {
6133 // TODO: implement the "local dynamic" model
6134 // TODO: implement the "initial exec"model for pic executables
6136 // If GV is an alias then use the aliasee for determining
6137 // thread-localness.
6138 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6139 GV = GA->resolveAliasedGlobal(false);
6141 TLSModel::Model model
6142 = getTLSModel(GV, getTargetMachine().getRelocationModel());
6145 case TLSModel::GeneralDynamic:
6146 case TLSModel::LocalDynamic: // not implemented
6147 if (Subtarget->is64Bit())
6148 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6149 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6151 case TLSModel::InitialExec:
6152 case TLSModel::LocalExec:
6153 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6154 Subtarget->is64Bit());
6156 } else if (Subtarget->isTargetDarwin()) {
6157 // Darwin only has one model of TLS. Lower to that.
6158 unsigned char OpFlag = 0;
6159 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6160 X86ISD::WrapperRIP : X86ISD::Wrapper;
6162 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6164 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6165 !Subtarget->is64Bit();
6167 OpFlag = X86II::MO_TLVP_PIC_BASE;
6169 OpFlag = X86II::MO_TLVP;
6170 DebugLoc DL = Op.getDebugLoc();
6171 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6172 GA->getValueType(0),
6173 GA->getOffset(), OpFlag);
6174 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6176 // With PIC32, the address is actually $g + Offset.
6178 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6179 DAG.getNode(X86ISD::GlobalBaseReg,
6180 DebugLoc(), getPointerTy()),
6183 // Lowering the machine isd will make sure everything is in the right
6185 SDValue Chain = DAG.getEntryNode();
6186 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6187 SDValue Args[] = { Chain, Offset };
6188 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6190 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6191 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6192 MFI->setAdjustsStack(true);
6194 // And our return value (tls address) is in the standard call return value
6196 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6197 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6201 "TLS not implemented for this target.");
6203 llvm_unreachable("Unreachable");
6208 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
6209 /// take a 2 x i32 value to shift plus a shift amount.
6210 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
6211 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6212 EVT VT = Op.getValueType();
6213 unsigned VTBits = VT.getSizeInBits();
6214 DebugLoc dl = Op.getDebugLoc();
6215 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6216 SDValue ShOpLo = Op.getOperand(0);
6217 SDValue ShOpHi = Op.getOperand(1);
6218 SDValue ShAmt = Op.getOperand(2);
6219 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6220 DAG.getConstant(VTBits - 1, MVT::i8))
6221 : DAG.getConstant(0, VT);
6224 if (Op.getOpcode() == ISD::SHL_PARTS) {
6225 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6226 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6228 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6229 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6232 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6233 DAG.getConstant(VTBits, MVT::i8));
6234 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6235 AndNode, DAG.getConstant(0, MVT::i8));
6238 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6239 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6240 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6242 if (Op.getOpcode() == ISD::SHL_PARTS) {
6243 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6244 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6246 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6247 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6250 SDValue Ops[2] = { Lo, Hi };
6251 return DAG.getMergeValues(Ops, 2, dl);
6254 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6255 SelectionDAG &DAG) const {
6256 EVT SrcVT = Op.getOperand(0).getValueType();
6258 if (SrcVT.isVector())
6261 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6262 "Unknown SINT_TO_FP to lower!");
6264 // These are really Legal; return the operand so the caller accepts it as
6266 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6268 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6269 Subtarget->is64Bit()) {
6273 DebugLoc dl = Op.getDebugLoc();
6274 unsigned Size = SrcVT.getSizeInBits()/8;
6275 MachineFunction &MF = DAG.getMachineFunction();
6276 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6277 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6278 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6280 MachinePointerInfo::getFixedStack(SSFI),
6282 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6285 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6287 SelectionDAG &DAG) const {
6289 DebugLoc DL = Op.getDebugLoc();
6291 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6293 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
6295 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6297 unsigned ByteSize = SrcVT.getSizeInBits()/8;
6299 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6300 MachineMemOperand *MMO =
6301 DAG.getMachineFunction()
6302 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6303 MachineMemOperand::MOLoad, ByteSize, ByteSize);
6305 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6306 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6308 Tys, Ops, array_lengthof(Ops),
6312 Chain = Result.getValue(1);
6313 SDValue InFlag = Result.getValue(2);
6315 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6316 // shouldn't be necessary except that RFP cannot be live across
6317 // multiple blocks. When stackifier is fixed, they can be uncoupled.
6318 MachineFunction &MF = DAG.getMachineFunction();
6319 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6320 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6321 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6322 Tys = DAG.getVTList(MVT::Other);
6324 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6326 MachineMemOperand *MMO =
6327 DAG.getMachineFunction()
6328 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6329 MachineMemOperand::MOStore, SSFISize, SSFISize);
6331 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6332 Ops, array_lengthof(Ops),
6333 Op.getValueType(), MMO);
6334 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6335 MachinePointerInfo::getFixedStack(SSFI),
6342 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6343 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6344 SelectionDAG &DAG) const {
6345 // This algorithm is not obvious. Here it is in C code, more or less:
6347 double uint64_to_double( uint32_t hi, uint32_t lo ) {
6348 static const __m128i exp = { 0x4330000045300000ULL, 0 };
6349 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6351 // Copy ints to xmm registers.
6352 __m128i xh = _mm_cvtsi32_si128( hi );
6353 __m128i xl = _mm_cvtsi32_si128( lo );
6355 // Combine into low half of a single xmm register.
6356 __m128i x = _mm_unpacklo_epi32( xh, xl );
6360 // Merge in appropriate exponents to give the integer bits the right
6362 x = _mm_unpacklo_epi32( x, exp );
6364 // Subtract away the biases to deal with the IEEE-754 double precision
6366 d = _mm_sub_pd( (__m128d) x, bias );
6368 // All conversions up to here are exact. The correctly rounded result is
6369 // calculated using the current rounding mode using the following
6371 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6372 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
6373 // store doesn't really need to be here (except
6374 // maybe to zero the other double)
6379 DebugLoc dl = Op.getDebugLoc();
6380 LLVMContext *Context = DAG.getContext();
6382 // Build some magic constants.
6383 std::vector<Constant*> CV0;
6384 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6385 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6386 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6387 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6388 Constant *C0 = ConstantVector::get(CV0);
6389 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6391 std::vector<Constant*> CV1;
6393 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6395 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6396 Constant *C1 = ConstantVector::get(CV1);
6397 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6399 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6400 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6402 DAG.getIntPtrConstant(1)));
6403 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6404 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6406 DAG.getIntPtrConstant(0)));
6407 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6408 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6409 MachinePointerInfo::getConstantPool(),
6411 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6412 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6413 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6414 MachinePointerInfo::getConstantPool(),
6416 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6418 // Add the halves; easiest way is to swap them into another reg first.
6419 int ShufMask[2] = { 1, -1 };
6420 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6421 DAG.getUNDEF(MVT::v2f64), ShufMask);
6422 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6423 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6424 DAG.getIntPtrConstant(0));
6427 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6428 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6429 SelectionDAG &DAG) const {
6430 DebugLoc dl = Op.getDebugLoc();
6431 // FP constant to bias correct the final result.
6432 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6435 // Load the 32-bit value into an XMM register.
6436 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6437 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6439 DAG.getIntPtrConstant(0)));
6441 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6442 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6443 DAG.getIntPtrConstant(0));
6445 // Or the load with the bias.
6446 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6447 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6448 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6450 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6451 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6452 MVT::v2f64, Bias)));
6453 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6454 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6455 DAG.getIntPtrConstant(0));
6457 // Subtract the bias.
6458 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6460 // Handle final rounding.
6461 EVT DestVT = Op.getValueType();
6463 if (DestVT.bitsLT(MVT::f64)) {
6464 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6465 DAG.getIntPtrConstant(0));
6466 } else if (DestVT.bitsGT(MVT::f64)) {
6467 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6470 // Handle final rounding.
6474 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6475 SelectionDAG &DAG) const {
6476 SDValue N0 = Op.getOperand(0);
6477 DebugLoc dl = Op.getDebugLoc();
6479 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6480 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6481 // the optimization here.
6482 if (DAG.SignBitIsZero(N0))
6483 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6485 EVT SrcVT = N0.getValueType();
6486 EVT DstVT = Op.getValueType();
6487 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6488 return LowerUINT_TO_FP_i64(Op, DAG);
6489 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6490 return LowerUINT_TO_FP_i32(Op, DAG);
6492 // Make a 64-bit buffer, and use it to build an FILD.
6493 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6494 if (SrcVT == MVT::i32) {
6495 SDValue WordOff = DAG.getConstant(4, getPointerTy());
6496 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6497 getPointerTy(), StackSlot, WordOff);
6498 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6499 StackSlot, MachinePointerInfo(),
6501 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6502 OffsetSlot, MachinePointerInfo(),
6504 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6508 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6509 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6510 StackSlot, MachinePointerInfo(),
6512 // For i64 source, we need to add the appropriate power of 2 if the input
6513 // was negative. This is the same as the optimization in
6514 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6515 // we must be careful to do the computation in x87 extended precision, not
6516 // in SSE. (The generic code can't know it's OK to do this, or how to.)
6517 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6518 MachineMemOperand *MMO =
6519 DAG.getMachineFunction()
6520 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6521 MachineMemOperand::MOLoad, 8, 8);
6523 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6524 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6525 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
6528 APInt FF(32, 0x5F800000ULL);
6530 // Check whether the sign bit is set.
6531 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6532 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6535 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6536 SDValue FudgePtr = DAG.getConstantPool(
6537 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6540 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6541 SDValue Zero = DAG.getIntPtrConstant(0);
6542 SDValue Four = DAG.getIntPtrConstant(4);
6543 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6545 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6547 // Load the value out, extending it from f32 to f80.
6548 // FIXME: Avoid the extend by constructing the right constant pool?
6549 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, MVT::f80, dl, DAG.getEntryNode(),
6550 FudgePtr, MachinePointerInfo::getConstantPool(),
6551 MVT::f32, false, false, 4);
6552 // Extend everything to 80 bits to force it to be done on x87.
6553 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6554 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6557 std::pair<SDValue,SDValue> X86TargetLowering::
6558 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6559 DebugLoc DL = Op.getDebugLoc();
6561 EVT DstTy = Op.getValueType();
6564 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
6568 assert(DstTy.getSimpleVT() <= MVT::i64 &&
6569 DstTy.getSimpleVT() >= MVT::i16 &&
6570 "Unknown FP_TO_SINT to lower!");
6572 // These are really Legal.
6573 if (DstTy == MVT::i32 &&
6574 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6575 return std::make_pair(SDValue(), SDValue());
6576 if (Subtarget->is64Bit() &&
6577 DstTy == MVT::i64 &&
6578 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6579 return std::make_pair(SDValue(), SDValue());
6581 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
6583 MachineFunction &MF = DAG.getMachineFunction();
6584 unsigned MemSize = DstTy.getSizeInBits()/8;
6585 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6586 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6591 switch (DstTy.getSimpleVT().SimpleTy) {
6592 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
6593 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
6594 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
6595 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
6598 SDValue Chain = DAG.getEntryNode();
6599 SDValue Value = Op.getOperand(0);
6600 EVT TheVT = Op.getOperand(0).getValueType();
6601 if (isScalarFPTypeInSSEReg(TheVT)) {
6602 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
6603 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
6604 MachinePointerInfo::getFixedStack(SSFI),
6606 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
6608 Chain, StackSlot, DAG.getValueType(TheVT)
6611 MachineMemOperand *MMO =
6612 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6613 MachineMemOperand::MOLoad, MemSize, MemSize);
6614 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
6616 Chain = Value.getValue(1);
6617 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6618 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6621 MachineMemOperand *MMO =
6622 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6623 MachineMemOperand::MOStore, MemSize, MemSize);
6625 // Build the FP_TO_INT*_IN_MEM
6626 SDValue Ops[] = { Chain, Value, StackSlot };
6627 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
6628 Ops, 3, DstTy, MMO);
6630 return std::make_pair(FIST, StackSlot);
6633 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
6634 SelectionDAG &DAG) const {
6635 if (Op.getValueType().isVector())
6638 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
6639 SDValue FIST = Vals.first, StackSlot = Vals.second;
6640 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
6641 if (FIST.getNode() == 0) return Op;
6644 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6645 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6648 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
6649 SelectionDAG &DAG) const {
6650 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
6651 SDValue FIST = Vals.first, StackSlot = Vals.second;
6652 assert(FIST.getNode() && "Unexpected failure");
6655 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6656 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6659 SDValue X86TargetLowering::LowerFABS(SDValue Op,
6660 SelectionDAG &DAG) const {
6661 LLVMContext *Context = DAG.getContext();
6662 DebugLoc dl = Op.getDebugLoc();
6663 EVT VT = Op.getValueType();
6666 EltVT = VT.getVectorElementType();
6667 std::vector<Constant*> CV;
6668 if (EltVT == MVT::f64) {
6669 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
6673 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
6679 Constant *C = ConstantVector::get(CV);
6680 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6681 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6682 MachinePointerInfo::getConstantPool(),
6684 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
6687 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
6688 LLVMContext *Context = DAG.getContext();
6689 DebugLoc dl = Op.getDebugLoc();
6690 EVT VT = Op.getValueType();
6693 EltVT = VT.getVectorElementType();
6694 std::vector<Constant*> CV;
6695 if (EltVT == MVT::f64) {
6696 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
6700 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
6706 Constant *C = ConstantVector::get(CV);
6707 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6708 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6709 MachinePointerInfo::getConstantPool(),
6711 if (VT.isVector()) {
6712 return DAG.getNode(ISD::BITCAST, dl, VT,
6713 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
6714 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6716 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
6718 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
6722 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
6723 LLVMContext *Context = DAG.getContext();
6724 SDValue Op0 = Op.getOperand(0);
6725 SDValue Op1 = Op.getOperand(1);
6726 DebugLoc dl = Op.getDebugLoc();
6727 EVT VT = Op.getValueType();
6728 EVT SrcVT = Op1.getValueType();
6730 // If second operand is smaller, extend it first.
6731 if (SrcVT.bitsLT(VT)) {
6732 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
6735 // And if it is bigger, shrink it first.
6736 if (SrcVT.bitsGT(VT)) {
6737 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
6741 // At this point the operands and the result should have the same
6742 // type, and that won't be f80 since that is not custom lowered.
6744 // First get the sign bit of second operand.
6745 std::vector<Constant*> CV;
6746 if (SrcVT == MVT::f64) {
6747 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
6748 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6750 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
6751 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6752 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6753 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6755 Constant *C = ConstantVector::get(CV);
6756 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6757 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
6758 MachinePointerInfo::getConstantPool(),
6760 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
6762 // Shift sign bit right or left if the two operands have different types.
6763 if (SrcVT.bitsGT(VT)) {
6764 // Op0 is MVT::f32, Op1 is MVT::f64.
6765 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
6766 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
6767 DAG.getConstant(32, MVT::i32));
6768 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
6769 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
6770 DAG.getIntPtrConstant(0));
6773 // Clear first operand sign bit.
6775 if (VT == MVT::f64) {
6776 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
6777 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6779 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
6780 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6781 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6782 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6784 C = ConstantVector::get(CV);
6785 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6786 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6787 MachinePointerInfo::getConstantPool(),
6789 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
6791 // Or the value with the sign bit.
6792 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
6795 /// Emit nodes that will be selected as "test Op0,Op0", or something
6797 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
6798 SelectionDAG &DAG) const {
6799 DebugLoc dl = Op.getDebugLoc();
6801 // CF and OF aren't always set the way we want. Determine which
6802 // of these we need.
6803 bool NeedCF = false;
6804 bool NeedOF = false;
6807 case X86::COND_A: case X86::COND_AE:
6808 case X86::COND_B: case X86::COND_BE:
6811 case X86::COND_G: case X86::COND_GE:
6812 case X86::COND_L: case X86::COND_LE:
6813 case X86::COND_O: case X86::COND_NO:
6818 // See if we can use the EFLAGS value from the operand instead of
6819 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
6820 // we prove that the arithmetic won't overflow, we can't use OF or CF.
6821 if (Op.getResNo() != 0 || NeedOF || NeedCF)
6822 // Emit a CMP with 0, which is the TEST pattern.
6823 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6824 DAG.getConstant(0, Op.getValueType()));
6826 unsigned Opcode = 0;
6827 unsigned NumOperands = 0;
6828 switch (Op.getNode()->getOpcode()) {
6830 // Due to an isel shortcoming, be conservative if this add is likely to be
6831 // selected as part of a load-modify-store instruction. When the root node
6832 // in a match is a store, isel doesn't know how to remap non-chain non-flag
6833 // uses of other nodes in the match, such as the ADD in this case. This
6834 // leads to the ADD being left around and reselected, with the result being
6835 // two adds in the output. Alas, even if none our users are stores, that
6836 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
6837 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
6838 // climbing the DAG back to the root, and it doesn't seem to be worth the
6840 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6841 UE = Op.getNode()->use_end(); UI != UE; ++UI)
6842 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
6845 if (ConstantSDNode *C =
6846 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
6847 // An add of one will be selected as an INC.
6848 if (C->getAPIntValue() == 1) {
6849 Opcode = X86ISD::INC;
6854 // An add of negative one (subtract of one) will be selected as a DEC.
6855 if (C->getAPIntValue().isAllOnesValue()) {
6856 Opcode = X86ISD::DEC;
6862 // Otherwise use a regular EFLAGS-setting add.
6863 Opcode = X86ISD::ADD;
6867 // If the primary and result isn't used, don't bother using X86ISD::AND,
6868 // because a TEST instruction will be better.
6869 bool NonFlagUse = false;
6870 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6871 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
6873 unsigned UOpNo = UI.getOperandNo();
6874 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
6875 // Look pass truncate.
6876 UOpNo = User->use_begin().getOperandNo();
6877 User = *User->use_begin();
6880 if (User->getOpcode() != ISD::BRCOND &&
6881 User->getOpcode() != ISD::SETCC &&
6882 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
6895 // Due to the ISEL shortcoming noted above, be conservative if this op is
6896 // likely to be selected as part of a load-modify-store instruction.
6897 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6898 UE = Op.getNode()->use_end(); UI != UE; ++UI)
6899 if (UI->getOpcode() == ISD::STORE)
6902 // Otherwise use a regular EFLAGS-setting instruction.
6903 switch (Op.getNode()->getOpcode()) {
6904 default: llvm_unreachable("unexpected operator!");
6905 case ISD::SUB: Opcode = X86ISD::SUB; break;
6906 case ISD::OR: Opcode = X86ISD::OR; break;
6907 case ISD::XOR: Opcode = X86ISD::XOR; break;
6908 case ISD::AND: Opcode = X86ISD::AND; break;
6920 return SDValue(Op.getNode(), 1);
6927 // Emit a CMP with 0, which is the TEST pattern.
6928 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6929 DAG.getConstant(0, Op.getValueType()));
6931 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
6932 SmallVector<SDValue, 4> Ops;
6933 for (unsigned i = 0; i != NumOperands; ++i)
6934 Ops.push_back(Op.getOperand(i));
6936 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
6937 DAG.ReplaceAllUsesWith(Op, New);
6938 return SDValue(New.getNode(), 1);
6941 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
6943 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
6944 SelectionDAG &DAG) const {
6945 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
6946 if (C->getAPIntValue() == 0)
6947 return EmitTest(Op0, X86CC, DAG);
6949 DebugLoc dl = Op0.getDebugLoc();
6950 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
6953 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
6954 /// if it's possible.
6955 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
6956 DebugLoc dl, SelectionDAG &DAG) const {
6957 SDValue Op0 = And.getOperand(0);
6958 SDValue Op1 = And.getOperand(1);
6959 if (Op0.getOpcode() == ISD::TRUNCATE)
6960 Op0 = Op0.getOperand(0);
6961 if (Op1.getOpcode() == ISD::TRUNCATE)
6962 Op1 = Op1.getOperand(0);
6965 if (Op1.getOpcode() == ISD::SHL)
6966 std::swap(Op0, Op1);
6967 if (Op0.getOpcode() == ISD::SHL) {
6968 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
6969 if (And00C->getZExtValue() == 1) {
6970 // If we looked past a truncate, check that it's only truncating away
6972 unsigned BitWidth = Op0.getValueSizeInBits();
6973 unsigned AndBitWidth = And.getValueSizeInBits();
6974 if (BitWidth > AndBitWidth) {
6975 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
6976 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
6977 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
6981 RHS = Op0.getOperand(1);
6983 } else if (Op1.getOpcode() == ISD::Constant) {
6984 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
6985 SDValue AndLHS = Op0;
6986 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
6987 LHS = AndLHS.getOperand(0);
6988 RHS = AndLHS.getOperand(1);
6992 if (LHS.getNode()) {
6993 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
6994 // instruction. Since the shift amount is in-range-or-undefined, we know
6995 // that doing a bittest on the i32 value is ok. We extend to i32 because
6996 // the encoding for the i16 version is larger than the i32 version.
6997 // Also promote i16 to i32 for performance / code size reason.
6998 if (LHS.getValueType() == MVT::i8 ||
6999 LHS.getValueType() == MVT::i16)
7000 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7002 // If the operand types disagree, extend the shift amount to match. Since
7003 // BT ignores high bits (like shifts) we can use anyextend.
7004 if (LHS.getValueType() != RHS.getValueType())
7005 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7007 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7008 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7009 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7010 DAG.getConstant(Cond, MVT::i8), BT);
7016 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7017 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7018 SDValue Op0 = Op.getOperand(0);
7019 SDValue Op1 = Op.getOperand(1);
7020 DebugLoc dl = Op.getDebugLoc();
7021 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7023 // Optimize to BT if possible.
7024 // Lower (X & (1 << N)) == 0 to BT(X, N).
7025 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7026 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7027 if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
7028 Op1.getOpcode() == ISD::Constant &&
7029 cast<ConstantSDNode>(Op1)->isNullValue() &&
7030 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7031 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7032 if (NewSetCC.getNode())
7036 // Look for X == 0, X == 1, X != 0, or X != 1. We can simplify some forms of
7038 if (Op1.getOpcode() == ISD::Constant &&
7039 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7040 cast<ConstantSDNode>(Op1)->isNullValue()) &&
7041 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7043 // If the input is a setcc, then reuse the input setcc or use a new one with
7044 // the inverted condition.
7045 if (Op0.getOpcode() == X86ISD::SETCC) {
7046 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7047 bool Invert = (CC == ISD::SETNE) ^
7048 cast<ConstantSDNode>(Op1)->isNullValue();
7049 if (!Invert) return Op0;
7051 CCode = X86::GetOppositeBranchCondition(CCode);
7052 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7053 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7057 bool isFP = Op1.getValueType().isFloatingPoint();
7058 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7059 if (X86CC == X86::COND_INVALID)
7062 SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, DAG);
7063 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7064 DAG.getConstant(X86CC, MVT::i8), EFLAGS);
7067 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7069 SDValue Op0 = Op.getOperand(0);
7070 SDValue Op1 = Op.getOperand(1);
7071 SDValue CC = Op.getOperand(2);
7072 EVT VT = Op.getValueType();
7073 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7074 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7075 DebugLoc dl = Op.getDebugLoc();
7079 EVT VT0 = Op0.getValueType();
7080 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7081 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7084 switch (SetCCOpcode) {
7087 case ISD::SETEQ: SSECC = 0; break;
7089 case ISD::SETGT: Swap = true; // Fallthrough
7091 case ISD::SETOLT: SSECC = 1; break;
7093 case ISD::SETGE: Swap = true; // Fallthrough
7095 case ISD::SETOLE: SSECC = 2; break;
7096 case ISD::SETUO: SSECC = 3; break;
7098 case ISD::SETNE: SSECC = 4; break;
7099 case ISD::SETULE: Swap = true;
7100 case ISD::SETUGE: SSECC = 5; break;
7101 case ISD::SETULT: Swap = true;
7102 case ISD::SETUGT: SSECC = 6; break;
7103 case ISD::SETO: SSECC = 7; break;
7106 std::swap(Op0, Op1);
7108 // In the two special cases we can't handle, emit two comparisons.
7110 if (SetCCOpcode == ISD::SETUEQ) {
7112 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7113 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7114 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7116 else if (SetCCOpcode == ISD::SETONE) {
7118 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7119 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7120 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7122 llvm_unreachable("Illegal FP comparison");
7124 // Handle all other FP comparisons here.
7125 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7128 // We are handling one of the integer comparisons here. Since SSE only has
7129 // GT and EQ comparisons for integer, swapping operands and multiple
7130 // operations may be required for some comparisons.
7131 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7132 bool Swap = false, Invert = false, FlipSigns = false;
7134 switch (VT.getSimpleVT().SimpleTy) {
7136 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7137 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7138 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7139 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7142 switch (SetCCOpcode) {
7144 case ISD::SETNE: Invert = true;
7145 case ISD::SETEQ: Opc = EQOpc; break;
7146 case ISD::SETLT: Swap = true;
7147 case ISD::SETGT: Opc = GTOpc; break;
7148 case ISD::SETGE: Swap = true;
7149 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
7150 case ISD::SETULT: Swap = true;
7151 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7152 case ISD::SETUGE: Swap = true;
7153 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7156 std::swap(Op0, Op1);
7158 // Since SSE has no unsigned integer comparisons, we need to flip the sign
7159 // bits of the inputs before performing those operations.
7161 EVT EltVT = VT.getVectorElementType();
7162 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7164 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7165 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7167 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7168 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7171 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7173 // If the logical-not of the result is required, perform that now.
7175 Result = DAG.getNOT(dl, Result, VT);
7180 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7181 static bool isX86LogicalCmp(SDValue Op) {
7182 unsigned Opc = Op.getNode()->getOpcode();
7183 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7185 if (Op.getResNo() == 1 &&
7186 (Opc == X86ISD::ADD ||
7187 Opc == X86ISD::SUB ||
7188 Opc == X86ISD::ADC ||
7189 Opc == X86ISD::SBB ||
7190 Opc == X86ISD::SMUL ||
7191 Opc == X86ISD::UMUL ||
7192 Opc == X86ISD::INC ||
7193 Opc == X86ISD::DEC ||
7194 Opc == X86ISD::OR ||
7195 Opc == X86ISD::XOR ||
7196 Opc == X86ISD::AND))
7199 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7205 static bool isZero(SDValue V) {
7206 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7207 return C && C->isNullValue();
7210 static bool isAllOnes(SDValue V) {
7211 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7212 return C && C->isAllOnesValue();
7215 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7216 bool addTest = true;
7217 SDValue Cond = Op.getOperand(0);
7218 SDValue Op1 = Op.getOperand(1);
7219 SDValue Op2 = Op.getOperand(2);
7220 DebugLoc DL = Op.getDebugLoc();
7223 if (Cond.getOpcode() == ISD::SETCC) {
7224 SDValue NewCond = LowerSETCC(Cond, DAG);
7225 if (NewCond.getNode())
7229 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7230 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7231 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7232 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7233 if (Cond.getOpcode() == X86ISD::SETCC &&
7234 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7235 isZero(Cond.getOperand(1).getOperand(1))) {
7236 SDValue Cmp = Cond.getOperand(1);
7238 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7240 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7241 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7242 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7244 SDValue CmpOp0 = Cmp.getOperand(0);
7245 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7246 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7248 SDValue Res = // Res = 0 or -1.
7249 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7250 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7252 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7253 Res = DAG.getNOT(DL, Res, Res.getValueType());
7255 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7256 if (N2C == 0 || !N2C->isNullValue())
7257 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7262 // Look past (and (setcc_carry (cmp ...)), 1).
7263 if (Cond.getOpcode() == ISD::AND &&
7264 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7265 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7266 if (C && C->getAPIntValue() == 1)
7267 Cond = Cond.getOperand(0);
7270 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7271 // setting operand in place of the X86ISD::SETCC.
7272 if (Cond.getOpcode() == X86ISD::SETCC ||
7273 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7274 CC = Cond.getOperand(0);
7276 SDValue Cmp = Cond.getOperand(1);
7277 unsigned Opc = Cmp.getOpcode();
7278 EVT VT = Op.getValueType();
7280 bool IllegalFPCMov = false;
7281 if (VT.isFloatingPoint() && !VT.isVector() &&
7282 !isScalarFPTypeInSSEReg(VT)) // FPStack?
7283 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7285 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7286 Opc == X86ISD::BT) { // FIXME
7293 // Look pass the truncate.
7294 if (Cond.getOpcode() == ISD::TRUNCATE)
7295 Cond = Cond.getOperand(0);
7297 // We know the result of AND is compared against zero. Try to match
7299 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7300 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7301 if (NewSetCC.getNode()) {
7302 CC = NewSetCC.getOperand(0);
7303 Cond = NewSetCC.getOperand(1);
7310 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7311 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7314 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7315 // condition is true.
7316 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
7317 SDValue Ops[] = { Op2, Op1, CC, Cond };
7318 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7321 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7322 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7323 // from the AND / OR.
7324 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7325 Opc = Op.getOpcode();
7326 if (Opc != ISD::OR && Opc != ISD::AND)
7328 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7329 Op.getOperand(0).hasOneUse() &&
7330 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7331 Op.getOperand(1).hasOneUse());
7334 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7335 // 1 and that the SETCC node has a single use.
7336 static bool isXor1OfSetCC(SDValue Op) {
7337 if (Op.getOpcode() != ISD::XOR)
7339 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7340 if (N1C && N1C->getAPIntValue() == 1) {
7341 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7342 Op.getOperand(0).hasOneUse();
7347 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7348 bool addTest = true;
7349 SDValue Chain = Op.getOperand(0);
7350 SDValue Cond = Op.getOperand(1);
7351 SDValue Dest = Op.getOperand(2);
7352 DebugLoc dl = Op.getDebugLoc();
7355 if (Cond.getOpcode() == ISD::SETCC) {
7356 SDValue NewCond = LowerSETCC(Cond, DAG);
7357 if (NewCond.getNode())
7361 // FIXME: LowerXALUO doesn't handle these!!
7362 else if (Cond.getOpcode() == X86ISD::ADD ||
7363 Cond.getOpcode() == X86ISD::SUB ||
7364 Cond.getOpcode() == X86ISD::SMUL ||
7365 Cond.getOpcode() == X86ISD::UMUL)
7366 Cond = LowerXALUO(Cond, DAG);
7369 // Look pass (and (setcc_carry (cmp ...)), 1).
7370 if (Cond.getOpcode() == ISD::AND &&
7371 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7372 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7373 if (C && C->getAPIntValue() == 1)
7374 Cond = Cond.getOperand(0);
7377 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7378 // setting operand in place of the X86ISD::SETCC.
7379 if (Cond.getOpcode() == X86ISD::SETCC ||
7380 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7381 CC = Cond.getOperand(0);
7383 SDValue Cmp = Cond.getOperand(1);
7384 unsigned Opc = Cmp.getOpcode();
7385 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7386 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7390 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7394 // These can only come from an arithmetic instruction with overflow,
7395 // e.g. SADDO, UADDO.
7396 Cond = Cond.getNode()->getOperand(1);
7403 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7404 SDValue Cmp = Cond.getOperand(0).getOperand(1);
7405 if (CondOpc == ISD::OR) {
7406 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7407 // two branches instead of an explicit OR instruction with a
7409 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7410 isX86LogicalCmp(Cmp)) {
7411 CC = Cond.getOperand(0).getOperand(0);
7412 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7413 Chain, Dest, CC, Cmp);
7414 CC = Cond.getOperand(1).getOperand(0);
7418 } else { // ISD::AND
7419 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7420 // two branches instead of an explicit AND instruction with a
7421 // separate test. However, we only do this if this block doesn't
7422 // have a fall-through edge, because this requires an explicit
7423 // jmp when the condition is false.
7424 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7425 isX86LogicalCmp(Cmp) &&
7426 Op.getNode()->hasOneUse()) {
7427 X86::CondCode CCode =
7428 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7429 CCode = X86::GetOppositeBranchCondition(CCode);
7430 CC = DAG.getConstant(CCode, MVT::i8);
7431 SDNode *User = *Op.getNode()->use_begin();
7432 // Look for an unconditional branch following this conditional branch.
7433 // We need this because we need to reverse the successors in order
7434 // to implement FCMP_OEQ.
7435 if (User->getOpcode() == ISD::BR) {
7436 SDValue FalseBB = User->getOperand(1);
7438 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7439 assert(NewBR == User);
7443 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7444 Chain, Dest, CC, Cmp);
7445 X86::CondCode CCode =
7446 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7447 CCode = X86::GetOppositeBranchCondition(CCode);
7448 CC = DAG.getConstant(CCode, MVT::i8);
7454 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7455 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7456 // It should be transformed during dag combiner except when the condition
7457 // is set by a arithmetics with overflow node.
7458 X86::CondCode CCode =
7459 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7460 CCode = X86::GetOppositeBranchCondition(CCode);
7461 CC = DAG.getConstant(CCode, MVT::i8);
7462 Cond = Cond.getOperand(0).getOperand(1);
7468 // Look pass the truncate.
7469 if (Cond.getOpcode() == ISD::TRUNCATE)
7470 Cond = Cond.getOperand(0);
7472 // We know the result of AND is compared against zero. Try to match
7474 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7475 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7476 if (NewSetCC.getNode()) {
7477 CC = NewSetCC.getOperand(0);
7478 Cond = NewSetCC.getOperand(1);
7485 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7486 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7488 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7489 Chain, Dest, CC, Cond);
7493 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7494 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7495 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7496 // that the guard pages used by the OS virtual memory manager are allocated in
7497 // correct sequence.
7499 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7500 SelectionDAG &DAG) const {
7501 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
7502 "This should be used only on Windows targets");
7503 DebugLoc dl = Op.getDebugLoc();
7506 SDValue Chain = Op.getOperand(0);
7507 SDValue Size = Op.getOperand(1);
7508 // FIXME: Ensure alignment here
7512 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7514 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
7515 Flag = Chain.getValue(1);
7517 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
7519 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
7520 Flag = Chain.getValue(1);
7522 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
7524 SDValue Ops1[2] = { Chain.getValue(0), Chain };
7525 return DAG.getMergeValues(Ops1, 2, dl);
7528 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
7529 MachineFunction &MF = DAG.getMachineFunction();
7530 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
7532 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7533 DebugLoc DL = Op.getDebugLoc();
7535 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
7536 // vastart just stores the address of the VarArgsFrameIndex slot into the
7537 // memory location argument.
7538 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7540 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7541 MachinePointerInfo(SV), false, false, 0);
7545 // gp_offset (0 - 6 * 8)
7546 // fp_offset (48 - 48 + 8 * 16)
7547 // overflow_arg_area (point to parameters coming in memory).
7549 SmallVector<SDValue, 8> MemOps;
7550 SDValue FIN = Op.getOperand(1);
7552 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
7553 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
7555 FIN, MachinePointerInfo(SV), false, false, 0);
7556 MemOps.push_back(Store);
7559 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7560 FIN, DAG.getIntPtrConstant(4));
7561 Store = DAG.getStore(Op.getOperand(0), DL,
7562 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
7564 FIN, MachinePointerInfo(SV, 4), false, false, 0);
7565 MemOps.push_back(Store);
7567 // Store ptr to overflow_arg_area
7568 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7569 FIN, DAG.getIntPtrConstant(4));
7570 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7572 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
7573 MachinePointerInfo(SV, 8),
7575 MemOps.push_back(Store);
7577 // Store ptr to reg_save_area.
7578 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7579 FIN, DAG.getIntPtrConstant(8));
7580 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
7582 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
7583 MachinePointerInfo(SV, 16), false, false, 0);
7584 MemOps.push_back(Store);
7585 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
7586 &MemOps[0], MemOps.size());
7589 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
7590 assert(Subtarget->is64Bit() &&
7591 "LowerVAARG only handles 64-bit va_arg!");
7592 assert((Subtarget->isTargetLinux() ||
7593 Subtarget->isTargetDarwin()) &&
7594 "Unhandled target in LowerVAARG");
7595 assert(Op.getNode()->getNumOperands() == 4);
7596 SDValue Chain = Op.getOperand(0);
7597 SDValue SrcPtr = Op.getOperand(1);
7598 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7599 unsigned Align = Op.getConstantOperandVal(3);
7600 DebugLoc dl = Op.getDebugLoc();
7602 EVT ArgVT = Op.getNode()->getValueType(0);
7603 const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7604 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
7607 // Decide which area this value should be read from.
7608 // TODO: Implement the AMD64 ABI in its entirety. This simple
7609 // selection mechanism works only for the basic types.
7610 if (ArgVT == MVT::f80) {
7611 llvm_unreachable("va_arg for f80 not yet implemented");
7612 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
7613 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
7614 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
7615 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
7617 llvm_unreachable("Unhandled argument type in LowerVAARG");
7621 // Sanity Check: Make sure using fp_offset makes sense.
7622 assert(!UseSoftFloat &&
7623 !(DAG.getMachineFunction()
7624 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
7625 Subtarget->hasXMM());
7628 // Insert VAARG_64 node into the DAG
7629 // VAARG_64 returns two values: Variable Argument Address, Chain
7630 SmallVector<SDValue, 11> InstOps;
7631 InstOps.push_back(Chain);
7632 InstOps.push_back(SrcPtr);
7633 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
7634 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
7635 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
7636 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
7637 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
7638 VTs, &InstOps[0], InstOps.size(),
7640 MachinePointerInfo(SV),
7645 Chain = VAARG.getValue(1);
7647 // Load the next argument and return it
7648 return DAG.getLoad(ArgVT, dl,
7651 MachinePointerInfo(),
7655 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
7656 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
7657 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
7658 SDValue Chain = Op.getOperand(0);
7659 SDValue DstPtr = Op.getOperand(1);
7660 SDValue SrcPtr = Op.getOperand(2);
7661 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
7662 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7663 DebugLoc DL = Op.getDebugLoc();
7665 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
7666 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
7668 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
7672 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
7673 DebugLoc dl = Op.getDebugLoc();
7674 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7676 default: return SDValue(); // Don't custom lower most intrinsics.
7677 // Comparison intrinsics.
7678 case Intrinsic::x86_sse_comieq_ss:
7679 case Intrinsic::x86_sse_comilt_ss:
7680 case Intrinsic::x86_sse_comile_ss:
7681 case Intrinsic::x86_sse_comigt_ss:
7682 case Intrinsic::x86_sse_comige_ss:
7683 case Intrinsic::x86_sse_comineq_ss:
7684 case Intrinsic::x86_sse_ucomieq_ss:
7685 case Intrinsic::x86_sse_ucomilt_ss:
7686 case Intrinsic::x86_sse_ucomile_ss:
7687 case Intrinsic::x86_sse_ucomigt_ss:
7688 case Intrinsic::x86_sse_ucomige_ss:
7689 case Intrinsic::x86_sse_ucomineq_ss:
7690 case Intrinsic::x86_sse2_comieq_sd:
7691 case Intrinsic::x86_sse2_comilt_sd:
7692 case Intrinsic::x86_sse2_comile_sd:
7693 case Intrinsic::x86_sse2_comigt_sd:
7694 case Intrinsic::x86_sse2_comige_sd:
7695 case Intrinsic::x86_sse2_comineq_sd:
7696 case Intrinsic::x86_sse2_ucomieq_sd:
7697 case Intrinsic::x86_sse2_ucomilt_sd:
7698 case Intrinsic::x86_sse2_ucomile_sd:
7699 case Intrinsic::x86_sse2_ucomigt_sd:
7700 case Intrinsic::x86_sse2_ucomige_sd:
7701 case Intrinsic::x86_sse2_ucomineq_sd: {
7703 ISD::CondCode CC = ISD::SETCC_INVALID;
7706 case Intrinsic::x86_sse_comieq_ss:
7707 case Intrinsic::x86_sse2_comieq_sd:
7711 case Intrinsic::x86_sse_comilt_ss:
7712 case Intrinsic::x86_sse2_comilt_sd:
7716 case Intrinsic::x86_sse_comile_ss:
7717 case Intrinsic::x86_sse2_comile_sd:
7721 case Intrinsic::x86_sse_comigt_ss:
7722 case Intrinsic::x86_sse2_comigt_sd:
7726 case Intrinsic::x86_sse_comige_ss:
7727 case Intrinsic::x86_sse2_comige_sd:
7731 case Intrinsic::x86_sse_comineq_ss:
7732 case Intrinsic::x86_sse2_comineq_sd:
7736 case Intrinsic::x86_sse_ucomieq_ss:
7737 case Intrinsic::x86_sse2_ucomieq_sd:
7738 Opc = X86ISD::UCOMI;
7741 case Intrinsic::x86_sse_ucomilt_ss:
7742 case Intrinsic::x86_sse2_ucomilt_sd:
7743 Opc = X86ISD::UCOMI;
7746 case Intrinsic::x86_sse_ucomile_ss:
7747 case Intrinsic::x86_sse2_ucomile_sd:
7748 Opc = X86ISD::UCOMI;
7751 case Intrinsic::x86_sse_ucomigt_ss:
7752 case Intrinsic::x86_sse2_ucomigt_sd:
7753 Opc = X86ISD::UCOMI;
7756 case Intrinsic::x86_sse_ucomige_ss:
7757 case Intrinsic::x86_sse2_ucomige_sd:
7758 Opc = X86ISD::UCOMI;
7761 case Intrinsic::x86_sse_ucomineq_ss:
7762 case Intrinsic::x86_sse2_ucomineq_sd:
7763 Opc = X86ISD::UCOMI;
7768 SDValue LHS = Op.getOperand(1);
7769 SDValue RHS = Op.getOperand(2);
7770 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
7771 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
7772 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
7773 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7774 DAG.getConstant(X86CC, MVT::i8), Cond);
7775 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7777 // ptest and testp intrinsics. The intrinsic these come from are designed to
7778 // return an integer value, not just an instruction so lower it to the ptest
7779 // or testp pattern and a setcc for the result.
7780 case Intrinsic::x86_sse41_ptestz:
7781 case Intrinsic::x86_sse41_ptestc:
7782 case Intrinsic::x86_sse41_ptestnzc:
7783 case Intrinsic::x86_avx_ptestz_256:
7784 case Intrinsic::x86_avx_ptestc_256:
7785 case Intrinsic::x86_avx_ptestnzc_256:
7786 case Intrinsic::x86_avx_vtestz_ps:
7787 case Intrinsic::x86_avx_vtestc_ps:
7788 case Intrinsic::x86_avx_vtestnzc_ps:
7789 case Intrinsic::x86_avx_vtestz_pd:
7790 case Intrinsic::x86_avx_vtestc_pd:
7791 case Intrinsic::x86_avx_vtestnzc_pd:
7792 case Intrinsic::x86_avx_vtestz_ps_256:
7793 case Intrinsic::x86_avx_vtestc_ps_256:
7794 case Intrinsic::x86_avx_vtestnzc_ps_256:
7795 case Intrinsic::x86_avx_vtestz_pd_256:
7796 case Intrinsic::x86_avx_vtestc_pd_256:
7797 case Intrinsic::x86_avx_vtestnzc_pd_256: {
7798 bool IsTestPacked = false;
7801 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
7802 case Intrinsic::x86_avx_vtestz_ps:
7803 case Intrinsic::x86_avx_vtestz_pd:
7804 case Intrinsic::x86_avx_vtestz_ps_256:
7805 case Intrinsic::x86_avx_vtestz_pd_256:
7806 IsTestPacked = true; // Fallthrough
7807 case Intrinsic::x86_sse41_ptestz:
7808 case Intrinsic::x86_avx_ptestz_256:
7810 X86CC = X86::COND_E;
7812 case Intrinsic::x86_avx_vtestc_ps:
7813 case Intrinsic::x86_avx_vtestc_pd:
7814 case Intrinsic::x86_avx_vtestc_ps_256:
7815 case Intrinsic::x86_avx_vtestc_pd_256:
7816 IsTestPacked = true; // Fallthrough
7817 case Intrinsic::x86_sse41_ptestc:
7818 case Intrinsic::x86_avx_ptestc_256:
7820 X86CC = X86::COND_B;
7822 case Intrinsic::x86_avx_vtestnzc_ps:
7823 case Intrinsic::x86_avx_vtestnzc_pd:
7824 case Intrinsic::x86_avx_vtestnzc_ps_256:
7825 case Intrinsic::x86_avx_vtestnzc_pd_256:
7826 IsTestPacked = true; // Fallthrough
7827 case Intrinsic::x86_sse41_ptestnzc:
7828 case Intrinsic::x86_avx_ptestnzc_256:
7830 X86CC = X86::COND_A;
7834 SDValue LHS = Op.getOperand(1);
7835 SDValue RHS = Op.getOperand(2);
7836 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
7837 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
7838 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
7839 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
7840 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7843 // Fix vector shift instructions where the last operand is a non-immediate
7845 case Intrinsic::x86_sse2_pslli_w:
7846 case Intrinsic::x86_sse2_pslli_d:
7847 case Intrinsic::x86_sse2_pslli_q:
7848 case Intrinsic::x86_sse2_psrli_w:
7849 case Intrinsic::x86_sse2_psrli_d:
7850 case Intrinsic::x86_sse2_psrli_q:
7851 case Intrinsic::x86_sse2_psrai_w:
7852 case Intrinsic::x86_sse2_psrai_d:
7853 case Intrinsic::x86_mmx_pslli_w:
7854 case Intrinsic::x86_mmx_pslli_d:
7855 case Intrinsic::x86_mmx_pslli_q:
7856 case Intrinsic::x86_mmx_psrli_w:
7857 case Intrinsic::x86_mmx_psrli_d:
7858 case Intrinsic::x86_mmx_psrli_q:
7859 case Intrinsic::x86_mmx_psrai_w:
7860 case Intrinsic::x86_mmx_psrai_d: {
7861 SDValue ShAmt = Op.getOperand(2);
7862 if (isa<ConstantSDNode>(ShAmt))
7865 unsigned NewIntNo = 0;
7866 EVT ShAmtVT = MVT::v4i32;
7868 case Intrinsic::x86_sse2_pslli_w:
7869 NewIntNo = Intrinsic::x86_sse2_psll_w;
7871 case Intrinsic::x86_sse2_pslli_d:
7872 NewIntNo = Intrinsic::x86_sse2_psll_d;
7874 case Intrinsic::x86_sse2_pslli_q:
7875 NewIntNo = Intrinsic::x86_sse2_psll_q;
7877 case Intrinsic::x86_sse2_psrli_w:
7878 NewIntNo = Intrinsic::x86_sse2_psrl_w;
7880 case Intrinsic::x86_sse2_psrli_d:
7881 NewIntNo = Intrinsic::x86_sse2_psrl_d;
7883 case Intrinsic::x86_sse2_psrli_q:
7884 NewIntNo = Intrinsic::x86_sse2_psrl_q;
7886 case Intrinsic::x86_sse2_psrai_w:
7887 NewIntNo = Intrinsic::x86_sse2_psra_w;
7889 case Intrinsic::x86_sse2_psrai_d:
7890 NewIntNo = Intrinsic::x86_sse2_psra_d;
7893 ShAmtVT = MVT::v2i32;
7895 case Intrinsic::x86_mmx_pslli_w:
7896 NewIntNo = Intrinsic::x86_mmx_psll_w;
7898 case Intrinsic::x86_mmx_pslli_d:
7899 NewIntNo = Intrinsic::x86_mmx_psll_d;
7901 case Intrinsic::x86_mmx_pslli_q:
7902 NewIntNo = Intrinsic::x86_mmx_psll_q;
7904 case Intrinsic::x86_mmx_psrli_w:
7905 NewIntNo = Intrinsic::x86_mmx_psrl_w;
7907 case Intrinsic::x86_mmx_psrli_d:
7908 NewIntNo = Intrinsic::x86_mmx_psrl_d;
7910 case Intrinsic::x86_mmx_psrli_q:
7911 NewIntNo = Intrinsic::x86_mmx_psrl_q;
7913 case Intrinsic::x86_mmx_psrai_w:
7914 NewIntNo = Intrinsic::x86_mmx_psra_w;
7916 case Intrinsic::x86_mmx_psrai_d:
7917 NewIntNo = Intrinsic::x86_mmx_psra_d;
7919 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7925 // The vector shift intrinsics with scalars uses 32b shift amounts but
7926 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
7930 ShOps[1] = DAG.getConstant(0, MVT::i32);
7931 if (ShAmtVT == MVT::v4i32) {
7932 ShOps[2] = DAG.getUNDEF(MVT::i32);
7933 ShOps[3] = DAG.getUNDEF(MVT::i32);
7934 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
7936 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
7937 // FIXME this must be lowered to get rid of the invalid type.
7940 EVT VT = Op.getValueType();
7941 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
7942 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7943 DAG.getConstant(NewIntNo, MVT::i32),
7944 Op.getOperand(1), ShAmt);
7949 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
7950 SelectionDAG &DAG) const {
7951 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7952 MFI->setReturnAddressIsTaken(true);
7954 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7955 DebugLoc dl = Op.getDebugLoc();
7958 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7960 DAG.getConstant(TD->getPointerSize(),
7961 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
7962 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7963 DAG.getNode(ISD::ADD, dl, getPointerTy(),
7965 MachinePointerInfo(), false, false, 0);
7968 // Just load the return address.
7969 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
7970 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7971 RetAddrFI, MachinePointerInfo(), false, false, 0);
7974 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
7975 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7976 MFI->setFrameAddressIsTaken(true);
7978 EVT VT = Op.getValueType();
7979 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
7980 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7981 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
7982 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
7984 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
7985 MachinePointerInfo(),
7990 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
7991 SelectionDAG &DAG) const {
7992 return DAG.getIntPtrConstant(2*TD->getPointerSize());
7995 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
7996 MachineFunction &MF = DAG.getMachineFunction();
7997 SDValue Chain = Op.getOperand(0);
7998 SDValue Offset = Op.getOperand(1);
7999 SDValue Handler = Op.getOperand(2);
8000 DebugLoc dl = Op.getDebugLoc();
8002 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8003 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8005 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8007 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8008 DAG.getIntPtrConstant(TD->getPointerSize()));
8009 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8010 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8012 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8013 MF.getRegInfo().addLiveOut(StoreAddrReg);
8015 return DAG.getNode(X86ISD::EH_RETURN, dl,
8017 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8020 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8021 SelectionDAG &DAG) const {
8022 SDValue Root = Op.getOperand(0);
8023 SDValue Trmp = Op.getOperand(1); // trampoline
8024 SDValue FPtr = Op.getOperand(2); // nested function
8025 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8026 DebugLoc dl = Op.getDebugLoc();
8028 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8030 if (Subtarget->is64Bit()) {
8031 SDValue OutChains[6];
8033 // Large code-model.
8034 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
8035 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8037 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8038 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8040 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8042 // Load the pointer to the nested function into R11.
8043 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8044 SDValue Addr = Trmp;
8045 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8046 Addr, MachinePointerInfo(TrmpAddr),
8049 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8050 DAG.getConstant(2, MVT::i64));
8051 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8052 MachinePointerInfo(TrmpAddr, 2),
8055 // Load the 'nest' parameter value into R10.
8056 // R10 is specified in X86CallingConv.td
8057 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8058 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8059 DAG.getConstant(10, MVT::i64));
8060 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8061 Addr, MachinePointerInfo(TrmpAddr, 10),
8064 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8065 DAG.getConstant(12, MVT::i64));
8066 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8067 MachinePointerInfo(TrmpAddr, 12),
8070 // Jump to the nested function.
8071 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8072 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8073 DAG.getConstant(20, MVT::i64));
8074 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8075 Addr, MachinePointerInfo(TrmpAddr, 20),
8078 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8079 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8080 DAG.getConstant(22, MVT::i64));
8081 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8082 MachinePointerInfo(TrmpAddr, 22),
8086 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8087 return DAG.getMergeValues(Ops, 2, dl);
8089 const Function *Func =
8090 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8091 CallingConv::ID CC = Func->getCallingConv();
8096 llvm_unreachable("Unsupported calling convention");
8097 case CallingConv::C:
8098 case CallingConv::X86_StdCall: {
8099 // Pass 'nest' parameter in ECX.
8100 // Must be kept in sync with X86CallingConv.td
8103 // Check that ECX wasn't needed by an 'inreg' parameter.
8104 const FunctionType *FTy = Func->getFunctionType();
8105 const AttrListPtr &Attrs = Func->getAttributes();
8107 if (!Attrs.isEmpty() && !Func->isVarArg()) {
8108 unsigned InRegCount = 0;
8111 for (FunctionType::param_iterator I = FTy->param_begin(),
8112 E = FTy->param_end(); I != E; ++I, ++Idx)
8113 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8114 // FIXME: should only count parameters that are lowered to integers.
8115 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8117 if (InRegCount > 2) {
8118 report_fatal_error("Nest register in use - reduce number of inreg"
8124 case CallingConv::X86_FastCall:
8125 case CallingConv::X86_ThisCall:
8126 case CallingConv::Fast:
8127 // Pass 'nest' parameter in EAX.
8128 // Must be kept in sync with X86CallingConv.td
8133 SDValue OutChains[4];
8136 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8137 DAG.getConstant(10, MVT::i32));
8138 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8140 // This is storing the opcode for MOV32ri.
8141 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8142 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8143 OutChains[0] = DAG.getStore(Root, dl,
8144 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8145 Trmp, MachinePointerInfo(TrmpAddr),
8148 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8149 DAG.getConstant(1, MVT::i32));
8150 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8151 MachinePointerInfo(TrmpAddr, 1),
8154 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8155 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8156 DAG.getConstant(5, MVT::i32));
8157 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8158 MachinePointerInfo(TrmpAddr, 5),
8161 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8162 DAG.getConstant(6, MVT::i32));
8163 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8164 MachinePointerInfo(TrmpAddr, 6),
8168 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8169 return DAG.getMergeValues(Ops, 2, dl);
8173 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8174 SelectionDAG &DAG) const {
8176 The rounding mode is in bits 11:10 of FPSR, and has the following
8183 FLT_ROUNDS, on the other hand, expects the following:
8190 To perform the conversion, we do:
8191 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8194 MachineFunction &MF = DAG.getMachineFunction();
8195 const TargetMachine &TM = MF.getTarget();
8196 const TargetFrameInfo &TFI = *TM.getFrameInfo();
8197 unsigned StackAlignment = TFI.getStackAlignment();
8198 EVT VT = Op.getValueType();
8199 DebugLoc DL = Op.getDebugLoc();
8201 // Save FP Control Word to stack slot
8202 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8203 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8206 MachineMemOperand *MMO =
8207 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8208 MachineMemOperand::MOStore, 2, 2);
8210 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8211 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8212 DAG.getVTList(MVT::Other),
8213 Ops, 2, MVT::i16, MMO);
8215 // Load FP Control Word from stack slot
8216 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8217 MachinePointerInfo(), false, false, 0);
8219 // Transform as necessary
8221 DAG.getNode(ISD::SRL, DL, MVT::i16,
8222 DAG.getNode(ISD::AND, DL, MVT::i16,
8223 CWD, DAG.getConstant(0x800, MVT::i16)),
8224 DAG.getConstant(11, MVT::i8));
8226 DAG.getNode(ISD::SRL, DL, MVT::i16,
8227 DAG.getNode(ISD::AND, DL, MVT::i16,
8228 CWD, DAG.getConstant(0x400, MVT::i16)),
8229 DAG.getConstant(9, MVT::i8));
8232 DAG.getNode(ISD::AND, DL, MVT::i16,
8233 DAG.getNode(ISD::ADD, DL, MVT::i16,
8234 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8235 DAG.getConstant(1, MVT::i16)),
8236 DAG.getConstant(3, MVT::i16));
8239 return DAG.getNode((VT.getSizeInBits() < 16 ?
8240 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8243 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8244 EVT VT = Op.getValueType();
8246 unsigned NumBits = VT.getSizeInBits();
8247 DebugLoc dl = Op.getDebugLoc();
8249 Op = Op.getOperand(0);
8250 if (VT == MVT::i8) {
8251 // Zero extend to i32 since there is not an i8 bsr.
8253 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8256 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8257 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8258 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8260 // If src is zero (i.e. bsr sets ZF), returns NumBits.
8263 DAG.getConstant(NumBits+NumBits-1, OpVT),
8264 DAG.getConstant(X86::COND_E, MVT::i8),
8267 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8269 // Finally xor with NumBits-1.
8270 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8273 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8277 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8278 EVT VT = Op.getValueType();
8280 unsigned NumBits = VT.getSizeInBits();
8281 DebugLoc dl = Op.getDebugLoc();
8283 Op = Op.getOperand(0);
8284 if (VT == MVT::i8) {
8286 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8289 // Issue a bsf (scan bits forward) which also sets EFLAGS.
8290 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8291 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8293 // If src is zero (i.e. bsf sets ZF), returns NumBits.
8296 DAG.getConstant(NumBits, OpVT),
8297 DAG.getConstant(X86::COND_E, MVT::i8),
8300 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8303 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8307 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8308 EVT VT = Op.getValueType();
8309 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8310 DebugLoc dl = Op.getDebugLoc();
8312 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8313 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8314 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8315 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8316 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8318 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8319 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8320 // return AloBlo + AloBhi + AhiBlo;
8322 SDValue A = Op.getOperand(0);
8323 SDValue B = Op.getOperand(1);
8325 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8326 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8327 A, DAG.getConstant(32, MVT::i32));
8328 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8329 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8330 B, DAG.getConstant(32, MVT::i32));
8331 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8332 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8334 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8335 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8337 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8338 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8340 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8341 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8342 AloBhi, DAG.getConstant(32, MVT::i32));
8343 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8344 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8345 AhiBlo, DAG.getConstant(32, MVT::i32));
8346 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8347 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8351 SDValue X86TargetLowering::LowerSHL(SDValue Op, SelectionDAG &DAG) const {
8352 EVT VT = Op.getValueType();
8353 DebugLoc dl = Op.getDebugLoc();
8354 SDValue R = Op.getOperand(0);
8356 LLVMContext *Context = DAG.getContext();
8358 assert(Subtarget->hasSSE41() && "Cannot lower SHL without SSE4.1 or later");
8360 if (VT == MVT::v4i32) {
8361 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8362 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8363 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8365 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8367 std::vector<Constant*> CV(4, CI);
8368 Constant *C = ConstantVector::get(CV);
8369 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8370 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8371 MachinePointerInfo::getConstantPool(),
8374 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8375 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8376 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8377 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8379 if (VT == MVT::v16i8) {
8381 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8382 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8383 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8385 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8386 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8388 std::vector<Constant*> CVM1(16, CM1);
8389 std::vector<Constant*> CVM2(16, CM2);
8390 Constant *C = ConstantVector::get(CVM1);
8391 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8392 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8393 MachinePointerInfo::getConstantPool(),
8396 // r = pblendv(r, psllw(r & (char16)15, 4), a);
8397 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8398 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8399 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8400 DAG.getConstant(4, MVT::i32));
8401 R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8402 DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8405 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8407 C = ConstantVector::get(CVM2);
8408 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8409 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8410 MachinePointerInfo::getConstantPool(),
8413 // r = pblendv(r, psllw(r & (char16)63, 2), a);
8414 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8415 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8416 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8417 DAG.getConstant(2, MVT::i32));
8418 R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8419 DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8422 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8424 // return pblendv(r, r+r, a);
8425 R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8426 DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8427 R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8433 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8434 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8435 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8436 // looks for this combo and may remove the "setcc" instruction if the "setcc"
8437 // has only one use.
8438 SDNode *N = Op.getNode();
8439 SDValue LHS = N->getOperand(0);
8440 SDValue RHS = N->getOperand(1);
8441 unsigned BaseOp = 0;
8443 DebugLoc DL = Op.getDebugLoc();
8444 switch (Op.getOpcode()) {
8445 default: llvm_unreachable("Unknown ovf instruction!");
8447 // A subtract of one will be selected as a INC. Note that INC doesn't
8448 // set CF, so we can't do this for UADDO.
8449 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8450 if (C->getAPIntValue() == 1) {
8451 BaseOp = X86ISD::INC;
8455 BaseOp = X86ISD::ADD;
8459 BaseOp = X86ISD::ADD;
8463 // A subtract of one will be selected as a DEC. Note that DEC doesn't
8464 // set CF, so we can't do this for USUBO.
8465 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8466 if (C->getAPIntValue() == 1) {
8467 BaseOp = X86ISD::DEC;
8471 BaseOp = X86ISD::SUB;
8475 BaseOp = X86ISD::SUB;
8479 BaseOp = X86ISD::SMUL;
8482 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
8483 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
8485 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
8488 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8489 DAG.getConstant(X86::COND_O, MVT::i32),
8490 SDValue(Sum.getNode(), 2));
8492 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8497 // Also sets EFLAGS.
8498 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
8499 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
8502 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
8503 DAG.getConstant(Cond, MVT::i32),
8504 SDValue(Sum.getNode(), 1));
8506 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8510 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
8511 DebugLoc dl = Op.getDebugLoc();
8513 if (!Subtarget->hasSSE2()) {
8514 SDValue Chain = Op.getOperand(0);
8515 SDValue Zero = DAG.getConstant(0,
8516 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8518 DAG.getRegister(X86::ESP, MVT::i32), // Base
8519 DAG.getTargetConstant(1, MVT::i8), // Scale
8520 DAG.getRegister(0, MVT::i32), // Index
8521 DAG.getTargetConstant(0, MVT::i32), // Disp
8522 DAG.getRegister(0, MVT::i32), // Segment.
8527 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
8528 array_lengthof(Ops));
8529 return SDValue(Res, 0);
8532 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
8534 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
8536 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8537 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8538 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
8539 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
8541 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
8542 if (!Op1 && !Op2 && !Op3 && Op4)
8543 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
8545 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
8546 if (Op1 && !Op2 && !Op3 && !Op4)
8547 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
8549 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
8551 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
8554 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8555 EVT T = Op.getValueType();
8556 DebugLoc DL = Op.getDebugLoc();
8559 switch(T.getSimpleVT().SimpleTy) {
8561 assert(false && "Invalid value type!");
8562 case MVT::i8: Reg = X86::AL; size = 1; break;
8563 case MVT::i16: Reg = X86::AX; size = 2; break;
8564 case MVT::i32: Reg = X86::EAX; size = 4; break;
8566 assert(Subtarget->is64Bit() && "Node not type legal!");
8567 Reg = X86::RAX; size = 8;
8570 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
8571 Op.getOperand(2), SDValue());
8572 SDValue Ops[] = { cpIn.getValue(0),
8575 DAG.getTargetConstant(size, MVT::i8),
8577 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8578 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
8579 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
8582 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
8586 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
8587 SelectionDAG &DAG) const {
8588 assert(Subtarget->is64Bit() && "Result not type legalized?");
8589 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8590 SDValue TheChain = Op.getOperand(0);
8591 DebugLoc dl = Op.getDebugLoc();
8592 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8593 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
8594 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
8596 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
8597 DAG.getConstant(32, MVT::i8));
8599 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
8602 return DAG.getMergeValues(Ops, 2, dl);
8605 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
8606 SelectionDAG &DAG) const {
8607 EVT SrcVT = Op.getOperand(0).getValueType();
8608 EVT DstVT = Op.getValueType();
8609 assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
8610 Subtarget->hasMMX() && "Unexpected custom BITCAST");
8611 assert((DstVT == MVT::i64 ||
8612 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
8613 "Unexpected custom BITCAST");
8614 // i64 <=> MMX conversions are Legal.
8615 if (SrcVT==MVT::i64 && DstVT.isVector())
8617 if (DstVT==MVT::i64 && SrcVT.isVector())
8619 // MMX <=> MMX conversions are Legal.
8620 if (SrcVT.isVector() && DstVT.isVector())
8622 // All other conversions need to be expanded.
8626 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
8627 SDNode *Node = Op.getNode();
8628 DebugLoc dl = Node->getDebugLoc();
8629 EVT T = Node->getValueType(0);
8630 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
8631 DAG.getConstant(0, T), Node->getOperand(2));
8632 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
8633 cast<AtomicSDNode>(Node)->getMemoryVT(),
8634 Node->getOperand(0),
8635 Node->getOperand(1), negOp,
8636 cast<AtomicSDNode>(Node)->getSrcValue(),
8637 cast<AtomicSDNode>(Node)->getAlignment());
8640 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
8641 EVT VT = Op.getNode()->getValueType(0);
8643 // Let legalize expand this if it isn't a legal type yet.
8644 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8647 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
8650 bool ExtraOp = false;
8651 switch (Op.getOpcode()) {
8652 default: assert(0 && "Invalid code");
8653 case ISD::ADDC: Opc = X86ISD::ADD; break;
8654 case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
8655 case ISD::SUBC: Opc = X86ISD::SUB; break;
8656 case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
8660 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
8662 return DAG.getNode(Opc, Op->getDebugLoc(), VTs, Op.getOperand(0),
8663 Op.getOperand(1), Op.getOperand(2));
8666 /// LowerOperation - Provide custom lowering hooks for some operations.
8668 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8669 switch (Op.getOpcode()) {
8670 default: llvm_unreachable("Should not custom lower this!");
8671 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
8672 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
8673 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
8674 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
8675 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
8676 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
8677 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8678 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
8679 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
8680 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
8681 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
8682 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
8683 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
8684 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
8685 case ISD::SHL_PARTS:
8686 case ISD::SRA_PARTS:
8687 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
8688 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
8689 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
8690 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
8691 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
8692 case ISD::FABS: return LowerFABS(Op, DAG);
8693 case ISD::FNEG: return LowerFNEG(Op, DAG);
8694 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
8695 case ISD::SETCC: return LowerSETCC(Op, DAG);
8696 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
8697 case ISD::SELECT: return LowerSELECT(Op, DAG);
8698 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
8699 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
8700 case ISD::VASTART: return LowerVASTART(Op, DAG);
8701 case ISD::VAARG: return LowerVAARG(Op, DAG);
8702 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
8703 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8704 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
8705 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
8706 case ISD::FRAME_TO_ARGS_OFFSET:
8707 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
8708 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
8709 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
8710 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
8711 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
8712 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
8713 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
8714 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
8715 case ISD::SHL: return LowerSHL(Op, DAG);
8721 case ISD::UMULO: return LowerXALUO(Op, DAG);
8722 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
8723 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
8727 case ISD::SUBE: return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
8731 void X86TargetLowering::
8732 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
8733 SelectionDAG &DAG, unsigned NewOp) const {
8734 EVT T = Node->getValueType(0);
8735 DebugLoc dl = Node->getDebugLoc();
8736 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
8738 SDValue Chain = Node->getOperand(0);
8739 SDValue In1 = Node->getOperand(1);
8740 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8741 Node->getOperand(2), DAG.getIntPtrConstant(0));
8742 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8743 Node->getOperand(2), DAG.getIntPtrConstant(1));
8744 SDValue Ops[] = { Chain, In1, In2L, In2H };
8745 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8747 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
8748 cast<MemSDNode>(Node)->getMemOperand());
8749 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
8750 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8751 Results.push_back(Result.getValue(2));
8754 /// ReplaceNodeResults - Replace a node with an illegal result type
8755 /// with a new node built out of custom code.
8756 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
8757 SmallVectorImpl<SDValue>&Results,
8758 SelectionDAG &DAG) const {
8759 DebugLoc dl = N->getDebugLoc();
8760 switch (N->getOpcode()) {
8762 assert(false && "Do not know how to custom type legalize this operation!");
8768 // We don't want to expand or promote these.
8770 case ISD::FP_TO_SINT: {
8771 std::pair<SDValue,SDValue> Vals =
8772 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
8773 SDValue FIST = Vals.first, StackSlot = Vals.second;
8774 if (FIST.getNode() != 0) {
8775 EVT VT = N->getValueType(0);
8776 // Return a load from the stack slot.
8777 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
8778 MachinePointerInfo(), false, false, 0));
8782 case ISD::READCYCLECOUNTER: {
8783 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8784 SDValue TheChain = N->getOperand(0);
8785 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8786 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
8788 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
8790 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
8791 SDValue Ops[] = { eax, edx };
8792 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
8793 Results.push_back(edx.getValue(1));
8796 case ISD::ATOMIC_CMP_SWAP: {
8797 EVT T = N->getValueType(0);
8798 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
8799 SDValue cpInL, cpInH;
8800 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8801 DAG.getConstant(0, MVT::i32));
8802 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8803 DAG.getConstant(1, MVT::i32));
8804 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
8805 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
8807 SDValue swapInL, swapInH;
8808 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8809 DAG.getConstant(0, MVT::i32));
8810 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8811 DAG.getConstant(1, MVT::i32));
8812 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
8814 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
8815 swapInL.getValue(1));
8816 SDValue Ops[] = { swapInH.getValue(0),
8818 swapInH.getValue(1) };
8819 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8820 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
8821 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
8823 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
8824 MVT::i32, Result.getValue(1));
8825 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
8826 MVT::i32, cpOutL.getValue(2));
8827 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
8828 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8829 Results.push_back(cpOutH.getValue(1));
8832 case ISD::ATOMIC_LOAD_ADD:
8833 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
8835 case ISD::ATOMIC_LOAD_AND:
8836 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
8838 case ISD::ATOMIC_LOAD_NAND:
8839 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
8841 case ISD::ATOMIC_LOAD_OR:
8842 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
8844 case ISD::ATOMIC_LOAD_SUB:
8845 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
8847 case ISD::ATOMIC_LOAD_XOR:
8848 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
8850 case ISD::ATOMIC_SWAP:
8851 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
8856 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
8858 default: return NULL;
8859 case X86ISD::BSF: return "X86ISD::BSF";
8860 case X86ISD::BSR: return "X86ISD::BSR";
8861 case X86ISD::SHLD: return "X86ISD::SHLD";
8862 case X86ISD::SHRD: return "X86ISD::SHRD";
8863 case X86ISD::FAND: return "X86ISD::FAND";
8864 case X86ISD::FOR: return "X86ISD::FOR";
8865 case X86ISD::FXOR: return "X86ISD::FXOR";
8866 case X86ISD::FSRL: return "X86ISD::FSRL";
8867 case X86ISD::FILD: return "X86ISD::FILD";
8868 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
8869 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
8870 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
8871 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
8872 case X86ISD::FLD: return "X86ISD::FLD";
8873 case X86ISD::FST: return "X86ISD::FST";
8874 case X86ISD::CALL: return "X86ISD::CALL";
8875 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
8876 case X86ISD::BT: return "X86ISD::BT";
8877 case X86ISD::CMP: return "X86ISD::CMP";
8878 case X86ISD::COMI: return "X86ISD::COMI";
8879 case X86ISD::UCOMI: return "X86ISD::UCOMI";
8880 case X86ISD::SETCC: return "X86ISD::SETCC";
8881 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
8882 case X86ISD::CMOV: return "X86ISD::CMOV";
8883 case X86ISD::BRCOND: return "X86ISD::BRCOND";
8884 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
8885 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
8886 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
8887 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
8888 case X86ISD::Wrapper: return "X86ISD::Wrapper";
8889 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
8890 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
8891 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
8892 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
8893 case X86ISD::PINSRB: return "X86ISD::PINSRB";
8894 case X86ISD::PINSRW: return "X86ISD::PINSRW";
8895 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
8896 case X86ISD::PANDN: return "X86ISD::PANDN";
8897 case X86ISD::PSIGNB: return "X86ISD::PSIGNB";
8898 case X86ISD::PSIGNW: return "X86ISD::PSIGNW";
8899 case X86ISD::PSIGND: return "X86ISD::PSIGND";
8900 case X86ISD::FMAX: return "X86ISD::FMAX";
8901 case X86ISD::FMIN: return "X86ISD::FMIN";
8902 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
8903 case X86ISD::FRCP: return "X86ISD::FRCP";
8904 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
8905 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
8906 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
8907 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
8908 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
8909 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
8910 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
8911 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
8912 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
8913 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
8914 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
8915 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
8916 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
8917 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
8918 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
8919 case X86ISD::VSHL: return "X86ISD::VSHL";
8920 case X86ISD::VSRL: return "X86ISD::VSRL";
8921 case X86ISD::CMPPD: return "X86ISD::CMPPD";
8922 case X86ISD::CMPPS: return "X86ISD::CMPPS";
8923 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
8924 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
8925 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
8926 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
8927 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
8928 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
8929 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
8930 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
8931 case X86ISD::ADD: return "X86ISD::ADD";
8932 case X86ISD::SUB: return "X86ISD::SUB";
8933 case X86ISD::ADC: return "X86ISD::ADC";
8934 case X86ISD::SBB: return "X86ISD::SBB";
8935 case X86ISD::SMUL: return "X86ISD::SMUL";
8936 case X86ISD::UMUL: return "X86ISD::UMUL";
8937 case X86ISD::INC: return "X86ISD::INC";
8938 case X86ISD::DEC: return "X86ISD::DEC";
8939 case X86ISD::OR: return "X86ISD::OR";
8940 case X86ISD::XOR: return "X86ISD::XOR";
8941 case X86ISD::AND: return "X86ISD::AND";
8942 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
8943 case X86ISD::PTEST: return "X86ISD::PTEST";
8944 case X86ISD::TESTP: return "X86ISD::TESTP";
8945 case X86ISD::PALIGN: return "X86ISD::PALIGN";
8946 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
8947 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
8948 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
8949 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
8950 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
8951 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
8952 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
8953 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
8954 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
8955 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
8956 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD";
8957 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
8958 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
8959 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
8960 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
8961 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
8962 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
8963 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
8964 case X86ISD::MOVSD: return "X86ISD::MOVSD";
8965 case X86ISD::MOVSS: return "X86ISD::MOVSS";
8966 case X86ISD::UNPCKLPS: return "X86ISD::UNPCKLPS";
8967 case X86ISD::UNPCKLPD: return "X86ISD::UNPCKLPD";
8968 case X86ISD::UNPCKHPS: return "X86ISD::UNPCKHPS";
8969 case X86ISD::UNPCKHPD: return "X86ISD::UNPCKHPD";
8970 case X86ISD::PUNPCKLBW: return "X86ISD::PUNPCKLBW";
8971 case X86ISD::PUNPCKLWD: return "X86ISD::PUNPCKLWD";
8972 case X86ISD::PUNPCKLDQ: return "X86ISD::PUNPCKLDQ";
8973 case X86ISD::PUNPCKLQDQ: return "X86ISD::PUNPCKLQDQ";
8974 case X86ISD::PUNPCKHBW: return "X86ISD::PUNPCKHBW";
8975 case X86ISD::PUNPCKHWD: return "X86ISD::PUNPCKHWD";
8976 case X86ISD::PUNPCKHDQ: return "X86ISD::PUNPCKHDQ";
8977 case X86ISD::PUNPCKHQDQ: return "X86ISD::PUNPCKHQDQ";
8978 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
8979 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
8980 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
8984 // isLegalAddressingMode - Return true if the addressing mode represented
8985 // by AM is legal for this target, for a load/store of the specified type.
8986 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
8987 const Type *Ty) const {
8988 // X86 supports extremely general addressing modes.
8989 CodeModel::Model M = getTargetMachine().getCodeModel();
8990 Reloc::Model R = getTargetMachine().getRelocationModel();
8992 // X86 allows a sign-extended 32-bit immediate field as a displacement.
8993 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
8998 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
9000 // If a reference to this global requires an extra load, we can't fold it.
9001 if (isGlobalStubReference(GVFlags))
9004 // If BaseGV requires a register for the PIC base, we cannot also have a
9005 // BaseReg specified.
9006 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
9009 // If lower 4G is not available, then we must use rip-relative addressing.
9010 if ((M != CodeModel::Small || R != Reloc::Static) &&
9011 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
9021 // These scales always work.
9026 // These scales are formed with basereg+scalereg. Only accept if there is
9031 default: // Other stuff never works.
9039 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
9040 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9042 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9043 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9044 if (NumBits1 <= NumBits2)
9049 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9050 if (!VT1.isInteger() || !VT2.isInteger())
9052 unsigned NumBits1 = VT1.getSizeInBits();
9053 unsigned NumBits2 = VT2.getSizeInBits();
9054 if (NumBits1 <= NumBits2)
9059 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9060 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9061 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9064 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9065 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9066 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9069 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9070 // i16 instructions are longer (0x66 prefix) and potentially slower.
9071 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9074 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9075 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9076 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9077 /// are assumed to be legal.
9079 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9081 // Very little shuffling can be done for 64-bit vectors right now.
9082 if (VT.getSizeInBits() == 64)
9083 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9085 // FIXME: pshufb, blends, shifts.
9086 return (VT.getVectorNumElements() == 2 ||
9087 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9088 isMOVLMask(M, VT) ||
9089 isSHUFPMask(M, VT) ||
9090 isPSHUFDMask(M, VT) ||
9091 isPSHUFHWMask(M, VT) ||
9092 isPSHUFLWMask(M, VT) ||
9093 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9094 isUNPCKLMask(M, VT) ||
9095 isUNPCKHMask(M, VT) ||
9096 isUNPCKL_v_undef_Mask(M, VT) ||
9097 isUNPCKH_v_undef_Mask(M, VT));
9101 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9103 unsigned NumElts = VT.getVectorNumElements();
9104 // FIXME: This collection of masks seems suspect.
9107 if (NumElts == 4 && VT.getSizeInBits() == 128) {
9108 return (isMOVLMask(Mask, VT) ||
9109 isCommutedMOVLMask(Mask, VT, true) ||
9110 isSHUFPMask(Mask, VT) ||
9111 isCommutedSHUFPMask(Mask, VT));
9116 //===----------------------------------------------------------------------===//
9117 // X86 Scheduler Hooks
9118 //===----------------------------------------------------------------------===//
9120 // private utility function
9122 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9123 MachineBasicBlock *MBB,
9130 TargetRegisterClass *RC,
9131 bool invSrc) const {
9132 // For the atomic bitwise operator, we generate
9135 // ld t1 = [bitinstr.addr]
9136 // op t2 = t1, [bitinstr.val]
9138 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9140 // fallthrough -->nextMBB
9141 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9142 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9143 MachineFunction::iterator MBBIter = MBB;
9146 /// First build the CFG
9147 MachineFunction *F = MBB->getParent();
9148 MachineBasicBlock *thisMBB = MBB;
9149 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9150 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9151 F->insert(MBBIter, newMBB);
9152 F->insert(MBBIter, nextMBB);
9154 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9155 nextMBB->splice(nextMBB->begin(), thisMBB,
9156 llvm::next(MachineBasicBlock::iterator(bInstr)),
9158 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9160 // Update thisMBB to fall through to newMBB
9161 thisMBB->addSuccessor(newMBB);
9163 // newMBB jumps to itself and fall through to nextMBB
9164 newMBB->addSuccessor(nextMBB);
9165 newMBB->addSuccessor(newMBB);
9167 // Insert instructions into newMBB based on incoming instruction
9168 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9169 "unexpected number of operands");
9170 DebugLoc dl = bInstr->getDebugLoc();
9171 MachineOperand& destOper = bInstr->getOperand(0);
9172 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9173 int numArgs = bInstr->getNumOperands() - 1;
9174 for (int i=0; i < numArgs; ++i)
9175 argOpers[i] = &bInstr->getOperand(i+1);
9177 // x86 address has 4 operands: base, index, scale, and displacement
9178 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9179 int valArgIndx = lastAddrIndx + 1;
9181 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9182 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9183 for (int i=0; i <= lastAddrIndx; ++i)
9184 (*MIB).addOperand(*argOpers[i]);
9186 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9188 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9193 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9194 assert((argOpers[valArgIndx]->isReg() ||
9195 argOpers[valArgIndx]->isImm()) &&
9197 if (argOpers[valArgIndx]->isReg())
9198 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9200 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9202 (*MIB).addOperand(*argOpers[valArgIndx]);
9204 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9207 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9208 for (int i=0; i <= lastAddrIndx; ++i)
9209 (*MIB).addOperand(*argOpers[i]);
9211 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9212 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9213 bInstr->memoperands_end());
9215 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9219 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9221 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9225 // private utility function: 64 bit atomics on 32 bit host.
9227 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9228 MachineBasicBlock *MBB,
9233 bool invSrc) const {
9234 // For the atomic bitwise operator, we generate
9235 // thisMBB (instructions are in pairs, except cmpxchg8b)
9236 // ld t1,t2 = [bitinstr.addr]
9238 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9239 // op t5, t6 <- out1, out2, [bitinstr.val]
9240 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
9241 // mov ECX, EBX <- t5, t6
9242 // mov EAX, EDX <- t1, t2
9243 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
9244 // mov t3, t4 <- EAX, EDX
9246 // result in out1, out2
9247 // fallthrough -->nextMBB
9249 const TargetRegisterClass *RC = X86::GR32RegisterClass;
9250 const unsigned LoadOpc = X86::MOV32rm;
9251 const unsigned NotOpc = X86::NOT32r;
9252 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9253 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9254 MachineFunction::iterator MBBIter = MBB;
9257 /// First build the CFG
9258 MachineFunction *F = MBB->getParent();
9259 MachineBasicBlock *thisMBB = MBB;
9260 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9261 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9262 F->insert(MBBIter, newMBB);
9263 F->insert(MBBIter, nextMBB);
9265 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9266 nextMBB->splice(nextMBB->begin(), thisMBB,
9267 llvm::next(MachineBasicBlock::iterator(bInstr)),
9269 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9271 // Update thisMBB to fall through to newMBB
9272 thisMBB->addSuccessor(newMBB);
9274 // newMBB jumps to itself and fall through to nextMBB
9275 newMBB->addSuccessor(nextMBB);
9276 newMBB->addSuccessor(newMBB);
9278 DebugLoc dl = bInstr->getDebugLoc();
9279 // Insert instructions into newMBB based on incoming instruction
9280 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9281 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9282 "unexpected number of operands");
9283 MachineOperand& dest1Oper = bInstr->getOperand(0);
9284 MachineOperand& dest2Oper = bInstr->getOperand(1);
9285 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9286 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9287 argOpers[i] = &bInstr->getOperand(i+2);
9289 // We use some of the operands multiple times, so conservatively just
9290 // clear any kill flags that might be present.
9291 if (argOpers[i]->isReg() && argOpers[i]->isUse())
9292 argOpers[i]->setIsKill(false);
9295 // x86 address has 5 operands: base, index, scale, displacement, and segment.
9296 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9298 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9299 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9300 for (int i=0; i <= lastAddrIndx; ++i)
9301 (*MIB).addOperand(*argOpers[i]);
9302 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9303 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9304 // add 4 to displacement.
9305 for (int i=0; i <= lastAddrIndx-2; ++i)
9306 (*MIB).addOperand(*argOpers[i]);
9307 MachineOperand newOp3 = *(argOpers[3]);
9309 newOp3.setImm(newOp3.getImm()+4);
9311 newOp3.setOffset(newOp3.getOffset()+4);
9312 (*MIB).addOperand(newOp3);
9313 (*MIB).addOperand(*argOpers[lastAddrIndx]);
9315 // t3/4 are defined later, at the bottom of the loop
9316 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9317 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9318 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9319 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9320 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9321 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9323 // The subsequent operations should be using the destination registers of
9324 //the PHI instructions.
9326 t1 = F->getRegInfo().createVirtualRegister(RC);
9327 t2 = F->getRegInfo().createVirtualRegister(RC);
9328 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9329 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9331 t1 = dest1Oper.getReg();
9332 t2 = dest2Oper.getReg();
9335 int valArgIndx = lastAddrIndx + 1;
9336 assert((argOpers[valArgIndx]->isReg() ||
9337 argOpers[valArgIndx]->isImm()) &&
9339 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9340 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9341 if (argOpers[valArgIndx]->isReg())
9342 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9344 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9345 if (regOpcL != X86::MOV32rr)
9347 (*MIB).addOperand(*argOpers[valArgIndx]);
9348 assert(argOpers[valArgIndx + 1]->isReg() ==
9349 argOpers[valArgIndx]->isReg());
9350 assert(argOpers[valArgIndx + 1]->isImm() ==
9351 argOpers[valArgIndx]->isImm());
9352 if (argOpers[valArgIndx + 1]->isReg())
9353 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9355 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9356 if (regOpcH != X86::MOV32rr)
9358 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9360 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9362 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9365 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9367 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9370 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9371 for (int i=0; i <= lastAddrIndx; ++i)
9372 (*MIB).addOperand(*argOpers[i]);
9374 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9375 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9376 bInstr->memoperands_end());
9378 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9379 MIB.addReg(X86::EAX);
9380 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9381 MIB.addReg(X86::EDX);
9384 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9386 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9390 // private utility function
9392 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9393 MachineBasicBlock *MBB,
9394 unsigned cmovOpc) const {
9395 // For the atomic min/max operator, we generate
9398 // ld t1 = [min/max.addr]
9399 // mov t2 = [min/max.val]
9401 // cmov[cond] t2 = t1
9403 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9405 // fallthrough -->nextMBB
9407 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9408 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9409 MachineFunction::iterator MBBIter = MBB;
9412 /// First build the CFG
9413 MachineFunction *F = MBB->getParent();
9414 MachineBasicBlock *thisMBB = MBB;
9415 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9416 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9417 F->insert(MBBIter, newMBB);
9418 F->insert(MBBIter, nextMBB);
9420 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9421 nextMBB->splice(nextMBB->begin(), thisMBB,
9422 llvm::next(MachineBasicBlock::iterator(mInstr)),
9424 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9426 // Update thisMBB to fall through to newMBB
9427 thisMBB->addSuccessor(newMBB);
9429 // newMBB jumps to newMBB and fall through to nextMBB
9430 newMBB->addSuccessor(nextMBB);
9431 newMBB->addSuccessor(newMBB);
9433 DebugLoc dl = mInstr->getDebugLoc();
9434 // Insert instructions into newMBB based on incoming instruction
9435 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9436 "unexpected number of operands");
9437 MachineOperand& destOper = mInstr->getOperand(0);
9438 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9439 int numArgs = mInstr->getNumOperands() - 1;
9440 for (int i=0; i < numArgs; ++i)
9441 argOpers[i] = &mInstr->getOperand(i+1);
9443 // x86 address has 4 operands: base, index, scale, and displacement
9444 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9445 int valArgIndx = lastAddrIndx + 1;
9447 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9448 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9449 for (int i=0; i <= lastAddrIndx; ++i)
9450 (*MIB).addOperand(*argOpers[i]);
9452 // We only support register and immediate values
9453 assert((argOpers[valArgIndx]->isReg() ||
9454 argOpers[valArgIndx]->isImm()) &&
9457 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9458 if (argOpers[valArgIndx]->isReg())
9459 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9461 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9462 (*MIB).addOperand(*argOpers[valArgIndx]);
9464 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9467 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
9472 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9473 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
9477 // Cmp and exchange if none has modified the memory location
9478 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
9479 for (int i=0; i <= lastAddrIndx; ++i)
9480 (*MIB).addOperand(*argOpers[i]);
9482 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9483 (*MIB).setMemRefs(mInstr->memoperands_begin(),
9484 mInstr->memoperands_end());
9486 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9487 MIB.addReg(X86::EAX);
9490 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9492 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
9496 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
9497 // or XMM0_V32I8 in AVX all of this code can be replaced with that
9500 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
9501 unsigned numArgs, bool memArg) const {
9502 assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
9503 "Target must have SSE4.2 or AVX features enabled");
9505 DebugLoc dl = MI->getDebugLoc();
9506 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9508 if (!Subtarget->hasAVX()) {
9510 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
9512 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
9515 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
9517 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
9520 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
9521 for (unsigned i = 0; i < numArgs; ++i) {
9522 MachineOperand &Op = MI->getOperand(i+1);
9523 if (!(Op.isReg() && Op.isImplicit()))
9526 BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
9529 MI->eraseFromParent();
9534 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
9535 DebugLoc dl = MI->getDebugLoc();
9536 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9538 // Address into RAX/EAX, other two args into ECX, EDX.
9539 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
9540 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
9541 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
9542 for (int i = 0; i < X86::AddrNumOperands; ++i)
9543 MIB.addOperand(MI->getOperand(i));
9545 unsigned ValOps = X86::AddrNumOperands;
9546 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9547 .addReg(MI->getOperand(ValOps).getReg());
9548 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
9549 .addReg(MI->getOperand(ValOps+1).getReg());
9551 // The instruction doesn't actually take any operands though.
9552 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
9554 MI->eraseFromParent(); // The pseudo is gone now.
9559 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
9560 DebugLoc dl = MI->getDebugLoc();
9561 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9563 // First arg in ECX, the second in EAX.
9564 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9565 .addReg(MI->getOperand(0).getReg());
9566 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
9567 .addReg(MI->getOperand(1).getReg());
9569 // The instruction doesn't actually take any operands though.
9570 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
9572 MI->eraseFromParent(); // The pseudo is gone now.
9577 X86TargetLowering::EmitVAARG64WithCustomInserter(
9579 MachineBasicBlock *MBB) const {
9580 // Emit va_arg instruction on X86-64.
9582 // Operands to this pseudo-instruction:
9583 // 0 ) Output : destination address (reg)
9584 // 1-5) Input : va_list address (addr, i64mem)
9585 // 6 ) ArgSize : Size (in bytes) of vararg type
9586 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
9587 // 8 ) Align : Alignment of type
9588 // 9 ) EFLAGS (implicit-def)
9590 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
9591 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
9593 unsigned DestReg = MI->getOperand(0).getReg();
9594 MachineOperand &Base = MI->getOperand(1);
9595 MachineOperand &Scale = MI->getOperand(2);
9596 MachineOperand &Index = MI->getOperand(3);
9597 MachineOperand &Disp = MI->getOperand(4);
9598 MachineOperand &Segment = MI->getOperand(5);
9599 unsigned ArgSize = MI->getOperand(6).getImm();
9600 unsigned ArgMode = MI->getOperand(7).getImm();
9601 unsigned Align = MI->getOperand(8).getImm();
9604 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
9605 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
9606 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
9608 // Machine Information
9609 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9610 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
9611 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
9612 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
9613 DebugLoc DL = MI->getDebugLoc();
9618 // i64 overflow_area (address)
9619 // i64 reg_save_area (address)
9621 // sizeof(va_list) = 24
9622 // alignment(va_list) = 8
9624 unsigned TotalNumIntRegs = 6;
9625 unsigned TotalNumXMMRegs = 8;
9626 bool UseGPOffset = (ArgMode == 1);
9627 bool UseFPOffset = (ArgMode == 2);
9628 unsigned MaxOffset = TotalNumIntRegs * 8 +
9629 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
9631 /* Align ArgSize to a multiple of 8 */
9632 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
9633 bool NeedsAlign = (Align > 8);
9635 MachineBasicBlock *thisMBB = MBB;
9636 MachineBasicBlock *overflowMBB;
9637 MachineBasicBlock *offsetMBB;
9638 MachineBasicBlock *endMBB;
9640 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
9641 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
9642 unsigned OffsetReg = 0;
9644 if (!UseGPOffset && !UseFPOffset) {
9645 // If we only pull from the overflow region, we don't create a branch.
9646 // We don't need to alter control flow.
9647 OffsetDestReg = 0; // unused
9648 OverflowDestReg = DestReg;
9651 overflowMBB = thisMBB;
9654 // First emit code to check if gp_offset (or fp_offset) is below the bound.
9655 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
9656 // If not, pull from overflow_area. (branch to overflowMBB)
9661 // offsetMBB overflowMBB
9666 // Registers for the PHI in endMBB
9667 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
9668 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
9670 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9671 MachineFunction *MF = MBB->getParent();
9672 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9673 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9674 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9676 MachineFunction::iterator MBBIter = MBB;
9679 // Insert the new basic blocks
9680 MF->insert(MBBIter, offsetMBB);
9681 MF->insert(MBBIter, overflowMBB);
9682 MF->insert(MBBIter, endMBB);
9684 // Transfer the remainder of MBB and its successor edges to endMBB.
9685 endMBB->splice(endMBB->begin(), thisMBB,
9686 llvm::next(MachineBasicBlock::iterator(MI)),
9688 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9690 // Make offsetMBB and overflowMBB successors of thisMBB
9691 thisMBB->addSuccessor(offsetMBB);
9692 thisMBB->addSuccessor(overflowMBB);
9694 // endMBB is a successor of both offsetMBB and overflowMBB
9695 offsetMBB->addSuccessor(endMBB);
9696 overflowMBB->addSuccessor(endMBB);
9698 // Load the offset value into a register
9699 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
9700 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
9704 .addDisp(Disp, UseFPOffset ? 4 : 0)
9705 .addOperand(Segment)
9706 .setMemRefs(MMOBegin, MMOEnd);
9708 // Check if there is enough room left to pull this argument.
9709 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
9711 .addImm(MaxOffset + 8 - ArgSizeA8);
9713 // Branch to "overflowMBB" if offset >= max
9714 // Fall through to "offsetMBB" otherwise
9715 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
9716 .addMBB(overflowMBB);
9719 // In offsetMBB, emit code to use the reg_save_area.
9721 assert(OffsetReg != 0);
9723 // Read the reg_save_area address.
9724 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
9725 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
9730 .addOperand(Segment)
9731 .setMemRefs(MMOBegin, MMOEnd);
9733 // Zero-extend the offset
9734 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
9735 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
9738 .addImm(X86::sub_32bit);
9740 // Add the offset to the reg_save_area to get the final address.
9741 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
9742 .addReg(OffsetReg64)
9743 .addReg(RegSaveReg);
9745 // Compute the offset for the next argument
9746 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
9747 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
9749 .addImm(UseFPOffset ? 16 : 8);
9751 // Store it back into the va_list.
9752 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
9756 .addDisp(Disp, UseFPOffset ? 4 : 0)
9757 .addOperand(Segment)
9758 .addReg(NextOffsetReg)
9759 .setMemRefs(MMOBegin, MMOEnd);
9762 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
9767 // Emit code to use overflow area
9770 // Load the overflow_area address into a register.
9771 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
9772 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
9777 .addOperand(Segment)
9778 .setMemRefs(MMOBegin, MMOEnd);
9780 // If we need to align it, do so. Otherwise, just copy the address
9781 // to OverflowDestReg.
9783 // Align the overflow address
9784 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
9785 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
9787 // aligned_addr = (addr + (align-1)) & ~(align-1)
9788 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
9789 .addReg(OverflowAddrReg)
9792 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
9794 .addImm(~(uint64_t)(Align-1));
9796 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
9797 .addReg(OverflowAddrReg);
9800 // Compute the next overflow address after this argument.
9801 // (the overflow address should be kept 8-byte aligned)
9802 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
9803 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
9804 .addReg(OverflowDestReg)
9807 // Store the new overflow address.
9808 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
9813 .addOperand(Segment)
9814 .addReg(NextAddrReg)
9815 .setMemRefs(MMOBegin, MMOEnd);
9817 // If we branched, emit the PHI to the front of endMBB.
9819 BuildMI(*endMBB, endMBB->begin(), DL,
9820 TII->get(X86::PHI), DestReg)
9821 .addReg(OffsetDestReg).addMBB(offsetMBB)
9822 .addReg(OverflowDestReg).addMBB(overflowMBB);
9825 // Erase the pseudo instruction
9826 MI->eraseFromParent();
9832 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
9834 MachineBasicBlock *MBB) const {
9835 // Emit code to save XMM registers to the stack. The ABI says that the
9836 // number of registers to save is given in %al, so it's theoretically
9837 // possible to do an indirect jump trick to avoid saving all of them,
9838 // however this code takes a simpler approach and just executes all
9839 // of the stores if %al is non-zero. It's less code, and it's probably
9840 // easier on the hardware branch predictor, and stores aren't all that
9841 // expensive anyway.
9843 // Create the new basic blocks. One block contains all the XMM stores,
9844 // and one block is the final destination regardless of whether any
9845 // stores were performed.
9846 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9847 MachineFunction *F = MBB->getParent();
9848 MachineFunction::iterator MBBIter = MBB;
9850 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
9851 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
9852 F->insert(MBBIter, XMMSaveMBB);
9853 F->insert(MBBIter, EndMBB);
9855 // Transfer the remainder of MBB and its successor edges to EndMBB.
9856 EndMBB->splice(EndMBB->begin(), MBB,
9857 llvm::next(MachineBasicBlock::iterator(MI)),
9859 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
9861 // The original block will now fall through to the XMM save block.
9862 MBB->addSuccessor(XMMSaveMBB);
9863 // The XMMSaveMBB will fall through to the end block.
9864 XMMSaveMBB->addSuccessor(EndMBB);
9866 // Now add the instructions.
9867 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9868 DebugLoc DL = MI->getDebugLoc();
9870 unsigned CountReg = MI->getOperand(0).getReg();
9871 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
9872 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
9874 if (!Subtarget->isTargetWin64()) {
9875 // If %al is 0, branch around the XMM save block.
9876 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
9877 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
9878 MBB->addSuccessor(EndMBB);
9881 // In the XMM save block, save all the XMM argument registers.
9882 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
9883 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
9884 MachineMemOperand *MMO =
9885 F->getMachineMemOperand(
9886 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
9887 MachineMemOperand::MOStore,
9888 /*Size=*/16, /*Align=*/16);
9889 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
9890 .addFrameIndex(RegSaveFrameIndex)
9891 .addImm(/*Scale=*/1)
9892 .addReg(/*IndexReg=*/0)
9893 .addImm(/*Disp=*/Offset)
9894 .addReg(/*Segment=*/0)
9895 .addReg(MI->getOperand(i).getReg())
9896 .addMemOperand(MMO);
9899 MI->eraseFromParent(); // The pseudo instruction is gone now.
9905 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
9906 MachineBasicBlock *BB) const {
9907 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9908 DebugLoc DL = MI->getDebugLoc();
9910 // To "insert" a SELECT_CC instruction, we actually have to insert the
9911 // diamond control-flow pattern. The incoming instruction knows the
9912 // destination vreg to set, the condition code register to branch on, the
9913 // true/false values to select between, and a branch opcode to use.
9914 const BasicBlock *LLVM_BB = BB->getBasicBlock();
9915 MachineFunction::iterator It = BB;
9921 // cmpTY ccX, r1, r2
9923 // fallthrough --> copy0MBB
9924 MachineBasicBlock *thisMBB = BB;
9925 MachineFunction *F = BB->getParent();
9926 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9927 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9928 F->insert(It, copy0MBB);
9929 F->insert(It, sinkMBB);
9931 // If the EFLAGS register isn't dead in the terminator, then claim that it's
9932 // live into the sink and copy blocks.
9933 const MachineFunction *MF = BB->getParent();
9934 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
9935 BitVector ReservedRegs = TRI->getReservedRegs(*MF);
9937 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
9938 const MachineOperand &MO = MI->getOperand(I);
9939 if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
9940 unsigned Reg = MO.getReg();
9941 if (Reg != X86::EFLAGS) continue;
9942 copy0MBB->addLiveIn(Reg);
9943 sinkMBB->addLiveIn(Reg);
9946 // Transfer the remainder of BB and its successor edges to sinkMBB.
9947 sinkMBB->splice(sinkMBB->begin(), BB,
9948 llvm::next(MachineBasicBlock::iterator(MI)),
9950 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9952 // Add the true and fallthrough blocks as its successors.
9953 BB->addSuccessor(copy0MBB);
9954 BB->addSuccessor(sinkMBB);
9956 // Create the conditional branch instruction.
9958 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
9959 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
9962 // %FalseValue = ...
9963 // # fallthrough to sinkMBB
9964 copy0MBB->addSuccessor(sinkMBB);
9967 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9969 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
9970 TII->get(X86::PHI), MI->getOperand(0).getReg())
9971 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
9972 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
9974 MI->eraseFromParent(); // The pseudo instruction is gone now.
9979 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
9980 MachineBasicBlock *BB) const {
9981 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9982 DebugLoc DL = MI->getDebugLoc();
9984 // The lowering is pretty easy: we're just emitting the call to _alloca. The
9985 // non-trivial part is impdef of ESP.
9986 // FIXME: The code should be tweaked as soon as we'll try to do codegen for
9989 const char *StackProbeSymbol =
9990 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
9992 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
9993 .addExternalSymbol(StackProbeSymbol)
9994 .addReg(X86::EAX, RegState::Implicit)
9995 .addReg(X86::ESP, RegState::Implicit)
9996 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
9997 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
9998 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
10000 MI->eraseFromParent(); // The pseudo instruction is gone now.
10004 MachineBasicBlock *
10005 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
10006 MachineBasicBlock *BB) const {
10007 // This is pretty easy. We're taking the value that we received from
10008 // our load from the relocation, sticking it in either RDI (x86-64)
10009 // or EAX and doing an indirect call. The return value will then
10010 // be in the normal return register.
10011 const X86InstrInfo *TII
10012 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
10013 DebugLoc DL = MI->getDebugLoc();
10014 MachineFunction *F = BB->getParent();
10016 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
10017 assert(MI->getOperand(3).isGlobal() && "This should be a global");
10019 if (Subtarget->is64Bit()) {
10020 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10021 TII->get(X86::MOV64rm), X86::RDI)
10023 .addImm(0).addReg(0)
10024 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10025 MI->getOperand(3).getTargetFlags())
10027 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10028 addDirectMem(MIB, X86::RDI);
10029 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10030 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10031 TII->get(X86::MOV32rm), X86::EAX)
10033 .addImm(0).addReg(0)
10034 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10035 MI->getOperand(3).getTargetFlags())
10037 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10038 addDirectMem(MIB, X86::EAX);
10040 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10041 TII->get(X86::MOV32rm), X86::EAX)
10042 .addReg(TII->getGlobalBaseReg(F))
10043 .addImm(0).addReg(0)
10044 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10045 MI->getOperand(3).getTargetFlags())
10047 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10048 addDirectMem(MIB, X86::EAX);
10051 MI->eraseFromParent(); // The pseudo instruction is gone now.
10055 MachineBasicBlock *
10056 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10057 MachineBasicBlock *BB) const {
10058 switch (MI->getOpcode()) {
10059 default: assert(false && "Unexpected instr type to insert");
10060 case X86::WIN_ALLOCA:
10061 return EmitLoweredWinAlloca(MI, BB);
10062 case X86::TLSCall_32:
10063 case X86::TLSCall_64:
10064 return EmitLoweredTLSCall(MI, BB);
10065 case X86::CMOV_GR8:
10066 case X86::CMOV_FR32:
10067 case X86::CMOV_FR64:
10068 case X86::CMOV_V4F32:
10069 case X86::CMOV_V2F64:
10070 case X86::CMOV_V2I64:
10071 case X86::CMOV_GR16:
10072 case X86::CMOV_GR32:
10073 case X86::CMOV_RFP32:
10074 case X86::CMOV_RFP64:
10075 case X86::CMOV_RFP80:
10076 return EmitLoweredSelect(MI, BB);
10078 case X86::FP32_TO_INT16_IN_MEM:
10079 case X86::FP32_TO_INT32_IN_MEM:
10080 case X86::FP32_TO_INT64_IN_MEM:
10081 case X86::FP64_TO_INT16_IN_MEM:
10082 case X86::FP64_TO_INT32_IN_MEM:
10083 case X86::FP64_TO_INT64_IN_MEM:
10084 case X86::FP80_TO_INT16_IN_MEM:
10085 case X86::FP80_TO_INT32_IN_MEM:
10086 case X86::FP80_TO_INT64_IN_MEM: {
10087 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10088 DebugLoc DL = MI->getDebugLoc();
10090 // Change the floating point control register to use "round towards zero"
10091 // mode when truncating to an integer value.
10092 MachineFunction *F = BB->getParent();
10093 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10094 addFrameReference(BuildMI(*BB, MI, DL,
10095 TII->get(X86::FNSTCW16m)), CWFrameIdx);
10097 // Load the old value of the high byte of the control word...
10099 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10100 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10103 // Set the high part to be round to zero...
10104 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10107 // Reload the modified control word now...
10108 addFrameReference(BuildMI(*BB, MI, DL,
10109 TII->get(X86::FLDCW16m)), CWFrameIdx);
10111 // Restore the memory image of control word to original value
10112 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10115 // Get the X86 opcode to use.
10117 switch (MI->getOpcode()) {
10118 default: llvm_unreachable("illegal opcode!");
10119 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10120 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10121 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10122 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10123 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10124 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10125 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10126 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10127 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10131 MachineOperand &Op = MI->getOperand(0);
10133 AM.BaseType = X86AddressMode::RegBase;
10134 AM.Base.Reg = Op.getReg();
10136 AM.BaseType = X86AddressMode::FrameIndexBase;
10137 AM.Base.FrameIndex = Op.getIndex();
10139 Op = MI->getOperand(1);
10141 AM.Scale = Op.getImm();
10142 Op = MI->getOperand(2);
10144 AM.IndexReg = Op.getImm();
10145 Op = MI->getOperand(3);
10146 if (Op.isGlobal()) {
10147 AM.GV = Op.getGlobal();
10149 AM.Disp = Op.getImm();
10151 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10152 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10154 // Reload the original control word now.
10155 addFrameReference(BuildMI(*BB, MI, DL,
10156 TII->get(X86::FLDCW16m)), CWFrameIdx);
10158 MI->eraseFromParent(); // The pseudo instruction is gone now.
10161 // String/text processing lowering.
10162 case X86::PCMPISTRM128REG:
10163 case X86::VPCMPISTRM128REG:
10164 return EmitPCMP(MI, BB, 3, false /* in-mem */);
10165 case X86::PCMPISTRM128MEM:
10166 case X86::VPCMPISTRM128MEM:
10167 return EmitPCMP(MI, BB, 3, true /* in-mem */);
10168 case X86::PCMPESTRM128REG:
10169 case X86::VPCMPESTRM128REG:
10170 return EmitPCMP(MI, BB, 5, false /* in mem */);
10171 case X86::PCMPESTRM128MEM:
10172 case X86::VPCMPESTRM128MEM:
10173 return EmitPCMP(MI, BB, 5, true /* in mem */);
10175 // Thread synchronization.
10177 return EmitMonitor(MI, BB);
10179 return EmitMwait(MI, BB);
10181 // Atomic Lowering.
10182 case X86::ATOMAND32:
10183 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10184 X86::AND32ri, X86::MOV32rm,
10186 X86::NOT32r, X86::EAX,
10187 X86::GR32RegisterClass);
10188 case X86::ATOMOR32:
10189 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10190 X86::OR32ri, X86::MOV32rm,
10192 X86::NOT32r, X86::EAX,
10193 X86::GR32RegisterClass);
10194 case X86::ATOMXOR32:
10195 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10196 X86::XOR32ri, X86::MOV32rm,
10198 X86::NOT32r, X86::EAX,
10199 X86::GR32RegisterClass);
10200 case X86::ATOMNAND32:
10201 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10202 X86::AND32ri, X86::MOV32rm,
10204 X86::NOT32r, X86::EAX,
10205 X86::GR32RegisterClass, true);
10206 case X86::ATOMMIN32:
10207 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10208 case X86::ATOMMAX32:
10209 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10210 case X86::ATOMUMIN32:
10211 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10212 case X86::ATOMUMAX32:
10213 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10215 case X86::ATOMAND16:
10216 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10217 X86::AND16ri, X86::MOV16rm,
10219 X86::NOT16r, X86::AX,
10220 X86::GR16RegisterClass);
10221 case X86::ATOMOR16:
10222 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10223 X86::OR16ri, X86::MOV16rm,
10225 X86::NOT16r, X86::AX,
10226 X86::GR16RegisterClass);
10227 case X86::ATOMXOR16:
10228 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10229 X86::XOR16ri, X86::MOV16rm,
10231 X86::NOT16r, X86::AX,
10232 X86::GR16RegisterClass);
10233 case X86::ATOMNAND16:
10234 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10235 X86::AND16ri, X86::MOV16rm,
10237 X86::NOT16r, X86::AX,
10238 X86::GR16RegisterClass, true);
10239 case X86::ATOMMIN16:
10240 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10241 case X86::ATOMMAX16:
10242 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10243 case X86::ATOMUMIN16:
10244 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10245 case X86::ATOMUMAX16:
10246 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10248 case X86::ATOMAND8:
10249 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10250 X86::AND8ri, X86::MOV8rm,
10252 X86::NOT8r, X86::AL,
10253 X86::GR8RegisterClass);
10255 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10256 X86::OR8ri, X86::MOV8rm,
10258 X86::NOT8r, X86::AL,
10259 X86::GR8RegisterClass);
10260 case X86::ATOMXOR8:
10261 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10262 X86::XOR8ri, X86::MOV8rm,
10264 X86::NOT8r, X86::AL,
10265 X86::GR8RegisterClass);
10266 case X86::ATOMNAND8:
10267 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10268 X86::AND8ri, X86::MOV8rm,
10270 X86::NOT8r, X86::AL,
10271 X86::GR8RegisterClass, true);
10272 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10273 // This group is for 64-bit host.
10274 case X86::ATOMAND64:
10275 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10276 X86::AND64ri32, X86::MOV64rm,
10278 X86::NOT64r, X86::RAX,
10279 X86::GR64RegisterClass);
10280 case X86::ATOMOR64:
10281 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10282 X86::OR64ri32, X86::MOV64rm,
10284 X86::NOT64r, X86::RAX,
10285 X86::GR64RegisterClass);
10286 case X86::ATOMXOR64:
10287 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10288 X86::XOR64ri32, X86::MOV64rm,
10290 X86::NOT64r, X86::RAX,
10291 X86::GR64RegisterClass);
10292 case X86::ATOMNAND64:
10293 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10294 X86::AND64ri32, X86::MOV64rm,
10296 X86::NOT64r, X86::RAX,
10297 X86::GR64RegisterClass, true);
10298 case X86::ATOMMIN64:
10299 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10300 case X86::ATOMMAX64:
10301 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10302 case X86::ATOMUMIN64:
10303 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10304 case X86::ATOMUMAX64:
10305 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10307 // This group does 64-bit operations on a 32-bit host.
10308 case X86::ATOMAND6432:
10309 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10310 X86::AND32rr, X86::AND32rr,
10311 X86::AND32ri, X86::AND32ri,
10313 case X86::ATOMOR6432:
10314 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10315 X86::OR32rr, X86::OR32rr,
10316 X86::OR32ri, X86::OR32ri,
10318 case X86::ATOMXOR6432:
10319 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10320 X86::XOR32rr, X86::XOR32rr,
10321 X86::XOR32ri, X86::XOR32ri,
10323 case X86::ATOMNAND6432:
10324 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10325 X86::AND32rr, X86::AND32rr,
10326 X86::AND32ri, X86::AND32ri,
10328 case X86::ATOMADD6432:
10329 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10330 X86::ADD32rr, X86::ADC32rr,
10331 X86::ADD32ri, X86::ADC32ri,
10333 case X86::ATOMSUB6432:
10334 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10335 X86::SUB32rr, X86::SBB32rr,
10336 X86::SUB32ri, X86::SBB32ri,
10338 case X86::ATOMSWAP6432:
10339 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10340 X86::MOV32rr, X86::MOV32rr,
10341 X86::MOV32ri, X86::MOV32ri,
10343 case X86::VASTART_SAVE_XMM_REGS:
10344 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10346 case X86::VAARG_64:
10347 return EmitVAARG64WithCustomInserter(MI, BB);
10351 //===----------------------------------------------------------------------===//
10352 // X86 Optimization Hooks
10353 //===----------------------------------------------------------------------===//
10355 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10359 const SelectionDAG &DAG,
10360 unsigned Depth) const {
10361 unsigned Opc = Op.getOpcode();
10362 assert((Opc >= ISD::BUILTIN_OP_END ||
10363 Opc == ISD::INTRINSIC_WO_CHAIN ||
10364 Opc == ISD::INTRINSIC_W_CHAIN ||
10365 Opc == ISD::INTRINSIC_VOID) &&
10366 "Should use MaskedValueIsZero if you don't know whether Op"
10367 " is a target node!");
10369 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
10383 // These nodes' second result is a boolean.
10384 if (Op.getResNo() == 0)
10387 case X86ISD::SETCC:
10388 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
10389 Mask.getBitWidth() - 1);
10394 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
10395 unsigned Depth) const {
10396 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
10397 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
10398 return Op.getValueType().getScalarType().getSizeInBits();
10404 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
10405 /// node is a GlobalAddress + offset.
10406 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
10407 const GlobalValue* &GA,
10408 int64_t &Offset) const {
10409 if (N->getOpcode() == X86ISD::Wrapper) {
10410 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
10411 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
10412 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
10416 return TargetLowering::isGAPlusOffset(N, GA, Offset);
10419 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
10420 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
10421 /// if the load addresses are consecutive, non-overlapping, and in the right
10423 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
10424 TargetLowering::DAGCombinerInfo &DCI) {
10425 DebugLoc dl = N->getDebugLoc();
10426 EVT VT = N->getValueType(0);
10428 if (VT.getSizeInBits() != 128)
10431 // Don't create instructions with illegal types after legalize types has run.
10432 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10433 if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
10436 SmallVector<SDValue, 16> Elts;
10437 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
10438 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
10440 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
10443 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
10444 /// generation and convert it from being a bunch of shuffles and extracts
10445 /// to a simple store and scalar loads to extract the elements.
10446 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
10447 const TargetLowering &TLI) {
10448 SDValue InputVector = N->getOperand(0);
10450 // Only operate on vectors of 4 elements, where the alternative shuffling
10451 // gets to be more expensive.
10452 if (InputVector.getValueType() != MVT::v4i32)
10455 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
10456 // single use which is a sign-extend or zero-extend, and all elements are
10458 SmallVector<SDNode *, 4> Uses;
10459 unsigned ExtractedElements = 0;
10460 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
10461 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
10462 if (UI.getUse().getResNo() != InputVector.getResNo())
10465 SDNode *Extract = *UI;
10466 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10469 if (Extract->getValueType(0) != MVT::i32)
10471 if (!Extract->hasOneUse())
10473 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
10474 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
10476 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
10479 // Record which element was extracted.
10480 ExtractedElements |=
10481 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
10483 Uses.push_back(Extract);
10486 // If not all the elements were used, this may not be worthwhile.
10487 if (ExtractedElements != 15)
10490 // Ok, we've now decided to do the transformation.
10491 DebugLoc dl = InputVector.getDebugLoc();
10493 // Store the value to a temporary stack slot.
10494 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
10495 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
10496 MachinePointerInfo(), false, false, 0);
10498 // Replace each use (extract) with a load of the appropriate element.
10499 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
10500 UE = Uses.end(); UI != UE; ++UI) {
10501 SDNode *Extract = *UI;
10503 // Compute the element's address.
10504 SDValue Idx = Extract->getOperand(1);
10506 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
10507 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
10508 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
10510 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(),
10511 StackPtr, OffsetVal);
10513 // Load the scalar.
10514 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
10515 ScalarAddr, MachinePointerInfo(),
10518 // Replace the exact with the load.
10519 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
10522 // The replacement was made in place; don't return anything.
10526 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
10527 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
10528 const X86Subtarget *Subtarget) {
10529 DebugLoc DL = N->getDebugLoc();
10530 SDValue Cond = N->getOperand(0);
10531 // Get the LHS/RHS of the select.
10532 SDValue LHS = N->getOperand(1);
10533 SDValue RHS = N->getOperand(2);
10535 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
10536 // instructions match the semantics of the common C idiom x<y?x:y but not
10537 // x<=y?x:y, because of how they handle negative zero (which can be
10538 // ignored in unsafe-math mode).
10539 if (Subtarget->hasSSE2() &&
10540 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
10541 Cond.getOpcode() == ISD::SETCC) {
10542 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
10544 unsigned Opcode = 0;
10545 // Check for x CC y ? x : y.
10546 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
10547 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
10551 // Converting this to a min would handle NaNs incorrectly, and swapping
10552 // the operands would cause it to handle comparisons between positive
10553 // and negative zero incorrectly.
10554 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10555 if (!UnsafeFPMath &&
10556 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10558 std::swap(LHS, RHS);
10560 Opcode = X86ISD::FMIN;
10563 // Converting this to a min would handle comparisons between positive
10564 // and negative zero incorrectly.
10565 if (!UnsafeFPMath &&
10566 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
10568 Opcode = X86ISD::FMIN;
10571 // Converting this to a min would handle both negative zeros and NaNs
10572 // incorrectly, but we can swap the operands to fix both.
10573 std::swap(LHS, RHS);
10577 Opcode = X86ISD::FMIN;
10581 // Converting this to a max would handle comparisons between positive
10582 // and negative zero incorrectly.
10583 if (!UnsafeFPMath &&
10584 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
10586 Opcode = X86ISD::FMAX;
10589 // Converting this to a max would handle NaNs incorrectly, and swapping
10590 // the operands would cause it to handle comparisons between positive
10591 // and negative zero incorrectly.
10592 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10593 if (!UnsafeFPMath &&
10594 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10596 std::swap(LHS, RHS);
10598 Opcode = X86ISD::FMAX;
10601 // Converting this to a max would handle both negative zeros and NaNs
10602 // incorrectly, but we can swap the operands to fix both.
10603 std::swap(LHS, RHS);
10607 Opcode = X86ISD::FMAX;
10610 // Check for x CC y ? y : x -- a min/max with reversed arms.
10611 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
10612 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
10616 // Converting this to a min would handle comparisons between positive
10617 // and negative zero incorrectly, and swapping the operands would
10618 // cause it to handle NaNs incorrectly.
10619 if (!UnsafeFPMath &&
10620 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
10621 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10623 std::swap(LHS, RHS);
10625 Opcode = X86ISD::FMIN;
10628 // Converting this to a min would handle NaNs incorrectly.
10629 if (!UnsafeFPMath &&
10630 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
10632 Opcode = X86ISD::FMIN;
10635 // Converting this to a min would handle both negative zeros and NaNs
10636 // incorrectly, but we can swap the operands to fix both.
10637 std::swap(LHS, RHS);
10641 Opcode = X86ISD::FMIN;
10645 // Converting this to a max would handle NaNs incorrectly.
10646 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10648 Opcode = X86ISD::FMAX;
10651 // Converting this to a max would handle comparisons between positive
10652 // and negative zero incorrectly, and swapping the operands would
10653 // cause it to handle NaNs incorrectly.
10654 if (!UnsafeFPMath &&
10655 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
10656 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10658 std::swap(LHS, RHS);
10660 Opcode = X86ISD::FMAX;
10663 // Converting this to a max would handle both negative zeros and NaNs
10664 // incorrectly, but we can swap the operands to fix both.
10665 std::swap(LHS, RHS);
10669 Opcode = X86ISD::FMAX;
10675 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
10678 // If this is a select between two integer constants, try to do some
10680 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
10681 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
10682 // Don't do this for crazy integer types.
10683 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
10684 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
10685 // so that TrueC (the true value) is larger than FalseC.
10686 bool NeedsCondInvert = false;
10688 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
10689 // Efficiently invertible.
10690 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
10691 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
10692 isa<ConstantSDNode>(Cond.getOperand(1))))) {
10693 NeedsCondInvert = true;
10694 std::swap(TrueC, FalseC);
10697 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
10698 if (FalseC->getAPIntValue() == 0 &&
10699 TrueC->getAPIntValue().isPowerOf2()) {
10700 if (NeedsCondInvert) // Invert the condition if needed.
10701 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10702 DAG.getConstant(1, Cond.getValueType()));
10704 // Zero extend the condition if needed.
10705 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
10707 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10708 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
10709 DAG.getConstant(ShAmt, MVT::i8));
10712 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
10713 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10714 if (NeedsCondInvert) // Invert the condition if needed.
10715 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10716 DAG.getConstant(1, Cond.getValueType()));
10718 // Zero extend the condition if needed.
10719 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10720 FalseC->getValueType(0), Cond);
10721 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10722 SDValue(FalseC, 0));
10725 // Optimize cases that will turn into an LEA instruction. This requires
10726 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10727 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10728 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10729 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10731 bool isFastMultiplier = false;
10733 switch ((unsigned char)Diff) {
10735 case 1: // result = add base, cond
10736 case 2: // result = lea base( , cond*2)
10737 case 3: // result = lea base(cond, cond*2)
10738 case 4: // result = lea base( , cond*4)
10739 case 5: // result = lea base(cond, cond*4)
10740 case 8: // result = lea base( , cond*8)
10741 case 9: // result = lea base(cond, cond*8)
10742 isFastMultiplier = true;
10747 if (isFastMultiplier) {
10748 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10749 if (NeedsCondInvert) // Invert the condition if needed.
10750 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10751 DAG.getConstant(1, Cond.getValueType()));
10753 // Zero extend the condition if needed.
10754 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10756 // Scale the condition by the difference.
10758 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10759 DAG.getConstant(Diff, Cond.getValueType()));
10761 // Add the base if non-zero.
10762 if (FalseC->getAPIntValue() != 0)
10763 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10764 SDValue(FalseC, 0));
10774 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
10775 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
10776 TargetLowering::DAGCombinerInfo &DCI) {
10777 DebugLoc DL = N->getDebugLoc();
10779 // If the flag operand isn't dead, don't touch this CMOV.
10780 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
10783 // If this is a select between two integer constants, try to do some
10784 // optimizations. Note that the operands are ordered the opposite of SELECT
10786 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
10787 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10788 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
10789 // larger than FalseC (the false value).
10790 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
10792 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
10793 CC = X86::GetOppositeBranchCondition(CC);
10794 std::swap(TrueC, FalseC);
10797 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
10798 // This is efficient for any integer data type (including i8/i16) and
10800 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
10801 SDValue Cond = N->getOperand(3);
10802 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10803 DAG.getConstant(CC, MVT::i8), Cond);
10805 // Zero extend the condition if needed.
10806 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
10808 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10809 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
10810 DAG.getConstant(ShAmt, MVT::i8));
10811 if (N->getNumValues() == 2) // Dead flag value?
10812 return DCI.CombineTo(N, Cond, SDValue());
10816 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
10817 // for any integer data type, including i8/i16.
10818 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10819 SDValue Cond = N->getOperand(3);
10820 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10821 DAG.getConstant(CC, MVT::i8), Cond);
10823 // Zero extend the condition if needed.
10824 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10825 FalseC->getValueType(0), Cond);
10826 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10827 SDValue(FalseC, 0));
10829 if (N->getNumValues() == 2) // Dead flag value?
10830 return DCI.CombineTo(N, Cond, SDValue());
10834 // Optimize cases that will turn into an LEA instruction. This requires
10835 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10836 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10837 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10838 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10840 bool isFastMultiplier = false;
10842 switch ((unsigned char)Diff) {
10844 case 1: // result = add base, cond
10845 case 2: // result = lea base( , cond*2)
10846 case 3: // result = lea base(cond, cond*2)
10847 case 4: // result = lea base( , cond*4)
10848 case 5: // result = lea base(cond, cond*4)
10849 case 8: // result = lea base( , cond*8)
10850 case 9: // result = lea base(cond, cond*8)
10851 isFastMultiplier = true;
10856 if (isFastMultiplier) {
10857 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10858 SDValue Cond = N->getOperand(3);
10859 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10860 DAG.getConstant(CC, MVT::i8), Cond);
10861 // Zero extend the condition if needed.
10862 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10864 // Scale the condition by the difference.
10866 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10867 DAG.getConstant(Diff, Cond.getValueType()));
10869 // Add the base if non-zero.
10870 if (FalseC->getAPIntValue() != 0)
10871 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10872 SDValue(FalseC, 0));
10873 if (N->getNumValues() == 2) // Dead flag value?
10874 return DCI.CombineTo(N, Cond, SDValue());
10884 /// PerformMulCombine - Optimize a single multiply with constant into two
10885 /// in order to implement it with two cheaper instructions, e.g.
10886 /// LEA + SHL, LEA + LEA.
10887 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
10888 TargetLowering::DAGCombinerInfo &DCI) {
10889 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10892 EVT VT = N->getValueType(0);
10893 if (VT != MVT::i64)
10896 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10899 uint64_t MulAmt = C->getZExtValue();
10900 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
10903 uint64_t MulAmt1 = 0;
10904 uint64_t MulAmt2 = 0;
10905 if ((MulAmt % 9) == 0) {
10907 MulAmt2 = MulAmt / 9;
10908 } else if ((MulAmt % 5) == 0) {
10910 MulAmt2 = MulAmt / 5;
10911 } else if ((MulAmt % 3) == 0) {
10913 MulAmt2 = MulAmt / 3;
10916 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
10917 DebugLoc DL = N->getDebugLoc();
10919 if (isPowerOf2_64(MulAmt2) &&
10920 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
10921 // If second multiplifer is pow2, issue it first. We want the multiply by
10922 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
10924 std::swap(MulAmt1, MulAmt2);
10927 if (isPowerOf2_64(MulAmt1))
10928 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
10929 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
10931 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
10932 DAG.getConstant(MulAmt1, VT));
10934 if (isPowerOf2_64(MulAmt2))
10935 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
10936 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
10938 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
10939 DAG.getConstant(MulAmt2, VT));
10941 // Do not add new nodes to DAG combiner worklist.
10942 DCI.CombineTo(N, NewMul, false);
10947 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
10948 SDValue N0 = N->getOperand(0);
10949 SDValue N1 = N->getOperand(1);
10950 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
10951 EVT VT = N0.getValueType();
10953 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
10954 // since the result of setcc_c is all zero's or all ones.
10955 if (N1C && N0.getOpcode() == ISD::AND &&
10956 N0.getOperand(1).getOpcode() == ISD::Constant) {
10957 SDValue N00 = N0.getOperand(0);
10958 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
10959 ((N00.getOpcode() == ISD::ANY_EXTEND ||
10960 N00.getOpcode() == ISD::ZERO_EXTEND) &&
10961 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
10962 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
10963 APInt ShAmt = N1C->getAPIntValue();
10964 Mask = Mask.shl(ShAmt);
10966 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
10967 N00, DAG.getConstant(Mask, VT));
10974 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
10976 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
10977 const X86Subtarget *Subtarget) {
10978 EVT VT = N->getValueType(0);
10979 if (!VT.isVector() && VT.isInteger() &&
10980 N->getOpcode() == ISD::SHL)
10981 return PerformSHLCombine(N, DAG);
10983 // On X86 with SSE2 support, we can transform this to a vector shift if
10984 // all elements are shifted by the same amount. We can't do this in legalize
10985 // because the a constant vector is typically transformed to a constant pool
10986 // so we have no knowledge of the shift amount.
10987 if (!Subtarget->hasSSE2())
10990 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
10993 SDValue ShAmtOp = N->getOperand(1);
10994 EVT EltVT = VT.getVectorElementType();
10995 DebugLoc DL = N->getDebugLoc();
10996 SDValue BaseShAmt = SDValue();
10997 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
10998 unsigned NumElts = VT.getVectorNumElements();
11000 for (; i != NumElts; ++i) {
11001 SDValue Arg = ShAmtOp.getOperand(i);
11002 if (Arg.getOpcode() == ISD::UNDEF) continue;
11006 for (; i != NumElts; ++i) {
11007 SDValue Arg = ShAmtOp.getOperand(i);
11008 if (Arg.getOpcode() == ISD::UNDEF) continue;
11009 if (Arg != BaseShAmt) {
11013 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
11014 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
11015 SDValue InVec = ShAmtOp.getOperand(0);
11016 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
11017 unsigned NumElts = InVec.getValueType().getVectorNumElements();
11019 for (; i != NumElts; ++i) {
11020 SDValue Arg = InVec.getOperand(i);
11021 if (Arg.getOpcode() == ISD::UNDEF) continue;
11025 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
11026 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
11027 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
11028 if (C->getZExtValue() == SplatIdx)
11029 BaseShAmt = InVec.getOperand(1);
11032 if (BaseShAmt.getNode() == 0)
11033 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11034 DAG.getIntPtrConstant(0));
11038 // The shift amount is an i32.
11039 if (EltVT.bitsGT(MVT::i32))
11040 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11041 else if (EltVT.bitsLT(MVT::i32))
11042 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11044 // The shift amount is identical so we can do a vector shift.
11045 SDValue ValOp = N->getOperand(0);
11046 switch (N->getOpcode()) {
11048 llvm_unreachable("Unknown shift opcode!");
11051 if (VT == MVT::v2i64)
11052 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11053 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11055 if (VT == MVT::v4i32)
11056 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11057 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11059 if (VT == MVT::v8i16)
11060 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11061 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11065 if (VT == MVT::v4i32)
11066 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11067 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11069 if (VT == MVT::v8i16)
11070 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11071 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11075 if (VT == MVT::v2i64)
11076 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11077 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11079 if (VT == MVT::v4i32)
11080 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11081 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11083 if (VT == MVT::v8i16)
11084 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11085 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11093 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11094 TargetLowering::DAGCombinerInfo &DCI,
11095 const X86Subtarget *Subtarget) {
11096 if (DCI.isBeforeLegalizeOps())
11099 // Want to form PANDN nodes, in the hopes of then easily combining them with
11100 // OR and AND nodes to form PBLEND/PSIGN.
11101 EVT VT = N->getValueType(0);
11102 if (VT != MVT::v2i64)
11105 SDValue N0 = N->getOperand(0);
11106 SDValue N1 = N->getOperand(1);
11107 DebugLoc DL = N->getDebugLoc();
11109 // Check LHS for vnot
11110 if (N0.getOpcode() == ISD::XOR &&
11111 ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11112 return DAG.getNode(X86ISD::PANDN, DL, VT, N0.getOperand(0), N1);
11114 // Check RHS for vnot
11115 if (N1.getOpcode() == ISD::XOR &&
11116 ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11117 return DAG.getNode(X86ISD::PANDN, DL, VT, N1.getOperand(0), N0);
11122 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11123 TargetLowering::DAGCombinerInfo &DCI,
11124 const X86Subtarget *Subtarget) {
11125 if (DCI.isBeforeLegalizeOps())
11128 EVT VT = N->getValueType(0);
11129 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11132 SDValue N0 = N->getOperand(0);
11133 SDValue N1 = N->getOperand(1);
11135 // look for psign/blend
11136 if (Subtarget->hasSSSE3()) {
11137 if (VT == MVT::v2i64) {
11138 // Canonicalize pandn to RHS
11139 if (N0.getOpcode() == X86ISD::PANDN)
11141 // or (and (m, x), (pandn m, y))
11142 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::PANDN) {
11143 SDValue Mask = N1.getOperand(0);
11144 SDValue X = N1.getOperand(1);
11146 if (N0.getOperand(0) == Mask)
11147 Y = N0.getOperand(1);
11148 if (N0.getOperand(1) == Mask)
11149 Y = N0.getOperand(0);
11151 // Check to see if the mask appeared in both the AND and PANDN and
11155 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11156 if (Mask.getOpcode() != ISD::BITCAST ||
11157 X.getOpcode() != ISD::BITCAST ||
11158 Y.getOpcode() != ISD::BITCAST)
11161 // Look through mask bitcast.
11162 Mask = Mask.getOperand(0);
11163 EVT MaskVT = Mask.getValueType();
11165 // Validate that the Mask operand is a vector sra node. The sra node
11166 // will be an intrinsic.
11167 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11170 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11171 // there is no psrai.b
11172 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11173 case Intrinsic::x86_sse2_psrai_w:
11174 case Intrinsic::x86_sse2_psrai_d:
11176 default: return SDValue();
11179 // Check that the SRA is all signbits.
11180 SDValue SraC = Mask.getOperand(2);
11181 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
11182 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11183 if ((SraAmt + 1) != EltBits)
11186 DebugLoc DL = N->getDebugLoc();
11188 // Now we know we at least have a plendvb with the mask val. See if
11189 // we can form a psignb/w/d.
11190 // psign = x.type == y.type == mask.type && y = sub(0, x);
11191 X = X.getOperand(0);
11192 Y = Y.getOperand(0);
11193 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11194 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11195 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11198 case 8: Opc = X86ISD::PSIGNB; break;
11199 case 16: Opc = X86ISD::PSIGNW; break;
11200 case 32: Opc = X86ISD::PSIGND; break;
11204 SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11205 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
11208 // PBLENDVB only available on SSE 4.1
11209 if (!Subtarget->hasSSE41())
11212 unsigned IID = Intrinsic::x86_sse41_pblendvb;
11213 X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
11214 Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
11215 Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
11216 Mask = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::v16i8,
11217 DAG.getConstant(IID, MVT::i32), X, Y, Mask);
11218 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
11223 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11224 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11226 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11228 if (!N0.hasOneUse() || !N1.hasOneUse())
11231 SDValue ShAmt0 = N0.getOperand(1);
11232 if (ShAmt0.getValueType() != MVT::i8)
11234 SDValue ShAmt1 = N1.getOperand(1);
11235 if (ShAmt1.getValueType() != MVT::i8)
11237 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
11238 ShAmt0 = ShAmt0.getOperand(0);
11239 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
11240 ShAmt1 = ShAmt1.getOperand(0);
11242 DebugLoc DL = N->getDebugLoc();
11243 unsigned Opc = X86ISD::SHLD;
11244 SDValue Op0 = N0.getOperand(0);
11245 SDValue Op1 = N1.getOperand(0);
11246 if (ShAmt0.getOpcode() == ISD::SUB) {
11247 Opc = X86ISD::SHRD;
11248 std::swap(Op0, Op1);
11249 std::swap(ShAmt0, ShAmt1);
11252 unsigned Bits = VT.getSizeInBits();
11253 if (ShAmt1.getOpcode() == ISD::SUB) {
11254 SDValue Sum = ShAmt1.getOperand(0);
11255 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11256 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11257 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11258 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11259 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11260 return DAG.getNode(Opc, DL, VT,
11262 DAG.getNode(ISD::TRUNCATE, DL,
11265 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11266 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11268 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11269 return DAG.getNode(Opc, DL, VT,
11270 N0.getOperand(0), N1.getOperand(0),
11271 DAG.getNode(ISD::TRUNCATE, DL,
11278 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
11279 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
11280 const X86Subtarget *Subtarget) {
11281 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
11282 // the FP state in cases where an emms may be missing.
11283 // A preferable solution to the general problem is to figure out the right
11284 // places to insert EMMS. This qualifies as a quick hack.
11286 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
11287 StoreSDNode *St = cast<StoreSDNode>(N);
11288 EVT VT = St->getValue().getValueType();
11289 if (VT.getSizeInBits() != 64)
11292 const Function *F = DAG.getMachineFunction().getFunction();
11293 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
11294 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
11295 && Subtarget->hasSSE2();
11296 if ((VT.isVector() ||
11297 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
11298 isa<LoadSDNode>(St->getValue()) &&
11299 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
11300 St->getChain().hasOneUse() && !St->isVolatile()) {
11301 SDNode* LdVal = St->getValue().getNode();
11302 LoadSDNode *Ld = 0;
11303 int TokenFactorIndex = -1;
11304 SmallVector<SDValue, 8> Ops;
11305 SDNode* ChainVal = St->getChain().getNode();
11306 // Must be a store of a load. We currently handle two cases: the load
11307 // is a direct child, and it's under an intervening TokenFactor. It is
11308 // possible to dig deeper under nested TokenFactors.
11309 if (ChainVal == LdVal)
11310 Ld = cast<LoadSDNode>(St->getChain());
11311 else if (St->getValue().hasOneUse() &&
11312 ChainVal->getOpcode() == ISD::TokenFactor) {
11313 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
11314 if (ChainVal->getOperand(i).getNode() == LdVal) {
11315 TokenFactorIndex = i;
11316 Ld = cast<LoadSDNode>(St->getValue());
11318 Ops.push_back(ChainVal->getOperand(i));
11322 if (!Ld || !ISD::isNormalLoad(Ld))
11325 // If this is not the MMX case, i.e. we are just turning i64 load/store
11326 // into f64 load/store, avoid the transformation if there are multiple
11327 // uses of the loaded value.
11328 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
11331 DebugLoc LdDL = Ld->getDebugLoc();
11332 DebugLoc StDL = N->getDebugLoc();
11333 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
11334 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
11336 if (Subtarget->is64Bit() || F64IsLegal) {
11337 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
11338 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
11339 Ld->getPointerInfo(), Ld->isVolatile(),
11340 Ld->isNonTemporal(), Ld->getAlignment());
11341 SDValue NewChain = NewLd.getValue(1);
11342 if (TokenFactorIndex != -1) {
11343 Ops.push_back(NewChain);
11344 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11347 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
11348 St->getPointerInfo(),
11349 St->isVolatile(), St->isNonTemporal(),
11350 St->getAlignment());
11353 // Otherwise, lower to two pairs of 32-bit loads / stores.
11354 SDValue LoAddr = Ld->getBasePtr();
11355 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
11356 DAG.getConstant(4, MVT::i32));
11358 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
11359 Ld->getPointerInfo(),
11360 Ld->isVolatile(), Ld->isNonTemporal(),
11361 Ld->getAlignment());
11362 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
11363 Ld->getPointerInfo().getWithOffset(4),
11364 Ld->isVolatile(), Ld->isNonTemporal(),
11365 MinAlign(Ld->getAlignment(), 4));
11367 SDValue NewChain = LoLd.getValue(1);
11368 if (TokenFactorIndex != -1) {
11369 Ops.push_back(LoLd);
11370 Ops.push_back(HiLd);
11371 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11375 LoAddr = St->getBasePtr();
11376 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
11377 DAG.getConstant(4, MVT::i32));
11379 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
11380 St->getPointerInfo(),
11381 St->isVolatile(), St->isNonTemporal(),
11382 St->getAlignment());
11383 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
11384 St->getPointerInfo().getWithOffset(4),
11386 St->isNonTemporal(),
11387 MinAlign(St->getAlignment(), 4));
11388 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
11393 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
11394 /// X86ISD::FXOR nodes.
11395 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
11396 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
11397 // F[X]OR(0.0, x) -> x
11398 // F[X]OR(x, 0.0) -> x
11399 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11400 if (C->getValueAPF().isPosZero())
11401 return N->getOperand(1);
11402 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11403 if (C->getValueAPF().isPosZero())
11404 return N->getOperand(0);
11408 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
11409 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
11410 // FAND(0.0, x) -> 0.0
11411 // FAND(x, 0.0) -> 0.0
11412 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11413 if (C->getValueAPF().isPosZero())
11414 return N->getOperand(0);
11415 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11416 if (C->getValueAPF().isPosZero())
11417 return N->getOperand(1);
11421 static SDValue PerformBTCombine(SDNode *N,
11423 TargetLowering::DAGCombinerInfo &DCI) {
11424 // BT ignores high bits in the bit index operand.
11425 SDValue Op1 = N->getOperand(1);
11426 if (Op1.hasOneUse()) {
11427 unsigned BitWidth = Op1.getValueSizeInBits();
11428 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
11429 APInt KnownZero, KnownOne;
11430 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
11431 !DCI.isBeforeLegalizeOps());
11432 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11433 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
11434 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
11435 DCI.CommitTargetLoweringOpt(TLO);
11440 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
11441 SDValue Op = N->getOperand(0);
11442 if (Op.getOpcode() == ISD::BITCAST)
11443 Op = Op.getOperand(0);
11444 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
11445 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
11446 VT.getVectorElementType().getSizeInBits() ==
11447 OpVT.getVectorElementType().getSizeInBits()) {
11448 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
11453 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
11454 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
11455 // (and (i32 x86isd::setcc_carry), 1)
11456 // This eliminates the zext. This transformation is necessary because
11457 // ISD::SETCC is always legalized to i8.
11458 DebugLoc dl = N->getDebugLoc();
11459 SDValue N0 = N->getOperand(0);
11460 EVT VT = N->getValueType(0);
11461 if (N0.getOpcode() == ISD::AND &&
11463 N0.getOperand(0).hasOneUse()) {
11464 SDValue N00 = N0.getOperand(0);
11465 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
11467 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
11468 if (!C || C->getZExtValue() != 1)
11470 return DAG.getNode(ISD::AND, dl, VT,
11471 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
11472 N00.getOperand(0), N00.getOperand(1)),
11473 DAG.getConstant(1, VT));
11479 // Optimize RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
11480 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG) {
11481 unsigned X86CC = N->getConstantOperandVal(0);
11482 SDValue EFLAG = N->getOperand(1);
11483 DebugLoc DL = N->getDebugLoc();
11485 // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
11486 // a zext and produces an all-ones bit which is more useful than 0/1 in some
11488 if (X86CC == X86::COND_B)
11489 return DAG.getNode(ISD::AND, DL, MVT::i8,
11490 DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
11491 DAG.getConstant(X86CC, MVT::i8), EFLAG),
11492 DAG.getConstant(1, MVT::i8));
11497 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
11498 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
11499 X86TargetLowering::DAGCombinerInfo &DCI) {
11500 // If the LHS and RHS of the ADC node are zero, then it can't overflow and
11501 // the result is either zero or one (depending on the input carry bit).
11502 // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
11503 if (X86::isZeroNode(N->getOperand(0)) &&
11504 X86::isZeroNode(N->getOperand(1)) &&
11505 // We don't have a good way to replace an EFLAGS use, so only do this when
11507 SDValue(N, 1).use_empty()) {
11508 DebugLoc DL = N->getDebugLoc();
11509 EVT VT = N->getValueType(0);
11510 SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
11511 SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
11512 DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
11513 DAG.getConstant(X86::COND_B,MVT::i8),
11515 DAG.getConstant(1, VT));
11516 return DCI.CombineTo(N, Res1, CarryOut);
11523 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
11524 DAGCombinerInfo &DCI) const {
11525 SelectionDAG &DAG = DCI.DAG;
11526 switch (N->getOpcode()) {
11528 case ISD::EXTRACT_VECTOR_ELT:
11529 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
11530 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
11531 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
11532 case X86ISD::ADC: return PerformADCCombine(N, DAG, DCI);
11533 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
11536 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
11537 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
11538 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
11539 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
11541 case X86ISD::FOR: return PerformFORCombine(N, DAG);
11542 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
11543 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
11544 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
11545 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
11546 case X86ISD::SETCC: return PerformSETCCCombine(N, DAG);
11547 case X86ISD::SHUFPS: // Handle all target specific shuffles
11548 case X86ISD::SHUFPD:
11549 case X86ISD::PALIGN:
11550 case X86ISD::PUNPCKHBW:
11551 case X86ISD::PUNPCKHWD:
11552 case X86ISD::PUNPCKHDQ:
11553 case X86ISD::PUNPCKHQDQ:
11554 case X86ISD::UNPCKHPS:
11555 case X86ISD::UNPCKHPD:
11556 case X86ISD::PUNPCKLBW:
11557 case X86ISD::PUNPCKLWD:
11558 case X86ISD::PUNPCKLDQ:
11559 case X86ISD::PUNPCKLQDQ:
11560 case X86ISD::UNPCKLPS:
11561 case X86ISD::UNPCKLPD:
11562 case X86ISD::MOVHLPS:
11563 case X86ISD::MOVLHPS:
11564 case X86ISD::PSHUFD:
11565 case X86ISD::PSHUFHW:
11566 case X86ISD::PSHUFLW:
11567 case X86ISD::MOVSS:
11568 case X86ISD::MOVSD:
11569 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI);
11575 /// isTypeDesirableForOp - Return true if the target has native support for
11576 /// the specified value type and it is 'desirable' to use the type for the
11577 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
11578 /// instruction encodings are longer and some i16 instructions are slow.
11579 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
11580 if (!isTypeLegal(VT))
11582 if (VT != MVT::i16)
11589 case ISD::SIGN_EXTEND:
11590 case ISD::ZERO_EXTEND:
11591 case ISD::ANY_EXTEND:
11604 /// IsDesirableToPromoteOp - This method query the target whether it is
11605 /// beneficial for dag combiner to promote the specified node. If true, it
11606 /// should return the desired promotion type by reference.
11607 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
11608 EVT VT = Op.getValueType();
11609 if (VT != MVT::i16)
11612 bool Promote = false;
11613 bool Commute = false;
11614 switch (Op.getOpcode()) {
11617 LoadSDNode *LD = cast<LoadSDNode>(Op);
11618 // If the non-extending load has a single use and it's not live out, then it
11619 // might be folded.
11620 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
11621 Op.hasOneUse()*/) {
11622 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11623 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
11624 // The only case where we'd want to promote LOAD (rather then it being
11625 // promoted as an operand is when it's only use is liveout.
11626 if (UI->getOpcode() != ISD::CopyToReg)
11633 case ISD::SIGN_EXTEND:
11634 case ISD::ZERO_EXTEND:
11635 case ISD::ANY_EXTEND:
11640 SDValue N0 = Op.getOperand(0);
11641 // Look out for (store (shl (load), x)).
11642 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
11655 SDValue N0 = Op.getOperand(0);
11656 SDValue N1 = Op.getOperand(1);
11657 if (!Commute && MayFoldLoad(N1))
11659 // Avoid disabling potential load folding opportunities.
11660 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
11662 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
11672 //===----------------------------------------------------------------------===//
11673 // X86 Inline Assembly Support
11674 //===----------------------------------------------------------------------===//
11676 static bool LowerToBSwap(CallInst *CI) {
11677 // FIXME: this should verify that we are targetting a 486 or better. If not,
11678 // we will turn this bswap into something that will be lowered to logical ops
11679 // instead of emitting the bswap asm. For now, we don't support 486 or lower
11680 // so don't worry about this.
11682 // Verify this is a simple bswap.
11683 if (CI->getNumArgOperands() != 1 ||
11684 CI->getType() != CI->getArgOperand(0)->getType() ||
11685 !CI->getType()->isIntegerTy())
11688 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11689 if (!Ty || Ty->getBitWidth() % 16 != 0)
11692 // Okay, we can do this xform, do so now.
11693 const Type *Tys[] = { Ty };
11694 Module *M = CI->getParent()->getParent()->getParent();
11695 Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
11697 Value *Op = CI->getArgOperand(0);
11698 Op = CallInst::Create(Int, Op, CI->getName(), CI);
11700 CI->replaceAllUsesWith(Op);
11701 CI->eraseFromParent();
11705 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
11706 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
11707 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
11709 std::string AsmStr = IA->getAsmString();
11711 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
11712 SmallVector<StringRef, 4> AsmPieces;
11713 SplitString(AsmStr, AsmPieces, ";\n");
11715 switch (AsmPieces.size()) {
11716 default: return false;
11718 AsmStr = AsmPieces[0];
11720 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
11723 if (AsmPieces.size() == 2 &&
11724 (AsmPieces[0] == "bswap" ||
11725 AsmPieces[0] == "bswapq" ||
11726 AsmPieces[0] == "bswapl") &&
11727 (AsmPieces[1] == "$0" ||
11728 AsmPieces[1] == "${0:q}")) {
11729 // No need to check constraints, nothing other than the equivalent of
11730 // "=r,0" would be valid here.
11731 return LowerToBSwap(CI);
11733 // rorw $$8, ${0:w} --> llvm.bswap.i16
11734 if (CI->getType()->isIntegerTy(16) &&
11735 AsmPieces.size() == 3 &&
11736 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
11737 AsmPieces[1] == "$$8," &&
11738 AsmPieces[2] == "${0:w}" &&
11739 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
11741 const std::string &Constraints = IA->getConstraintString();
11742 SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
11743 std::sort(AsmPieces.begin(), AsmPieces.end());
11744 if (AsmPieces.size() == 4 &&
11745 AsmPieces[0] == "~{cc}" &&
11746 AsmPieces[1] == "~{dirflag}" &&
11747 AsmPieces[2] == "~{flags}" &&
11748 AsmPieces[3] == "~{fpsr}") {
11749 return LowerToBSwap(CI);
11754 if (CI->getType()->isIntegerTy(32) &&
11755 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
11756 SmallVector<StringRef, 4> Words;
11757 SplitString(AsmPieces[0], Words, " \t,");
11758 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
11759 Words[2] == "${0:w}") {
11761 SplitString(AsmPieces[1], Words, " \t,");
11762 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
11763 Words[2] == "$0") {
11765 SplitString(AsmPieces[2], Words, " \t,");
11766 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
11767 Words[2] == "${0:w}") {
11769 const std::string &Constraints = IA->getConstraintString();
11770 SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
11771 std::sort(AsmPieces.begin(), AsmPieces.end());
11772 if (AsmPieces.size() == 4 &&
11773 AsmPieces[0] == "~{cc}" &&
11774 AsmPieces[1] == "~{dirflag}" &&
11775 AsmPieces[2] == "~{flags}" &&
11776 AsmPieces[3] == "~{fpsr}") {
11777 return LowerToBSwap(CI);
11783 if (CI->getType()->isIntegerTy(64) &&
11784 Constraints.size() >= 2 &&
11785 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
11786 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
11787 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
11788 SmallVector<StringRef, 4> Words;
11789 SplitString(AsmPieces[0], Words, " \t");
11790 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
11792 SplitString(AsmPieces[1], Words, " \t");
11793 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
11795 SplitString(AsmPieces[2], Words, " \t,");
11796 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
11797 Words[2] == "%edx") {
11798 return LowerToBSwap(CI);
11810 /// getConstraintType - Given a constraint letter, return the type of
11811 /// constraint it is for this target.
11812 X86TargetLowering::ConstraintType
11813 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
11814 if (Constraint.size() == 1) {
11815 switch (Constraint[0]) {
11825 return C_RegisterClass;
11849 return TargetLowering::getConstraintType(Constraint);
11852 /// Examine constraint type and operand type and determine a weight value.
11853 /// This object must already have been set up with the operand type
11854 /// and the current alternative constraint selected.
11855 TargetLowering::ConstraintWeight
11856 X86TargetLowering::getSingleConstraintMatchWeight(
11857 AsmOperandInfo &info, const char *constraint) const {
11858 ConstraintWeight weight = CW_Invalid;
11859 Value *CallOperandVal = info.CallOperandVal;
11860 // If we don't have a value, we can't do a match,
11861 // but allow it at the lowest weight.
11862 if (CallOperandVal == NULL)
11864 const Type *type = CallOperandVal->getType();
11865 // Look at the constraint type.
11866 switch (*constraint) {
11868 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11879 if (CallOperandVal->getType()->isIntegerTy())
11880 weight = CW_SpecificReg;
11885 if (type->isFloatingPointTy())
11886 weight = CW_SpecificReg;
11889 if (type->isX86_MMXTy() && Subtarget->hasMMX())
11890 weight = CW_SpecificReg;
11894 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
11895 weight = CW_Register;
11898 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
11899 if (C->getZExtValue() <= 31)
11900 weight = CW_Constant;
11904 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11905 if (C->getZExtValue() <= 63)
11906 weight = CW_Constant;
11910 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11911 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
11912 weight = CW_Constant;
11916 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11917 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
11918 weight = CW_Constant;
11922 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11923 if (C->getZExtValue() <= 3)
11924 weight = CW_Constant;
11928 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11929 if (C->getZExtValue() <= 0xff)
11930 weight = CW_Constant;
11935 if (dyn_cast<ConstantFP>(CallOperandVal)) {
11936 weight = CW_Constant;
11940 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11941 if ((C->getSExtValue() >= -0x80000000LL) &&
11942 (C->getSExtValue() <= 0x7fffffffLL))
11943 weight = CW_Constant;
11947 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11948 if (C->getZExtValue() <= 0xffffffff)
11949 weight = CW_Constant;
11956 /// LowerXConstraint - try to replace an X constraint, which matches anything,
11957 /// with another that has more specific requirements based on the type of the
11958 /// corresponding operand.
11959 const char *X86TargetLowering::
11960 LowerXConstraint(EVT ConstraintVT) const {
11961 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
11962 // 'f' like normal targets.
11963 if (ConstraintVT.isFloatingPoint()) {
11964 if (Subtarget->hasXMMInt())
11966 if (Subtarget->hasXMM())
11970 return TargetLowering::LowerXConstraint(ConstraintVT);
11973 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11974 /// vector. If it is invalid, don't add anything to Ops.
11975 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11977 std::vector<SDValue>&Ops,
11978 SelectionDAG &DAG) const {
11979 SDValue Result(0, 0);
11981 switch (Constraint) {
11984 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11985 if (C->getZExtValue() <= 31) {
11986 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11992 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11993 if (C->getZExtValue() <= 63) {
11994 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12000 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12001 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
12002 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12008 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12009 if (C->getZExtValue() <= 255) {
12010 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12016 // 32-bit signed value
12017 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12018 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12019 C->getSExtValue())) {
12020 // Widen to 64 bits here to get it sign extended.
12021 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
12024 // FIXME gcc accepts some relocatable values here too, but only in certain
12025 // memory models; it's complicated.
12030 // 32-bit unsigned value
12031 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
12032 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
12033 C->getZExtValue())) {
12034 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
12038 // FIXME gcc accepts some relocatable values here too, but only in certain
12039 // memory models; it's complicated.
12043 // Literal immediates are always ok.
12044 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
12045 // Widen to 64 bits here to get it sign extended.
12046 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
12050 // In any sort of PIC mode addresses need to be computed at runtime by
12051 // adding in a register or some sort of table lookup. These can't
12052 // be used as immediates.
12053 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
12056 // If we are in non-pic codegen mode, we allow the address of a global (with
12057 // an optional displacement) to be used with 'i'.
12058 GlobalAddressSDNode *GA = 0;
12059 int64_t Offset = 0;
12061 // Match either (GA), (GA+C), (GA+C1+C2), etc.
12063 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
12064 Offset += GA->getOffset();
12066 } else if (Op.getOpcode() == ISD::ADD) {
12067 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12068 Offset += C->getZExtValue();
12069 Op = Op.getOperand(0);
12072 } else if (Op.getOpcode() == ISD::SUB) {
12073 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
12074 Offset += -C->getZExtValue();
12075 Op = Op.getOperand(0);
12080 // Otherwise, this isn't something we can handle, reject it.
12084 const GlobalValue *GV = GA->getGlobal();
12085 // If we require an extra load to get this address, as in PIC mode, we
12086 // can't accept it.
12087 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12088 getTargetMachine())))
12091 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12092 GA->getValueType(0), Offset);
12097 if (Result.getNode()) {
12098 Ops.push_back(Result);
12101 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12104 std::vector<unsigned> X86TargetLowering::
12105 getRegClassForInlineAsmConstraint(const std::string &Constraint,
12107 if (Constraint.size() == 1) {
12108 // FIXME: not handling fp-stack yet!
12109 switch (Constraint[0]) { // GCC X86 Constraint Letters
12110 default: break; // Unknown constraint letter
12111 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12112 if (Subtarget->is64Bit()) {
12113 if (VT == MVT::i32)
12114 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
12115 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
12116 X86::R10D,X86::R11D,X86::R12D,
12117 X86::R13D,X86::R14D,X86::R15D,
12118 X86::EBP, X86::ESP, 0);
12119 else if (VT == MVT::i16)
12120 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
12121 X86::SI, X86::DI, X86::R8W,X86::R9W,
12122 X86::R10W,X86::R11W,X86::R12W,
12123 X86::R13W,X86::R14W,X86::R15W,
12124 X86::BP, X86::SP, 0);
12125 else if (VT == MVT::i8)
12126 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
12127 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
12128 X86::R10B,X86::R11B,X86::R12B,
12129 X86::R13B,X86::R14B,X86::R15B,
12130 X86::BPL, X86::SPL, 0);
12132 else if (VT == MVT::i64)
12133 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
12134 X86::RSI, X86::RDI, X86::R8, X86::R9,
12135 X86::R10, X86::R11, X86::R12,
12136 X86::R13, X86::R14, X86::R15,
12137 X86::RBP, X86::RSP, 0);
12141 // 32-bit fallthrough
12142 case 'Q': // Q_REGS
12143 if (VT == MVT::i32)
12144 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
12145 else if (VT == MVT::i16)
12146 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
12147 else if (VT == MVT::i8)
12148 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
12149 else if (VT == MVT::i64)
12150 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
12155 return std::vector<unsigned>();
12158 std::pair<unsigned, const TargetRegisterClass*>
12159 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12161 // First, see if this is a constraint that directly corresponds to an LLVM
12163 if (Constraint.size() == 1) {
12164 // GCC Constraint Letters
12165 switch (Constraint[0]) {
12167 case 'r': // GENERAL_REGS
12168 case 'l': // INDEX_REGS
12170 return std::make_pair(0U, X86::GR8RegisterClass);
12171 if (VT == MVT::i16)
12172 return std::make_pair(0U, X86::GR16RegisterClass);
12173 if (VT == MVT::i32 || !Subtarget->is64Bit())
12174 return std::make_pair(0U, X86::GR32RegisterClass);
12175 return std::make_pair(0U, X86::GR64RegisterClass);
12176 case 'R': // LEGACY_REGS
12178 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
12179 if (VT == MVT::i16)
12180 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
12181 if (VT == MVT::i32 || !Subtarget->is64Bit())
12182 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
12183 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
12184 case 'f': // FP Stack registers.
12185 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
12186 // value to the correct fpstack register class.
12187 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
12188 return std::make_pair(0U, X86::RFP32RegisterClass);
12189 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
12190 return std::make_pair(0U, X86::RFP64RegisterClass);
12191 return std::make_pair(0U, X86::RFP80RegisterClass);
12192 case 'y': // MMX_REGS if MMX allowed.
12193 if (!Subtarget->hasMMX()) break;
12194 return std::make_pair(0U, X86::VR64RegisterClass);
12195 case 'Y': // SSE_REGS if SSE2 allowed
12196 if (!Subtarget->hasXMMInt()) break;
12198 case 'x': // SSE_REGS if SSE1 allowed
12199 if (!Subtarget->hasXMM()) break;
12201 switch (VT.getSimpleVT().SimpleTy) {
12203 // Scalar SSE types.
12206 return std::make_pair(0U, X86::FR32RegisterClass);
12209 return std::make_pair(0U, X86::FR64RegisterClass);
12217 return std::make_pair(0U, X86::VR128RegisterClass);
12223 // Use the default implementation in TargetLowering to convert the register
12224 // constraint into a member of a register class.
12225 std::pair<unsigned, const TargetRegisterClass*> Res;
12226 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
12228 // Not found as a standard register?
12229 if (Res.second == 0) {
12230 // Map st(0) -> st(7) -> ST0
12231 if (Constraint.size() == 7 && Constraint[0] == '{' &&
12232 tolower(Constraint[1]) == 's' &&
12233 tolower(Constraint[2]) == 't' &&
12234 Constraint[3] == '(' &&
12235 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
12236 Constraint[5] == ')' &&
12237 Constraint[6] == '}') {
12239 Res.first = X86::ST0+Constraint[4]-'0';
12240 Res.second = X86::RFP80RegisterClass;
12244 // GCC allows "st(0)" to be called just plain "st".
12245 if (StringRef("{st}").equals_lower(Constraint)) {
12246 Res.first = X86::ST0;
12247 Res.second = X86::RFP80RegisterClass;
12252 if (StringRef("{flags}").equals_lower(Constraint)) {
12253 Res.first = X86::EFLAGS;
12254 Res.second = X86::CCRRegisterClass;
12258 // 'A' means EAX + EDX.
12259 if (Constraint == "A") {
12260 Res.first = X86::EAX;
12261 Res.second = X86::GR32_ADRegisterClass;
12267 // Otherwise, check to see if this is a register class of the wrong value
12268 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
12269 // turn into {ax},{dx}.
12270 if (Res.second->hasType(VT))
12271 return Res; // Correct type already, nothing to do.
12273 // All of the single-register GCC register classes map their values onto
12274 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
12275 // really want an 8-bit or 32-bit register, map to the appropriate register
12276 // class and return the appropriate register.
12277 if (Res.second == X86::GR16RegisterClass) {
12278 if (VT == MVT::i8) {
12279 unsigned DestReg = 0;
12280 switch (Res.first) {
12282 case X86::AX: DestReg = X86::AL; break;
12283 case X86::DX: DestReg = X86::DL; break;
12284 case X86::CX: DestReg = X86::CL; break;
12285 case X86::BX: DestReg = X86::BL; break;
12288 Res.first = DestReg;
12289 Res.second = X86::GR8RegisterClass;
12291 } else if (VT == MVT::i32) {
12292 unsigned DestReg = 0;
12293 switch (Res.first) {
12295 case X86::AX: DestReg = X86::EAX; break;
12296 case X86::DX: DestReg = X86::EDX; break;
12297 case X86::CX: DestReg = X86::ECX; break;
12298 case X86::BX: DestReg = X86::EBX; break;
12299 case X86::SI: DestReg = X86::ESI; break;
12300 case X86::DI: DestReg = X86::EDI; break;
12301 case X86::BP: DestReg = X86::EBP; break;
12302 case X86::SP: DestReg = X86::ESP; break;
12305 Res.first = DestReg;
12306 Res.second = X86::GR32RegisterClass;
12308 } else if (VT == MVT::i64) {
12309 unsigned DestReg = 0;
12310 switch (Res.first) {
12312 case X86::AX: DestReg = X86::RAX; break;
12313 case X86::DX: DestReg = X86::RDX; break;
12314 case X86::CX: DestReg = X86::RCX; break;
12315 case X86::BX: DestReg = X86::RBX; break;
12316 case X86::SI: DestReg = X86::RSI; break;
12317 case X86::DI: DestReg = X86::RDI; break;
12318 case X86::BP: DestReg = X86::RBP; break;
12319 case X86::SP: DestReg = X86::RSP; break;
12322 Res.first = DestReg;
12323 Res.second = X86::GR64RegisterClass;
12326 } else if (Res.second == X86::FR32RegisterClass ||
12327 Res.second == X86::FR64RegisterClass ||
12328 Res.second == X86::VR128RegisterClass) {
12329 // Handle references to XMM physical registers that got mapped into the
12330 // wrong class. This can happen with constraints like {xmm0} where the
12331 // target independent register mapper will just pick the first match it can
12332 // find, ignoring the required type.
12333 if (VT == MVT::f32)
12334 Res.second = X86::FR32RegisterClass;
12335 else if (VT == MVT::f64)
12336 Res.second = X86::FR64RegisterClass;
12337 else if (X86::VR128RegisterClass->hasType(VT))
12338 Res.second = X86::VR128RegisterClass;