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");
59 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
61 // Forward declarations.
62 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
65 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
67 bool is64Bit = TM.getSubtarget<X86Subtarget>().is64Bit();
69 if (TM.getSubtarget<X86Subtarget>().isTargetDarwin()) {
70 if (is64Bit) return new X8664_MachoTargetObjectFile();
71 return new TargetLoweringObjectFileMachO();
72 } else if (TM.getSubtarget<X86Subtarget>().isTargetELF() ){
73 if (is64Bit) return new X8664_ELFTargetObjectFile(TM);
74 return new X8632_ELFTargetObjectFile(TM);
75 } else if (TM.getSubtarget<X86Subtarget>().isTargetCOFF()) {
76 return new TargetLoweringObjectFileCOFF();
78 llvm_unreachable("unknown subtarget type");
81 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
82 : TargetLowering(TM, createTLOF(TM)) {
83 Subtarget = &TM.getSubtarget<X86Subtarget>();
84 X86ScalarSSEf64 = Subtarget->hasSSE2();
85 X86ScalarSSEf32 = Subtarget->hasSSE1();
86 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
88 RegInfo = TM.getRegisterInfo();
91 // Set up the TargetLowering object.
93 // X86 is weird, it always uses i8 for shift amounts and setcc results.
94 setShiftAmountType(MVT::i8);
95 setBooleanContents(ZeroOrOneBooleanContent);
96 setSchedulingPreference(Sched::RegPressure);
97 setStackPointerRegisterToSaveRestore(X86StackPtr);
99 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
100 // Setup Windows compiler runtime calls.
101 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
102 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
103 setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
104 setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
105 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
106 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
107 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
108 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
111 if (Subtarget->isTargetDarwin()) {
112 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
113 setUseUnderscoreSetJmp(false);
114 setUseUnderscoreLongJmp(false);
115 } else if (Subtarget->isTargetMingw()) {
116 // MS runtime is weird: it exports _setjmp, but longjmp!
117 setUseUnderscoreSetJmp(true);
118 setUseUnderscoreLongJmp(false);
120 setUseUnderscoreSetJmp(true);
121 setUseUnderscoreLongJmp(true);
124 // Set up the register classes.
125 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
126 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
127 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
128 if (Subtarget->is64Bit())
129 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
131 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
133 // We don't accept any truncstore of integer registers.
134 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
135 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
136 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
137 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
138 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
139 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
141 // SETOEQ and SETUNE require checking two conditions.
142 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
143 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
144 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
145 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
146 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
147 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
149 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
151 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
152 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
153 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
155 if (Subtarget->is64Bit()) {
156 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
157 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
158 } else if (!UseSoftFloat) {
159 // We have an algorithm for SSE2->double, and we turn this into a
160 // 64-bit FILD followed by conditional FADD for other targets.
161 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
162 // We have an algorithm for SSE2, and we turn this into a 64-bit
163 // FILD for other targets.
164 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
167 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
169 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
170 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
173 // SSE has no i16 to fp conversion, only i32
174 if (X86ScalarSSEf32) {
175 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
176 // f32 and f64 cases are Legal, f80 case is not
177 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
179 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
180 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
183 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
184 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
187 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
188 // are Legal, f80 is custom lowered.
189 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
190 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
192 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
194 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
195 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
197 if (X86ScalarSSEf32) {
198 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
199 // f32 and f64 cases are Legal, f80 case is not
200 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
202 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
203 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
206 // Handle FP_TO_UINT by promoting the destination to a larger signed
208 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
209 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
210 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
212 if (Subtarget->is64Bit()) {
213 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
214 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
215 } else if (!UseSoftFloat) {
216 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
217 // Expand FP_TO_UINT into a select.
218 // FIXME: We would like to use a Custom expander here eventually to do
219 // the optimal thing for SSE vs. the default expansion in the legalizer.
220 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
222 // With SSE3 we can use fisttpll to convert to a signed i64; without
223 // SSE, we're stuck with a fistpll.
224 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
227 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
228 if (!X86ScalarSSEf64) {
229 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
230 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
231 if (Subtarget->is64Bit()) {
232 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
233 // Without SSE, i64->f64 goes through memory.
234 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
238 // Scalar integer divide and remainder are lowered to use operations that
239 // produce two results, to match the available instructions. This exposes
240 // the two-result form to trivial CSE, which is able to combine x/y and x%y
241 // into a single instruction.
243 // Scalar integer multiply-high is also lowered to use two-result
244 // operations, to match the available instructions. However, plain multiply
245 // (low) operations are left as Legal, as there are single-result
246 // instructions for this in x86. Using the two-result multiply instructions
247 // when both high and low results are needed must be arranged by dagcombine.
248 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
249 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
250 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
251 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
252 setOperationAction(ISD::SREM , MVT::i8 , Expand);
253 setOperationAction(ISD::UREM , MVT::i8 , Expand);
254 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
255 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
256 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
257 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
258 setOperationAction(ISD::SREM , MVT::i16 , Expand);
259 setOperationAction(ISD::UREM , MVT::i16 , Expand);
260 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
261 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
262 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
263 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
264 setOperationAction(ISD::SREM , MVT::i32 , Expand);
265 setOperationAction(ISD::UREM , MVT::i32 , Expand);
266 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
267 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
268 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
269 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
270 setOperationAction(ISD::SREM , MVT::i64 , Expand);
271 setOperationAction(ISD::UREM , MVT::i64 , Expand);
273 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
274 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
275 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
276 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
277 if (Subtarget->is64Bit())
278 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
279 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
280 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
281 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
282 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
283 setOperationAction(ISD::FREM , MVT::f32 , Expand);
284 setOperationAction(ISD::FREM , MVT::f64 , Expand);
285 setOperationAction(ISD::FREM , MVT::f80 , Expand);
286 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
288 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
289 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
290 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
291 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
292 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
293 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
294 if (Subtarget->is64Bit()) {
295 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
296 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
299 if (Subtarget->hasPOPCNT()) {
300 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
302 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
303 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
304 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
305 if (Subtarget->is64Bit())
306 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
309 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
310 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
312 // These should be promoted to a larger select which is supported.
313 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
314 // X86 wants to expand cmov itself.
315 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
316 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
317 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
318 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
319 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
320 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
321 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
322 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
323 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
324 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
325 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
326 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
327 if (Subtarget->is64Bit()) {
328 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
329 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
331 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
334 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
335 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
336 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
337 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
338 if (Subtarget->is64Bit())
339 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
340 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
341 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
342 if (Subtarget->is64Bit()) {
343 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
344 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
345 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
346 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
347 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
349 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
350 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
351 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
352 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
353 if (Subtarget->is64Bit()) {
354 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
355 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
356 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
359 if (Subtarget->hasSSE1())
360 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
362 // We may not have a libcall for MEMBARRIER so we should lower this.
363 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
365 // On X86 and X86-64, atomic operations are lowered to locked instructions.
366 // Locked instructions, in turn, have implicit fence semantics (all memory
367 // operations are flushed before issuing the locked instruction, and they
368 // are not buffered), so we can fold away the common pattern of
369 // fence-atomic-fence.
370 setShouldFoldAtomicFences(true);
372 // Expand certain atomics
373 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
374 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
375 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
376 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
378 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
379 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
380 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
381 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
383 if (!Subtarget->is64Bit()) {
384 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
385 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
386 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
387 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
388 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
389 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
390 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
393 // FIXME - use subtarget debug flags
394 if (!Subtarget->isTargetDarwin() &&
395 !Subtarget->isTargetELF() &&
396 !Subtarget->isTargetCygMing()) {
397 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
400 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
401 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
402 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
403 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
404 if (Subtarget->is64Bit()) {
405 setExceptionPointerRegister(X86::RAX);
406 setExceptionSelectorRegister(X86::RDX);
408 setExceptionPointerRegister(X86::EAX);
409 setExceptionSelectorRegister(X86::EDX);
411 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
412 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
414 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
416 setOperationAction(ISD::TRAP, MVT::Other, Legal);
418 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
419 setOperationAction(ISD::VASTART , MVT::Other, Custom);
420 setOperationAction(ISD::VAEND , MVT::Other, Expand);
421 if (Subtarget->is64Bit()) {
422 setOperationAction(ISD::VAARG , MVT::Other, Custom);
423 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
425 setOperationAction(ISD::VAARG , MVT::Other, Expand);
426 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
429 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
430 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
431 if (Subtarget->is64Bit())
432 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
433 if (Subtarget->isTargetCygMing() || Subtarget->isTargetWindows())
434 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
436 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
438 if (!UseSoftFloat && X86ScalarSSEf64) {
439 // f32 and f64 use SSE.
440 // Set up the FP register classes.
441 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
442 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
444 // Use ANDPD to simulate FABS.
445 setOperationAction(ISD::FABS , MVT::f64, Custom);
446 setOperationAction(ISD::FABS , MVT::f32, Custom);
448 // Use XORP to simulate FNEG.
449 setOperationAction(ISD::FNEG , MVT::f64, Custom);
450 setOperationAction(ISD::FNEG , MVT::f32, Custom);
452 // Use ANDPD and ORPD to simulate FCOPYSIGN.
453 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
454 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
456 // We don't support sin/cos/fmod
457 setOperationAction(ISD::FSIN , MVT::f64, Expand);
458 setOperationAction(ISD::FCOS , MVT::f64, Expand);
459 setOperationAction(ISD::FSIN , MVT::f32, Expand);
460 setOperationAction(ISD::FCOS , MVT::f32, Expand);
462 // Expand FP immediates into loads from the stack, except for the special
464 addLegalFPImmediate(APFloat(+0.0)); // xorpd
465 addLegalFPImmediate(APFloat(+0.0f)); // xorps
466 } else if (!UseSoftFloat && X86ScalarSSEf32) {
467 // Use SSE for f32, x87 for f64.
468 // Set up the FP register classes.
469 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
470 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
472 // Use ANDPS to simulate FABS.
473 setOperationAction(ISD::FABS , MVT::f32, Custom);
475 // Use XORP to simulate FNEG.
476 setOperationAction(ISD::FNEG , MVT::f32, Custom);
478 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
480 // Use ANDPS and ORPS to simulate FCOPYSIGN.
481 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
482 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
484 // We don't support sin/cos/fmod
485 setOperationAction(ISD::FSIN , MVT::f32, Expand);
486 setOperationAction(ISD::FCOS , MVT::f32, Expand);
488 // Special cases we handle for FP constants.
489 addLegalFPImmediate(APFloat(+0.0f)); // xorps
490 addLegalFPImmediate(APFloat(+0.0)); // FLD0
491 addLegalFPImmediate(APFloat(+1.0)); // FLD1
492 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
493 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
496 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
497 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
499 } else if (!UseSoftFloat) {
500 // f32 and f64 in x87.
501 // Set up the FP register classes.
502 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
503 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
505 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
506 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
507 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
508 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
511 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
512 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
514 addLegalFPImmediate(APFloat(+0.0)); // FLD0
515 addLegalFPImmediate(APFloat(+1.0)); // FLD1
516 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
517 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
518 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
519 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
520 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
521 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
524 // Long double always uses X87.
526 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
527 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
528 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
530 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
531 addLegalFPImmediate(TmpFlt); // FLD0
533 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
536 APFloat TmpFlt2(+1.0);
537 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
539 addLegalFPImmediate(TmpFlt2); // FLD1
540 TmpFlt2.changeSign();
541 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
545 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
546 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
550 // Always use a library call for pow.
551 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
552 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
553 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
555 setOperationAction(ISD::FLOG, MVT::f80, Expand);
556 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
557 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
558 setOperationAction(ISD::FEXP, MVT::f80, Expand);
559 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
561 // First set operation action for all vector types to either promote
562 // (for widening) or expand (for scalarization). Then we will selectively
563 // turn on ones that can be effectively codegen'd.
564 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
565 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
566 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
567 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
568 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
569 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
570 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
571 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
572 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
573 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
574 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
575 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
576 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
577 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
578 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
579 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
580 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
581 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
582 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
583 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
584 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
585 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
586 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
587 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
588 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
589 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
590 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
591 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
592 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
593 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
594 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
595 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
596 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
597 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
598 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
599 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
600 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
601 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
602 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
603 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
604 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
605 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
606 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
607 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
608 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
609 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
610 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
611 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
612 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
613 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
614 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
615 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
616 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
617 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
618 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
619 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
620 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
621 setTruncStoreAction((MVT::SimpleValueType)VT,
622 (MVT::SimpleValueType)InnerVT, Expand);
623 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
624 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
625 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
628 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
629 // with -msoft-float, disable use of MMX as well.
630 if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
631 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
632 // No operations on x86mmx supported, everything uses intrinsics.
635 // MMX-sized vectors (other than x86mmx) are expected to be expanded
636 // into smaller operations.
637 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
638 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
639 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
640 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
641 setOperationAction(ISD::AND, MVT::v8i8, Expand);
642 setOperationAction(ISD::AND, MVT::v4i16, Expand);
643 setOperationAction(ISD::AND, MVT::v2i32, Expand);
644 setOperationAction(ISD::AND, MVT::v1i64, Expand);
645 setOperationAction(ISD::OR, MVT::v8i8, Expand);
646 setOperationAction(ISD::OR, MVT::v4i16, Expand);
647 setOperationAction(ISD::OR, MVT::v2i32, Expand);
648 setOperationAction(ISD::OR, MVT::v1i64, Expand);
649 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
650 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
651 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
652 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
653 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
654 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
655 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
656 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
657 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
658 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
659 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
660 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
661 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
662 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
663 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
664 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
665 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
667 if (!UseSoftFloat && Subtarget->hasSSE1()) {
668 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
670 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
671 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
672 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
673 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
674 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
675 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
676 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
677 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
678 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
679 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
680 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
681 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
684 if (!UseSoftFloat && Subtarget->hasSSE2()) {
685 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
687 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
688 // registers cannot be used even for integer operations.
689 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
690 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
691 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
692 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
694 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
695 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
696 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
697 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
698 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
699 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
700 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
701 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
702 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
703 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
704 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
705 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
706 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
707 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
708 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
709 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
711 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
712 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
713 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
714 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
716 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
717 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
718 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
719 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
720 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
722 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
723 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
724 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
725 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
726 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
728 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
729 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
730 EVT VT = (MVT::SimpleValueType)i;
731 // Do not attempt to custom lower non-power-of-2 vectors
732 if (!isPowerOf2_32(VT.getVectorNumElements()))
734 // Do not attempt to custom lower non-128-bit vectors
735 if (!VT.is128BitVector())
737 setOperationAction(ISD::BUILD_VECTOR,
738 VT.getSimpleVT().SimpleTy, Custom);
739 setOperationAction(ISD::VECTOR_SHUFFLE,
740 VT.getSimpleVT().SimpleTy, Custom);
741 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
742 VT.getSimpleVT().SimpleTy, Custom);
745 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
746 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
747 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
748 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
749 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
750 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
752 if (Subtarget->is64Bit()) {
753 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
754 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
757 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
758 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
759 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
762 // Do not attempt to promote non-128-bit vectors
763 if (!VT.is128BitVector())
766 setOperationAction(ISD::AND, SVT, Promote);
767 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
768 setOperationAction(ISD::OR, SVT, Promote);
769 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
770 setOperationAction(ISD::XOR, SVT, Promote);
771 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
772 setOperationAction(ISD::LOAD, SVT, Promote);
773 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
774 setOperationAction(ISD::SELECT, SVT, Promote);
775 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
778 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
780 // Custom lower v2i64 and v2f64 selects.
781 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
782 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
783 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
784 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
786 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
787 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
790 if (Subtarget->hasSSE41()) {
791 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
792 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
793 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
794 setOperationAction(ISD::FRINT, MVT::f32, Legal);
795 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
796 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
797 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
798 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
799 setOperationAction(ISD::FRINT, MVT::f64, Legal);
800 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
802 // FIXME: Do we need to handle scalar-to-vector here?
803 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
805 // Can turn SHL into an integer multiply.
806 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
807 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
809 // i8 and i16 vectors are custom , because the source register and source
810 // source memory operand types are not the same width. f32 vectors are
811 // custom since the immediate controlling the insert encodes additional
813 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
814 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
815 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
816 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
818 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
819 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
820 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
821 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
823 if (Subtarget->is64Bit()) {
824 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
825 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
829 if (Subtarget->hasSSE42()) {
830 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
833 if (!UseSoftFloat && Subtarget->hasAVX()) {
834 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
835 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
836 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
837 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
838 addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
840 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
841 setOperationAction(ISD::LOAD, MVT::v8i32, Legal);
842 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
843 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
844 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
845 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
846 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
847 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
848 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
849 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
850 setOperationAction(ISD::BUILD_VECTOR, MVT::v8f32, Custom);
851 //setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Custom);
852 //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
853 //setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
854 //setOperationAction(ISD::VSETCC, MVT::v8f32, Custom);
856 // Operations to consider commented out -v16i16 v32i8
857 //setOperationAction(ISD::ADD, MVT::v16i16, Legal);
858 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
859 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
860 //setOperationAction(ISD::SUB, MVT::v32i8, Legal);
861 //setOperationAction(ISD::SUB, MVT::v16i16, Legal);
862 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
863 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
864 //setOperationAction(ISD::MUL, MVT::v16i16, Legal);
865 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
866 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
867 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
868 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
869 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
870 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
872 setOperationAction(ISD::VSETCC, MVT::v4f64, Custom);
873 // setOperationAction(ISD::VSETCC, MVT::v32i8, Custom);
874 // setOperationAction(ISD::VSETCC, MVT::v16i16, Custom);
875 setOperationAction(ISD::VSETCC, MVT::v8i32, Custom);
877 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v32i8, Custom);
878 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i16, Custom);
879 // setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i16, Custom);
880 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i32, Custom);
881 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8f32, Custom);
883 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
884 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i64, Custom);
885 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f64, Custom);
886 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i64, Custom);
887 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f64, Custom);
888 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
891 // Not sure we want to do this since there are no 256-bit integer
894 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
895 // This includes 256-bit vectors
896 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
897 EVT VT = (MVT::SimpleValueType)i;
899 // Do not attempt to custom lower non-power-of-2 vectors
900 if (!isPowerOf2_32(VT.getVectorNumElements()))
903 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
904 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
905 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
908 if (Subtarget->is64Bit()) {
909 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i64, Custom);
910 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
915 // Not sure we want to do this since there are no 256-bit integer
918 // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
919 // Including 256-bit vectors
920 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
921 EVT VT = (MVT::SimpleValueType)i;
923 if (!VT.is256BitVector()) {
926 setOperationAction(ISD::AND, VT, Promote);
927 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
928 setOperationAction(ISD::OR, VT, Promote);
929 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
930 setOperationAction(ISD::XOR, VT, Promote);
931 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
932 setOperationAction(ISD::LOAD, VT, Promote);
933 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
934 setOperationAction(ISD::SELECT, VT, Promote);
935 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
938 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
942 // We want to custom lower some of our intrinsics.
943 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
945 // Add/Sub/Mul with overflow operations are custom lowered.
946 setOperationAction(ISD::SADDO, MVT::i32, Custom);
947 setOperationAction(ISD::UADDO, MVT::i32, Custom);
948 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
949 setOperationAction(ISD::USUBO, MVT::i32, Custom);
950 setOperationAction(ISD::SMULO, MVT::i32, Custom);
951 setOperationAction(ISD::UMULO, MVT::i32, Custom);
953 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
954 // handle type legalization for these operations here.
956 // FIXME: We really should do custom legalization for addition and
957 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
958 // than generic legalization for 64-bit multiplication-with-overflow, though.
959 if (Subtarget->is64Bit()) {
960 setOperationAction(ISD::SADDO, MVT::i64, Custom);
961 setOperationAction(ISD::UADDO, MVT::i64, Custom);
962 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
963 setOperationAction(ISD::USUBO, MVT::i64, Custom);
964 setOperationAction(ISD::SMULO, MVT::i64, Custom);
965 setOperationAction(ISD::UMULO, MVT::i64, Custom);
968 if (!Subtarget->is64Bit()) {
969 // These libcalls are not available in 32-bit.
970 setLibcallName(RTLIB::SHL_I128, 0);
971 setLibcallName(RTLIB::SRL_I128, 0);
972 setLibcallName(RTLIB::SRA_I128, 0);
975 // We have target-specific dag combine patterns for the following nodes:
976 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
977 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
978 setTargetDAGCombine(ISD::BUILD_VECTOR);
979 setTargetDAGCombine(ISD::SELECT);
980 setTargetDAGCombine(ISD::SHL);
981 setTargetDAGCombine(ISD::SRA);
982 setTargetDAGCombine(ISD::SRL);
983 setTargetDAGCombine(ISD::OR);
984 setTargetDAGCombine(ISD::STORE);
985 setTargetDAGCombine(ISD::ZERO_EXTEND);
986 if (Subtarget->is64Bit())
987 setTargetDAGCombine(ISD::MUL);
989 computeRegisterProperties();
991 // FIXME: These should be based on subtarget info. Plus, the values should
992 // be smaller when we are in optimizing for size mode.
993 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
994 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
995 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
996 setPrefLoopAlignment(16);
997 benefitFromCodePlacementOpt = true;
1001 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1006 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1007 /// the desired ByVal argument alignment.
1008 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1011 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1012 if (VTy->getBitWidth() == 128)
1014 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1015 unsigned EltAlign = 0;
1016 getMaxByValAlign(ATy->getElementType(), EltAlign);
1017 if (EltAlign > MaxAlign)
1018 MaxAlign = EltAlign;
1019 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1020 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1021 unsigned EltAlign = 0;
1022 getMaxByValAlign(STy->getElementType(i), EltAlign);
1023 if (EltAlign > MaxAlign)
1024 MaxAlign = EltAlign;
1032 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1033 /// function arguments in the caller parameter area. For X86, aggregates
1034 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1035 /// are at 4-byte boundaries.
1036 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1037 if (Subtarget->is64Bit()) {
1038 // Max of 8 and alignment of type.
1039 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1046 if (Subtarget->hasSSE1())
1047 getMaxByValAlign(Ty, Align);
1051 /// getOptimalMemOpType - Returns the target specific optimal type for load
1052 /// and store operations as a result of memset, memcpy, and memmove
1053 /// lowering. If DstAlign is zero that means it's safe to destination
1054 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1055 /// means there isn't a need to check it against alignment requirement,
1056 /// probably because the source does not need to be loaded. If
1057 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1058 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1059 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1060 /// constant so it does not need to be loaded.
1061 /// It returns EVT::Other if the type should be determined using generic
1062 /// target-independent logic.
1064 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1065 unsigned DstAlign, unsigned SrcAlign,
1066 bool NonScalarIntSafe,
1068 MachineFunction &MF) const {
1069 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1070 // linux. This is because the stack realignment code can't handle certain
1071 // cases like PR2962. This should be removed when PR2962 is fixed.
1072 const Function *F = MF.getFunction();
1073 if (NonScalarIntSafe &&
1074 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1076 (Subtarget->isUnalignedMemAccessFast() ||
1077 ((DstAlign == 0 || DstAlign >= 16) &&
1078 (SrcAlign == 0 || SrcAlign >= 16))) &&
1079 Subtarget->getStackAlignment() >= 16) {
1080 if (Subtarget->hasSSE2())
1082 if (Subtarget->hasSSE1())
1084 } else if (!MemcpyStrSrc && Size >= 8 &&
1085 !Subtarget->is64Bit() &&
1086 Subtarget->getStackAlignment() >= 8 &&
1087 Subtarget->hasSSE2()) {
1088 // Do not use f64 to lower memcpy if source is string constant. It's
1089 // better to use i32 to avoid the loads.
1093 if (Subtarget->is64Bit() && Size >= 8)
1098 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1099 /// current function. The returned value is a member of the
1100 /// MachineJumpTableInfo::JTEntryKind enum.
1101 unsigned X86TargetLowering::getJumpTableEncoding() const {
1102 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1104 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1105 Subtarget->isPICStyleGOT())
1106 return MachineJumpTableInfo::EK_Custom32;
1108 // Otherwise, use the normal jump table encoding heuristics.
1109 return TargetLowering::getJumpTableEncoding();
1113 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1114 const MachineBasicBlock *MBB,
1115 unsigned uid,MCContext &Ctx) const{
1116 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1117 Subtarget->isPICStyleGOT());
1118 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1120 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1121 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1124 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1126 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1127 SelectionDAG &DAG) const {
1128 if (!Subtarget->is64Bit())
1129 // This doesn't have DebugLoc associated with it, but is not really the
1130 // same as a Register.
1131 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1135 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1136 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1138 const MCExpr *X86TargetLowering::
1139 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1140 MCContext &Ctx) const {
1141 // X86-64 uses RIP relative addressing based on the jump table label.
1142 if (Subtarget->isPICStyleRIPRel())
1143 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1145 // Otherwise, the reference is relative to the PIC base.
1146 return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1149 /// getFunctionAlignment - Return the Log2 alignment of this function.
1150 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1151 return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1154 std::pair<const TargetRegisterClass*, uint8_t>
1155 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1156 const TargetRegisterClass *RRC = 0;
1158 switch (VT.getSimpleVT().SimpleTy) {
1160 return TargetLowering::findRepresentativeClass(VT);
1161 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1162 RRC = (Subtarget->is64Bit()
1163 ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1166 RRC = X86::VR64RegisterClass;
1168 case MVT::f32: case MVT::f64:
1169 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1170 case MVT::v4f32: case MVT::v2f64:
1171 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1173 RRC = X86::VR128RegisterClass;
1176 return std::make_pair(RRC, Cost);
1180 X86TargetLowering::getRegPressureLimit(const TargetRegisterClass *RC,
1181 MachineFunction &MF) const {
1182 const TargetFrameInfo *TFI = MF.getTarget().getFrameInfo();
1184 unsigned FPDiff = TFI->hasFP(MF) ? 1 : 0;
1185 switch (RC->getID()) {
1188 case X86::GR32RegClassID:
1190 case X86::GR64RegClassID:
1192 case X86::VR128RegClassID:
1193 return Subtarget->is64Bit() ? 10 : 4;
1194 case X86::VR64RegClassID:
1199 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1200 unsigned &Offset) const {
1201 if (!Subtarget->isTargetLinux())
1204 if (Subtarget->is64Bit()) {
1205 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1207 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1220 //===----------------------------------------------------------------------===//
1221 // Return Value Calling Convention Implementation
1222 //===----------------------------------------------------------------------===//
1224 #include "X86GenCallingConv.inc"
1227 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1228 const SmallVectorImpl<ISD::OutputArg> &Outs,
1229 LLVMContext &Context) const {
1230 SmallVector<CCValAssign, 16> RVLocs;
1231 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1233 return CCInfo.CheckReturn(Outs, RetCC_X86);
1237 X86TargetLowering::LowerReturn(SDValue Chain,
1238 CallingConv::ID CallConv, bool isVarArg,
1239 const SmallVectorImpl<ISD::OutputArg> &Outs,
1240 const SmallVectorImpl<SDValue> &OutVals,
1241 DebugLoc dl, SelectionDAG &DAG) const {
1242 MachineFunction &MF = DAG.getMachineFunction();
1243 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1245 SmallVector<CCValAssign, 16> RVLocs;
1246 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1247 RVLocs, *DAG.getContext());
1248 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1250 // Add the regs to the liveout set for the function.
1251 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1252 for (unsigned i = 0; i != RVLocs.size(); ++i)
1253 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1254 MRI.addLiveOut(RVLocs[i].getLocReg());
1258 SmallVector<SDValue, 6> RetOps;
1259 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1260 // Operand #1 = Bytes To Pop
1261 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1264 // Copy the result values into the output registers.
1265 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1266 CCValAssign &VA = RVLocs[i];
1267 assert(VA.isRegLoc() && "Can only return in registers!");
1268 SDValue ValToCopy = OutVals[i];
1269 EVT ValVT = ValToCopy.getValueType();
1271 // If this is x86-64, and we disabled SSE, we can't return FP values,
1272 // or SSE or MMX vectors.
1273 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1274 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1275 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1276 report_fatal_error("SSE register return with SSE disabled");
1278 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1279 // llvm-gcc has never done it right and no one has noticed, so this
1280 // should be OK for now.
1281 if (ValVT == MVT::f64 &&
1282 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1283 report_fatal_error("SSE2 register return with SSE2 disabled");
1285 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1286 // the RET instruction and handled by the FP Stackifier.
1287 if (VA.getLocReg() == X86::ST0 ||
1288 VA.getLocReg() == X86::ST1) {
1289 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1290 // change the value to the FP stack register class.
1291 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1292 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1293 RetOps.push_back(ValToCopy);
1294 // Don't emit a copytoreg.
1298 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1299 // which is returned in RAX / RDX.
1300 if (Subtarget->is64Bit()) {
1301 if (ValVT == MVT::x86mmx) {
1302 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1303 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1304 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1306 // If we don't have SSE2 available, convert to v4f32 so the generated
1307 // register is legal.
1308 if (!Subtarget->hasSSE2())
1309 ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1314 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1315 Flag = Chain.getValue(1);
1318 // The x86-64 ABI for returning structs by value requires that we copy
1319 // the sret argument into %rax for the return. We saved the argument into
1320 // a virtual register in the entry block, so now we copy the value out
1322 if (Subtarget->is64Bit() &&
1323 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1324 MachineFunction &MF = DAG.getMachineFunction();
1325 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1326 unsigned Reg = FuncInfo->getSRetReturnReg();
1328 "SRetReturnReg should have been set in LowerFormalArguments().");
1329 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1331 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1332 Flag = Chain.getValue(1);
1334 // RAX now acts like a return value.
1335 MRI.addLiveOut(X86::RAX);
1338 RetOps[0] = Chain; // Update chain.
1340 // Add the flag if we have it.
1342 RetOps.push_back(Flag);
1344 return DAG.getNode(X86ISD::RET_FLAG, dl,
1345 MVT::Other, &RetOps[0], RetOps.size());
1348 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N) const {
1349 if (N->getNumValues() != 1)
1351 if (!N->hasNUsesOfValue(1, 0))
1354 SDNode *Copy = *N->use_begin();
1355 if (Copy->getOpcode() != ISD::CopyToReg &&
1356 Copy->getOpcode() != ISD::FP_EXTEND)
1359 bool HasRet = false;
1360 for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1362 if (UI->getOpcode() != X86ISD::RET_FLAG)
1370 /// LowerCallResult - Lower the result values of a call into the
1371 /// appropriate copies out of appropriate physical registers.
1374 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1375 CallingConv::ID CallConv, bool isVarArg,
1376 const SmallVectorImpl<ISD::InputArg> &Ins,
1377 DebugLoc dl, SelectionDAG &DAG,
1378 SmallVectorImpl<SDValue> &InVals) const {
1380 // Assign locations to each value returned by this call.
1381 SmallVector<CCValAssign, 16> RVLocs;
1382 bool Is64Bit = Subtarget->is64Bit();
1383 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1384 RVLocs, *DAG.getContext());
1385 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1387 // Copy all of the result registers out of their specified physreg.
1388 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1389 CCValAssign &VA = RVLocs[i];
1390 EVT CopyVT = VA.getValVT();
1392 // If this is x86-64, and we disabled SSE, we can't return FP values
1393 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1394 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1395 report_fatal_error("SSE register return with SSE disabled");
1400 // If this is a call to a function that returns an fp value on the floating
1401 // point stack, we must guarantee the the value is popped from the stack, so
1402 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1403 // if the return value is not used. We use the FpGET_ST0 instructions
1405 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1406 // If we prefer to use the value in xmm registers, copy it out as f80 and
1407 // use a truncate to move it from fp stack reg to xmm reg.
1408 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1409 bool isST0 = VA.getLocReg() == X86::ST0;
1411 if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1412 if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1413 if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1414 SDValue Ops[] = { Chain, InFlag };
1415 Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Flag,
1417 Val = Chain.getValue(0);
1419 // Round the f80 to the right size, which also moves it to the appropriate
1421 if (CopyVT != VA.getValVT())
1422 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1423 // This truncation won't change the value.
1424 DAG.getIntPtrConstant(1));
1425 } else if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1426 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1427 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1428 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1429 MVT::v2i64, InFlag).getValue(1);
1430 Val = Chain.getValue(0);
1431 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1432 Val, DAG.getConstant(0, MVT::i64));
1434 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1435 MVT::i64, InFlag).getValue(1);
1436 Val = Chain.getValue(0);
1438 Val = DAG.getNode(ISD::BITCAST, dl, CopyVT, Val);
1440 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1441 CopyVT, InFlag).getValue(1);
1442 Val = Chain.getValue(0);
1444 InFlag = Chain.getValue(2);
1445 InVals.push_back(Val);
1452 //===----------------------------------------------------------------------===//
1453 // C & StdCall & Fast Calling Convention implementation
1454 //===----------------------------------------------------------------------===//
1455 // StdCall calling convention seems to be standard for many Windows' API
1456 // routines and around. It differs from C calling convention just a little:
1457 // callee should clean up the stack, not caller. Symbols should be also
1458 // decorated in some fancy way :) It doesn't support any vector arguments.
1459 // For info on fast calling convention see Fast Calling Convention (tail call)
1460 // implementation LowerX86_32FastCCCallTo.
1462 /// CallIsStructReturn - Determines whether a call uses struct return
1464 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1468 return Outs[0].Flags.isSRet();
1471 /// ArgsAreStructReturn - Determines whether a function uses struct
1472 /// return semantics.
1474 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1478 return Ins[0].Flags.isSRet();
1481 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1482 /// by "Src" to address "Dst" with size and alignment information specified by
1483 /// the specific parameter attribute. The copy will be passed as a byval
1484 /// function parameter.
1486 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1487 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1489 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1491 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1492 /*isVolatile*/false, /*AlwaysInline=*/true,
1493 MachinePointerInfo(), MachinePointerInfo());
1496 /// IsTailCallConvention - Return true if the calling convention is one that
1497 /// supports tail call optimization.
1498 static bool IsTailCallConvention(CallingConv::ID CC) {
1499 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1502 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1503 /// a tailcall target by changing its ABI.
1504 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1505 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1509 X86TargetLowering::LowerMemArgument(SDValue Chain,
1510 CallingConv::ID CallConv,
1511 const SmallVectorImpl<ISD::InputArg> &Ins,
1512 DebugLoc dl, SelectionDAG &DAG,
1513 const CCValAssign &VA,
1514 MachineFrameInfo *MFI,
1516 // Create the nodes corresponding to a load from this parameter slot.
1517 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1518 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1519 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1522 // If value is passed by pointer we have address passed instead of the value
1524 if (VA.getLocInfo() == CCValAssign::Indirect)
1525 ValVT = VA.getLocVT();
1527 ValVT = VA.getValVT();
1529 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1530 // changed with more analysis.
1531 // In case of tail call optimization mark all arguments mutable. Since they
1532 // could be overwritten by lowering of arguments in case of a tail call.
1533 if (Flags.isByVal()) {
1534 int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1535 VA.getLocMemOffset(), isImmutable);
1536 return DAG.getFrameIndex(FI, getPointerTy());
1538 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1539 VA.getLocMemOffset(), isImmutable);
1540 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1541 return DAG.getLoad(ValVT, dl, Chain, FIN,
1542 MachinePointerInfo::getFixedStack(FI),
1548 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1549 CallingConv::ID CallConv,
1551 const SmallVectorImpl<ISD::InputArg> &Ins,
1554 SmallVectorImpl<SDValue> &InVals)
1556 MachineFunction &MF = DAG.getMachineFunction();
1557 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1559 const Function* Fn = MF.getFunction();
1560 if (Fn->hasExternalLinkage() &&
1561 Subtarget->isTargetCygMing() &&
1562 Fn->getName() == "main")
1563 FuncInfo->setForceFramePointer(true);
1565 MachineFrameInfo *MFI = MF.getFrameInfo();
1566 bool Is64Bit = Subtarget->is64Bit();
1567 bool IsWin64 = Subtarget->isTargetWin64();
1569 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1570 "Var args not supported with calling convention fastcc or ghc");
1572 // Assign locations to all of the incoming arguments.
1573 SmallVector<CCValAssign, 16> ArgLocs;
1574 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1575 ArgLocs, *DAG.getContext());
1576 CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
1578 unsigned LastVal = ~0U;
1580 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1581 CCValAssign &VA = ArgLocs[i];
1582 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1584 assert(VA.getValNo() != LastVal &&
1585 "Don't support value assigned to multiple locs yet");
1586 LastVal = VA.getValNo();
1588 if (VA.isRegLoc()) {
1589 EVT RegVT = VA.getLocVT();
1590 TargetRegisterClass *RC = NULL;
1591 if (RegVT == MVT::i32)
1592 RC = X86::GR32RegisterClass;
1593 else if (Is64Bit && RegVT == MVT::i64)
1594 RC = X86::GR64RegisterClass;
1595 else if (RegVT == MVT::f32)
1596 RC = X86::FR32RegisterClass;
1597 else if (RegVT == MVT::f64)
1598 RC = X86::FR64RegisterClass;
1599 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1600 RC = X86::VR256RegisterClass;
1601 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1602 RC = X86::VR128RegisterClass;
1603 else if (RegVT == MVT::x86mmx)
1604 RC = X86::VR64RegisterClass;
1606 llvm_unreachable("Unknown argument type!");
1608 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1609 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1611 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1612 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1614 if (VA.getLocInfo() == CCValAssign::SExt)
1615 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1616 DAG.getValueType(VA.getValVT()));
1617 else if (VA.getLocInfo() == CCValAssign::ZExt)
1618 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1619 DAG.getValueType(VA.getValVT()));
1620 else if (VA.getLocInfo() == CCValAssign::BCvt)
1621 ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
1623 if (VA.isExtInLoc()) {
1624 // Handle MMX values passed in XMM regs.
1625 if (RegVT.isVector()) {
1626 ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(),
1629 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1632 assert(VA.isMemLoc());
1633 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1636 // If value is passed via pointer - do a load.
1637 if (VA.getLocInfo() == CCValAssign::Indirect)
1638 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1639 MachinePointerInfo(), false, false, 0);
1641 InVals.push_back(ArgValue);
1644 // The x86-64 ABI for returning structs by value requires that we copy
1645 // the sret argument into %rax for the return. Save the argument into
1646 // a virtual register so that we can access it from the return points.
1647 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1648 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1649 unsigned Reg = FuncInfo->getSRetReturnReg();
1651 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1652 FuncInfo->setSRetReturnReg(Reg);
1654 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1655 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1658 unsigned StackSize = CCInfo.getNextStackOffset();
1659 // Align stack specially for tail calls.
1660 if (FuncIsMadeTailCallSafe(CallConv))
1661 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1663 // If the function takes variable number of arguments, make a frame index for
1664 // the start of the first vararg value... for expansion of llvm.va_start.
1666 if (!IsWin64 && (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1667 CallConv != CallingConv::X86_ThisCall))) {
1668 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1671 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1673 // FIXME: We should really autogenerate these arrays
1674 static const unsigned GPR64ArgRegsWin64[] = {
1675 X86::RCX, X86::RDX, X86::R8, X86::R9
1677 static const unsigned GPR64ArgRegs64Bit[] = {
1678 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1680 static const unsigned XMMArgRegs64Bit[] = {
1681 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1682 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1684 const unsigned *GPR64ArgRegs;
1685 unsigned NumXMMRegs = 0;
1688 // The XMM registers which might contain var arg parameters are shadowed
1689 // in their paired GPR. So we only need to save the GPR to their home
1691 TotalNumIntRegs = 4;
1692 GPR64ArgRegs = GPR64ArgRegsWin64;
1694 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1695 GPR64ArgRegs = GPR64ArgRegs64Bit;
1697 NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit, TotalNumXMMRegs);
1699 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1702 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1703 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1704 "SSE register cannot be used when SSE is disabled!");
1705 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1706 "SSE register cannot be used when SSE is disabled!");
1707 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1708 // Kernel mode asks for SSE to be disabled, so don't push them
1710 TotalNumXMMRegs = 0;
1713 const TargetFrameInfo &TFI = *getTargetMachine().getFrameInfo();
1714 // Get to the caller-allocated home save location. Add 8 to account
1715 // for the return address.
1716 int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
1717 FuncInfo->setRegSaveFrameIndex(
1718 MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
1719 FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
1721 // For X86-64, if there are vararg parameters that are passed via
1722 // registers, then we must store them to their spots on the stack so they
1723 // may be loaded by deferencing the result of va_next.
1724 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1725 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1726 FuncInfo->setRegSaveFrameIndex(
1727 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1731 // Store the integer parameter registers.
1732 SmallVector<SDValue, 8> MemOps;
1733 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1735 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1736 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1737 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1738 DAG.getIntPtrConstant(Offset));
1739 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1740 X86::GR64RegisterClass);
1741 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1743 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1744 MachinePointerInfo::getFixedStack(
1745 FuncInfo->getRegSaveFrameIndex(), Offset),
1747 MemOps.push_back(Store);
1751 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1752 // Now store the XMM (fp + vector) parameter registers.
1753 SmallVector<SDValue, 11> SaveXMMOps;
1754 SaveXMMOps.push_back(Chain);
1756 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1757 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1758 SaveXMMOps.push_back(ALVal);
1760 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1761 FuncInfo->getRegSaveFrameIndex()));
1762 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1763 FuncInfo->getVarArgsFPOffset()));
1765 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1766 unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
1767 X86::VR128RegisterClass);
1768 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1769 SaveXMMOps.push_back(Val);
1771 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1773 &SaveXMMOps[0], SaveXMMOps.size()));
1776 if (!MemOps.empty())
1777 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1778 &MemOps[0], MemOps.size());
1782 // Some CCs need callee pop.
1783 if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1784 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1786 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1787 // If this is an sret function, the return should pop the hidden pointer.
1788 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1789 FuncInfo->setBytesToPopOnReturn(4);
1793 // RegSaveFrameIndex is X86-64 only.
1794 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1795 if (CallConv == CallingConv::X86_FastCall ||
1796 CallConv == CallingConv::X86_ThisCall)
1797 // fastcc functions can't have varargs.
1798 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1805 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1806 SDValue StackPtr, SDValue Arg,
1807 DebugLoc dl, SelectionDAG &DAG,
1808 const CCValAssign &VA,
1809 ISD::ArgFlagsTy Flags) const {
1810 const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1811 unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1812 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1813 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1814 if (Flags.isByVal())
1815 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1817 return DAG.getStore(Chain, dl, Arg, PtrOff,
1818 MachinePointerInfo::getStack(LocMemOffset),
1822 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1823 /// optimization is performed and it is required.
1825 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1826 SDValue &OutRetAddr, SDValue Chain,
1827 bool IsTailCall, bool Is64Bit,
1828 int FPDiff, DebugLoc dl) const {
1829 // Adjust the Return address stack slot.
1830 EVT VT = getPointerTy();
1831 OutRetAddr = getReturnAddressFrameIndex(DAG);
1833 // Load the "old" Return address.
1834 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1836 return SDValue(OutRetAddr.getNode(), 1);
1839 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1840 /// optimization is performed and it is required (FPDiff!=0).
1842 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1843 SDValue Chain, SDValue RetAddrFrIdx,
1844 bool Is64Bit, int FPDiff, DebugLoc dl) {
1845 // Store the return address to the appropriate stack slot.
1846 if (!FPDiff) return Chain;
1847 // Calculate the new stack slot for the return address.
1848 int SlotSize = Is64Bit ? 8 : 4;
1849 int NewReturnAddrFI =
1850 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1851 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1852 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1853 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1854 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1860 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1861 CallingConv::ID CallConv, bool isVarArg,
1863 const SmallVectorImpl<ISD::OutputArg> &Outs,
1864 const SmallVectorImpl<SDValue> &OutVals,
1865 const SmallVectorImpl<ISD::InputArg> &Ins,
1866 DebugLoc dl, SelectionDAG &DAG,
1867 SmallVectorImpl<SDValue> &InVals) const {
1868 MachineFunction &MF = DAG.getMachineFunction();
1869 bool Is64Bit = Subtarget->is64Bit();
1870 bool IsStructRet = CallIsStructReturn(Outs);
1871 bool IsSibcall = false;
1874 // Check if it's really possible to do a tail call.
1875 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1876 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1877 Outs, OutVals, Ins, DAG);
1879 // Sibcalls are automatically detected tailcalls which do not require
1881 if (!GuaranteedTailCallOpt && isTailCall)
1888 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1889 "Var args not supported with calling convention fastcc or ghc");
1891 // Analyze operands of the call, assigning locations to each operand.
1892 SmallVector<CCValAssign, 16> ArgLocs;
1893 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1894 ArgLocs, *DAG.getContext());
1895 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
1897 // Get a count of how many bytes are to be pushed on the stack.
1898 unsigned NumBytes = CCInfo.getNextStackOffset();
1900 // This is a sibcall. The memory operands are available in caller's
1901 // own caller's stack.
1903 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1904 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1907 if (isTailCall && !IsSibcall) {
1908 // Lower arguments at fp - stackoffset + fpdiff.
1909 unsigned NumBytesCallerPushed =
1910 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1911 FPDiff = NumBytesCallerPushed - NumBytes;
1913 // Set the delta of movement of the returnaddr stackslot.
1914 // But only set if delta is greater than previous delta.
1915 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1916 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1920 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1922 SDValue RetAddrFrIdx;
1923 // Load return adress for tail calls.
1924 if (isTailCall && FPDiff)
1925 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1926 Is64Bit, FPDiff, dl);
1928 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1929 SmallVector<SDValue, 8> MemOpChains;
1932 // Walk the register/memloc assignments, inserting copies/loads. In the case
1933 // of tail call optimization arguments are handle later.
1934 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1935 CCValAssign &VA = ArgLocs[i];
1936 EVT RegVT = VA.getLocVT();
1937 SDValue Arg = OutVals[i];
1938 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1939 bool isByVal = Flags.isByVal();
1941 // Promote the value if needed.
1942 switch (VA.getLocInfo()) {
1943 default: llvm_unreachable("Unknown loc info!");
1944 case CCValAssign::Full: break;
1945 case CCValAssign::SExt:
1946 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1948 case CCValAssign::ZExt:
1949 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1951 case CCValAssign::AExt:
1952 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1953 // Special case: passing MMX values in XMM registers.
1954 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
1955 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1956 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1958 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1960 case CCValAssign::BCvt:
1961 Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
1963 case CCValAssign::Indirect: {
1964 // Store the argument.
1965 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1966 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1967 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1968 MachinePointerInfo::getFixedStack(FI),
1975 if (VA.isRegLoc()) {
1976 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1977 if (isVarArg && Subtarget->isTargetWin64()) {
1978 // Win64 ABI requires argument XMM reg to be copied to the corresponding
1979 // shadow reg if callee is a varargs function.
1980 unsigned ShadowReg = 0;
1981 switch (VA.getLocReg()) {
1982 case X86::XMM0: ShadowReg = X86::RCX; break;
1983 case X86::XMM1: ShadowReg = X86::RDX; break;
1984 case X86::XMM2: ShadowReg = X86::R8; break;
1985 case X86::XMM3: ShadowReg = X86::R9; break;
1988 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
1990 } else if (!IsSibcall && (!isTailCall || isByVal)) {
1991 assert(VA.isMemLoc());
1992 if (StackPtr.getNode() == 0)
1993 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1994 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1995 dl, DAG, VA, Flags));
1999 if (!MemOpChains.empty())
2000 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2001 &MemOpChains[0], MemOpChains.size());
2003 // Build a sequence of copy-to-reg nodes chained together with token chain
2004 // and flag operands which copy the outgoing args into registers.
2006 // Tail call byval lowering might overwrite argument registers so in case of
2007 // tail call optimization the copies to registers are lowered later.
2009 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2010 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2011 RegsToPass[i].second, InFlag);
2012 InFlag = Chain.getValue(1);
2015 if (Subtarget->isPICStyleGOT()) {
2016 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2019 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2020 DAG.getNode(X86ISD::GlobalBaseReg,
2021 DebugLoc(), getPointerTy()),
2023 InFlag = Chain.getValue(1);
2025 // If we are tail calling and generating PIC/GOT style code load the
2026 // address of the callee into ECX. The value in ecx is used as target of
2027 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2028 // for tail calls on PIC/GOT architectures. Normally we would just put the
2029 // address of GOT into ebx and then call target@PLT. But for tail calls
2030 // ebx would be restored (since ebx is callee saved) before jumping to the
2033 // Note: The actual moving to ECX is done further down.
2034 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2035 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2036 !G->getGlobal()->hasProtectedVisibility())
2037 Callee = LowerGlobalAddress(Callee, DAG);
2038 else if (isa<ExternalSymbolSDNode>(Callee))
2039 Callee = LowerExternalSymbol(Callee, DAG);
2043 if (Is64Bit && isVarArg && !Subtarget->isTargetWin64()) {
2044 // From AMD64 ABI document:
2045 // For calls that may call functions that use varargs or stdargs
2046 // (prototype-less calls or calls to functions containing ellipsis (...) in
2047 // the declaration) %al is used as hidden argument to specify the number
2048 // of SSE registers used. The contents of %al do not need to match exactly
2049 // the number of registers, but must be an ubound on the number of SSE
2050 // registers used and is in the range 0 - 8 inclusive.
2052 // Count the number of XMM registers allocated.
2053 static const unsigned XMMArgRegs[] = {
2054 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2055 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2057 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2058 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2059 && "SSE registers cannot be used when SSE is disabled");
2061 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2062 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2063 InFlag = Chain.getValue(1);
2067 // For tail calls lower the arguments to the 'real' stack slot.
2069 // Force all the incoming stack arguments to be loaded from the stack
2070 // before any new outgoing arguments are stored to the stack, because the
2071 // outgoing stack slots may alias the incoming argument stack slots, and
2072 // the alias isn't otherwise explicit. This is slightly more conservative
2073 // than necessary, because it means that each store effectively depends
2074 // on every argument instead of just those arguments it would clobber.
2075 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2077 SmallVector<SDValue, 8> MemOpChains2;
2080 // Do not flag preceeding copytoreg stuff together with the following stuff.
2082 if (GuaranteedTailCallOpt) {
2083 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2084 CCValAssign &VA = ArgLocs[i];
2087 assert(VA.isMemLoc());
2088 SDValue Arg = OutVals[i];
2089 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2090 // Create frame index.
2091 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2092 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2093 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2094 FIN = DAG.getFrameIndex(FI, getPointerTy());
2096 if (Flags.isByVal()) {
2097 // Copy relative to framepointer.
2098 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2099 if (StackPtr.getNode() == 0)
2100 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2102 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2104 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2108 // Store relative to framepointer.
2109 MemOpChains2.push_back(
2110 DAG.getStore(ArgChain, dl, Arg, FIN,
2111 MachinePointerInfo::getFixedStack(FI),
2117 if (!MemOpChains2.empty())
2118 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2119 &MemOpChains2[0], MemOpChains2.size());
2121 // Copy arguments to their registers.
2122 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2123 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2124 RegsToPass[i].second, InFlag);
2125 InFlag = Chain.getValue(1);
2129 // Store the return address to the appropriate stack slot.
2130 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2134 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2135 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2136 // In the 64-bit large code model, we have to make all calls
2137 // through a register, since the call instruction's 32-bit
2138 // pc-relative offset may not be large enough to hold the whole
2140 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2141 // If the callee is a GlobalAddress node (quite common, every direct call
2142 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2145 // We should use extra load for direct calls to dllimported functions in
2147 const GlobalValue *GV = G->getGlobal();
2148 if (!GV->hasDLLImportLinkage()) {
2149 unsigned char OpFlags = 0;
2151 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2152 // external symbols most go through the PLT in PIC mode. If the symbol
2153 // has hidden or protected visibility, or if it is static or local, then
2154 // we don't need to use the PLT - we can directly call it.
2155 if (Subtarget->isTargetELF() &&
2156 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2157 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2158 OpFlags = X86II::MO_PLT;
2159 } else if (Subtarget->isPICStyleStubAny() &&
2160 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2161 Subtarget->getDarwinVers() < 9) {
2162 // PC-relative references to external symbols should go through $stub,
2163 // unless we're building with the leopard linker or later, which
2164 // automatically synthesizes these stubs.
2165 OpFlags = X86II::MO_DARWIN_STUB;
2168 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2169 G->getOffset(), OpFlags);
2171 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2172 unsigned char OpFlags = 0;
2174 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2175 // external symbols should go through the PLT.
2176 if (Subtarget->isTargetELF() &&
2177 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2178 OpFlags = X86II::MO_PLT;
2179 } else if (Subtarget->isPICStyleStubAny() &&
2180 Subtarget->getDarwinVers() < 9) {
2181 // PC-relative references to external symbols should go through $stub,
2182 // unless we're building with the leopard linker or later, which
2183 // automatically synthesizes these stubs.
2184 OpFlags = X86II::MO_DARWIN_STUB;
2187 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2191 // Returns a chain & a flag for retval copy to use.
2192 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2193 SmallVector<SDValue, 8> Ops;
2195 if (!IsSibcall && isTailCall) {
2196 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2197 DAG.getIntPtrConstant(0, true), InFlag);
2198 InFlag = Chain.getValue(1);
2201 Ops.push_back(Chain);
2202 Ops.push_back(Callee);
2205 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2207 // Add argument registers to the end of the list so that they are known live
2209 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2210 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2211 RegsToPass[i].second.getValueType()));
2213 // Add an implicit use GOT pointer in EBX.
2214 if (!isTailCall && Subtarget->isPICStyleGOT())
2215 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2217 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2218 if (Is64Bit && isVarArg && !Subtarget->isTargetWin64())
2219 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2221 if (InFlag.getNode())
2222 Ops.push_back(InFlag);
2226 //// If this is the first return lowered for this function, add the regs
2227 //// to the liveout set for the function.
2228 // This isn't right, although it's probably harmless on x86; liveouts
2229 // should be computed from returns not tail calls. Consider a void
2230 // function making a tail call to a function returning int.
2231 return DAG.getNode(X86ISD::TC_RETURN, dl,
2232 NodeTys, &Ops[0], Ops.size());
2235 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2236 InFlag = Chain.getValue(1);
2238 // Create the CALLSEQ_END node.
2239 unsigned NumBytesForCalleeToPush;
2240 if (Subtarget->IsCalleePop(isVarArg, CallConv))
2241 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2242 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2243 // If this is a call to a struct-return function, the callee
2244 // pops the hidden struct pointer, so we have to push it back.
2245 // This is common for Darwin/X86, Linux & Mingw32 targets.
2246 NumBytesForCalleeToPush = 4;
2248 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2250 // Returns a flag for retval copy to use.
2252 Chain = DAG.getCALLSEQ_END(Chain,
2253 DAG.getIntPtrConstant(NumBytes, true),
2254 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2257 InFlag = Chain.getValue(1);
2260 // Handle result values, copying them out of physregs into vregs that we
2262 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2263 Ins, dl, DAG, InVals);
2267 //===----------------------------------------------------------------------===//
2268 // Fast Calling Convention (tail call) implementation
2269 //===----------------------------------------------------------------------===//
2271 // Like std call, callee cleans arguments, convention except that ECX is
2272 // reserved for storing the tail called function address. Only 2 registers are
2273 // free for argument passing (inreg). Tail call optimization is performed
2275 // * tailcallopt is enabled
2276 // * caller/callee are fastcc
2277 // On X86_64 architecture with GOT-style position independent code only local
2278 // (within module) calls are supported at the moment.
2279 // To keep the stack aligned according to platform abi the function
2280 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2281 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2282 // If a tail called function callee has more arguments than the caller the
2283 // caller needs to make sure that there is room to move the RETADDR to. This is
2284 // achieved by reserving an area the size of the argument delta right after the
2285 // original REtADDR, but before the saved framepointer or the spilled registers
2286 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2298 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2299 /// for a 16 byte align requirement.
2301 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2302 SelectionDAG& DAG) const {
2303 MachineFunction &MF = DAG.getMachineFunction();
2304 const TargetMachine &TM = MF.getTarget();
2305 const TargetFrameInfo &TFI = *TM.getFrameInfo();
2306 unsigned StackAlignment = TFI.getStackAlignment();
2307 uint64_t AlignMask = StackAlignment - 1;
2308 int64_t Offset = StackSize;
2309 uint64_t SlotSize = TD->getPointerSize();
2310 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2311 // Number smaller than 12 so just add the difference.
2312 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2314 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2315 Offset = ((~AlignMask) & Offset) + StackAlignment +
2316 (StackAlignment-SlotSize);
2321 /// MatchingStackOffset - Return true if the given stack call argument is
2322 /// already available in the same position (relatively) of the caller's
2323 /// incoming argument stack.
2325 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2326 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2327 const X86InstrInfo *TII) {
2328 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2330 if (Arg.getOpcode() == ISD::CopyFromReg) {
2331 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2332 if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2334 MachineInstr *Def = MRI->getVRegDef(VR);
2337 if (!Flags.isByVal()) {
2338 if (!TII->isLoadFromStackSlot(Def, FI))
2341 unsigned Opcode = Def->getOpcode();
2342 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2343 Def->getOperand(1).isFI()) {
2344 FI = Def->getOperand(1).getIndex();
2345 Bytes = Flags.getByValSize();
2349 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2350 if (Flags.isByVal())
2351 // ByVal argument is passed in as a pointer but it's now being
2352 // dereferenced. e.g.
2353 // define @foo(%struct.X* %A) {
2354 // tail call @bar(%struct.X* byval %A)
2357 SDValue Ptr = Ld->getBasePtr();
2358 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2361 FI = FINode->getIndex();
2365 assert(FI != INT_MAX);
2366 if (!MFI->isFixedObjectIndex(FI))
2368 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2371 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2372 /// for tail call optimization. Targets which want to do tail call
2373 /// optimization should implement this function.
2375 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2376 CallingConv::ID CalleeCC,
2378 bool isCalleeStructRet,
2379 bool isCallerStructRet,
2380 const SmallVectorImpl<ISD::OutputArg> &Outs,
2381 const SmallVectorImpl<SDValue> &OutVals,
2382 const SmallVectorImpl<ISD::InputArg> &Ins,
2383 SelectionDAG& DAG) const {
2384 if (!IsTailCallConvention(CalleeCC) &&
2385 CalleeCC != CallingConv::C)
2388 // If -tailcallopt is specified, make fastcc functions tail-callable.
2389 const MachineFunction &MF = DAG.getMachineFunction();
2390 const Function *CallerF = DAG.getMachineFunction().getFunction();
2391 CallingConv::ID CallerCC = CallerF->getCallingConv();
2392 bool CCMatch = CallerCC == CalleeCC;
2394 if (GuaranteedTailCallOpt) {
2395 if (IsTailCallConvention(CalleeCC) && CCMatch)
2400 // Look for obvious safe cases to perform tail call optimization that do not
2401 // require ABI changes. This is what gcc calls sibcall.
2403 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2404 // emit a special epilogue.
2405 if (RegInfo->needsStackRealignment(MF))
2408 // Do not sibcall optimize vararg calls unless the call site is not passing
2410 if (isVarArg && !Outs.empty())
2413 // Also avoid sibcall optimization if either caller or callee uses struct
2414 // return semantics.
2415 if (isCalleeStructRet || isCallerStructRet)
2418 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2419 // Therefore if it's not used by the call it is not safe to optimize this into
2421 bool Unused = false;
2422 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2429 SmallVector<CCValAssign, 16> RVLocs;
2430 CCState CCInfo(CalleeCC, false, getTargetMachine(),
2431 RVLocs, *DAG.getContext());
2432 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2433 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2434 CCValAssign &VA = RVLocs[i];
2435 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2440 // If the calling conventions do not match, then we'd better make sure the
2441 // results are returned in the same way as what the caller expects.
2443 SmallVector<CCValAssign, 16> RVLocs1;
2444 CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2445 RVLocs1, *DAG.getContext());
2446 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2448 SmallVector<CCValAssign, 16> RVLocs2;
2449 CCState CCInfo2(CallerCC, false, getTargetMachine(),
2450 RVLocs2, *DAG.getContext());
2451 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2453 if (RVLocs1.size() != RVLocs2.size())
2455 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2456 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2458 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2460 if (RVLocs1[i].isRegLoc()) {
2461 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2464 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2470 // If the callee takes no arguments then go on to check the results of the
2472 if (!Outs.empty()) {
2473 // Check if stack adjustment is needed. For now, do not do this if any
2474 // argument is passed on the stack.
2475 SmallVector<CCValAssign, 16> ArgLocs;
2476 CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2477 ArgLocs, *DAG.getContext());
2478 CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2479 if (CCInfo.getNextStackOffset()) {
2480 MachineFunction &MF = DAG.getMachineFunction();
2481 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2483 if (Subtarget->isTargetWin64())
2484 // Win64 ABI has additional complications.
2487 // Check if the arguments are already laid out in the right way as
2488 // the caller's fixed stack objects.
2489 MachineFrameInfo *MFI = MF.getFrameInfo();
2490 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2491 const X86InstrInfo *TII =
2492 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2493 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2494 CCValAssign &VA = ArgLocs[i];
2495 SDValue Arg = OutVals[i];
2496 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2497 if (VA.getLocInfo() == CCValAssign::Indirect)
2499 if (!VA.isRegLoc()) {
2500 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2507 // If the tailcall address may be in a register, then make sure it's
2508 // possible to register allocate for it. In 32-bit, the call address can
2509 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2510 // callee-saved registers are restored. These happen to be the same
2511 // registers used to pass 'inreg' arguments so watch out for those.
2512 if (!Subtarget->is64Bit() &&
2513 !isa<GlobalAddressSDNode>(Callee) &&
2514 !isa<ExternalSymbolSDNode>(Callee)) {
2515 unsigned NumInRegs = 0;
2516 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2517 CCValAssign &VA = ArgLocs[i];
2520 unsigned Reg = VA.getLocReg();
2523 case X86::EAX: case X86::EDX: case X86::ECX:
2524 if (++NumInRegs == 3)
2532 // An stdcall caller is expected to clean up its arguments; the callee
2533 // isn't going to do that.
2534 if (!CCMatch && CallerCC==CallingConv::X86_StdCall)
2541 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2542 return X86::createFastISel(funcInfo);
2546 //===----------------------------------------------------------------------===//
2547 // Other Lowering Hooks
2548 //===----------------------------------------------------------------------===//
2550 static bool MayFoldLoad(SDValue Op) {
2551 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2554 static bool MayFoldIntoStore(SDValue Op) {
2555 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2558 static bool isTargetShuffle(unsigned Opcode) {
2560 default: return false;
2561 case X86ISD::PSHUFD:
2562 case X86ISD::PSHUFHW:
2563 case X86ISD::PSHUFLW:
2564 case X86ISD::SHUFPD:
2565 case X86ISD::PALIGN:
2566 case X86ISD::SHUFPS:
2567 case X86ISD::MOVLHPS:
2568 case X86ISD::MOVLHPD:
2569 case X86ISD::MOVHLPS:
2570 case X86ISD::MOVLPS:
2571 case X86ISD::MOVLPD:
2572 case X86ISD::MOVSHDUP:
2573 case X86ISD::MOVSLDUP:
2574 case X86ISD::MOVDDUP:
2577 case X86ISD::UNPCKLPS:
2578 case X86ISD::UNPCKLPD:
2579 case X86ISD::PUNPCKLWD:
2580 case X86ISD::PUNPCKLBW:
2581 case X86ISD::PUNPCKLDQ:
2582 case X86ISD::PUNPCKLQDQ:
2583 case X86ISD::UNPCKHPS:
2584 case X86ISD::UNPCKHPD:
2585 case X86ISD::PUNPCKHWD:
2586 case X86ISD::PUNPCKHBW:
2587 case X86ISD::PUNPCKHDQ:
2588 case X86ISD::PUNPCKHQDQ:
2594 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2595 SDValue V1, SelectionDAG &DAG) {
2597 default: llvm_unreachable("Unknown x86 shuffle node");
2598 case X86ISD::MOVSHDUP:
2599 case X86ISD::MOVSLDUP:
2600 case X86ISD::MOVDDUP:
2601 return DAG.getNode(Opc, dl, VT, V1);
2607 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2608 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2610 default: llvm_unreachable("Unknown x86 shuffle node");
2611 case X86ISD::PSHUFD:
2612 case X86ISD::PSHUFHW:
2613 case X86ISD::PSHUFLW:
2614 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2620 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2621 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2623 default: llvm_unreachable("Unknown x86 shuffle node");
2624 case X86ISD::PALIGN:
2625 case X86ISD::SHUFPD:
2626 case X86ISD::SHUFPS:
2627 return DAG.getNode(Opc, dl, VT, V1, V2,
2628 DAG.getConstant(TargetMask, MVT::i8));
2633 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2634 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2636 default: llvm_unreachable("Unknown x86 shuffle node");
2637 case X86ISD::MOVLHPS:
2638 case X86ISD::MOVLHPD:
2639 case X86ISD::MOVHLPS:
2640 case X86ISD::MOVLPS:
2641 case X86ISD::MOVLPD:
2644 case X86ISD::UNPCKLPS:
2645 case X86ISD::UNPCKLPD:
2646 case X86ISD::PUNPCKLWD:
2647 case X86ISD::PUNPCKLBW:
2648 case X86ISD::PUNPCKLDQ:
2649 case X86ISD::PUNPCKLQDQ:
2650 case X86ISD::UNPCKHPS:
2651 case X86ISD::UNPCKHPD:
2652 case X86ISD::PUNPCKHWD:
2653 case X86ISD::PUNPCKHBW:
2654 case X86ISD::PUNPCKHDQ:
2655 case X86ISD::PUNPCKHQDQ:
2656 return DAG.getNode(Opc, dl, VT, V1, V2);
2661 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2662 MachineFunction &MF = DAG.getMachineFunction();
2663 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2664 int ReturnAddrIndex = FuncInfo->getRAIndex();
2666 if (ReturnAddrIndex == 0) {
2667 // Set up a frame object for the return address.
2668 uint64_t SlotSize = TD->getPointerSize();
2669 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2671 FuncInfo->setRAIndex(ReturnAddrIndex);
2674 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2678 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2679 bool hasSymbolicDisplacement) {
2680 // Offset should fit into 32 bit immediate field.
2681 if (!isInt<32>(Offset))
2684 // If we don't have a symbolic displacement - we don't have any extra
2686 if (!hasSymbolicDisplacement)
2689 // FIXME: Some tweaks might be needed for medium code model.
2690 if (M != CodeModel::Small && M != CodeModel::Kernel)
2693 // For small code model we assume that latest object is 16MB before end of 31
2694 // bits boundary. We may also accept pretty large negative constants knowing
2695 // that all objects are in the positive half of address space.
2696 if (M == CodeModel::Small && Offset < 16*1024*1024)
2699 // For kernel code model we know that all object resist in the negative half
2700 // of 32bits address space. We may not accept negative offsets, since they may
2701 // be just off and we may accept pretty large positive ones.
2702 if (M == CodeModel::Kernel && Offset > 0)
2708 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2709 /// specific condition code, returning the condition code and the LHS/RHS of the
2710 /// comparison to make.
2711 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2712 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2714 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2715 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2716 // X > -1 -> X == 0, jump !sign.
2717 RHS = DAG.getConstant(0, RHS.getValueType());
2718 return X86::COND_NS;
2719 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2720 // X < 0 -> X == 0, jump on sign.
2722 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2724 RHS = DAG.getConstant(0, RHS.getValueType());
2725 return X86::COND_LE;
2729 switch (SetCCOpcode) {
2730 default: llvm_unreachable("Invalid integer condition!");
2731 case ISD::SETEQ: return X86::COND_E;
2732 case ISD::SETGT: return X86::COND_G;
2733 case ISD::SETGE: return X86::COND_GE;
2734 case ISD::SETLT: return X86::COND_L;
2735 case ISD::SETLE: return X86::COND_LE;
2736 case ISD::SETNE: return X86::COND_NE;
2737 case ISD::SETULT: return X86::COND_B;
2738 case ISD::SETUGT: return X86::COND_A;
2739 case ISD::SETULE: return X86::COND_BE;
2740 case ISD::SETUGE: return X86::COND_AE;
2744 // First determine if it is required or is profitable to flip the operands.
2746 // If LHS is a foldable load, but RHS is not, flip the condition.
2747 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2748 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2749 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2750 std::swap(LHS, RHS);
2753 switch (SetCCOpcode) {
2759 std::swap(LHS, RHS);
2763 // On a floating point condition, the flags are set as follows:
2765 // 0 | 0 | 0 | X > Y
2766 // 0 | 0 | 1 | X < Y
2767 // 1 | 0 | 0 | X == Y
2768 // 1 | 1 | 1 | unordered
2769 switch (SetCCOpcode) {
2770 default: llvm_unreachable("Condcode should be pre-legalized away");
2772 case ISD::SETEQ: return X86::COND_E;
2773 case ISD::SETOLT: // flipped
2775 case ISD::SETGT: return X86::COND_A;
2776 case ISD::SETOLE: // flipped
2778 case ISD::SETGE: return X86::COND_AE;
2779 case ISD::SETUGT: // flipped
2781 case ISD::SETLT: return X86::COND_B;
2782 case ISD::SETUGE: // flipped
2784 case ISD::SETLE: return X86::COND_BE;
2786 case ISD::SETNE: return X86::COND_NE;
2787 case ISD::SETUO: return X86::COND_P;
2788 case ISD::SETO: return X86::COND_NP;
2790 case ISD::SETUNE: return X86::COND_INVALID;
2794 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2795 /// code. Current x86 isa includes the following FP cmov instructions:
2796 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2797 static bool hasFPCMov(unsigned X86CC) {
2813 /// isFPImmLegal - Returns true if the target can instruction select the
2814 /// specified FP immediate natively. If false, the legalizer will
2815 /// materialize the FP immediate as a load from a constant pool.
2816 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2817 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2818 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2824 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2825 /// the specified range (L, H].
2826 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2827 return (Val < 0) || (Val >= Low && Val < Hi);
2830 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2831 /// specified value.
2832 static bool isUndefOrEqual(int Val, int CmpVal) {
2833 if (Val < 0 || Val == CmpVal)
2838 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2839 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2840 /// the second operand.
2841 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2842 if (VT == MVT::v4f32 || VT == MVT::v4i32 )
2843 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2844 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2845 return (Mask[0] < 2 && Mask[1] < 2);
2849 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2850 SmallVector<int, 8> M;
2852 return ::isPSHUFDMask(M, N->getValueType(0));
2855 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2856 /// is suitable for input to PSHUFHW.
2857 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2858 if (VT != MVT::v8i16)
2861 // Lower quadword copied in order or undef.
2862 for (int i = 0; i != 4; ++i)
2863 if (Mask[i] >= 0 && Mask[i] != i)
2866 // Upper quadword shuffled.
2867 for (int i = 4; i != 8; ++i)
2868 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2874 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2875 SmallVector<int, 8> M;
2877 return ::isPSHUFHWMask(M, N->getValueType(0));
2880 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2881 /// is suitable for input to PSHUFLW.
2882 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2883 if (VT != MVT::v8i16)
2886 // Upper quadword copied in order.
2887 for (int i = 4; i != 8; ++i)
2888 if (Mask[i] >= 0 && Mask[i] != i)
2891 // Lower quadword shuffled.
2892 for (int i = 0; i != 4; ++i)
2899 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2900 SmallVector<int, 8> M;
2902 return ::isPSHUFLWMask(M, N->getValueType(0));
2905 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2906 /// is suitable for input to PALIGNR.
2907 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2909 int i, e = VT.getVectorNumElements();
2911 // Do not handle v2i64 / v2f64 shuffles with palignr.
2912 if (e < 4 || !hasSSSE3)
2915 for (i = 0; i != e; ++i)
2919 // All undef, not a palignr.
2923 // Determine if it's ok to perform a palignr with only the LHS, since we
2924 // don't have access to the actual shuffle elements to see if RHS is undef.
2925 bool Unary = Mask[i] < (int)e;
2926 bool NeedsUnary = false;
2928 int s = Mask[i] - i;
2930 // Check the rest of the elements to see if they are consecutive.
2931 for (++i; i != e; ++i) {
2936 Unary = Unary && (m < (int)e);
2937 NeedsUnary = NeedsUnary || (m < s);
2939 if (NeedsUnary && !Unary)
2941 if (Unary && m != ((s+i) & (e-1)))
2943 if (!Unary && m != (s+i))
2949 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2950 SmallVector<int, 8> M;
2952 return ::isPALIGNRMask(M, N->getValueType(0), true);
2955 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2956 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2957 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2958 int NumElems = VT.getVectorNumElements();
2959 if (NumElems != 2 && NumElems != 4)
2962 int Half = NumElems / 2;
2963 for (int i = 0; i < Half; ++i)
2964 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2966 for (int i = Half; i < NumElems; ++i)
2967 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2973 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2974 SmallVector<int, 8> M;
2976 return ::isSHUFPMask(M, N->getValueType(0));
2979 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2980 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2981 /// half elements to come from vector 1 (which would equal the dest.) and
2982 /// the upper half to come from vector 2.
2983 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2984 int NumElems = VT.getVectorNumElements();
2986 if (NumElems != 2 && NumElems != 4)
2989 int Half = NumElems / 2;
2990 for (int i = 0; i < Half; ++i)
2991 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2993 for (int i = Half; i < NumElems; ++i)
2994 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2999 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3000 SmallVector<int, 8> M;
3002 return isCommutedSHUFPMask(M, N->getValueType(0));
3005 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3006 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3007 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3008 if (N->getValueType(0).getVectorNumElements() != 4)
3011 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3012 return isUndefOrEqual(N->getMaskElt(0), 6) &&
3013 isUndefOrEqual(N->getMaskElt(1), 7) &&
3014 isUndefOrEqual(N->getMaskElt(2), 2) &&
3015 isUndefOrEqual(N->getMaskElt(3), 3);
3018 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3019 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3021 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3022 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3027 return isUndefOrEqual(N->getMaskElt(0), 2) &&
3028 isUndefOrEqual(N->getMaskElt(1), 3) &&
3029 isUndefOrEqual(N->getMaskElt(2), 2) &&
3030 isUndefOrEqual(N->getMaskElt(3), 3);
3033 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3034 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3035 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3036 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3038 if (NumElems != 2 && NumElems != 4)
3041 for (unsigned i = 0; i < NumElems/2; ++i)
3042 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3045 for (unsigned i = NumElems/2; i < NumElems; ++i)
3046 if (!isUndefOrEqual(N->getMaskElt(i), i))
3052 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3053 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3054 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3055 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3057 if (NumElems != 2 && NumElems != 4)
3060 for (unsigned i = 0; i < NumElems/2; ++i)
3061 if (!isUndefOrEqual(N->getMaskElt(i), i))
3064 for (unsigned i = 0; i < NumElems/2; ++i)
3065 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3071 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3072 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3073 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3074 bool V2IsSplat = false) {
3075 int NumElts = VT.getVectorNumElements();
3076 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3079 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3081 int BitI1 = Mask[i+1];
3082 if (!isUndefOrEqual(BitI, j))
3085 if (!isUndefOrEqual(BitI1, NumElts))
3088 if (!isUndefOrEqual(BitI1, j + NumElts))
3095 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3096 SmallVector<int, 8> M;
3098 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3101 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3102 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3103 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3104 bool V2IsSplat = false) {
3105 int NumElts = VT.getVectorNumElements();
3106 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3109 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3111 int BitI1 = Mask[i+1];
3112 if (!isUndefOrEqual(BitI, j + NumElts/2))
3115 if (isUndefOrEqual(BitI1, NumElts))
3118 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3125 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3126 SmallVector<int, 8> M;
3128 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3131 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3132 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3134 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3135 int NumElems = VT.getVectorNumElements();
3136 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3139 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
3141 int BitI1 = Mask[i+1];
3142 if (!isUndefOrEqual(BitI, j))
3144 if (!isUndefOrEqual(BitI1, j))
3150 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3151 SmallVector<int, 8> M;
3153 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3156 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3157 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3159 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3160 int NumElems = VT.getVectorNumElements();
3161 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3164 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3166 int BitI1 = Mask[i+1];
3167 if (!isUndefOrEqual(BitI, j))
3169 if (!isUndefOrEqual(BitI1, j))
3175 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3176 SmallVector<int, 8> M;
3178 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3181 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3182 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3183 /// MOVSD, and MOVD, i.e. setting the lowest element.
3184 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3185 if (VT.getVectorElementType().getSizeInBits() < 32)
3188 int NumElts = VT.getVectorNumElements();
3190 if (!isUndefOrEqual(Mask[0], NumElts))
3193 for (int i = 1; i < NumElts; ++i)
3194 if (!isUndefOrEqual(Mask[i], i))
3200 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3201 SmallVector<int, 8> M;
3203 return ::isMOVLMask(M, N->getValueType(0));
3206 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3207 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3208 /// element of vector 2 and the other elements to come from vector 1 in order.
3209 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3210 bool V2IsSplat = false, bool V2IsUndef = false) {
3211 int NumOps = VT.getVectorNumElements();
3212 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3215 if (!isUndefOrEqual(Mask[0], 0))
3218 for (int i = 1; i < NumOps; ++i)
3219 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3220 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3221 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3227 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3228 bool V2IsUndef = false) {
3229 SmallVector<int, 8> M;
3231 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3234 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3235 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3236 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3237 if (N->getValueType(0).getVectorNumElements() != 4)
3240 // Expect 1, 1, 3, 3
3241 for (unsigned i = 0; i < 2; ++i) {
3242 int Elt = N->getMaskElt(i);
3243 if (Elt >= 0 && Elt != 1)
3248 for (unsigned i = 2; i < 4; ++i) {
3249 int Elt = N->getMaskElt(i);
3250 if (Elt >= 0 && Elt != 3)
3255 // Don't use movshdup if it can be done with a shufps.
3256 // FIXME: verify that matching u, u, 3, 3 is what we want.
3260 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3261 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3262 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3263 if (N->getValueType(0).getVectorNumElements() != 4)
3266 // Expect 0, 0, 2, 2
3267 for (unsigned i = 0; i < 2; ++i)
3268 if (N->getMaskElt(i) > 0)
3272 for (unsigned i = 2; i < 4; ++i) {
3273 int Elt = N->getMaskElt(i);
3274 if (Elt >= 0 && Elt != 2)
3279 // Don't use movsldup if it can be done with a shufps.
3283 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3284 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3285 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3286 int e = N->getValueType(0).getVectorNumElements() / 2;
3288 for (int i = 0; i < e; ++i)
3289 if (!isUndefOrEqual(N->getMaskElt(i), i))
3291 for (int i = 0; i < e; ++i)
3292 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3297 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3298 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3299 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3300 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3301 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3303 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3305 for (int i = 0; i < NumOperands; ++i) {
3306 int Val = SVOp->getMaskElt(NumOperands-i-1);
3307 if (Val < 0) Val = 0;
3308 if (Val >= NumOperands) Val -= NumOperands;
3310 if (i != NumOperands - 1)
3316 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3317 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3318 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3319 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3321 // 8 nodes, but we only care about the last 4.
3322 for (unsigned i = 7; i >= 4; --i) {
3323 int Val = SVOp->getMaskElt(i);
3332 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3333 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3334 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3335 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3337 // 8 nodes, but we only care about the first 4.
3338 for (int i = 3; i >= 0; --i) {
3339 int Val = SVOp->getMaskElt(i);
3348 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3349 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3350 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3351 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3352 EVT VVT = N->getValueType(0);
3353 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3357 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3358 Val = SVOp->getMaskElt(i);
3362 return (Val - i) * EltSize;
3365 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3367 bool X86::isZeroNode(SDValue Elt) {
3368 return ((isa<ConstantSDNode>(Elt) &&
3369 cast<ConstantSDNode>(Elt)->isNullValue()) ||
3370 (isa<ConstantFPSDNode>(Elt) &&
3371 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3374 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3375 /// their permute mask.
3376 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3377 SelectionDAG &DAG) {
3378 EVT VT = SVOp->getValueType(0);
3379 unsigned NumElems = VT.getVectorNumElements();
3380 SmallVector<int, 8> MaskVec;
3382 for (unsigned i = 0; i != NumElems; ++i) {
3383 int idx = SVOp->getMaskElt(i);
3385 MaskVec.push_back(idx);
3386 else if (idx < (int)NumElems)
3387 MaskVec.push_back(idx + NumElems);
3389 MaskVec.push_back(idx - NumElems);
3391 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3392 SVOp->getOperand(0), &MaskVec[0]);
3395 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3396 /// the two vector operands have swapped position.
3397 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3398 unsigned NumElems = VT.getVectorNumElements();
3399 for (unsigned i = 0; i != NumElems; ++i) {
3403 else if (idx < (int)NumElems)
3404 Mask[i] = idx + NumElems;
3406 Mask[i] = idx - NumElems;
3410 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3411 /// match movhlps. The lower half elements should come from upper half of
3412 /// V1 (and in order), and the upper half elements should come from the upper
3413 /// half of V2 (and in order).
3414 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3415 if (Op->getValueType(0).getVectorNumElements() != 4)
3417 for (unsigned i = 0, e = 2; i != e; ++i)
3418 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3420 for (unsigned i = 2; i != 4; ++i)
3421 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3426 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3427 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3429 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3430 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3432 N = N->getOperand(0).getNode();
3433 if (!ISD::isNON_EXTLoad(N))
3436 *LD = cast<LoadSDNode>(N);
3440 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3441 /// match movlp{s|d}. The lower half elements should come from lower half of
3442 /// V1 (and in order), and the upper half elements should come from the upper
3443 /// half of V2 (and in order). And since V1 will become the source of the
3444 /// MOVLP, it must be either a vector load or a scalar load to vector.
3445 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3446 ShuffleVectorSDNode *Op) {
3447 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3449 // Is V2 is a vector load, don't do this transformation. We will try to use
3450 // load folding shufps op.
3451 if (ISD::isNON_EXTLoad(V2))
3454 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3456 if (NumElems != 2 && NumElems != 4)
3458 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3459 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3461 for (unsigned i = NumElems/2; i != NumElems; ++i)
3462 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3467 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3469 static bool isSplatVector(SDNode *N) {
3470 if (N->getOpcode() != ISD::BUILD_VECTOR)
3473 SDValue SplatValue = N->getOperand(0);
3474 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3475 if (N->getOperand(i) != SplatValue)
3480 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3481 /// to an zero vector.
3482 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3483 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3484 SDValue V1 = N->getOperand(0);
3485 SDValue V2 = N->getOperand(1);
3486 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3487 for (unsigned i = 0; i != NumElems; ++i) {
3488 int Idx = N->getMaskElt(i);
3489 if (Idx >= (int)NumElems) {
3490 unsigned Opc = V2.getOpcode();
3491 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3493 if (Opc != ISD::BUILD_VECTOR ||
3494 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3496 } else if (Idx >= 0) {
3497 unsigned Opc = V1.getOpcode();
3498 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3500 if (Opc != ISD::BUILD_VECTOR ||
3501 !X86::isZeroNode(V1.getOperand(Idx)))
3508 /// getZeroVector - Returns a vector of specified type with all zero elements.
3510 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3512 assert(VT.isVector() && "Expected a vector type");
3514 // Always build SSE zero vectors as <4 x i32> bitcasted
3515 // to their dest type. This ensures they get CSE'd.
3517 if (VT.getSizeInBits() == 128) { // SSE
3518 if (HasSSE2) { // SSE2
3519 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3520 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3522 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3523 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3525 } else if (VT.getSizeInBits() == 256) { // AVX
3526 // 256-bit logic and arithmetic instructions in AVX are
3527 // all floating-point, no support for integer ops. Default
3528 // to emitting fp zeroed vectors then.
3529 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3530 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3531 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3533 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3536 /// getOnesVector - Returns a vector of specified type with all bits set.
3538 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3539 assert(VT.isVector() && "Expected a vector type");
3541 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3542 // type. This ensures they get CSE'd.
3543 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3545 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3546 return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
3550 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3551 /// that point to V2 points to its first element.
3552 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3553 EVT VT = SVOp->getValueType(0);
3554 unsigned NumElems = VT.getVectorNumElements();
3556 bool Changed = false;
3557 SmallVector<int, 8> MaskVec;
3558 SVOp->getMask(MaskVec);
3560 for (unsigned i = 0; i != NumElems; ++i) {
3561 if (MaskVec[i] > (int)NumElems) {
3562 MaskVec[i] = NumElems;
3567 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3568 SVOp->getOperand(1), &MaskVec[0]);
3569 return SDValue(SVOp, 0);
3572 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3573 /// operation of specified width.
3574 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3576 unsigned NumElems = VT.getVectorNumElements();
3577 SmallVector<int, 8> Mask;
3578 Mask.push_back(NumElems);
3579 for (unsigned i = 1; i != NumElems; ++i)
3581 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3584 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3585 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3587 unsigned NumElems = VT.getVectorNumElements();
3588 SmallVector<int, 8> Mask;
3589 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3591 Mask.push_back(i + NumElems);
3593 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3596 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3597 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3599 unsigned NumElems = VT.getVectorNumElements();
3600 unsigned Half = NumElems/2;
3601 SmallVector<int, 8> Mask;
3602 for (unsigned i = 0; i != Half; ++i) {
3603 Mask.push_back(i + Half);
3604 Mask.push_back(i + NumElems + Half);
3606 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3609 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3610 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3611 EVT PVT = MVT::v4f32;
3612 EVT VT = SV->getValueType(0);
3613 DebugLoc dl = SV->getDebugLoc();
3614 SDValue V1 = SV->getOperand(0);
3615 int NumElems = VT.getVectorNumElements();
3616 int EltNo = SV->getSplatIndex();
3618 // unpack elements to the correct location
3619 while (NumElems > 4) {
3620 if (EltNo < NumElems/2) {
3621 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3623 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3624 EltNo -= NumElems/2;
3629 // Perform the splat.
3630 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3631 V1 = DAG.getNode(ISD::BITCAST, dl, PVT, V1);
3632 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3633 return DAG.getNode(ISD::BITCAST, dl, VT, V1);
3636 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3637 /// vector of zero or undef vector. This produces a shuffle where the low
3638 /// element of V2 is swizzled into the zero/undef vector, landing at element
3639 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3640 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3641 bool isZero, bool HasSSE2,
3642 SelectionDAG &DAG) {
3643 EVT VT = V2.getValueType();
3645 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3646 unsigned NumElems = VT.getVectorNumElements();
3647 SmallVector<int, 16> MaskVec;
3648 for (unsigned i = 0; i != NumElems; ++i)
3649 // If this is the insertion idx, put the low elt of V2 here.
3650 MaskVec.push_back(i == Idx ? NumElems : i);
3651 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3654 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3655 /// element of the result of the vector shuffle.
3656 SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3659 return SDValue(); // Limit search depth.
3661 SDValue V = SDValue(N, 0);
3662 EVT VT = V.getValueType();
3663 unsigned Opcode = V.getOpcode();
3665 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3666 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3667 Index = SV->getMaskElt(Index);
3670 return DAG.getUNDEF(VT.getVectorElementType());
3672 int NumElems = VT.getVectorNumElements();
3673 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3674 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3677 // Recurse into target specific vector shuffles to find scalars.
3678 if (isTargetShuffle(Opcode)) {
3679 int NumElems = VT.getVectorNumElements();
3680 SmallVector<unsigned, 16> ShuffleMask;
3684 case X86ISD::SHUFPS:
3685 case X86ISD::SHUFPD:
3686 ImmN = N->getOperand(N->getNumOperands()-1);
3687 DecodeSHUFPSMask(NumElems,
3688 cast<ConstantSDNode>(ImmN)->getZExtValue(),
3691 case X86ISD::PUNPCKHBW:
3692 case X86ISD::PUNPCKHWD:
3693 case X86ISD::PUNPCKHDQ:
3694 case X86ISD::PUNPCKHQDQ:
3695 DecodePUNPCKHMask(NumElems, ShuffleMask);
3697 case X86ISD::UNPCKHPS:
3698 case X86ISD::UNPCKHPD:
3699 DecodeUNPCKHPMask(NumElems, ShuffleMask);
3701 case X86ISD::PUNPCKLBW:
3702 case X86ISD::PUNPCKLWD:
3703 case X86ISD::PUNPCKLDQ:
3704 case X86ISD::PUNPCKLQDQ:
3705 DecodePUNPCKLMask(NumElems, ShuffleMask);
3707 case X86ISD::UNPCKLPS:
3708 case X86ISD::UNPCKLPD:
3709 DecodeUNPCKLPMask(NumElems, ShuffleMask);
3711 case X86ISD::MOVHLPS:
3712 DecodeMOVHLPSMask(NumElems, ShuffleMask);
3714 case X86ISD::MOVLHPS:
3715 DecodeMOVLHPSMask(NumElems, ShuffleMask);
3717 case X86ISD::PSHUFD:
3718 ImmN = N->getOperand(N->getNumOperands()-1);
3719 DecodePSHUFMask(NumElems,
3720 cast<ConstantSDNode>(ImmN)->getZExtValue(),
3723 case X86ISD::PSHUFHW:
3724 ImmN = N->getOperand(N->getNumOperands()-1);
3725 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3728 case X86ISD::PSHUFLW:
3729 ImmN = N->getOperand(N->getNumOperands()-1);
3730 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3734 case X86ISD::MOVSD: {
3735 // The index 0 always comes from the first element of the second source,
3736 // this is why MOVSS and MOVSD are used in the first place. The other
3737 // elements come from the other positions of the first source vector.
3738 unsigned OpNum = (Index == 0) ? 1 : 0;
3739 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
3743 assert("not implemented for target shuffle node");
3747 Index = ShuffleMask[Index];
3749 return DAG.getUNDEF(VT.getVectorElementType());
3751 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
3752 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
3756 // Actual nodes that may contain scalar elements
3757 if (Opcode == ISD::BITCAST) {
3758 V = V.getOperand(0);
3759 EVT SrcVT = V.getValueType();
3760 unsigned NumElems = VT.getVectorNumElements();
3762 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
3766 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
3767 return (Index == 0) ? V.getOperand(0)
3768 : DAG.getUNDEF(VT.getVectorElementType());
3770 if (V.getOpcode() == ISD::BUILD_VECTOR)
3771 return V.getOperand(Index);
3776 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
3777 /// shuffle operation which come from a consecutively from a zero. The
3778 /// search can start in two diferent directions, from left or right.
3780 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
3781 bool ZerosFromLeft, SelectionDAG &DAG) {
3784 while (i < NumElems) {
3785 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
3786 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
3787 if (!(Elt.getNode() &&
3788 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
3796 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
3797 /// MaskE correspond consecutively to elements from one of the vector operands,
3798 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
3800 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
3801 int OpIdx, int NumElems, unsigned &OpNum) {
3802 bool SeenV1 = false;
3803 bool SeenV2 = false;
3805 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
3806 int Idx = SVOp->getMaskElt(i);
3807 // Ignore undef indicies
3816 // Only accept consecutive elements from the same vector
3817 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
3821 OpNum = SeenV1 ? 0 : 1;
3825 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
3826 /// logical left shift of a vector.
3827 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3828 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3829 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3830 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3831 false /* check zeros from right */, DAG);
3837 // Considering the elements in the mask that are not consecutive zeros,
3838 // check if they consecutively come from only one of the source vectors.
3840 // V1 = {X, A, B, C} 0
3842 // vector_shuffle V1, V2 <1, 2, 3, X>
3844 if (!isShuffleMaskConsecutive(SVOp,
3845 0, // Mask Start Index
3846 NumElems-NumZeros-1, // Mask End Index
3847 NumZeros, // Where to start looking in the src vector
3848 NumElems, // Number of elements in vector
3849 OpSrc)) // Which source operand ?
3854 ShVal = SVOp->getOperand(OpSrc);
3858 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
3859 /// logical left shift of a vector.
3860 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3861 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3862 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3863 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3864 true /* check zeros from left */, DAG);
3870 // Considering the elements in the mask that are not consecutive zeros,
3871 // check if they consecutively come from only one of the source vectors.
3873 // 0 { A, B, X, X } = V2
3875 // vector_shuffle V1, V2 <X, X, 4, 5>
3877 if (!isShuffleMaskConsecutive(SVOp,
3878 NumZeros, // Mask Start Index
3879 NumElems-1, // Mask End Index
3880 0, // Where to start looking in the src vector
3881 NumElems, // Number of elements in vector
3882 OpSrc)) // Which source operand ?
3887 ShVal = SVOp->getOperand(OpSrc);
3891 /// isVectorShift - Returns true if the shuffle can be implemented as a
3892 /// logical left or right shift of a vector.
3893 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3894 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3895 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
3896 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
3902 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3904 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3905 unsigned NumNonZero, unsigned NumZero,
3907 const TargetLowering &TLI) {
3911 DebugLoc dl = Op.getDebugLoc();
3914 for (unsigned i = 0; i < 16; ++i) {
3915 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3916 if (ThisIsNonZero && First) {
3918 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3920 V = DAG.getUNDEF(MVT::v8i16);
3925 SDValue ThisElt(0, 0), LastElt(0, 0);
3926 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3927 if (LastIsNonZero) {
3928 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3929 MVT::i16, Op.getOperand(i-1));
3931 if (ThisIsNonZero) {
3932 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3933 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3934 ThisElt, DAG.getConstant(8, MVT::i8));
3936 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3940 if (ThisElt.getNode())
3941 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3942 DAG.getIntPtrConstant(i/2));
3946 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
3949 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3951 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3952 unsigned NumNonZero, unsigned NumZero,
3954 const TargetLowering &TLI) {
3958 DebugLoc dl = Op.getDebugLoc();
3961 for (unsigned i = 0; i < 8; ++i) {
3962 bool isNonZero = (NonZeros & (1 << i)) != 0;
3966 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3968 V = DAG.getUNDEF(MVT::v8i16);
3971 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3972 MVT::v8i16, V, Op.getOperand(i),
3973 DAG.getIntPtrConstant(i));
3980 /// getVShift - Return a vector logical shift node.
3982 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3983 unsigned NumBits, SelectionDAG &DAG,
3984 const TargetLowering &TLI, DebugLoc dl) {
3985 EVT ShVT = MVT::v2i64;
3986 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3987 SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
3988 return DAG.getNode(ISD::BITCAST, dl, VT,
3989 DAG.getNode(Opc, dl, ShVT, SrcOp,
3990 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3994 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3995 SelectionDAG &DAG) const {
3997 // Check if the scalar load can be widened into a vector load. And if
3998 // the address is "base + cst" see if the cst can be "absorbed" into
3999 // the shuffle mask.
4000 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4001 SDValue Ptr = LD->getBasePtr();
4002 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4004 EVT PVT = LD->getValueType(0);
4005 if (PVT != MVT::i32 && PVT != MVT::f32)
4010 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4011 FI = FINode->getIndex();
4013 } else if (Ptr.getOpcode() == ISD::ADD &&
4014 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
4015 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4016 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4017 Offset = Ptr.getConstantOperandVal(1);
4018 Ptr = Ptr.getOperand(0);
4023 SDValue Chain = LD->getChain();
4024 // Make sure the stack object alignment is at least 16.
4025 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4026 if (DAG.InferPtrAlignment(Ptr) < 16) {
4027 if (MFI->isFixedObjectIndex(FI)) {
4028 // Can't change the alignment. FIXME: It's possible to compute
4029 // the exact stack offset and reference FI + adjust offset instead.
4030 // If someone *really* cares about this. That's the way to implement it.
4033 MFI->setObjectAlignment(FI, 16);
4037 // (Offset % 16) must be multiple of 4. Then address is then
4038 // Ptr + (Offset & ~15).
4041 if ((Offset % 16) & 3)
4043 int64_t StartOffset = Offset & ~15;
4045 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4046 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4048 int EltNo = (Offset - StartOffset) >> 2;
4049 int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4050 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4051 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4052 LD->getPointerInfo().getWithOffset(StartOffset),
4054 // Canonicalize it to a v4i32 shuffle.
4055 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, V1);
4056 return DAG.getNode(ISD::BITCAST, dl, VT,
4057 DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4058 DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4064 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4065 /// vector of type 'VT', see if the elements can be replaced by a single large
4066 /// load which has the same value as a build_vector whose operands are 'elts'.
4068 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4070 /// FIXME: we'd also like to handle the case where the last elements are zero
4071 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4072 /// There's even a handy isZeroNode for that purpose.
4073 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4074 DebugLoc &DL, SelectionDAG &DAG) {
4075 EVT EltVT = VT.getVectorElementType();
4076 unsigned NumElems = Elts.size();
4078 LoadSDNode *LDBase = NULL;
4079 unsigned LastLoadedElt = -1U;
4081 // For each element in the initializer, see if we've found a load or an undef.
4082 // If we don't find an initial load element, or later load elements are
4083 // non-consecutive, bail out.
4084 for (unsigned i = 0; i < NumElems; ++i) {
4085 SDValue Elt = Elts[i];
4087 if (!Elt.getNode() ||
4088 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4091 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4093 LDBase = cast<LoadSDNode>(Elt.getNode());
4097 if (Elt.getOpcode() == ISD::UNDEF)
4100 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4101 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4106 // If we have found an entire vector of loads and undefs, then return a large
4107 // load of the entire vector width starting at the base pointer. If we found
4108 // consecutive loads for the low half, generate a vzext_load node.
4109 if (LastLoadedElt == NumElems - 1) {
4110 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4111 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4112 LDBase->getPointerInfo(),
4113 LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4114 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4115 LDBase->getPointerInfo(),
4116 LDBase->isVolatile(), LDBase->isNonTemporal(),
4117 LDBase->getAlignment());
4118 } else if (NumElems == 4 && LastLoadedElt == 1) {
4119 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4120 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4121 SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4123 LDBase->getMemOperand());
4124 return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
4130 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4131 DebugLoc dl = Op.getDebugLoc();
4132 // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4133 // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4134 // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4135 // is present, so AllOnes is ignored.
4136 if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4137 (Op.getValueType().getSizeInBits() != 256 &&
4138 ISD::isBuildVectorAllOnes(Op.getNode()))) {
4139 // Canonicalize this to <4 x i32> (SSE) to
4140 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4141 // eliminated on x86-32 hosts.
4142 if (Op.getValueType() == MVT::v4i32)
4145 if (ISD::isBuildVectorAllOnes(Op.getNode()))
4146 return getOnesVector(Op.getValueType(), DAG, dl);
4147 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4150 EVT VT = Op.getValueType();
4151 EVT ExtVT = VT.getVectorElementType();
4152 unsigned EVTBits = ExtVT.getSizeInBits();
4154 unsigned NumElems = Op.getNumOperands();
4155 unsigned NumZero = 0;
4156 unsigned NumNonZero = 0;
4157 unsigned NonZeros = 0;
4158 bool IsAllConstants = true;
4159 SmallSet<SDValue, 8> Values;
4160 for (unsigned i = 0; i < NumElems; ++i) {
4161 SDValue Elt = Op.getOperand(i);
4162 if (Elt.getOpcode() == ISD::UNDEF)
4165 if (Elt.getOpcode() != ISD::Constant &&
4166 Elt.getOpcode() != ISD::ConstantFP)
4167 IsAllConstants = false;
4168 if (X86::isZeroNode(Elt))
4171 NonZeros |= (1 << i);
4176 // All undef vector. Return an UNDEF. All zero vectors were handled above.
4177 if (NumNonZero == 0)
4178 return DAG.getUNDEF(VT);
4180 // Special case for single non-zero, non-undef, element.
4181 if (NumNonZero == 1) {
4182 unsigned Idx = CountTrailingZeros_32(NonZeros);
4183 SDValue Item = Op.getOperand(Idx);
4185 // If this is an insertion of an i64 value on x86-32, and if the top bits of
4186 // the value are obviously zero, truncate the value to i32 and do the
4187 // insertion that way. Only do this if the value is non-constant or if the
4188 // value is a constant being inserted into element 0. It is cheaper to do
4189 // a constant pool load than it is to do a movd + shuffle.
4190 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4191 (!IsAllConstants || Idx == 0)) {
4192 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4194 assert(VT == MVT::v2i64 && "Expected an SSE value type!");
4195 EVT VecVT = MVT::v4i32;
4196 unsigned VecElts = 4;
4198 // Truncate the value (which may itself be a constant) to i32, and
4199 // convert it to a vector with movd (S2V+shuffle to zero extend).
4200 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4201 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4202 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4203 Subtarget->hasSSE2(), DAG);
4205 // Now we have our 32-bit value zero extended in the low element of
4206 // a vector. If Idx != 0, swizzle it into place.
4208 SmallVector<int, 4> Mask;
4209 Mask.push_back(Idx);
4210 for (unsigned i = 1; i != VecElts; ++i)
4212 Item = DAG.getVectorShuffle(VecVT, dl, Item,
4213 DAG.getUNDEF(Item.getValueType()),
4216 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Item);
4220 // If we have a constant or non-constant insertion into the low element of
4221 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4222 // the rest of the elements. This will be matched as movd/movq/movss/movsd
4223 // depending on what the source datatype is.
4226 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4227 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4228 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4229 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4230 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4231 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4233 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4234 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4235 assert(VT.getSizeInBits() == 128 && "Expected an SSE value type!");
4236 EVT MiddleVT = MVT::v4i32;
4237 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4238 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4239 Subtarget->hasSSE2(), DAG);
4240 return DAG.getNode(ISD::BITCAST, dl, VT, Item);
4244 // Is it a vector logical left shift?
4245 if (NumElems == 2 && Idx == 1 &&
4246 X86::isZeroNode(Op.getOperand(0)) &&
4247 !X86::isZeroNode(Op.getOperand(1))) {
4248 unsigned NumBits = VT.getSizeInBits();
4249 return getVShift(true, VT,
4250 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4251 VT, Op.getOperand(1)),
4252 NumBits/2, DAG, *this, dl);
4255 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4258 // Otherwise, if this is a vector with i32 or f32 elements, and the element
4259 // is a non-constant being inserted into an element other than the low one,
4260 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
4261 // movd/movss) to move this into the low element, then shuffle it into
4263 if (EVTBits == 32) {
4264 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4266 // Turn it into a shuffle of zero and zero-extended scalar to vector.
4267 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4268 Subtarget->hasSSE2(), DAG);
4269 SmallVector<int, 8> MaskVec;
4270 for (unsigned i = 0; i < NumElems; i++)
4271 MaskVec.push_back(i == Idx ? 0 : 1);
4272 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4276 // Splat is obviously ok. Let legalizer expand it to a shuffle.
4277 if (Values.size() == 1) {
4278 if (EVTBits == 32) {
4279 // Instead of a shuffle like this:
4280 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4281 // Check if it's possible to issue this instead.
4282 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4283 unsigned Idx = CountTrailingZeros_32(NonZeros);
4284 SDValue Item = Op.getOperand(Idx);
4285 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4286 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4291 // A vector full of immediates; various special cases are already
4292 // handled, so this is best done with a single constant-pool load.
4296 // Let legalizer expand 2-wide build_vectors.
4297 if (EVTBits == 64) {
4298 if (NumNonZero == 1) {
4299 // One half is zero or undef.
4300 unsigned Idx = CountTrailingZeros_32(NonZeros);
4301 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4302 Op.getOperand(Idx));
4303 return getShuffleVectorZeroOrUndef(V2, Idx, true,
4304 Subtarget->hasSSE2(), DAG);
4309 // If element VT is < 32 bits, convert it to inserts into a zero vector.
4310 if (EVTBits == 8 && NumElems == 16) {
4311 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4313 if (V.getNode()) return V;
4316 if (EVTBits == 16 && NumElems == 8) {
4317 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4319 if (V.getNode()) return V;
4322 // If element VT is == 32 bits, turn it into a number of shuffles.
4323 SmallVector<SDValue, 8> V;
4325 if (NumElems == 4 && NumZero > 0) {
4326 for (unsigned i = 0; i < 4; ++i) {
4327 bool isZero = !(NonZeros & (1 << i));
4329 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4331 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4334 for (unsigned i = 0; i < 2; ++i) {
4335 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4338 V[i] = V[i*2]; // Must be a zero vector.
4341 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4344 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4347 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4352 SmallVector<int, 8> MaskVec;
4353 bool Reverse = (NonZeros & 0x3) == 2;
4354 for (unsigned i = 0; i < 2; ++i)
4355 MaskVec.push_back(Reverse ? 1-i : i);
4356 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4357 for (unsigned i = 0; i < 2; ++i)
4358 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4359 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4362 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4363 // Check for a build vector of consecutive loads.
4364 for (unsigned i = 0; i < NumElems; ++i)
4365 V[i] = Op.getOperand(i);
4367 // Check for elements which are consecutive loads.
4368 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4372 // For SSE 4.1, use insertps to put the high elements into the low element.
4373 if (getSubtarget()->hasSSE41()) {
4375 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4376 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4378 Result = DAG.getUNDEF(VT);
4380 for (unsigned i = 1; i < NumElems; ++i) {
4381 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4382 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4383 Op.getOperand(i), DAG.getIntPtrConstant(i));
4388 // Otherwise, expand into a number of unpckl*, start by extending each of
4389 // our (non-undef) elements to the full vector width with the element in the
4390 // bottom slot of the vector (which generates no code for SSE).
4391 for (unsigned i = 0; i < NumElems; ++i) {
4392 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4393 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4395 V[i] = DAG.getUNDEF(VT);
4398 // Next, we iteratively mix elements, e.g. for v4f32:
4399 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4400 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4401 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
4402 unsigned EltStride = NumElems >> 1;
4403 while (EltStride != 0) {
4404 for (unsigned i = 0; i < EltStride; ++i) {
4405 // If V[i+EltStride] is undef and this is the first round of mixing,
4406 // then it is safe to just drop this shuffle: V[i] is already in the
4407 // right place, the one element (since it's the first round) being
4408 // inserted as undef can be dropped. This isn't safe for successive
4409 // rounds because they will permute elements within both vectors.
4410 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4411 EltStride == NumElems/2)
4414 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4424 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4425 // We support concatenate two MMX registers and place them in a MMX
4426 // register. This is better than doing a stack convert.
4427 DebugLoc dl = Op.getDebugLoc();
4428 EVT ResVT = Op.getValueType();
4429 assert(Op.getNumOperands() == 2);
4430 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4431 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4433 SDValue InVec = DAG.getNode(ISD::BITCAST,dl, MVT::v1i64, Op.getOperand(0));
4434 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4435 InVec = Op.getOperand(1);
4436 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4437 unsigned NumElts = ResVT.getVectorNumElements();
4438 VecOp = DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4439 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4440 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4442 InVec = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, InVec);
4443 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4444 Mask[0] = 0; Mask[1] = 2;
4445 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4447 return DAG.getNode(ISD::BITCAST, dl, ResVT, VecOp);
4450 // v8i16 shuffles - Prefer shuffles in the following order:
4451 // 1. [all] pshuflw, pshufhw, optional move
4452 // 2. [ssse3] 1 x pshufb
4453 // 3. [ssse3] 2 x pshufb + 1 x por
4454 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4456 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4457 SelectionDAG &DAG) const {
4458 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4459 SDValue V1 = SVOp->getOperand(0);
4460 SDValue V2 = SVOp->getOperand(1);
4461 DebugLoc dl = SVOp->getDebugLoc();
4462 SmallVector<int, 8> MaskVals;
4464 // Determine if more than 1 of the words in each of the low and high quadwords
4465 // of the result come from the same quadword of one of the two inputs. Undef
4466 // mask values count as coming from any quadword, for better codegen.
4467 SmallVector<unsigned, 4> LoQuad(4);
4468 SmallVector<unsigned, 4> HiQuad(4);
4469 BitVector InputQuads(4);
4470 for (unsigned i = 0; i < 8; ++i) {
4471 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4472 int EltIdx = SVOp->getMaskElt(i);
4473 MaskVals.push_back(EltIdx);
4482 InputQuads.set(EltIdx / 4);
4485 int BestLoQuad = -1;
4486 unsigned MaxQuad = 1;
4487 for (unsigned i = 0; i < 4; ++i) {
4488 if (LoQuad[i] > MaxQuad) {
4490 MaxQuad = LoQuad[i];
4494 int BestHiQuad = -1;
4496 for (unsigned i = 0; i < 4; ++i) {
4497 if (HiQuad[i] > MaxQuad) {
4499 MaxQuad = HiQuad[i];
4503 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4504 // of the two input vectors, shuffle them into one input vector so only a
4505 // single pshufb instruction is necessary. If There are more than 2 input
4506 // quads, disable the next transformation since it does not help SSSE3.
4507 bool V1Used = InputQuads[0] || InputQuads[1];
4508 bool V2Used = InputQuads[2] || InputQuads[3];
4509 if (Subtarget->hasSSSE3()) {
4510 if (InputQuads.count() == 2 && V1Used && V2Used) {
4511 BestLoQuad = InputQuads.find_first();
4512 BestHiQuad = InputQuads.find_next(BestLoQuad);
4514 if (InputQuads.count() > 2) {
4520 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4521 // the shuffle mask. If a quad is scored as -1, that means that it contains
4522 // words from all 4 input quadwords.
4524 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4525 SmallVector<int, 8> MaskV;
4526 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4527 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4528 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4529 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
4530 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
4531 NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
4533 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4534 // source words for the shuffle, to aid later transformations.
4535 bool AllWordsInNewV = true;
4536 bool InOrder[2] = { true, true };
4537 for (unsigned i = 0; i != 8; ++i) {
4538 int idx = MaskVals[i];
4540 InOrder[i/4] = false;
4541 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4543 AllWordsInNewV = false;
4547 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4548 if (AllWordsInNewV) {
4549 for (int i = 0; i != 8; ++i) {
4550 int idx = MaskVals[i];
4553 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4554 if ((idx != i) && idx < 4)
4556 if ((idx != i) && idx > 3)
4565 // If we've eliminated the use of V2, and the new mask is a pshuflw or
4566 // pshufhw, that's as cheap as it gets. Return the new shuffle.
4567 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4568 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4569 unsigned TargetMask = 0;
4570 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4571 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4572 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4573 X86::getShufflePSHUFLWImmediate(NewV.getNode());
4574 V1 = NewV.getOperand(0);
4575 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4579 // If we have SSSE3, and all words of the result are from 1 input vector,
4580 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
4581 // is present, fall back to case 4.
4582 if (Subtarget->hasSSSE3()) {
4583 SmallVector<SDValue,16> pshufbMask;
4585 // If we have elements from both input vectors, set the high bit of the
4586 // shuffle mask element to zero out elements that come from V2 in the V1
4587 // mask, and elements that come from V1 in the V2 mask, so that the two
4588 // results can be OR'd together.
4589 bool TwoInputs = V1Used && V2Used;
4590 for (unsigned i = 0; i != 8; ++i) {
4591 int EltIdx = MaskVals[i] * 2;
4592 if (TwoInputs && (EltIdx >= 16)) {
4593 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4594 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4597 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4598 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4600 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V1);
4601 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4602 DAG.getNode(ISD::BUILD_VECTOR, dl,
4603 MVT::v16i8, &pshufbMask[0], 16));
4605 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4607 // Calculate the shuffle mask for the second input, shuffle it, and
4608 // OR it with the first shuffled input.
4610 for (unsigned i = 0; i != 8; ++i) {
4611 int EltIdx = MaskVals[i] * 2;
4613 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4614 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4617 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4618 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4620 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V2);
4621 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4622 DAG.getNode(ISD::BUILD_VECTOR, dl,
4623 MVT::v16i8, &pshufbMask[0], 16));
4624 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4625 return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4628 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4629 // and update MaskVals with new element order.
4630 BitVector InOrder(8);
4631 if (BestLoQuad >= 0) {
4632 SmallVector<int, 8> MaskV;
4633 for (int i = 0; i != 4; ++i) {
4634 int idx = MaskVals[i];
4636 MaskV.push_back(-1);
4638 } else if ((idx / 4) == BestLoQuad) {
4639 MaskV.push_back(idx & 3);
4642 MaskV.push_back(-1);
4645 for (unsigned i = 4; i != 8; ++i)
4647 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4650 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4651 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4653 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4657 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4658 // and update MaskVals with the new element order.
4659 if (BestHiQuad >= 0) {
4660 SmallVector<int, 8> MaskV;
4661 for (unsigned i = 0; i != 4; ++i)
4663 for (unsigned i = 4; i != 8; ++i) {
4664 int idx = MaskVals[i];
4666 MaskV.push_back(-1);
4668 } else if ((idx / 4) == BestHiQuad) {
4669 MaskV.push_back((idx & 3) + 4);
4672 MaskV.push_back(-1);
4675 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4678 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4679 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
4681 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
4685 // In case BestHi & BestLo were both -1, which means each quadword has a word
4686 // from each of the four input quadwords, calculate the InOrder bitvector now
4687 // before falling through to the insert/extract cleanup.
4688 if (BestLoQuad == -1 && BestHiQuad == -1) {
4690 for (int i = 0; i != 8; ++i)
4691 if (MaskVals[i] < 0 || MaskVals[i] == i)
4695 // The other elements are put in the right place using pextrw and pinsrw.
4696 for (unsigned i = 0; i != 8; ++i) {
4699 int EltIdx = MaskVals[i];
4702 SDValue ExtOp = (EltIdx < 8)
4703 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4704 DAG.getIntPtrConstant(EltIdx))
4705 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4706 DAG.getIntPtrConstant(EltIdx - 8));
4707 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4708 DAG.getIntPtrConstant(i));
4713 // v16i8 shuffles - Prefer shuffles in the following order:
4714 // 1. [ssse3] 1 x pshufb
4715 // 2. [ssse3] 2 x pshufb + 1 x por
4716 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
4718 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4720 const X86TargetLowering &TLI) {
4721 SDValue V1 = SVOp->getOperand(0);
4722 SDValue V2 = SVOp->getOperand(1);
4723 DebugLoc dl = SVOp->getDebugLoc();
4724 SmallVector<int, 16> MaskVals;
4725 SVOp->getMask(MaskVals);
4727 // If we have SSSE3, case 1 is generated when all result bytes come from
4728 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
4729 // present, fall back to case 3.
4730 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4733 for (unsigned i = 0; i < 16; ++i) {
4734 int EltIdx = MaskVals[i];
4743 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4744 if (TLI.getSubtarget()->hasSSSE3()) {
4745 SmallVector<SDValue,16> pshufbMask;
4747 // If all result elements are from one input vector, then only translate
4748 // undef mask values to 0x80 (zero out result) in the pshufb mask.
4750 // Otherwise, we have elements from both input vectors, and must zero out
4751 // elements that come from V2 in the first mask, and V1 in the second mask
4752 // so that we can OR them together.
4753 bool TwoInputs = !(V1Only || V2Only);
4754 for (unsigned i = 0; i != 16; ++i) {
4755 int EltIdx = MaskVals[i];
4756 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4757 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4760 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4762 // If all the elements are from V2, assign it to V1 and return after
4763 // building the first pshufb.
4766 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4767 DAG.getNode(ISD::BUILD_VECTOR, dl,
4768 MVT::v16i8, &pshufbMask[0], 16));
4772 // Calculate the shuffle mask for the second input, shuffle it, and
4773 // OR it with the first shuffled input.
4775 for (unsigned i = 0; i != 16; ++i) {
4776 int EltIdx = MaskVals[i];
4778 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4781 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4783 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4784 DAG.getNode(ISD::BUILD_VECTOR, dl,
4785 MVT::v16i8, &pshufbMask[0], 16));
4786 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4789 // No SSSE3 - Calculate in place words and then fix all out of place words
4790 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
4791 // the 16 different words that comprise the two doublequadword input vectors.
4792 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
4793 V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
4794 SDValue NewV = V2Only ? V2 : V1;
4795 for (int i = 0; i != 8; ++i) {
4796 int Elt0 = MaskVals[i*2];
4797 int Elt1 = MaskVals[i*2+1];
4799 // This word of the result is all undef, skip it.
4800 if (Elt0 < 0 && Elt1 < 0)
4803 // This word of the result is already in the correct place, skip it.
4804 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4806 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4809 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4810 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4813 // If Elt0 and Elt1 are defined, are consecutive, and can be load
4814 // using a single extract together, load it and store it.
4815 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4816 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4817 DAG.getIntPtrConstant(Elt1 / 2));
4818 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4819 DAG.getIntPtrConstant(i));
4823 // If Elt1 is defined, extract it from the appropriate source. If the
4824 // source byte is not also odd, shift the extracted word left 8 bits
4825 // otherwise clear the bottom 8 bits if we need to do an or.
4827 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4828 DAG.getIntPtrConstant(Elt1 / 2));
4829 if ((Elt1 & 1) == 0)
4830 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4831 DAG.getConstant(8, TLI.getShiftAmountTy()));
4833 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4834 DAG.getConstant(0xFF00, MVT::i16));
4836 // If Elt0 is defined, extract it from the appropriate source. If the
4837 // source byte is not also even, shift the extracted word right 8 bits. If
4838 // Elt1 was also defined, OR the extracted values together before
4839 // inserting them in the result.
4841 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4842 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4843 if ((Elt0 & 1) != 0)
4844 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4845 DAG.getConstant(8, TLI.getShiftAmountTy()));
4847 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4848 DAG.getConstant(0x00FF, MVT::i16));
4849 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4852 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4853 DAG.getIntPtrConstant(i));
4855 return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
4858 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4859 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
4860 /// done when every pair / quad of shuffle mask elements point to elements in
4861 /// the right sequence. e.g.
4862 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
4864 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4865 SelectionDAG &DAG, DebugLoc dl) {
4866 EVT VT = SVOp->getValueType(0);
4867 SDValue V1 = SVOp->getOperand(0);
4868 SDValue V2 = SVOp->getOperand(1);
4869 unsigned NumElems = VT.getVectorNumElements();
4870 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4872 switch (VT.getSimpleVT().SimpleTy) {
4873 default: assert(false && "Unexpected!");
4874 case MVT::v4f32: NewVT = MVT::v2f64; break;
4875 case MVT::v4i32: NewVT = MVT::v2i64; break;
4876 case MVT::v8i16: NewVT = MVT::v4i32; break;
4877 case MVT::v16i8: NewVT = MVT::v4i32; break;
4880 int Scale = NumElems / NewWidth;
4881 SmallVector<int, 8> MaskVec;
4882 for (unsigned i = 0; i < NumElems; i += Scale) {
4884 for (int j = 0; j < Scale; ++j) {
4885 int EltIdx = SVOp->getMaskElt(i+j);
4889 StartIdx = EltIdx - (EltIdx % Scale);
4890 if (EltIdx != StartIdx + j)
4894 MaskVec.push_back(-1);
4896 MaskVec.push_back(StartIdx / Scale);
4899 V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
4900 V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
4901 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4904 /// getVZextMovL - Return a zero-extending vector move low node.
4906 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4907 SDValue SrcOp, SelectionDAG &DAG,
4908 const X86Subtarget *Subtarget, DebugLoc dl) {
4909 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4910 LoadSDNode *LD = NULL;
4911 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4912 LD = dyn_cast<LoadSDNode>(SrcOp);
4914 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4916 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4917 if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
4918 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4919 SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
4920 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4922 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4923 return DAG.getNode(ISD::BITCAST, dl, VT,
4924 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4925 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4933 return DAG.getNode(ISD::BITCAST, dl, VT,
4934 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4935 DAG.getNode(ISD::BITCAST, dl,
4939 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4942 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4943 SDValue V1 = SVOp->getOperand(0);
4944 SDValue V2 = SVOp->getOperand(1);
4945 DebugLoc dl = SVOp->getDebugLoc();
4946 EVT VT = SVOp->getValueType(0);
4948 SmallVector<std::pair<int, int>, 8> Locs;
4950 SmallVector<int, 8> Mask1(4U, -1);
4951 SmallVector<int, 8> PermMask;
4952 SVOp->getMask(PermMask);
4956 for (unsigned i = 0; i != 4; ++i) {
4957 int Idx = PermMask[i];
4959 Locs[i] = std::make_pair(-1, -1);
4961 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4963 Locs[i] = std::make_pair(0, NumLo);
4967 Locs[i] = std::make_pair(1, NumHi);
4969 Mask1[2+NumHi] = Idx;
4975 if (NumLo <= 2 && NumHi <= 2) {
4976 // If no more than two elements come from either vector. This can be
4977 // implemented with two shuffles. First shuffle gather the elements.
4978 // The second shuffle, which takes the first shuffle as both of its
4979 // vector operands, put the elements into the right order.
4980 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4982 SmallVector<int, 8> Mask2(4U, -1);
4984 for (unsigned i = 0; i != 4; ++i) {
4985 if (Locs[i].first == -1)
4988 unsigned Idx = (i < 2) ? 0 : 4;
4989 Idx += Locs[i].first * 2 + Locs[i].second;
4994 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4995 } else if (NumLo == 3 || NumHi == 3) {
4996 // Otherwise, we must have three elements from one vector, call it X, and
4997 // one element from the other, call it Y. First, use a shufps to build an
4998 // intermediate vector with the one element from Y and the element from X
4999 // that will be in the same half in the final destination (the indexes don't
5000 // matter). Then, use a shufps to build the final vector, taking the half
5001 // containing the element from Y from the intermediate, and the other half
5004 // Normalize it so the 3 elements come from V1.
5005 CommuteVectorShuffleMask(PermMask, VT);
5009 // Find the element from V2.
5011 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5012 int Val = PermMask[HiIndex];
5019 Mask1[0] = PermMask[HiIndex];
5021 Mask1[2] = PermMask[HiIndex^1];
5023 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5026 Mask1[0] = PermMask[0];
5027 Mask1[1] = PermMask[1];
5028 Mask1[2] = HiIndex & 1 ? 6 : 4;
5029 Mask1[3] = HiIndex & 1 ? 4 : 6;
5030 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5032 Mask1[0] = HiIndex & 1 ? 2 : 0;
5033 Mask1[1] = HiIndex & 1 ? 0 : 2;
5034 Mask1[2] = PermMask[2];
5035 Mask1[3] = PermMask[3];
5040 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5044 // Break it into (shuffle shuffle_hi, shuffle_lo).
5046 SmallVector<int,8> LoMask(4U, -1);
5047 SmallVector<int,8> HiMask(4U, -1);
5049 SmallVector<int,8> *MaskPtr = &LoMask;
5050 unsigned MaskIdx = 0;
5053 for (unsigned i = 0; i != 4; ++i) {
5060 int Idx = PermMask[i];
5062 Locs[i] = std::make_pair(-1, -1);
5063 } else if (Idx < 4) {
5064 Locs[i] = std::make_pair(MaskIdx, LoIdx);
5065 (*MaskPtr)[LoIdx] = Idx;
5068 Locs[i] = std::make_pair(MaskIdx, HiIdx);
5069 (*MaskPtr)[HiIdx] = Idx;
5074 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5075 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5076 SmallVector<int, 8> MaskOps;
5077 for (unsigned i = 0; i != 4; ++i) {
5078 if (Locs[i].first == -1) {
5079 MaskOps.push_back(-1);
5081 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5082 MaskOps.push_back(Idx);
5085 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5088 static bool MayFoldVectorLoad(SDValue V) {
5089 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5090 V = V.getOperand(0);
5091 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5092 V = V.getOperand(0);
5098 // FIXME: the version above should always be used. Since there's
5099 // a bug where several vector shuffles can't be folded because the
5100 // DAG is not updated during lowering and a node claims to have two
5101 // uses while it only has one, use this version, and let isel match
5102 // another instruction if the load really happens to have more than
5103 // one use. Remove this version after this bug get fixed.
5104 // rdar://8434668, PR8156
5105 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5106 if (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
5107 V = V.getOperand(0);
5108 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5109 V = V.getOperand(0);
5110 if (ISD::isNormalLoad(V.getNode()))
5115 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5116 /// a vector extract, and if both can be later optimized into a single load.
5117 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5118 /// here because otherwise a target specific shuffle node is going to be
5119 /// emitted for this shuffle, and the optimization not done.
5120 /// FIXME: This is probably not the best approach, but fix the problem
5121 /// until the right path is decided.
5123 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5124 const TargetLowering &TLI) {
5125 EVT VT = V.getValueType();
5126 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5128 // Be sure that the vector shuffle is present in a pattern like this:
5129 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5133 SDNode *N = *V.getNode()->use_begin();
5134 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5137 SDValue EltNo = N->getOperand(1);
5138 if (!isa<ConstantSDNode>(EltNo))
5141 // If the bit convert changed the number of elements, it is unsafe
5142 // to examine the mask.
5143 bool HasShuffleIntoBitcast = false;
5144 if (V.getOpcode() == ISD::BITCAST) {
5145 EVT SrcVT = V.getOperand(0).getValueType();
5146 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5148 V = V.getOperand(0);
5149 HasShuffleIntoBitcast = true;
5152 // Select the input vector, guarding against out of range extract vector.
5153 unsigned NumElems = VT.getVectorNumElements();
5154 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5155 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5156 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5158 // Skip one more bit_convert if necessary
5159 if (V.getOpcode() == ISD::BITCAST)
5160 V = V.getOperand(0);
5162 if (ISD::isNormalLoad(V.getNode())) {
5163 // Is the original load suitable?
5164 LoadSDNode *LN0 = cast<LoadSDNode>(V);
5166 // FIXME: avoid the multi-use bug that is preventing lots of
5167 // of foldings to be detected, this is still wrong of course, but
5168 // give the temporary desired behavior, and if it happens that
5169 // the load has real more uses, during isel it will not fold, and
5170 // will generate poor code.
5171 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5174 if (!HasShuffleIntoBitcast)
5177 // If there's a bitcast before the shuffle, check if the load type and
5178 // alignment is valid.
5179 unsigned Align = LN0->getAlignment();
5181 TLI.getTargetData()->getABITypeAlignment(
5182 VT.getTypeForEVT(*DAG.getContext()));
5184 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5192 SDValue getMOVDDup(SDValue &Op, DebugLoc &dl, SDValue V1, SelectionDAG &DAG) {
5193 EVT VT = Op.getValueType();
5195 // Canonizalize to v2f64.
5196 V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
5197 return DAG.getNode(ISD::BITCAST, dl, VT,
5198 getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
5203 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5205 SDValue V1 = Op.getOperand(0);
5206 SDValue V2 = Op.getOperand(1);
5207 EVT VT = Op.getValueType();
5209 assert(VT != MVT::v2i64 && "unsupported shuffle type");
5211 if (HasSSE2 && VT == MVT::v2f64)
5212 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5215 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5219 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5220 SDValue V1 = Op.getOperand(0);
5221 SDValue V2 = Op.getOperand(1);
5222 EVT VT = Op.getValueType();
5224 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5225 "unsupported shuffle type");
5227 if (V2.getOpcode() == ISD::UNDEF)
5231 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5235 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5236 SDValue V1 = Op.getOperand(0);
5237 SDValue V2 = Op.getOperand(1);
5238 EVT VT = Op.getValueType();
5239 unsigned NumElems = VT.getVectorNumElements();
5241 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5242 // operand of these instructions is only memory, so check if there's a
5243 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5245 bool CanFoldLoad = false;
5247 // Trivial case, when V2 comes from a load.
5248 if (MayFoldVectorLoad(V2))
5251 // When V1 is a load, it can be folded later into a store in isel, example:
5252 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5254 // (MOVLPSmr addr:$src1, VR128:$src2)
5255 // So, recognize this potential and also use MOVLPS or MOVLPD
5256 if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5260 if (HasSSE2 && NumElems == 2)
5261 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5264 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5267 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5268 // movl and movlp will both match v2i64, but v2i64 is never matched by
5269 // movl earlier because we make it strict to avoid messing with the movlp load
5270 // folding logic (see the code above getMOVLP call). Match it here then,
5271 // this is horrible, but will stay like this until we move all shuffle
5272 // matching to x86 specific nodes. Note that for the 1st condition all
5273 // types are matched with movsd.
5274 if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5275 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5277 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5280 assert(VT != MVT::v4i32 && "unsupported shuffle type");
5282 // Invert the operand order and use SHUFPS to match it.
5283 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5284 X86::getShuffleSHUFImmediate(SVOp), DAG);
5287 static inline unsigned getUNPCKLOpcode(EVT VT) {
5288 switch(VT.getSimpleVT().SimpleTy) {
5289 case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5290 case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5291 case MVT::v4f32: return X86ISD::UNPCKLPS;
5292 case MVT::v2f64: return X86ISD::UNPCKLPD;
5293 case MVT::v16i8: return X86ISD::PUNPCKLBW;
5294 case MVT::v8i16: return X86ISD::PUNPCKLWD;
5296 llvm_unreachable("Unknow type for unpckl");
5301 static inline unsigned getUNPCKHOpcode(EVT VT) {
5302 switch(VT.getSimpleVT().SimpleTy) {
5303 case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5304 case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5305 case MVT::v4f32: return X86ISD::UNPCKHPS;
5306 case MVT::v2f64: return X86ISD::UNPCKHPD;
5307 case MVT::v16i8: return X86ISD::PUNPCKHBW;
5308 case MVT::v8i16: return X86ISD::PUNPCKHWD;
5310 llvm_unreachable("Unknow type for unpckh");
5316 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5317 const TargetLowering &TLI,
5318 const X86Subtarget *Subtarget) {
5319 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5320 EVT VT = Op.getValueType();
5321 DebugLoc dl = Op.getDebugLoc();
5322 SDValue V1 = Op.getOperand(0);
5323 SDValue V2 = Op.getOperand(1);
5325 if (isZeroShuffle(SVOp))
5326 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5328 // Handle splat operations
5329 if (SVOp->isSplat()) {
5330 // Special case, this is the only place now where it's
5331 // allowed to return a vector_shuffle operation without
5332 // using a target specific node, because *hopefully* it
5333 // will be optimized away by the dag combiner.
5334 if (VT.getVectorNumElements() <= 4 &&
5335 CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5338 // Handle splats by matching through known masks
5339 if (VT.getVectorNumElements() <= 4)
5342 // Canonicalize all of the remaining to v4f32.
5343 return PromoteSplat(SVOp, DAG);
5346 // If the shuffle can be profitably rewritten as a narrower shuffle, then
5348 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5349 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5350 if (NewOp.getNode())
5351 return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
5352 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5353 // FIXME: Figure out a cleaner way to do this.
5354 // Try to make use of movq to zero out the top part.
5355 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5356 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5357 if (NewOp.getNode()) {
5358 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5359 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5360 DAG, Subtarget, dl);
5362 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5363 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5364 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5365 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5366 DAG, Subtarget, dl);
5373 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5374 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5375 SDValue V1 = Op.getOperand(0);
5376 SDValue V2 = Op.getOperand(1);
5377 EVT VT = Op.getValueType();
5378 DebugLoc dl = Op.getDebugLoc();
5379 unsigned NumElems = VT.getVectorNumElements();
5380 bool isMMX = VT.getSizeInBits() == 64;
5381 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5382 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5383 bool V1IsSplat = false;
5384 bool V2IsSplat = false;
5385 bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5386 bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5387 bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5388 MachineFunction &MF = DAG.getMachineFunction();
5389 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5391 // Shuffle operations on MMX not supported.
5395 // Vector shuffle lowering takes 3 steps:
5397 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5398 // narrowing and commutation of operands should be handled.
5399 // 2) Matching of shuffles with known shuffle masks to x86 target specific
5401 // 3) Rewriting of unmatched masks into new generic shuffle operations,
5402 // so the shuffle can be broken into other shuffles and the legalizer can
5403 // try the lowering again.
5405 // The general ideia is that no vector_shuffle operation should be left to
5406 // be matched during isel, all of them must be converted to a target specific
5409 // Normalize the input vectors. Here splats, zeroed vectors, profitable
5410 // narrowing and commutation of operands should be handled. The actual code
5411 // doesn't include all of those, work in progress...
5412 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5413 if (NewOp.getNode())
5416 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5417 // unpckh_undef). Only use pshufd if speed is more important than size.
5418 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5419 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5420 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5421 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5422 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5423 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5425 if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5426 RelaxedMayFoldVectorLoad(V1))
5427 return getMOVDDup(Op, dl, V1, DAG);
5429 if (X86::isMOVHLPS_v_undef_Mask(SVOp))
5430 return getMOVHighToLow(Op, dl, DAG);
5432 // Use to match splats
5433 if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5434 (VT == MVT::v2f64 || VT == MVT::v2i64))
5435 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5437 if (X86::isPSHUFDMask(SVOp)) {
5438 // The actual implementation will match the mask in the if above and then
5439 // during isel it can match several different instructions, not only pshufd
5440 // as its name says, sad but true, emulate the behavior for now...
5441 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5442 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5444 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5446 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5447 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5449 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5450 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5453 if (VT == MVT::v4f32)
5454 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5458 // Check if this can be converted into a logical shift.
5459 bool isLeft = false;
5462 bool isShift = getSubtarget()->hasSSE2() &&
5463 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5464 if (isShift && ShVal.hasOneUse()) {
5465 // If the shifted value has multiple uses, it may be cheaper to use
5466 // v_set0 + movlhps or movhlps, etc.
5467 EVT EltVT = VT.getVectorElementType();
5468 ShAmt *= EltVT.getSizeInBits();
5469 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5472 if (X86::isMOVLMask(SVOp)) {
5475 if (ISD::isBuildVectorAllZeros(V1.getNode()))
5476 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5477 if (!X86::isMOVLPMask(SVOp)) {
5478 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5479 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5481 if (VT == MVT::v4i32 || VT == MVT::v4f32)
5482 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5486 // FIXME: fold these into legal mask.
5487 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5488 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5490 if (X86::isMOVHLPSMask(SVOp))
5491 return getMOVHighToLow(Op, dl, DAG);
5493 if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5494 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5496 if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5497 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5499 if (X86::isMOVLPMask(SVOp))
5500 return getMOVLP(Op, dl, DAG, HasSSE2);
5502 if (ShouldXformToMOVHLPS(SVOp) ||
5503 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5504 return CommuteVectorShuffle(SVOp, DAG);
5507 // No better options. Use a vshl / vsrl.
5508 EVT EltVT = VT.getVectorElementType();
5509 ShAmt *= EltVT.getSizeInBits();
5510 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5513 bool Commuted = false;
5514 // FIXME: This should also accept a bitcast of a splat? Be careful, not
5515 // 1,1,1,1 -> v8i16 though.
5516 V1IsSplat = isSplatVector(V1.getNode());
5517 V2IsSplat = isSplatVector(V2.getNode());
5519 // Canonicalize the splat or undef, if present, to be on the RHS.
5520 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5521 Op = CommuteVectorShuffle(SVOp, DAG);
5522 SVOp = cast<ShuffleVectorSDNode>(Op);
5523 V1 = SVOp->getOperand(0);
5524 V2 = SVOp->getOperand(1);
5525 std::swap(V1IsSplat, V2IsSplat);
5526 std::swap(V1IsUndef, V2IsUndef);
5530 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5531 // Shuffling low element of v1 into undef, just return v1.
5534 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5535 // the instruction selector will not match, so get a canonical MOVL with
5536 // swapped operands to undo the commute.
5537 return getMOVL(DAG, dl, VT, V2, V1);
5540 if (X86::isUNPCKLMask(SVOp))
5541 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
5543 if (X86::isUNPCKHMask(SVOp))
5544 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5547 // Normalize mask so all entries that point to V2 points to its first
5548 // element then try to match unpck{h|l} again. If match, return a
5549 // new vector_shuffle with the corrected mask.
5550 SDValue NewMask = NormalizeMask(SVOp, DAG);
5551 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5552 if (NSVOp != SVOp) {
5553 if (X86::isUNPCKLMask(NSVOp, true)) {
5555 } else if (X86::isUNPCKHMask(NSVOp, true)) {
5562 // Commute is back and try unpck* again.
5563 // FIXME: this seems wrong.
5564 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5565 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5567 if (X86::isUNPCKLMask(NewSVOp))
5568 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
5570 if (X86::isUNPCKHMask(NewSVOp))
5571 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5574 // Normalize the node to match x86 shuffle ops if needed
5575 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5576 return CommuteVectorShuffle(SVOp, DAG);
5578 // The checks below are all present in isShuffleMaskLegal, but they are
5579 // inlined here right now to enable us to directly emit target specific
5580 // nodes, and remove one by one until they don't return Op anymore.
5581 SmallVector<int, 16> M;
5584 if (isPALIGNRMask(M, VT, HasSSSE3))
5585 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5586 X86::getShufflePALIGNRImmediate(SVOp),
5589 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5590 SVOp->getSplatIndex() == 0 && V2IsUndef) {
5591 if (VT == MVT::v2f64)
5592 return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
5593 if (VT == MVT::v2i64)
5594 return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5597 if (isPSHUFHWMask(M, VT))
5598 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5599 X86::getShufflePSHUFHWImmediate(SVOp),
5602 if (isPSHUFLWMask(M, VT))
5603 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5604 X86::getShufflePSHUFLWImmediate(SVOp),
5607 if (isSHUFPMask(M, VT)) {
5608 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5609 if (VT == MVT::v4f32 || VT == MVT::v4i32)
5610 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5612 if (VT == MVT::v2f64 || VT == MVT::v2i64)
5613 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5617 if (X86::isUNPCKL_v_undef_Mask(SVOp))
5618 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5619 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5620 if (X86::isUNPCKH_v_undef_Mask(SVOp))
5621 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5622 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5624 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5625 if (VT == MVT::v8i16) {
5626 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5627 if (NewOp.getNode())
5631 if (VT == MVT::v16i8) {
5632 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5633 if (NewOp.getNode())
5637 // Handle all 4 wide cases with a number of shuffles.
5639 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5645 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5646 SelectionDAG &DAG) const {
5647 EVT VT = Op.getValueType();
5648 DebugLoc dl = Op.getDebugLoc();
5649 if (VT.getSizeInBits() == 8) {
5650 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5651 Op.getOperand(0), Op.getOperand(1));
5652 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5653 DAG.getValueType(VT));
5654 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5655 } else if (VT.getSizeInBits() == 16) {
5656 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5657 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
5659 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5660 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5661 DAG.getNode(ISD::BITCAST, dl,
5665 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
5666 Op.getOperand(0), Op.getOperand(1));
5667 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5668 DAG.getValueType(VT));
5669 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5670 } else if (VT == MVT::f32) {
5671 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
5672 // the result back to FR32 register. It's only worth matching if the
5673 // result has a single use which is a store or a bitcast to i32. And in
5674 // the case of a store, it's not worth it if the index is a constant 0,
5675 // because a MOVSSmr can be used instead, which is smaller and faster.
5676 if (!Op.hasOneUse())
5678 SDNode *User = *Op.getNode()->use_begin();
5679 if ((User->getOpcode() != ISD::STORE ||
5680 (isa<ConstantSDNode>(Op.getOperand(1)) &&
5681 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
5682 (User->getOpcode() != ISD::BITCAST ||
5683 User->getValueType(0) != MVT::i32))
5685 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5686 DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
5689 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
5690 } else if (VT == MVT::i32) {
5691 // ExtractPS works with constant index.
5692 if (isa<ConstantSDNode>(Op.getOperand(1)))
5700 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5701 SelectionDAG &DAG) const {
5702 if (!isa<ConstantSDNode>(Op.getOperand(1)))
5705 if (Subtarget->hasSSE41()) {
5706 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
5711 EVT VT = Op.getValueType();
5712 DebugLoc dl = Op.getDebugLoc();
5713 // TODO: handle v16i8.
5714 if (VT.getSizeInBits() == 16) {
5715 SDValue Vec = Op.getOperand(0);
5716 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5718 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5719 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5720 DAG.getNode(ISD::BITCAST, dl,
5723 // Transform it so it match pextrw which produces a 32-bit result.
5724 EVT EltVT = MVT::i32;
5725 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
5726 Op.getOperand(0), Op.getOperand(1));
5727 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
5728 DAG.getValueType(VT));
5729 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5730 } else if (VT.getSizeInBits() == 32) {
5731 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5735 // SHUFPS the element to the lowest double word, then movss.
5736 int Mask[4] = { Idx, -1, -1, -1 };
5737 EVT VVT = Op.getOperand(0).getValueType();
5738 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5739 DAG.getUNDEF(VVT), Mask);
5740 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5741 DAG.getIntPtrConstant(0));
5742 } else if (VT.getSizeInBits() == 64) {
5743 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
5744 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
5745 // to match extract_elt for f64.
5746 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5750 // UNPCKHPD the element to the lowest double word, then movsd.
5751 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
5752 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
5753 int Mask[2] = { 1, -1 };
5754 EVT VVT = Op.getOperand(0).getValueType();
5755 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5756 DAG.getUNDEF(VVT), Mask);
5757 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5758 DAG.getIntPtrConstant(0));
5765 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
5766 SelectionDAG &DAG) const {
5767 EVT VT = Op.getValueType();
5768 EVT EltVT = VT.getVectorElementType();
5769 DebugLoc dl = Op.getDebugLoc();
5771 SDValue N0 = Op.getOperand(0);
5772 SDValue N1 = Op.getOperand(1);
5773 SDValue N2 = Op.getOperand(2);
5775 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
5776 isa<ConstantSDNode>(N2)) {
5778 if (VT == MVT::v8i16)
5779 Opc = X86ISD::PINSRW;
5780 else if (VT == MVT::v16i8)
5781 Opc = X86ISD::PINSRB;
5783 Opc = X86ISD::PINSRB;
5785 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
5787 if (N1.getValueType() != MVT::i32)
5788 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5789 if (N2.getValueType() != MVT::i32)
5790 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5791 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
5792 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
5793 // Bits [7:6] of the constant are the source select. This will always be
5794 // zero here. The DAG Combiner may combine an extract_elt index into these
5795 // bits. For example (insert (extract, 3), 2) could be matched by putting
5796 // the '3' into bits [7:6] of X86ISD::INSERTPS.
5797 // Bits [5:4] of the constant are the destination select. This is the
5798 // value of the incoming immediate.
5799 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
5800 // combine either bitwise AND or insert of float 0.0 to set these bits.
5801 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
5802 // Create this as a scalar to vector..
5803 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
5804 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
5805 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
5806 // PINSR* works with constant index.
5813 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
5814 EVT VT = Op.getValueType();
5815 EVT EltVT = VT.getVectorElementType();
5817 if (Subtarget->hasSSE41())
5818 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
5820 if (EltVT == MVT::i8)
5823 DebugLoc dl = Op.getDebugLoc();
5824 SDValue N0 = Op.getOperand(0);
5825 SDValue N1 = Op.getOperand(1);
5826 SDValue N2 = Op.getOperand(2);
5828 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
5829 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
5830 // as its second argument.
5831 if (N1.getValueType() != MVT::i32)
5832 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5833 if (N2.getValueType() != MVT::i32)
5834 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5835 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
5841 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5842 DebugLoc dl = Op.getDebugLoc();
5844 if (Op.getValueType() == MVT::v1i64 &&
5845 Op.getOperand(0).getValueType() == MVT::i64)
5846 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5848 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5849 assert(Op.getValueType().getSimpleVT().getSizeInBits() == 128 &&
5850 "Expected an SSE type!");
5851 return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(),
5852 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
5855 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5856 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5857 // one of the above mentioned nodes. It has to be wrapped because otherwise
5858 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5859 // be used to form addressing mode. These wrapped nodes will be selected
5862 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
5863 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5865 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5867 unsigned char OpFlag = 0;
5868 unsigned WrapperKind = X86ISD::Wrapper;
5869 CodeModel::Model M = getTargetMachine().getCodeModel();
5871 if (Subtarget->isPICStyleRIPRel() &&
5872 (M == CodeModel::Small || M == CodeModel::Kernel))
5873 WrapperKind = X86ISD::WrapperRIP;
5874 else if (Subtarget->isPICStyleGOT())
5875 OpFlag = X86II::MO_GOTOFF;
5876 else if (Subtarget->isPICStyleStubPIC())
5877 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5879 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5881 CP->getOffset(), OpFlag);
5882 DebugLoc DL = CP->getDebugLoc();
5883 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5884 // With PIC, the address is actually $g + Offset.
5886 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5887 DAG.getNode(X86ISD::GlobalBaseReg,
5888 DebugLoc(), getPointerTy()),
5895 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
5896 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5898 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5900 unsigned char OpFlag = 0;
5901 unsigned WrapperKind = X86ISD::Wrapper;
5902 CodeModel::Model M = getTargetMachine().getCodeModel();
5904 if (Subtarget->isPICStyleRIPRel() &&
5905 (M == CodeModel::Small || M == CodeModel::Kernel))
5906 WrapperKind = X86ISD::WrapperRIP;
5907 else if (Subtarget->isPICStyleGOT())
5908 OpFlag = X86II::MO_GOTOFF;
5909 else if (Subtarget->isPICStyleStubPIC())
5910 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5912 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5914 DebugLoc DL = JT->getDebugLoc();
5915 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5917 // With PIC, the address is actually $g + Offset.
5919 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5920 DAG.getNode(X86ISD::GlobalBaseReg,
5921 DebugLoc(), getPointerTy()),
5928 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
5929 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5931 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5933 unsigned char OpFlag = 0;
5934 unsigned WrapperKind = X86ISD::Wrapper;
5935 CodeModel::Model M = getTargetMachine().getCodeModel();
5937 if (Subtarget->isPICStyleRIPRel() &&
5938 (M == CodeModel::Small || M == CodeModel::Kernel))
5939 WrapperKind = X86ISD::WrapperRIP;
5940 else if (Subtarget->isPICStyleGOT())
5941 OpFlag = X86II::MO_GOTOFF;
5942 else if (Subtarget->isPICStyleStubPIC())
5943 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5945 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5947 DebugLoc DL = Op.getDebugLoc();
5948 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5951 // With PIC, the address is actually $g + Offset.
5952 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
5953 !Subtarget->is64Bit()) {
5954 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5955 DAG.getNode(X86ISD::GlobalBaseReg,
5956 DebugLoc(), getPointerTy()),
5964 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
5965 // Create the TargetBlockAddressAddress node.
5966 unsigned char OpFlags =
5967 Subtarget->ClassifyBlockAddressReference();
5968 CodeModel::Model M = getTargetMachine().getCodeModel();
5969 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5970 DebugLoc dl = Op.getDebugLoc();
5971 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5972 /*isTarget=*/true, OpFlags);
5974 if (Subtarget->isPICStyleRIPRel() &&
5975 (M == CodeModel::Small || M == CodeModel::Kernel))
5976 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5978 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5980 // With PIC, the address is actually $g + Offset.
5981 if (isGlobalRelativeToPICBase(OpFlags)) {
5982 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5983 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5991 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
5993 SelectionDAG &DAG) const {
5994 // Create the TargetGlobalAddress node, folding in the constant
5995 // offset if it is legal.
5996 unsigned char OpFlags =
5997 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5998 CodeModel::Model M = getTargetMachine().getCodeModel();
6000 if (OpFlags == X86II::MO_NO_FLAG &&
6001 X86::isOffsetSuitableForCodeModel(Offset, M)) {
6002 // A direct static reference to a global.
6003 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6006 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6009 if (Subtarget->isPICStyleRIPRel() &&
6010 (M == CodeModel::Small || M == CodeModel::Kernel))
6011 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6013 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6015 // With PIC, the address is actually $g + Offset.
6016 if (isGlobalRelativeToPICBase(OpFlags)) {
6017 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6018 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6022 // For globals that require a load from a stub to get the address, emit the
6024 if (isGlobalStubReference(OpFlags))
6025 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6026 MachinePointerInfo::getGOT(), false, false, 0);
6028 // If there was a non-zero offset that we didn't fold, create an explicit
6031 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6032 DAG.getConstant(Offset, getPointerTy()));
6038 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6039 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6040 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6041 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6045 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6046 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6047 unsigned char OperandFlags) {
6048 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6049 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6050 DebugLoc dl = GA->getDebugLoc();
6051 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6052 GA->getValueType(0),
6056 SDValue Ops[] = { Chain, TGA, *InFlag };
6057 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6059 SDValue Ops[] = { Chain, TGA };
6060 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6063 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6064 MFI->setAdjustsStack(true);
6066 SDValue Flag = Chain.getValue(1);
6067 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6070 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6072 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6075 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
6076 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6077 DAG.getNode(X86ISD::GlobalBaseReg,
6078 DebugLoc(), PtrVT), InFlag);
6079 InFlag = Chain.getValue(1);
6081 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6084 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6086 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6088 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6089 X86::RAX, X86II::MO_TLSGD);
6092 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6093 // "local exec" model.
6094 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6095 const EVT PtrVT, TLSModel::Model model,
6097 DebugLoc dl = GA->getDebugLoc();
6099 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6100 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6101 is64Bit ? 257 : 256));
6103 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6104 DAG.getIntPtrConstant(0),
6105 MachinePointerInfo(Ptr), false, false, 0);
6107 unsigned char OperandFlags = 0;
6108 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
6110 unsigned WrapperKind = X86ISD::Wrapper;
6111 if (model == TLSModel::LocalExec) {
6112 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6113 } else if (is64Bit) {
6114 assert(model == TLSModel::InitialExec);
6115 OperandFlags = X86II::MO_GOTTPOFF;
6116 WrapperKind = X86ISD::WrapperRIP;
6118 assert(model == TLSModel::InitialExec);
6119 OperandFlags = X86II::MO_INDNTPOFF;
6122 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6124 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6125 GA->getValueType(0),
6126 GA->getOffset(), OperandFlags);
6127 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6129 if (model == TLSModel::InitialExec)
6130 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6131 MachinePointerInfo::getGOT(), false, false, 0);
6133 // The address of the thread local variable is the add of the thread
6134 // pointer with the offset of the variable.
6135 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6139 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6141 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6142 const GlobalValue *GV = GA->getGlobal();
6144 if (Subtarget->isTargetELF()) {
6145 // TODO: implement the "local dynamic" model
6146 // TODO: implement the "initial exec"model for pic executables
6148 // If GV is an alias then use the aliasee for determining
6149 // thread-localness.
6150 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6151 GV = GA->resolveAliasedGlobal(false);
6153 TLSModel::Model model
6154 = getTLSModel(GV, getTargetMachine().getRelocationModel());
6157 case TLSModel::GeneralDynamic:
6158 case TLSModel::LocalDynamic: // not implemented
6159 if (Subtarget->is64Bit())
6160 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6161 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6163 case TLSModel::InitialExec:
6164 case TLSModel::LocalExec:
6165 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6166 Subtarget->is64Bit());
6168 } else if (Subtarget->isTargetDarwin()) {
6169 // Darwin only has one model of TLS. Lower to that.
6170 unsigned char OpFlag = 0;
6171 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6172 X86ISD::WrapperRIP : X86ISD::Wrapper;
6174 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6176 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6177 !Subtarget->is64Bit();
6179 OpFlag = X86II::MO_TLVP_PIC_BASE;
6181 OpFlag = X86II::MO_TLVP;
6182 DebugLoc DL = Op.getDebugLoc();
6183 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6185 GA->getOffset(), OpFlag);
6186 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6188 // With PIC32, the address is actually $g + Offset.
6190 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6191 DAG.getNode(X86ISD::GlobalBaseReg,
6192 DebugLoc(), getPointerTy()),
6195 // Lowering the machine isd will make sure everything is in the right
6197 SDValue Args[] = { Offset };
6198 SDValue RetVal = DAG.getNode(X86ISD::TLSCALL, DL, MVT::Other, Args, 1);
6200 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6201 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6202 MFI->setAdjustsStack(true);
6204 // And our return value (tls address) is in the standard call return value
6210 "TLS not implemented for this target.");
6212 llvm_unreachable("Unreachable");
6217 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
6218 /// take a 2 x i32 value to shift plus a shift amount.
6219 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
6220 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6221 EVT VT = Op.getValueType();
6222 unsigned VTBits = VT.getSizeInBits();
6223 DebugLoc dl = Op.getDebugLoc();
6224 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6225 SDValue ShOpLo = Op.getOperand(0);
6226 SDValue ShOpHi = Op.getOperand(1);
6227 SDValue ShAmt = Op.getOperand(2);
6228 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6229 DAG.getConstant(VTBits - 1, MVT::i8))
6230 : DAG.getConstant(0, VT);
6233 if (Op.getOpcode() == ISD::SHL_PARTS) {
6234 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6235 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6237 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6238 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6241 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6242 DAG.getConstant(VTBits, MVT::i8));
6243 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6244 AndNode, DAG.getConstant(0, MVT::i8));
6247 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6248 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6249 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6251 if (Op.getOpcode() == ISD::SHL_PARTS) {
6252 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6253 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6255 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6256 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6259 SDValue Ops[2] = { Lo, Hi };
6260 return DAG.getMergeValues(Ops, 2, dl);
6263 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6264 SelectionDAG &DAG) const {
6265 EVT SrcVT = Op.getOperand(0).getValueType();
6267 if (SrcVT.isVector())
6270 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6271 "Unknown SINT_TO_FP to lower!");
6273 // These are really Legal; return the operand so the caller accepts it as
6275 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6277 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6278 Subtarget->is64Bit()) {
6282 DebugLoc dl = Op.getDebugLoc();
6283 unsigned Size = SrcVT.getSizeInBits()/8;
6284 MachineFunction &MF = DAG.getMachineFunction();
6285 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6286 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6287 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6289 MachinePointerInfo::getFixedStack(SSFI),
6291 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6294 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6296 SelectionDAG &DAG) const {
6298 DebugLoc DL = Op.getDebugLoc();
6300 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6302 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
6304 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6306 unsigned ByteSize = SrcVT.getSizeInBits()/8;
6308 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6309 MachineMemOperand *MMO =
6310 DAG.getMachineFunction()
6311 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6312 MachineMemOperand::MOLoad, ByteSize, ByteSize);
6314 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6315 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6317 Tys, Ops, array_lengthof(Ops),
6321 Chain = Result.getValue(1);
6322 SDValue InFlag = Result.getValue(2);
6324 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6325 // shouldn't be necessary except that RFP cannot be live across
6326 // multiple blocks. When stackifier is fixed, they can be uncoupled.
6327 MachineFunction &MF = DAG.getMachineFunction();
6328 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6329 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6330 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6331 Tys = DAG.getVTList(MVT::Other);
6333 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6335 MachineMemOperand *MMO =
6336 DAG.getMachineFunction()
6337 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6338 MachineMemOperand::MOStore, SSFISize, SSFISize);
6340 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6341 Ops, array_lengthof(Ops),
6342 Op.getValueType(), MMO);
6343 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6344 MachinePointerInfo::getFixedStack(SSFI),
6351 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6352 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6353 SelectionDAG &DAG) const {
6354 // This algorithm is not obvious. Here it is in C code, more or less:
6356 double uint64_to_double( uint32_t hi, uint32_t lo ) {
6357 static const __m128i exp = { 0x4330000045300000ULL, 0 };
6358 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6360 // Copy ints to xmm registers.
6361 __m128i xh = _mm_cvtsi32_si128( hi );
6362 __m128i xl = _mm_cvtsi32_si128( lo );
6364 // Combine into low half of a single xmm register.
6365 __m128i x = _mm_unpacklo_epi32( xh, xl );
6369 // Merge in appropriate exponents to give the integer bits the right
6371 x = _mm_unpacklo_epi32( x, exp );
6373 // Subtract away the biases to deal with the IEEE-754 double precision
6375 d = _mm_sub_pd( (__m128d) x, bias );
6377 // All conversions up to here are exact. The correctly rounded result is
6378 // calculated using the current rounding mode using the following
6380 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6381 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
6382 // store doesn't really need to be here (except
6383 // maybe to zero the other double)
6388 DebugLoc dl = Op.getDebugLoc();
6389 LLVMContext *Context = DAG.getContext();
6391 // Build some magic constants.
6392 std::vector<Constant*> CV0;
6393 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6394 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6395 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6396 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6397 Constant *C0 = ConstantVector::get(CV0);
6398 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6400 std::vector<Constant*> CV1;
6402 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6404 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6405 Constant *C1 = ConstantVector::get(CV1);
6406 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6408 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6409 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6411 DAG.getIntPtrConstant(1)));
6412 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6413 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6415 DAG.getIntPtrConstant(0)));
6416 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6417 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6418 MachinePointerInfo::getConstantPool(),
6420 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6421 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6422 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6423 MachinePointerInfo::getConstantPool(),
6425 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6427 // Add the halves; easiest way is to swap them into another reg first.
6428 int ShufMask[2] = { 1, -1 };
6429 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6430 DAG.getUNDEF(MVT::v2f64), ShufMask);
6431 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6432 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6433 DAG.getIntPtrConstant(0));
6436 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6437 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6438 SelectionDAG &DAG) const {
6439 DebugLoc dl = Op.getDebugLoc();
6440 // FP constant to bias correct the final result.
6441 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6444 // Load the 32-bit value into an XMM register.
6445 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6446 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6448 DAG.getIntPtrConstant(0)));
6450 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6451 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6452 DAG.getIntPtrConstant(0));
6454 // Or the load with the bias.
6455 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6456 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6457 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6459 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6460 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6461 MVT::v2f64, Bias)));
6462 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6463 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6464 DAG.getIntPtrConstant(0));
6466 // Subtract the bias.
6467 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6469 // Handle final rounding.
6470 EVT DestVT = Op.getValueType();
6472 if (DestVT.bitsLT(MVT::f64)) {
6473 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6474 DAG.getIntPtrConstant(0));
6475 } else if (DestVT.bitsGT(MVT::f64)) {
6476 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6479 // Handle final rounding.
6483 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6484 SelectionDAG &DAG) const {
6485 SDValue N0 = Op.getOperand(0);
6486 DebugLoc dl = Op.getDebugLoc();
6488 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6489 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6490 // the optimization here.
6491 if (DAG.SignBitIsZero(N0))
6492 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6494 EVT SrcVT = N0.getValueType();
6495 EVT DstVT = Op.getValueType();
6496 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6497 return LowerUINT_TO_FP_i64(Op, DAG);
6498 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6499 return LowerUINT_TO_FP_i32(Op, DAG);
6501 // Make a 64-bit buffer, and use it to build an FILD.
6502 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6503 if (SrcVT == MVT::i32) {
6504 SDValue WordOff = DAG.getConstant(4, getPointerTy());
6505 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6506 getPointerTy(), StackSlot, WordOff);
6507 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6508 StackSlot, MachinePointerInfo(),
6510 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6511 OffsetSlot, MachinePointerInfo(),
6513 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6517 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6518 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6519 StackSlot, MachinePointerInfo(),
6521 // For i64 source, we need to add the appropriate power of 2 if the input
6522 // was negative. This is the same as the optimization in
6523 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6524 // we must be careful to do the computation in x87 extended precision, not
6525 // in SSE. (The generic code can't know it's OK to do this, or how to.)
6526 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6527 MachineMemOperand *MMO =
6528 DAG.getMachineFunction()
6529 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6530 MachineMemOperand::MOLoad, 8, 8);
6532 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6533 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6534 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
6537 APInt FF(32, 0x5F800000ULL);
6539 // Check whether the sign bit is set.
6540 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6541 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6544 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6545 SDValue FudgePtr = DAG.getConstantPool(
6546 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6549 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6550 SDValue Zero = DAG.getIntPtrConstant(0);
6551 SDValue Four = DAG.getIntPtrConstant(4);
6552 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6554 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6556 // Load the value out, extending it from f32 to f80.
6557 // FIXME: Avoid the extend by constructing the right constant pool?
6558 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, MVT::f80, dl, DAG.getEntryNode(),
6559 FudgePtr, MachinePointerInfo::getConstantPool(),
6560 MVT::f32, false, false, 4);
6561 // Extend everything to 80 bits to force it to be done on x87.
6562 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6563 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6566 std::pair<SDValue,SDValue> X86TargetLowering::
6567 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6568 DebugLoc DL = Op.getDebugLoc();
6570 EVT DstTy = Op.getValueType();
6573 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
6577 assert(DstTy.getSimpleVT() <= MVT::i64 &&
6578 DstTy.getSimpleVT() >= MVT::i16 &&
6579 "Unknown FP_TO_SINT to lower!");
6581 // These are really Legal.
6582 if (DstTy == MVT::i32 &&
6583 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6584 return std::make_pair(SDValue(), SDValue());
6585 if (Subtarget->is64Bit() &&
6586 DstTy == MVT::i64 &&
6587 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6588 return std::make_pair(SDValue(), SDValue());
6590 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
6592 MachineFunction &MF = DAG.getMachineFunction();
6593 unsigned MemSize = DstTy.getSizeInBits()/8;
6594 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6595 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6600 switch (DstTy.getSimpleVT().SimpleTy) {
6601 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
6602 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
6603 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
6604 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
6607 SDValue Chain = DAG.getEntryNode();
6608 SDValue Value = Op.getOperand(0);
6609 EVT TheVT = Op.getOperand(0).getValueType();
6610 if (isScalarFPTypeInSSEReg(TheVT)) {
6611 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
6612 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
6613 MachinePointerInfo::getFixedStack(SSFI),
6615 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
6617 Chain, StackSlot, DAG.getValueType(TheVT)
6620 MachineMemOperand *MMO =
6621 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6622 MachineMemOperand::MOLoad, MemSize, MemSize);
6623 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
6625 Chain = Value.getValue(1);
6626 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6627 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6630 MachineMemOperand *MMO =
6631 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6632 MachineMemOperand::MOStore, MemSize, MemSize);
6634 // Build the FP_TO_INT*_IN_MEM
6635 SDValue Ops[] = { Chain, Value, StackSlot };
6636 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
6637 Ops, 3, DstTy, MMO);
6639 return std::make_pair(FIST, StackSlot);
6642 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
6643 SelectionDAG &DAG) const {
6644 if (Op.getValueType().isVector())
6647 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
6648 SDValue FIST = Vals.first, StackSlot = Vals.second;
6649 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
6650 if (FIST.getNode() == 0) return Op;
6653 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6654 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6657 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
6658 SelectionDAG &DAG) const {
6659 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
6660 SDValue FIST = Vals.first, StackSlot = Vals.second;
6661 assert(FIST.getNode() && "Unexpected failure");
6664 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6665 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6668 SDValue X86TargetLowering::LowerFABS(SDValue Op,
6669 SelectionDAG &DAG) const {
6670 LLVMContext *Context = DAG.getContext();
6671 DebugLoc dl = Op.getDebugLoc();
6672 EVT VT = Op.getValueType();
6675 EltVT = VT.getVectorElementType();
6676 std::vector<Constant*> CV;
6677 if (EltVT == MVT::f64) {
6678 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
6682 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
6688 Constant *C = ConstantVector::get(CV);
6689 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6690 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6691 MachinePointerInfo::getConstantPool(),
6693 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
6696 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
6697 LLVMContext *Context = DAG.getContext();
6698 DebugLoc dl = Op.getDebugLoc();
6699 EVT VT = Op.getValueType();
6702 EltVT = VT.getVectorElementType();
6703 std::vector<Constant*> CV;
6704 if (EltVT == MVT::f64) {
6705 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
6709 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
6715 Constant *C = ConstantVector::get(CV);
6716 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6717 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6718 MachinePointerInfo::getConstantPool(),
6720 if (VT.isVector()) {
6721 return DAG.getNode(ISD::BITCAST, dl, VT,
6722 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
6723 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6725 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
6727 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
6731 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
6732 LLVMContext *Context = DAG.getContext();
6733 SDValue Op0 = Op.getOperand(0);
6734 SDValue Op1 = Op.getOperand(1);
6735 DebugLoc dl = Op.getDebugLoc();
6736 EVT VT = Op.getValueType();
6737 EVT SrcVT = Op1.getValueType();
6739 // If second operand is smaller, extend it first.
6740 if (SrcVT.bitsLT(VT)) {
6741 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
6744 // And if it is bigger, shrink it first.
6745 if (SrcVT.bitsGT(VT)) {
6746 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
6750 // At this point the operands and the result should have the same
6751 // type, and that won't be f80 since that is not custom lowered.
6753 // First get the sign bit of second operand.
6754 std::vector<Constant*> CV;
6755 if (SrcVT == MVT::f64) {
6756 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
6757 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6759 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
6760 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6761 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6762 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6764 Constant *C = ConstantVector::get(CV);
6765 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6766 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
6767 MachinePointerInfo::getConstantPool(),
6769 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
6771 // Shift sign bit right or left if the two operands have different types.
6772 if (SrcVT.bitsGT(VT)) {
6773 // Op0 is MVT::f32, Op1 is MVT::f64.
6774 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
6775 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
6776 DAG.getConstant(32, MVT::i32));
6777 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
6778 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
6779 DAG.getIntPtrConstant(0));
6782 // Clear first operand sign bit.
6784 if (VT == MVT::f64) {
6785 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
6786 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6788 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
6789 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6790 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6791 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6793 C = ConstantVector::get(CV);
6794 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6795 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6796 MachinePointerInfo::getConstantPool(),
6798 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
6800 // Or the value with the sign bit.
6801 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
6804 /// Emit nodes that will be selected as "test Op0,Op0", or something
6806 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
6807 SelectionDAG &DAG) const {
6808 DebugLoc dl = Op.getDebugLoc();
6810 // CF and OF aren't always set the way we want. Determine which
6811 // of these we need.
6812 bool NeedCF = false;
6813 bool NeedOF = false;
6816 case X86::COND_A: case X86::COND_AE:
6817 case X86::COND_B: case X86::COND_BE:
6820 case X86::COND_G: case X86::COND_GE:
6821 case X86::COND_L: case X86::COND_LE:
6822 case X86::COND_O: case X86::COND_NO:
6827 // See if we can use the EFLAGS value from the operand instead of
6828 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
6829 // we prove that the arithmetic won't overflow, we can't use OF or CF.
6830 if (Op.getResNo() != 0 || NeedOF || NeedCF)
6831 // Emit a CMP with 0, which is the TEST pattern.
6832 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6833 DAG.getConstant(0, Op.getValueType()));
6835 unsigned Opcode = 0;
6836 unsigned NumOperands = 0;
6837 switch (Op.getNode()->getOpcode()) {
6839 // Due to an isel shortcoming, be conservative if this add is likely to be
6840 // selected as part of a load-modify-store instruction. When the root node
6841 // in a match is a store, isel doesn't know how to remap non-chain non-flag
6842 // uses of other nodes in the match, such as the ADD in this case. This
6843 // leads to the ADD being left around and reselected, with the result being
6844 // two adds in the output. Alas, even if none our users are stores, that
6845 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
6846 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
6847 // climbing the DAG back to the root, and it doesn't seem to be worth the
6849 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6850 UE = Op.getNode()->use_end(); UI != UE; ++UI)
6851 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
6854 if (ConstantSDNode *C =
6855 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
6856 // An add of one will be selected as an INC.
6857 if (C->getAPIntValue() == 1) {
6858 Opcode = X86ISD::INC;
6863 // An add of negative one (subtract of one) will be selected as a DEC.
6864 if (C->getAPIntValue().isAllOnesValue()) {
6865 Opcode = X86ISD::DEC;
6871 // Otherwise use a regular EFLAGS-setting add.
6872 Opcode = X86ISD::ADD;
6876 // If the primary and result isn't used, don't bother using X86ISD::AND,
6877 // because a TEST instruction will be better.
6878 bool NonFlagUse = false;
6879 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6880 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
6882 unsigned UOpNo = UI.getOperandNo();
6883 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
6884 // Look pass truncate.
6885 UOpNo = User->use_begin().getOperandNo();
6886 User = *User->use_begin();
6889 if (User->getOpcode() != ISD::BRCOND &&
6890 User->getOpcode() != ISD::SETCC &&
6891 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
6904 // Due to the ISEL shortcoming noted above, be conservative if this op is
6905 // likely to be selected as part of a load-modify-store instruction.
6906 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6907 UE = Op.getNode()->use_end(); UI != UE; ++UI)
6908 if (UI->getOpcode() == ISD::STORE)
6911 // Otherwise use a regular EFLAGS-setting instruction.
6912 switch (Op.getNode()->getOpcode()) {
6913 default: llvm_unreachable("unexpected operator!");
6914 case ISD::SUB: Opcode = X86ISD::SUB; break;
6915 case ISD::OR: Opcode = X86ISD::OR; break;
6916 case ISD::XOR: Opcode = X86ISD::XOR; break;
6917 case ISD::AND: Opcode = X86ISD::AND; break;
6929 return SDValue(Op.getNode(), 1);
6936 // Emit a CMP with 0, which is the TEST pattern.
6937 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6938 DAG.getConstant(0, Op.getValueType()));
6940 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
6941 SmallVector<SDValue, 4> Ops;
6942 for (unsigned i = 0; i != NumOperands; ++i)
6943 Ops.push_back(Op.getOperand(i));
6945 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
6946 DAG.ReplaceAllUsesWith(Op, New);
6947 return SDValue(New.getNode(), 1);
6950 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
6952 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
6953 SelectionDAG &DAG) const {
6954 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
6955 if (C->getAPIntValue() == 0)
6956 return EmitTest(Op0, X86CC, DAG);
6958 DebugLoc dl = Op0.getDebugLoc();
6959 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
6962 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
6963 /// if it's possible.
6964 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
6965 DebugLoc dl, SelectionDAG &DAG) const {
6966 SDValue Op0 = And.getOperand(0);
6967 SDValue Op1 = And.getOperand(1);
6968 if (Op0.getOpcode() == ISD::TRUNCATE)
6969 Op0 = Op0.getOperand(0);
6970 if (Op1.getOpcode() == ISD::TRUNCATE)
6971 Op1 = Op1.getOperand(0);
6974 if (Op1.getOpcode() == ISD::SHL)
6975 std::swap(Op0, Op1);
6976 if (Op0.getOpcode() == ISD::SHL) {
6977 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
6978 if (And00C->getZExtValue() == 1) {
6979 // If we looked past a truncate, check that it's only truncating away
6981 unsigned BitWidth = Op0.getValueSizeInBits();
6982 unsigned AndBitWidth = And.getValueSizeInBits();
6983 if (BitWidth > AndBitWidth) {
6984 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
6985 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
6986 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
6990 RHS = Op0.getOperand(1);
6992 } else if (Op1.getOpcode() == ISD::Constant) {
6993 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
6994 SDValue AndLHS = Op0;
6995 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
6996 LHS = AndLHS.getOperand(0);
6997 RHS = AndLHS.getOperand(1);
7001 if (LHS.getNode()) {
7002 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
7003 // instruction. Since the shift amount is in-range-or-undefined, we know
7004 // that doing a bittest on the i32 value is ok. We extend to i32 because
7005 // the encoding for the i16 version is larger than the i32 version.
7006 // Also promote i16 to i32 for performance / code size reason.
7007 if (LHS.getValueType() == MVT::i8 ||
7008 LHS.getValueType() == MVT::i16)
7009 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7011 // If the operand types disagree, extend the shift amount to match. Since
7012 // BT ignores high bits (like shifts) we can use anyextend.
7013 if (LHS.getValueType() != RHS.getValueType())
7014 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7016 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7017 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7018 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7019 DAG.getConstant(Cond, MVT::i8), BT);
7025 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7026 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7027 SDValue Op0 = Op.getOperand(0);
7028 SDValue Op1 = Op.getOperand(1);
7029 DebugLoc dl = Op.getDebugLoc();
7030 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7032 // Optimize to BT if possible.
7033 // Lower (X & (1 << N)) == 0 to BT(X, N).
7034 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7035 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7036 if (Op0.getOpcode() == ISD::AND &&
7038 Op1.getOpcode() == ISD::Constant &&
7039 cast<ConstantSDNode>(Op1)->isNullValue() &&
7040 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7041 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7042 if (NewSetCC.getNode())
7046 // Look for "(setcc) == / != 1" to avoid unnecessary setcc.
7047 if (Op0.getOpcode() == X86ISD::SETCC &&
7048 Op1.getOpcode() == ISD::Constant &&
7049 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7050 cast<ConstantSDNode>(Op1)->isNullValue()) &&
7051 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7052 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7053 bool Invert = (CC == ISD::SETNE) ^
7054 cast<ConstantSDNode>(Op1)->isNullValue();
7056 CCode = X86::GetOppositeBranchCondition(CCode);
7057 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7058 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7061 bool isFP = Op1.getValueType().isFloatingPoint();
7062 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7063 if (X86CC == X86::COND_INVALID)
7066 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
7068 // Use sbb x, x to materialize carry bit into a GPR.
7069 if (X86CC == X86::COND_B)
7070 return DAG.getNode(ISD::AND, dl, MVT::i8,
7071 DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
7072 DAG.getConstant(X86CC, MVT::i8), Cond),
7073 DAG.getConstant(1, MVT::i8));
7075 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7076 DAG.getConstant(X86CC, MVT::i8), Cond);
7079 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7081 SDValue Op0 = Op.getOperand(0);
7082 SDValue Op1 = Op.getOperand(1);
7083 SDValue CC = Op.getOperand(2);
7084 EVT VT = Op.getValueType();
7085 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7086 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7087 DebugLoc dl = Op.getDebugLoc();
7091 EVT VT0 = Op0.getValueType();
7092 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7093 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7096 switch (SetCCOpcode) {
7099 case ISD::SETEQ: SSECC = 0; break;
7101 case ISD::SETGT: Swap = true; // Fallthrough
7103 case ISD::SETOLT: SSECC = 1; break;
7105 case ISD::SETGE: Swap = true; // Fallthrough
7107 case ISD::SETOLE: SSECC = 2; break;
7108 case ISD::SETUO: SSECC = 3; break;
7110 case ISD::SETNE: SSECC = 4; break;
7111 case ISD::SETULE: Swap = true;
7112 case ISD::SETUGE: SSECC = 5; break;
7113 case ISD::SETULT: Swap = true;
7114 case ISD::SETUGT: SSECC = 6; break;
7115 case ISD::SETO: SSECC = 7; break;
7118 std::swap(Op0, Op1);
7120 // In the two special cases we can't handle, emit two comparisons.
7122 if (SetCCOpcode == ISD::SETUEQ) {
7124 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7125 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7126 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7128 else if (SetCCOpcode == ISD::SETONE) {
7130 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7131 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7132 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7134 llvm_unreachable("Illegal FP comparison");
7136 // Handle all other FP comparisons here.
7137 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7140 // We are handling one of the integer comparisons here. Since SSE only has
7141 // GT and EQ comparisons for integer, swapping operands and multiple
7142 // operations may be required for some comparisons.
7143 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7144 bool Swap = false, Invert = false, FlipSigns = false;
7146 switch (VT.getSimpleVT().SimpleTy) {
7148 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7149 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7150 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7151 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7154 switch (SetCCOpcode) {
7156 case ISD::SETNE: Invert = true;
7157 case ISD::SETEQ: Opc = EQOpc; break;
7158 case ISD::SETLT: Swap = true;
7159 case ISD::SETGT: Opc = GTOpc; break;
7160 case ISD::SETGE: Swap = true;
7161 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
7162 case ISD::SETULT: Swap = true;
7163 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7164 case ISD::SETUGE: Swap = true;
7165 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7168 std::swap(Op0, Op1);
7170 // Since SSE has no unsigned integer comparisons, we need to flip the sign
7171 // bits of the inputs before performing those operations.
7173 EVT EltVT = VT.getVectorElementType();
7174 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7176 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7177 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7179 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7180 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7183 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7185 // If the logical-not of the result is required, perform that now.
7187 Result = DAG.getNOT(dl, Result, VT);
7192 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7193 static bool isX86LogicalCmp(SDValue Op) {
7194 unsigned Opc = Op.getNode()->getOpcode();
7195 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7197 if (Op.getResNo() == 1 &&
7198 (Opc == X86ISD::ADD ||
7199 Opc == X86ISD::SUB ||
7200 Opc == X86ISD::SMUL ||
7201 Opc == X86ISD::UMUL ||
7202 Opc == X86ISD::INC ||
7203 Opc == X86ISD::DEC ||
7204 Opc == X86ISD::OR ||
7205 Opc == X86ISD::XOR ||
7206 Opc == X86ISD::AND))
7209 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7215 static bool isZero(SDValue V) {
7216 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7217 return C && C->isNullValue();
7220 static bool isAllOnes(SDValue V) {
7221 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7222 return C && C->isAllOnesValue();
7225 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7226 bool addTest = true;
7227 SDValue Cond = Op.getOperand(0);
7228 SDValue Op1 = Op.getOperand(1);
7229 SDValue Op2 = Op.getOperand(2);
7230 DebugLoc DL = Op.getDebugLoc();
7233 if (Cond.getOpcode() == ISD::SETCC) {
7234 SDValue NewCond = LowerSETCC(Cond, DAG);
7235 if (NewCond.getNode())
7239 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7240 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7241 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7242 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7243 if (Cond.getOpcode() == X86ISD::SETCC &&
7244 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7245 isZero(Cond.getOperand(1).getOperand(1))) {
7246 SDValue Cmp = Cond.getOperand(1);
7248 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7250 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7251 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7252 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7254 SDValue CmpOp0 = Cmp.getOperand(0);
7255 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7256 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7258 SDValue Res = // Res = 0 or -1.
7259 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7260 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7262 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7263 Res = DAG.getNOT(DL, Res, Res.getValueType());
7265 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7266 if (N2C == 0 || !N2C->isNullValue())
7267 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7272 // Look past (and (setcc_carry (cmp ...)), 1).
7273 if (Cond.getOpcode() == ISD::AND &&
7274 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7275 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7276 if (C && C->getAPIntValue() == 1)
7277 Cond = Cond.getOperand(0);
7280 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7281 // setting operand in place of the X86ISD::SETCC.
7282 if (Cond.getOpcode() == X86ISD::SETCC ||
7283 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7284 CC = Cond.getOperand(0);
7286 SDValue Cmp = Cond.getOperand(1);
7287 unsigned Opc = Cmp.getOpcode();
7288 EVT VT = Op.getValueType();
7290 bool IllegalFPCMov = false;
7291 if (VT.isFloatingPoint() && !VT.isVector() &&
7292 !isScalarFPTypeInSSEReg(VT)) // FPStack?
7293 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7295 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7296 Opc == X86ISD::BT) { // FIXME
7303 // Look pass the truncate.
7304 if (Cond.getOpcode() == ISD::TRUNCATE)
7305 Cond = Cond.getOperand(0);
7307 // We know the result of AND is compared against zero. Try to match
7309 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7310 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7311 if (NewSetCC.getNode()) {
7312 CC = NewSetCC.getOperand(0);
7313 Cond = NewSetCC.getOperand(1);
7320 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7321 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7324 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7325 // condition is true.
7326 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
7327 SDValue Ops[] = { Op2, Op1, CC, Cond };
7328 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7331 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7332 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7333 // from the AND / OR.
7334 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7335 Opc = Op.getOpcode();
7336 if (Opc != ISD::OR && Opc != ISD::AND)
7338 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7339 Op.getOperand(0).hasOneUse() &&
7340 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7341 Op.getOperand(1).hasOneUse());
7344 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7345 // 1 and that the SETCC node has a single use.
7346 static bool isXor1OfSetCC(SDValue Op) {
7347 if (Op.getOpcode() != ISD::XOR)
7349 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7350 if (N1C && N1C->getAPIntValue() == 1) {
7351 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7352 Op.getOperand(0).hasOneUse();
7357 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7358 bool addTest = true;
7359 SDValue Chain = Op.getOperand(0);
7360 SDValue Cond = Op.getOperand(1);
7361 SDValue Dest = Op.getOperand(2);
7362 DebugLoc dl = Op.getDebugLoc();
7365 if (Cond.getOpcode() == ISD::SETCC) {
7366 SDValue NewCond = LowerSETCC(Cond, DAG);
7367 if (NewCond.getNode())
7371 // FIXME: LowerXALUO doesn't handle these!!
7372 else if (Cond.getOpcode() == X86ISD::ADD ||
7373 Cond.getOpcode() == X86ISD::SUB ||
7374 Cond.getOpcode() == X86ISD::SMUL ||
7375 Cond.getOpcode() == X86ISD::UMUL)
7376 Cond = LowerXALUO(Cond, DAG);
7379 // Look pass (and (setcc_carry (cmp ...)), 1).
7380 if (Cond.getOpcode() == ISD::AND &&
7381 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7382 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7383 if (C && C->getAPIntValue() == 1)
7384 Cond = Cond.getOperand(0);
7387 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7388 // setting operand in place of the X86ISD::SETCC.
7389 if (Cond.getOpcode() == X86ISD::SETCC ||
7390 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7391 CC = Cond.getOperand(0);
7393 SDValue Cmp = Cond.getOperand(1);
7394 unsigned Opc = Cmp.getOpcode();
7395 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7396 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7400 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7404 // These can only come from an arithmetic instruction with overflow,
7405 // e.g. SADDO, UADDO.
7406 Cond = Cond.getNode()->getOperand(1);
7413 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7414 SDValue Cmp = Cond.getOperand(0).getOperand(1);
7415 if (CondOpc == ISD::OR) {
7416 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7417 // two branches instead of an explicit OR instruction with a
7419 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7420 isX86LogicalCmp(Cmp)) {
7421 CC = Cond.getOperand(0).getOperand(0);
7422 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7423 Chain, Dest, CC, Cmp);
7424 CC = Cond.getOperand(1).getOperand(0);
7428 } else { // ISD::AND
7429 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7430 // two branches instead of an explicit AND instruction with a
7431 // separate test. However, we only do this if this block doesn't
7432 // have a fall-through edge, because this requires an explicit
7433 // jmp when the condition is false.
7434 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7435 isX86LogicalCmp(Cmp) &&
7436 Op.getNode()->hasOneUse()) {
7437 X86::CondCode CCode =
7438 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7439 CCode = X86::GetOppositeBranchCondition(CCode);
7440 CC = DAG.getConstant(CCode, MVT::i8);
7441 SDNode *User = *Op.getNode()->use_begin();
7442 // Look for an unconditional branch following this conditional branch.
7443 // We need this because we need to reverse the successors in order
7444 // to implement FCMP_OEQ.
7445 if (User->getOpcode() == ISD::BR) {
7446 SDValue FalseBB = User->getOperand(1);
7448 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7449 assert(NewBR == User);
7453 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7454 Chain, Dest, CC, Cmp);
7455 X86::CondCode CCode =
7456 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7457 CCode = X86::GetOppositeBranchCondition(CCode);
7458 CC = DAG.getConstant(CCode, MVT::i8);
7464 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7465 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7466 // It should be transformed during dag combiner except when the condition
7467 // is set by a arithmetics with overflow node.
7468 X86::CondCode CCode =
7469 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7470 CCode = X86::GetOppositeBranchCondition(CCode);
7471 CC = DAG.getConstant(CCode, MVT::i8);
7472 Cond = Cond.getOperand(0).getOperand(1);
7478 // Look pass the truncate.
7479 if (Cond.getOpcode() == ISD::TRUNCATE)
7480 Cond = Cond.getOperand(0);
7482 // We know the result of AND is compared against zero. Try to match
7484 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7485 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7486 if (NewSetCC.getNode()) {
7487 CC = NewSetCC.getOperand(0);
7488 Cond = NewSetCC.getOperand(1);
7495 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7496 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7498 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7499 Chain, Dest, CC, Cond);
7503 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7504 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7505 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7506 // that the guard pages used by the OS virtual memory manager are allocated in
7507 // correct sequence.
7509 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7510 SelectionDAG &DAG) const {
7511 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
7512 "This should be used only on Windows targets");
7513 DebugLoc dl = Op.getDebugLoc();
7516 SDValue Chain = Op.getOperand(0);
7517 SDValue Size = Op.getOperand(1);
7518 // FIXME: Ensure alignment here
7522 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7524 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
7525 Flag = Chain.getValue(1);
7527 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
7529 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
7530 Flag = Chain.getValue(1);
7532 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
7534 SDValue Ops1[2] = { Chain.getValue(0), Chain };
7535 return DAG.getMergeValues(Ops1, 2, dl);
7538 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
7539 MachineFunction &MF = DAG.getMachineFunction();
7540 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
7542 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7543 DebugLoc DL = Op.getDebugLoc();
7545 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
7546 // vastart just stores the address of the VarArgsFrameIndex slot into the
7547 // memory location argument.
7548 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7550 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7551 MachinePointerInfo(SV), false, false, 0);
7555 // gp_offset (0 - 6 * 8)
7556 // fp_offset (48 - 48 + 8 * 16)
7557 // overflow_arg_area (point to parameters coming in memory).
7559 SmallVector<SDValue, 8> MemOps;
7560 SDValue FIN = Op.getOperand(1);
7562 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
7563 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
7565 FIN, MachinePointerInfo(SV), false, false, 0);
7566 MemOps.push_back(Store);
7569 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7570 FIN, DAG.getIntPtrConstant(4));
7571 Store = DAG.getStore(Op.getOperand(0), DL,
7572 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
7574 FIN, MachinePointerInfo(SV, 4), false, false, 0);
7575 MemOps.push_back(Store);
7577 // Store ptr to overflow_arg_area
7578 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7579 FIN, DAG.getIntPtrConstant(4));
7580 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7582 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
7583 MachinePointerInfo(SV, 8),
7585 MemOps.push_back(Store);
7587 // Store ptr to reg_save_area.
7588 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7589 FIN, DAG.getIntPtrConstant(8));
7590 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
7592 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
7593 MachinePointerInfo(SV, 16), false, false, 0);
7594 MemOps.push_back(Store);
7595 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
7596 &MemOps[0], MemOps.size());
7599 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
7600 assert(Subtarget->is64Bit() &&
7601 "LowerVAARG only handles 64-bit va_arg!");
7602 assert((Subtarget->isTargetLinux() ||
7603 Subtarget->isTargetDarwin()) &&
7604 "Unhandled target in LowerVAARG");
7605 assert(Op.getNode()->getNumOperands() == 4);
7606 SDValue Chain = Op.getOperand(0);
7607 SDValue SrcPtr = Op.getOperand(1);
7608 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7609 unsigned Align = Op.getConstantOperandVal(3);
7610 DebugLoc dl = Op.getDebugLoc();
7612 EVT ArgVT = Op.getNode()->getValueType(0);
7613 const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7614 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
7617 // Decide which area this value should be read from.
7618 // TODO: Implement the AMD64 ABI in its entirety. This simple
7619 // selection mechanism works only for the basic types.
7620 if (ArgVT == MVT::f80) {
7621 llvm_unreachable("va_arg for f80 not yet implemented");
7622 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
7623 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
7624 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
7625 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
7627 llvm_unreachable("Unhandled argument type in LowerVAARG");
7631 // Sanity Check: Make sure using fp_offset makes sense.
7632 assert(!UseSoftFloat &&
7633 !(DAG.getMachineFunction()
7634 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
7635 Subtarget->hasSSE1());
7638 // Insert VAARG_64 node into the DAG
7639 // VAARG_64 returns two values: Variable Argument Address, Chain
7640 SmallVector<SDValue, 11> InstOps;
7641 InstOps.push_back(Chain);
7642 InstOps.push_back(SrcPtr);
7643 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
7644 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
7645 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
7646 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
7647 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
7648 VTs, &InstOps[0], InstOps.size(),
7650 MachinePointerInfo(SV),
7655 Chain = VAARG.getValue(1);
7657 // Load the next argument and return it
7658 return DAG.getLoad(ArgVT, dl,
7661 MachinePointerInfo(),
7665 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
7666 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
7667 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
7668 SDValue Chain = Op.getOperand(0);
7669 SDValue DstPtr = Op.getOperand(1);
7670 SDValue SrcPtr = Op.getOperand(2);
7671 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
7672 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7673 DebugLoc DL = Op.getDebugLoc();
7675 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
7676 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
7678 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
7682 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
7683 DebugLoc dl = Op.getDebugLoc();
7684 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7686 default: return SDValue(); // Don't custom lower most intrinsics.
7687 // Comparison intrinsics.
7688 case Intrinsic::x86_sse_comieq_ss:
7689 case Intrinsic::x86_sse_comilt_ss:
7690 case Intrinsic::x86_sse_comile_ss:
7691 case Intrinsic::x86_sse_comigt_ss:
7692 case Intrinsic::x86_sse_comige_ss:
7693 case Intrinsic::x86_sse_comineq_ss:
7694 case Intrinsic::x86_sse_ucomieq_ss:
7695 case Intrinsic::x86_sse_ucomilt_ss:
7696 case Intrinsic::x86_sse_ucomile_ss:
7697 case Intrinsic::x86_sse_ucomigt_ss:
7698 case Intrinsic::x86_sse_ucomige_ss:
7699 case Intrinsic::x86_sse_ucomineq_ss:
7700 case Intrinsic::x86_sse2_comieq_sd:
7701 case Intrinsic::x86_sse2_comilt_sd:
7702 case Intrinsic::x86_sse2_comile_sd:
7703 case Intrinsic::x86_sse2_comigt_sd:
7704 case Intrinsic::x86_sse2_comige_sd:
7705 case Intrinsic::x86_sse2_comineq_sd:
7706 case Intrinsic::x86_sse2_ucomieq_sd:
7707 case Intrinsic::x86_sse2_ucomilt_sd:
7708 case Intrinsic::x86_sse2_ucomile_sd:
7709 case Intrinsic::x86_sse2_ucomigt_sd:
7710 case Intrinsic::x86_sse2_ucomige_sd:
7711 case Intrinsic::x86_sse2_ucomineq_sd: {
7713 ISD::CondCode CC = ISD::SETCC_INVALID;
7716 case Intrinsic::x86_sse_comieq_ss:
7717 case Intrinsic::x86_sse2_comieq_sd:
7721 case Intrinsic::x86_sse_comilt_ss:
7722 case Intrinsic::x86_sse2_comilt_sd:
7726 case Intrinsic::x86_sse_comile_ss:
7727 case Intrinsic::x86_sse2_comile_sd:
7731 case Intrinsic::x86_sse_comigt_ss:
7732 case Intrinsic::x86_sse2_comigt_sd:
7736 case Intrinsic::x86_sse_comige_ss:
7737 case Intrinsic::x86_sse2_comige_sd:
7741 case Intrinsic::x86_sse_comineq_ss:
7742 case Intrinsic::x86_sse2_comineq_sd:
7746 case Intrinsic::x86_sse_ucomieq_ss:
7747 case Intrinsic::x86_sse2_ucomieq_sd:
7748 Opc = X86ISD::UCOMI;
7751 case Intrinsic::x86_sse_ucomilt_ss:
7752 case Intrinsic::x86_sse2_ucomilt_sd:
7753 Opc = X86ISD::UCOMI;
7756 case Intrinsic::x86_sse_ucomile_ss:
7757 case Intrinsic::x86_sse2_ucomile_sd:
7758 Opc = X86ISD::UCOMI;
7761 case Intrinsic::x86_sse_ucomigt_ss:
7762 case Intrinsic::x86_sse2_ucomigt_sd:
7763 Opc = X86ISD::UCOMI;
7766 case Intrinsic::x86_sse_ucomige_ss:
7767 case Intrinsic::x86_sse2_ucomige_sd:
7768 Opc = X86ISD::UCOMI;
7771 case Intrinsic::x86_sse_ucomineq_ss:
7772 case Intrinsic::x86_sse2_ucomineq_sd:
7773 Opc = X86ISD::UCOMI;
7778 SDValue LHS = Op.getOperand(1);
7779 SDValue RHS = Op.getOperand(2);
7780 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
7781 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
7782 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
7783 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7784 DAG.getConstant(X86CC, MVT::i8), Cond);
7785 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7787 // ptest and testp intrinsics. The intrinsic these come from are designed to
7788 // return an integer value, not just an instruction so lower it to the ptest
7789 // or testp pattern and a setcc for the result.
7790 case Intrinsic::x86_sse41_ptestz:
7791 case Intrinsic::x86_sse41_ptestc:
7792 case Intrinsic::x86_sse41_ptestnzc:
7793 case Intrinsic::x86_avx_ptestz_256:
7794 case Intrinsic::x86_avx_ptestc_256:
7795 case Intrinsic::x86_avx_ptestnzc_256:
7796 case Intrinsic::x86_avx_vtestz_ps:
7797 case Intrinsic::x86_avx_vtestc_ps:
7798 case Intrinsic::x86_avx_vtestnzc_ps:
7799 case Intrinsic::x86_avx_vtestz_pd:
7800 case Intrinsic::x86_avx_vtestc_pd:
7801 case Intrinsic::x86_avx_vtestnzc_pd:
7802 case Intrinsic::x86_avx_vtestz_ps_256:
7803 case Intrinsic::x86_avx_vtestc_ps_256:
7804 case Intrinsic::x86_avx_vtestnzc_ps_256:
7805 case Intrinsic::x86_avx_vtestz_pd_256:
7806 case Intrinsic::x86_avx_vtestc_pd_256:
7807 case Intrinsic::x86_avx_vtestnzc_pd_256: {
7808 bool IsTestPacked = false;
7811 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
7812 case Intrinsic::x86_avx_vtestz_ps:
7813 case Intrinsic::x86_avx_vtestz_pd:
7814 case Intrinsic::x86_avx_vtestz_ps_256:
7815 case Intrinsic::x86_avx_vtestz_pd_256:
7816 IsTestPacked = true; // Fallthrough
7817 case Intrinsic::x86_sse41_ptestz:
7818 case Intrinsic::x86_avx_ptestz_256:
7820 X86CC = X86::COND_E;
7822 case Intrinsic::x86_avx_vtestc_ps:
7823 case Intrinsic::x86_avx_vtestc_pd:
7824 case Intrinsic::x86_avx_vtestc_ps_256:
7825 case Intrinsic::x86_avx_vtestc_pd_256:
7826 IsTestPacked = true; // Fallthrough
7827 case Intrinsic::x86_sse41_ptestc:
7828 case Intrinsic::x86_avx_ptestc_256:
7830 X86CC = X86::COND_B;
7832 case Intrinsic::x86_avx_vtestnzc_ps:
7833 case Intrinsic::x86_avx_vtestnzc_pd:
7834 case Intrinsic::x86_avx_vtestnzc_ps_256:
7835 case Intrinsic::x86_avx_vtestnzc_pd_256:
7836 IsTestPacked = true; // Fallthrough
7837 case Intrinsic::x86_sse41_ptestnzc:
7838 case Intrinsic::x86_avx_ptestnzc_256:
7840 X86CC = X86::COND_A;
7844 SDValue LHS = Op.getOperand(1);
7845 SDValue RHS = Op.getOperand(2);
7846 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
7847 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
7848 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
7849 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
7850 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7853 // Fix vector shift instructions where the last operand is a non-immediate
7855 case Intrinsic::x86_sse2_pslli_w:
7856 case Intrinsic::x86_sse2_pslli_d:
7857 case Intrinsic::x86_sse2_pslli_q:
7858 case Intrinsic::x86_sse2_psrli_w:
7859 case Intrinsic::x86_sse2_psrli_d:
7860 case Intrinsic::x86_sse2_psrli_q:
7861 case Intrinsic::x86_sse2_psrai_w:
7862 case Intrinsic::x86_sse2_psrai_d:
7863 case Intrinsic::x86_mmx_pslli_w:
7864 case Intrinsic::x86_mmx_pslli_d:
7865 case Intrinsic::x86_mmx_pslli_q:
7866 case Intrinsic::x86_mmx_psrli_w:
7867 case Intrinsic::x86_mmx_psrli_d:
7868 case Intrinsic::x86_mmx_psrli_q:
7869 case Intrinsic::x86_mmx_psrai_w:
7870 case Intrinsic::x86_mmx_psrai_d: {
7871 SDValue ShAmt = Op.getOperand(2);
7872 if (isa<ConstantSDNode>(ShAmt))
7875 unsigned NewIntNo = 0;
7876 EVT ShAmtVT = MVT::v4i32;
7878 case Intrinsic::x86_sse2_pslli_w:
7879 NewIntNo = Intrinsic::x86_sse2_psll_w;
7881 case Intrinsic::x86_sse2_pslli_d:
7882 NewIntNo = Intrinsic::x86_sse2_psll_d;
7884 case Intrinsic::x86_sse2_pslli_q:
7885 NewIntNo = Intrinsic::x86_sse2_psll_q;
7887 case Intrinsic::x86_sse2_psrli_w:
7888 NewIntNo = Intrinsic::x86_sse2_psrl_w;
7890 case Intrinsic::x86_sse2_psrli_d:
7891 NewIntNo = Intrinsic::x86_sse2_psrl_d;
7893 case Intrinsic::x86_sse2_psrli_q:
7894 NewIntNo = Intrinsic::x86_sse2_psrl_q;
7896 case Intrinsic::x86_sse2_psrai_w:
7897 NewIntNo = Intrinsic::x86_sse2_psra_w;
7899 case Intrinsic::x86_sse2_psrai_d:
7900 NewIntNo = Intrinsic::x86_sse2_psra_d;
7903 ShAmtVT = MVT::v2i32;
7905 case Intrinsic::x86_mmx_pslli_w:
7906 NewIntNo = Intrinsic::x86_mmx_psll_w;
7908 case Intrinsic::x86_mmx_pslli_d:
7909 NewIntNo = Intrinsic::x86_mmx_psll_d;
7911 case Intrinsic::x86_mmx_pslli_q:
7912 NewIntNo = Intrinsic::x86_mmx_psll_q;
7914 case Intrinsic::x86_mmx_psrli_w:
7915 NewIntNo = Intrinsic::x86_mmx_psrl_w;
7917 case Intrinsic::x86_mmx_psrli_d:
7918 NewIntNo = Intrinsic::x86_mmx_psrl_d;
7920 case Intrinsic::x86_mmx_psrli_q:
7921 NewIntNo = Intrinsic::x86_mmx_psrl_q;
7923 case Intrinsic::x86_mmx_psrai_w:
7924 NewIntNo = Intrinsic::x86_mmx_psra_w;
7926 case Intrinsic::x86_mmx_psrai_d:
7927 NewIntNo = Intrinsic::x86_mmx_psra_d;
7929 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7935 // The vector shift intrinsics with scalars uses 32b shift amounts but
7936 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
7940 ShOps[1] = DAG.getConstant(0, MVT::i32);
7941 if (ShAmtVT == MVT::v4i32) {
7942 ShOps[2] = DAG.getUNDEF(MVT::i32);
7943 ShOps[3] = DAG.getUNDEF(MVT::i32);
7944 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
7946 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
7947 // FIXME this must be lowered to get rid of the invalid type.
7950 EVT VT = Op.getValueType();
7951 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
7952 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7953 DAG.getConstant(NewIntNo, MVT::i32),
7954 Op.getOperand(1), ShAmt);
7959 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
7960 SelectionDAG &DAG) const {
7961 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7962 MFI->setReturnAddressIsTaken(true);
7964 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7965 DebugLoc dl = Op.getDebugLoc();
7968 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7970 DAG.getConstant(TD->getPointerSize(),
7971 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
7972 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7973 DAG.getNode(ISD::ADD, dl, getPointerTy(),
7975 MachinePointerInfo(), false, false, 0);
7978 // Just load the return address.
7979 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
7980 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7981 RetAddrFI, MachinePointerInfo(), false, false, 0);
7984 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
7985 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7986 MFI->setFrameAddressIsTaken(true);
7988 EVT VT = Op.getValueType();
7989 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
7990 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7991 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
7992 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
7994 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
7995 MachinePointerInfo(),
8000 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8001 SelectionDAG &DAG) const {
8002 return DAG.getIntPtrConstant(2*TD->getPointerSize());
8005 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8006 MachineFunction &MF = DAG.getMachineFunction();
8007 SDValue Chain = Op.getOperand(0);
8008 SDValue Offset = Op.getOperand(1);
8009 SDValue Handler = Op.getOperand(2);
8010 DebugLoc dl = Op.getDebugLoc();
8012 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8013 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8015 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8017 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8018 DAG.getIntPtrConstant(TD->getPointerSize()));
8019 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8020 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8022 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8023 MF.getRegInfo().addLiveOut(StoreAddrReg);
8025 return DAG.getNode(X86ISD::EH_RETURN, dl,
8027 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8030 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8031 SelectionDAG &DAG) const {
8032 SDValue Root = Op.getOperand(0);
8033 SDValue Trmp = Op.getOperand(1); // trampoline
8034 SDValue FPtr = Op.getOperand(2); // nested function
8035 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8036 DebugLoc dl = Op.getDebugLoc();
8038 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8040 if (Subtarget->is64Bit()) {
8041 SDValue OutChains[6];
8043 // Large code-model.
8044 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
8045 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8047 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8048 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8050 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8052 // Load the pointer to the nested function into R11.
8053 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8054 SDValue Addr = Trmp;
8055 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8056 Addr, MachinePointerInfo(TrmpAddr),
8059 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8060 DAG.getConstant(2, MVT::i64));
8061 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8062 MachinePointerInfo(TrmpAddr, 2),
8065 // Load the 'nest' parameter value into R10.
8066 // R10 is specified in X86CallingConv.td
8067 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8068 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8069 DAG.getConstant(10, MVT::i64));
8070 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8071 Addr, MachinePointerInfo(TrmpAddr, 10),
8074 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8075 DAG.getConstant(12, MVT::i64));
8076 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8077 MachinePointerInfo(TrmpAddr, 12),
8080 // Jump to the nested function.
8081 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8082 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8083 DAG.getConstant(20, MVT::i64));
8084 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8085 Addr, MachinePointerInfo(TrmpAddr, 20),
8088 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8089 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8090 DAG.getConstant(22, MVT::i64));
8091 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8092 MachinePointerInfo(TrmpAddr, 22),
8096 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8097 return DAG.getMergeValues(Ops, 2, dl);
8099 const Function *Func =
8100 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8101 CallingConv::ID CC = Func->getCallingConv();
8106 llvm_unreachable("Unsupported calling convention");
8107 case CallingConv::C:
8108 case CallingConv::X86_StdCall: {
8109 // Pass 'nest' parameter in ECX.
8110 // Must be kept in sync with X86CallingConv.td
8113 // Check that ECX wasn't needed by an 'inreg' parameter.
8114 const FunctionType *FTy = Func->getFunctionType();
8115 const AttrListPtr &Attrs = Func->getAttributes();
8117 if (!Attrs.isEmpty() && !Func->isVarArg()) {
8118 unsigned InRegCount = 0;
8121 for (FunctionType::param_iterator I = FTy->param_begin(),
8122 E = FTy->param_end(); I != E; ++I, ++Idx)
8123 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8124 // FIXME: should only count parameters that are lowered to integers.
8125 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8127 if (InRegCount > 2) {
8128 report_fatal_error("Nest register in use - reduce number of inreg"
8134 case CallingConv::X86_FastCall:
8135 case CallingConv::X86_ThisCall:
8136 case CallingConv::Fast:
8137 // Pass 'nest' parameter in EAX.
8138 // Must be kept in sync with X86CallingConv.td
8143 SDValue OutChains[4];
8146 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8147 DAG.getConstant(10, MVT::i32));
8148 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8150 // This is storing the opcode for MOV32ri.
8151 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8152 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8153 OutChains[0] = DAG.getStore(Root, dl,
8154 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8155 Trmp, MachinePointerInfo(TrmpAddr),
8158 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8159 DAG.getConstant(1, MVT::i32));
8160 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8161 MachinePointerInfo(TrmpAddr, 1),
8164 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8165 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8166 DAG.getConstant(5, MVT::i32));
8167 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8168 MachinePointerInfo(TrmpAddr, 5),
8171 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8172 DAG.getConstant(6, MVT::i32));
8173 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8174 MachinePointerInfo(TrmpAddr, 6),
8178 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8179 return DAG.getMergeValues(Ops, 2, dl);
8183 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8184 SelectionDAG &DAG) const {
8186 The rounding mode is in bits 11:10 of FPSR, and has the following
8193 FLT_ROUNDS, on the other hand, expects the following:
8200 To perform the conversion, we do:
8201 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8204 MachineFunction &MF = DAG.getMachineFunction();
8205 const TargetMachine &TM = MF.getTarget();
8206 const TargetFrameInfo &TFI = *TM.getFrameInfo();
8207 unsigned StackAlignment = TFI.getStackAlignment();
8208 EVT VT = Op.getValueType();
8209 DebugLoc DL = Op.getDebugLoc();
8211 // Save FP Control Word to stack slot
8212 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8213 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8216 MachineMemOperand *MMO =
8217 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8218 MachineMemOperand::MOStore, 2, 2);
8220 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8221 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8222 DAG.getVTList(MVT::Other),
8223 Ops, 2, MVT::i16, MMO);
8225 // Load FP Control Word from stack slot
8226 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8227 MachinePointerInfo(), false, false, 0);
8229 // Transform as necessary
8231 DAG.getNode(ISD::SRL, DL, MVT::i16,
8232 DAG.getNode(ISD::AND, DL, MVT::i16,
8233 CWD, DAG.getConstant(0x800, MVT::i16)),
8234 DAG.getConstant(11, MVT::i8));
8236 DAG.getNode(ISD::SRL, DL, MVT::i16,
8237 DAG.getNode(ISD::AND, DL, MVT::i16,
8238 CWD, DAG.getConstant(0x400, MVT::i16)),
8239 DAG.getConstant(9, MVT::i8));
8242 DAG.getNode(ISD::AND, DL, MVT::i16,
8243 DAG.getNode(ISD::ADD, DL, MVT::i16,
8244 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8245 DAG.getConstant(1, MVT::i16)),
8246 DAG.getConstant(3, MVT::i16));
8249 return DAG.getNode((VT.getSizeInBits() < 16 ?
8250 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8253 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8254 EVT VT = Op.getValueType();
8256 unsigned NumBits = VT.getSizeInBits();
8257 DebugLoc dl = Op.getDebugLoc();
8259 Op = Op.getOperand(0);
8260 if (VT == MVT::i8) {
8261 // Zero extend to i32 since there is not an i8 bsr.
8263 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8266 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8267 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8268 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8270 // If src is zero (i.e. bsr sets ZF), returns NumBits.
8273 DAG.getConstant(NumBits+NumBits-1, OpVT),
8274 DAG.getConstant(X86::COND_E, MVT::i8),
8277 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8279 // Finally xor with NumBits-1.
8280 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8283 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8287 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8288 EVT VT = Op.getValueType();
8290 unsigned NumBits = VT.getSizeInBits();
8291 DebugLoc dl = Op.getDebugLoc();
8293 Op = Op.getOperand(0);
8294 if (VT == MVT::i8) {
8296 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8299 // Issue a bsf (scan bits forward) which also sets EFLAGS.
8300 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8301 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8303 // If src is zero (i.e. bsf sets ZF), returns NumBits.
8306 DAG.getConstant(NumBits, OpVT),
8307 DAG.getConstant(X86::COND_E, MVT::i8),
8310 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8313 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8317 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8318 EVT VT = Op.getValueType();
8319 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8320 DebugLoc dl = Op.getDebugLoc();
8322 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8323 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8324 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8325 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8326 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8328 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8329 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8330 // return AloBlo + AloBhi + AhiBlo;
8332 SDValue A = Op.getOperand(0);
8333 SDValue B = Op.getOperand(1);
8335 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8336 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8337 A, DAG.getConstant(32, MVT::i32));
8338 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8339 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8340 B, DAG.getConstant(32, MVT::i32));
8341 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8342 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8344 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8345 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8347 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8348 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8350 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8351 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8352 AloBhi, DAG.getConstant(32, MVT::i32));
8353 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8354 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8355 AhiBlo, DAG.getConstant(32, MVT::i32));
8356 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8357 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8361 SDValue X86TargetLowering::LowerSHL(SDValue Op, SelectionDAG &DAG) const {
8362 EVT VT = Op.getValueType();
8363 DebugLoc dl = Op.getDebugLoc();
8364 SDValue R = Op.getOperand(0);
8366 LLVMContext *Context = DAG.getContext();
8368 assert(Subtarget->hasSSE41() && "Cannot lower SHL without SSE4.1 or later");
8370 if (VT == MVT::v4i32) {
8371 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8372 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8373 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8375 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8377 std::vector<Constant*> CV(4, CI);
8378 Constant *C = ConstantVector::get(CV);
8379 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8380 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8381 MachinePointerInfo::getConstantPool(),
8384 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8385 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8386 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8387 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8389 if (VT == MVT::v16i8) {
8391 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8392 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8393 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8395 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8396 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8398 std::vector<Constant*> CVM1(16, CM1);
8399 std::vector<Constant*> CVM2(16, CM2);
8400 Constant *C = ConstantVector::get(CVM1);
8401 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8402 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8403 MachinePointerInfo::getConstantPool(),
8406 // r = pblendv(r, psllw(r & (char16)15, 4), a);
8407 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8408 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8409 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8410 DAG.getConstant(4, MVT::i32));
8411 R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8412 DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8415 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8417 C = ConstantVector::get(CVM2);
8418 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8419 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8420 MachinePointerInfo::getConstantPool(),
8423 // r = pblendv(r, psllw(r & (char16)63, 2), a);
8424 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8425 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8426 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8427 DAG.getConstant(2, MVT::i32));
8428 R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8429 DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8432 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8434 // return pblendv(r, r+r, a);
8435 R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8436 DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8437 R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8443 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8444 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8445 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8446 // looks for this combo and may remove the "setcc" instruction if the "setcc"
8447 // has only one use.
8448 SDNode *N = Op.getNode();
8449 SDValue LHS = N->getOperand(0);
8450 SDValue RHS = N->getOperand(1);
8451 unsigned BaseOp = 0;
8453 DebugLoc DL = Op.getDebugLoc();
8454 switch (Op.getOpcode()) {
8455 default: llvm_unreachable("Unknown ovf instruction!");
8457 // A subtract of one will be selected as a INC. Note that INC doesn't
8458 // set CF, so we can't do this for UADDO.
8459 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8460 if (C->getAPIntValue() == 1) {
8461 BaseOp = X86ISD::INC;
8465 BaseOp = X86ISD::ADD;
8469 BaseOp = X86ISD::ADD;
8473 // A subtract of one will be selected as a DEC. Note that DEC doesn't
8474 // set CF, so we can't do this for USUBO.
8475 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8476 if (C->getAPIntValue() == 1) {
8477 BaseOp = X86ISD::DEC;
8481 BaseOp = X86ISD::SUB;
8485 BaseOp = X86ISD::SUB;
8489 BaseOp = X86ISD::SMUL;
8492 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
8493 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
8495 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
8498 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8499 DAG.getConstant(X86::COND_O, MVT::i32),
8500 SDValue(Sum.getNode(), 2));
8502 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8507 // Also sets EFLAGS.
8508 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
8509 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
8512 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
8513 DAG.getConstant(Cond, MVT::i32),
8514 SDValue(Sum.getNode(), 1));
8516 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8520 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
8521 DebugLoc dl = Op.getDebugLoc();
8523 if (!Subtarget->hasSSE2()) {
8524 SDValue Chain = Op.getOperand(0);
8525 SDValue Zero = DAG.getConstant(0,
8526 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8528 DAG.getRegister(X86::ESP, MVT::i32), // Base
8529 DAG.getTargetConstant(1, MVT::i8), // Scale
8530 DAG.getRegister(0, MVT::i32), // Index
8531 DAG.getTargetConstant(0, MVT::i32), // Disp
8532 DAG.getRegister(0, MVT::i32), // Segment.
8537 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
8538 array_lengthof(Ops));
8539 return SDValue(Res, 0);
8542 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
8544 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
8546 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8547 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8548 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
8549 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
8551 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
8552 if (!Op1 && !Op2 && !Op3 && Op4)
8553 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
8555 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
8556 if (Op1 && !Op2 && !Op3 && !Op4)
8557 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
8559 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
8561 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
8564 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8565 EVT T = Op.getValueType();
8566 DebugLoc DL = Op.getDebugLoc();
8569 switch(T.getSimpleVT().SimpleTy) {
8571 assert(false && "Invalid value type!");
8572 case MVT::i8: Reg = X86::AL; size = 1; break;
8573 case MVT::i16: Reg = X86::AX; size = 2; break;
8574 case MVT::i32: Reg = X86::EAX; size = 4; break;
8576 assert(Subtarget->is64Bit() && "Node not type legal!");
8577 Reg = X86::RAX; size = 8;
8580 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
8581 Op.getOperand(2), SDValue());
8582 SDValue Ops[] = { cpIn.getValue(0),
8585 DAG.getTargetConstant(size, MVT::i8),
8587 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8588 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
8589 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
8592 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
8596 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
8597 SelectionDAG &DAG) const {
8598 assert(Subtarget->is64Bit() && "Result not type legalized?");
8599 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8600 SDValue TheChain = Op.getOperand(0);
8601 DebugLoc dl = Op.getDebugLoc();
8602 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8603 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
8604 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
8606 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
8607 DAG.getConstant(32, MVT::i8));
8609 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
8612 return DAG.getMergeValues(Ops, 2, dl);
8615 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
8616 SelectionDAG &DAG) const {
8617 EVT SrcVT = Op.getOperand(0).getValueType();
8618 EVT DstVT = Op.getValueType();
8619 assert((Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
8620 Subtarget->hasMMX() && !DisableMMX) &&
8621 "Unexpected custom BITCAST");
8622 assert((DstVT == MVT::i64 ||
8623 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
8624 "Unexpected custom BITCAST");
8625 // i64 <=> MMX conversions are Legal.
8626 if (SrcVT==MVT::i64 && DstVT.isVector())
8628 if (DstVT==MVT::i64 && SrcVT.isVector())
8630 // MMX <=> MMX conversions are Legal.
8631 if (SrcVT.isVector() && DstVT.isVector())
8633 // All other conversions need to be expanded.
8636 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
8637 SDNode *Node = Op.getNode();
8638 DebugLoc dl = Node->getDebugLoc();
8639 EVT T = Node->getValueType(0);
8640 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
8641 DAG.getConstant(0, T), Node->getOperand(2));
8642 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
8643 cast<AtomicSDNode>(Node)->getMemoryVT(),
8644 Node->getOperand(0),
8645 Node->getOperand(1), negOp,
8646 cast<AtomicSDNode>(Node)->getSrcValue(),
8647 cast<AtomicSDNode>(Node)->getAlignment());
8650 /// LowerOperation - Provide custom lowering hooks for some operations.
8652 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8653 switch (Op.getOpcode()) {
8654 default: llvm_unreachable("Should not custom lower this!");
8655 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
8656 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
8657 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
8658 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
8659 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
8660 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
8661 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8662 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
8663 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
8664 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
8665 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
8666 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
8667 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
8668 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
8669 case ISD::SHL_PARTS:
8670 case ISD::SRA_PARTS:
8671 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
8672 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
8673 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
8674 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
8675 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
8676 case ISD::FABS: return LowerFABS(Op, DAG);
8677 case ISD::FNEG: return LowerFNEG(Op, DAG);
8678 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
8679 case ISD::SETCC: return LowerSETCC(Op, DAG);
8680 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
8681 case ISD::SELECT: return LowerSELECT(Op, DAG);
8682 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
8683 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
8684 case ISD::VASTART: return LowerVASTART(Op, DAG);
8685 case ISD::VAARG: return LowerVAARG(Op, DAG);
8686 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
8687 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8688 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
8689 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
8690 case ISD::FRAME_TO_ARGS_OFFSET:
8691 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
8692 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
8693 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
8694 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
8695 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
8696 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
8697 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
8698 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
8699 case ISD::SHL: return LowerSHL(Op, DAG);
8705 case ISD::UMULO: return LowerXALUO(Op, DAG);
8706 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
8707 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
8711 void X86TargetLowering::
8712 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
8713 SelectionDAG &DAG, unsigned NewOp) const {
8714 EVT T = Node->getValueType(0);
8715 DebugLoc dl = Node->getDebugLoc();
8716 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
8718 SDValue Chain = Node->getOperand(0);
8719 SDValue In1 = Node->getOperand(1);
8720 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8721 Node->getOperand(2), DAG.getIntPtrConstant(0));
8722 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8723 Node->getOperand(2), DAG.getIntPtrConstant(1));
8724 SDValue Ops[] = { Chain, In1, In2L, In2H };
8725 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8727 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
8728 cast<MemSDNode>(Node)->getMemOperand());
8729 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
8730 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8731 Results.push_back(Result.getValue(2));
8734 /// ReplaceNodeResults - Replace a node with an illegal result type
8735 /// with a new node built out of custom code.
8736 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
8737 SmallVectorImpl<SDValue>&Results,
8738 SelectionDAG &DAG) const {
8739 DebugLoc dl = N->getDebugLoc();
8740 switch (N->getOpcode()) {
8742 assert(false && "Do not know how to custom type legalize this operation!");
8744 case ISD::FP_TO_SINT: {
8745 std::pair<SDValue,SDValue> Vals =
8746 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
8747 SDValue FIST = Vals.first, StackSlot = Vals.second;
8748 if (FIST.getNode() != 0) {
8749 EVT VT = N->getValueType(0);
8750 // Return a load from the stack slot.
8751 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
8752 MachinePointerInfo(), false, false, 0));
8756 case ISD::READCYCLECOUNTER: {
8757 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8758 SDValue TheChain = N->getOperand(0);
8759 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8760 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
8762 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
8764 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
8765 SDValue Ops[] = { eax, edx };
8766 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
8767 Results.push_back(edx.getValue(1));
8770 case ISD::ATOMIC_CMP_SWAP: {
8771 EVT T = N->getValueType(0);
8772 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
8773 SDValue cpInL, cpInH;
8774 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8775 DAG.getConstant(0, MVT::i32));
8776 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8777 DAG.getConstant(1, MVT::i32));
8778 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
8779 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
8781 SDValue swapInL, swapInH;
8782 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8783 DAG.getConstant(0, MVT::i32));
8784 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8785 DAG.getConstant(1, MVT::i32));
8786 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
8788 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
8789 swapInL.getValue(1));
8790 SDValue Ops[] = { swapInH.getValue(0),
8792 swapInH.getValue(1) };
8793 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8794 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
8795 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
8797 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
8798 MVT::i32, Result.getValue(1));
8799 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
8800 MVT::i32, cpOutL.getValue(2));
8801 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
8802 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8803 Results.push_back(cpOutH.getValue(1));
8806 case ISD::ATOMIC_LOAD_ADD:
8807 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
8809 case ISD::ATOMIC_LOAD_AND:
8810 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
8812 case ISD::ATOMIC_LOAD_NAND:
8813 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
8815 case ISD::ATOMIC_LOAD_OR:
8816 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
8818 case ISD::ATOMIC_LOAD_SUB:
8819 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
8821 case ISD::ATOMIC_LOAD_XOR:
8822 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
8824 case ISD::ATOMIC_SWAP:
8825 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
8830 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
8832 default: return NULL;
8833 case X86ISD::BSF: return "X86ISD::BSF";
8834 case X86ISD::BSR: return "X86ISD::BSR";
8835 case X86ISD::SHLD: return "X86ISD::SHLD";
8836 case X86ISD::SHRD: return "X86ISD::SHRD";
8837 case X86ISD::FAND: return "X86ISD::FAND";
8838 case X86ISD::FOR: return "X86ISD::FOR";
8839 case X86ISD::FXOR: return "X86ISD::FXOR";
8840 case X86ISD::FSRL: return "X86ISD::FSRL";
8841 case X86ISD::FILD: return "X86ISD::FILD";
8842 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
8843 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
8844 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
8845 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
8846 case X86ISD::FLD: return "X86ISD::FLD";
8847 case X86ISD::FST: return "X86ISD::FST";
8848 case X86ISD::CALL: return "X86ISD::CALL";
8849 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
8850 case X86ISD::BT: return "X86ISD::BT";
8851 case X86ISD::CMP: return "X86ISD::CMP";
8852 case X86ISD::COMI: return "X86ISD::COMI";
8853 case X86ISD::UCOMI: return "X86ISD::UCOMI";
8854 case X86ISD::SETCC: return "X86ISD::SETCC";
8855 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
8856 case X86ISD::CMOV: return "X86ISD::CMOV";
8857 case X86ISD::BRCOND: return "X86ISD::BRCOND";
8858 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
8859 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
8860 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
8861 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
8862 case X86ISD::Wrapper: return "X86ISD::Wrapper";
8863 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
8864 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
8865 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
8866 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
8867 case X86ISD::PINSRB: return "X86ISD::PINSRB";
8868 case X86ISD::PINSRW: return "X86ISD::PINSRW";
8869 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
8870 case X86ISD::FMAX: return "X86ISD::FMAX";
8871 case X86ISD::FMIN: return "X86ISD::FMIN";
8872 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
8873 case X86ISD::FRCP: return "X86ISD::FRCP";
8874 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
8875 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
8876 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
8877 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
8878 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
8879 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
8880 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
8881 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
8882 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
8883 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
8884 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
8885 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
8886 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
8887 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
8888 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
8889 case X86ISD::VSHL: return "X86ISD::VSHL";
8890 case X86ISD::VSRL: return "X86ISD::VSRL";
8891 case X86ISD::CMPPD: return "X86ISD::CMPPD";
8892 case X86ISD::CMPPS: return "X86ISD::CMPPS";
8893 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
8894 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
8895 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
8896 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
8897 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
8898 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
8899 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
8900 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
8901 case X86ISD::ADD: return "X86ISD::ADD";
8902 case X86ISD::SUB: return "X86ISD::SUB";
8903 case X86ISD::SMUL: return "X86ISD::SMUL";
8904 case X86ISD::UMUL: return "X86ISD::UMUL";
8905 case X86ISD::INC: return "X86ISD::INC";
8906 case X86ISD::DEC: return "X86ISD::DEC";
8907 case X86ISD::OR: return "X86ISD::OR";
8908 case X86ISD::XOR: return "X86ISD::XOR";
8909 case X86ISD::AND: return "X86ISD::AND";
8910 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
8911 case X86ISD::PTEST: return "X86ISD::PTEST";
8912 case X86ISD::TESTP: return "X86ISD::TESTP";
8913 case X86ISD::PALIGN: return "X86ISD::PALIGN";
8914 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
8915 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
8916 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
8917 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
8918 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
8919 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
8920 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
8921 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
8922 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
8923 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
8924 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD";
8925 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
8926 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
8927 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
8928 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
8929 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
8930 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
8931 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
8932 case X86ISD::MOVSD: return "X86ISD::MOVSD";
8933 case X86ISD::MOVSS: return "X86ISD::MOVSS";
8934 case X86ISD::UNPCKLPS: return "X86ISD::UNPCKLPS";
8935 case X86ISD::UNPCKLPD: return "X86ISD::UNPCKLPD";
8936 case X86ISD::UNPCKHPS: return "X86ISD::UNPCKHPS";
8937 case X86ISD::UNPCKHPD: return "X86ISD::UNPCKHPD";
8938 case X86ISD::PUNPCKLBW: return "X86ISD::PUNPCKLBW";
8939 case X86ISD::PUNPCKLWD: return "X86ISD::PUNPCKLWD";
8940 case X86ISD::PUNPCKLDQ: return "X86ISD::PUNPCKLDQ";
8941 case X86ISD::PUNPCKLQDQ: return "X86ISD::PUNPCKLQDQ";
8942 case X86ISD::PUNPCKHBW: return "X86ISD::PUNPCKHBW";
8943 case X86ISD::PUNPCKHWD: return "X86ISD::PUNPCKHWD";
8944 case X86ISD::PUNPCKHDQ: return "X86ISD::PUNPCKHDQ";
8945 case X86ISD::PUNPCKHQDQ: return "X86ISD::PUNPCKHQDQ";
8946 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
8947 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
8948 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
8952 // isLegalAddressingMode - Return true if the addressing mode represented
8953 // by AM is legal for this target, for a load/store of the specified type.
8954 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
8955 const Type *Ty) const {
8956 // X86 supports extremely general addressing modes.
8957 CodeModel::Model M = getTargetMachine().getCodeModel();
8958 Reloc::Model R = getTargetMachine().getRelocationModel();
8960 // X86 allows a sign-extended 32-bit immediate field as a displacement.
8961 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
8966 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
8968 // If a reference to this global requires an extra load, we can't fold it.
8969 if (isGlobalStubReference(GVFlags))
8972 // If BaseGV requires a register for the PIC base, we cannot also have a
8973 // BaseReg specified.
8974 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
8977 // If lower 4G is not available, then we must use rip-relative addressing.
8978 if ((M != CodeModel::Small || R != Reloc::Static) &&
8979 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
8989 // These scales always work.
8994 // These scales are formed with basereg+scalereg. Only accept if there is
8999 default: // Other stuff never works.
9007 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
9008 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9010 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9011 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9012 if (NumBits1 <= NumBits2)
9017 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9018 if (!VT1.isInteger() || !VT2.isInteger())
9020 unsigned NumBits1 = VT1.getSizeInBits();
9021 unsigned NumBits2 = VT2.getSizeInBits();
9022 if (NumBits1 <= NumBits2)
9027 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9028 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9029 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9032 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9033 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9034 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9037 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9038 // i16 instructions are longer (0x66 prefix) and potentially slower.
9039 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9042 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9043 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9044 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9045 /// are assumed to be legal.
9047 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9049 // Very little shuffling can be done for 64-bit vectors right now.
9050 if (VT.getSizeInBits() == 64)
9051 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9053 // FIXME: pshufb, blends, shifts.
9054 return (VT.getVectorNumElements() == 2 ||
9055 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9056 isMOVLMask(M, VT) ||
9057 isSHUFPMask(M, VT) ||
9058 isPSHUFDMask(M, VT) ||
9059 isPSHUFHWMask(M, VT) ||
9060 isPSHUFLWMask(M, VT) ||
9061 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9062 isUNPCKLMask(M, VT) ||
9063 isUNPCKHMask(M, VT) ||
9064 isUNPCKL_v_undef_Mask(M, VT) ||
9065 isUNPCKH_v_undef_Mask(M, VT));
9069 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9071 unsigned NumElts = VT.getVectorNumElements();
9072 // FIXME: This collection of masks seems suspect.
9075 if (NumElts == 4 && VT.getSizeInBits() == 128) {
9076 return (isMOVLMask(Mask, VT) ||
9077 isCommutedMOVLMask(Mask, VT, true) ||
9078 isSHUFPMask(Mask, VT) ||
9079 isCommutedSHUFPMask(Mask, VT));
9084 //===----------------------------------------------------------------------===//
9085 // X86 Scheduler Hooks
9086 //===----------------------------------------------------------------------===//
9088 // private utility function
9090 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9091 MachineBasicBlock *MBB,
9098 TargetRegisterClass *RC,
9099 bool invSrc) const {
9100 // For the atomic bitwise operator, we generate
9103 // ld t1 = [bitinstr.addr]
9104 // op t2 = t1, [bitinstr.val]
9106 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9108 // fallthrough -->nextMBB
9109 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9110 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9111 MachineFunction::iterator MBBIter = MBB;
9114 /// First build the CFG
9115 MachineFunction *F = MBB->getParent();
9116 MachineBasicBlock *thisMBB = MBB;
9117 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9118 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9119 F->insert(MBBIter, newMBB);
9120 F->insert(MBBIter, nextMBB);
9122 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9123 nextMBB->splice(nextMBB->begin(), thisMBB,
9124 llvm::next(MachineBasicBlock::iterator(bInstr)),
9126 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9128 // Update thisMBB to fall through to newMBB
9129 thisMBB->addSuccessor(newMBB);
9131 // newMBB jumps to itself and fall through to nextMBB
9132 newMBB->addSuccessor(nextMBB);
9133 newMBB->addSuccessor(newMBB);
9135 // Insert instructions into newMBB based on incoming instruction
9136 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9137 "unexpected number of operands");
9138 DebugLoc dl = bInstr->getDebugLoc();
9139 MachineOperand& destOper = bInstr->getOperand(0);
9140 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9141 int numArgs = bInstr->getNumOperands() - 1;
9142 for (int i=0; i < numArgs; ++i)
9143 argOpers[i] = &bInstr->getOperand(i+1);
9145 // x86 address has 4 operands: base, index, scale, and displacement
9146 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9147 int valArgIndx = lastAddrIndx + 1;
9149 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9150 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9151 for (int i=0; i <= lastAddrIndx; ++i)
9152 (*MIB).addOperand(*argOpers[i]);
9154 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9156 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9161 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9162 assert((argOpers[valArgIndx]->isReg() ||
9163 argOpers[valArgIndx]->isImm()) &&
9165 if (argOpers[valArgIndx]->isReg())
9166 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9168 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9170 (*MIB).addOperand(*argOpers[valArgIndx]);
9172 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9175 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9176 for (int i=0; i <= lastAddrIndx; ++i)
9177 (*MIB).addOperand(*argOpers[i]);
9179 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9180 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9181 bInstr->memoperands_end());
9183 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9187 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9189 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9193 // private utility function: 64 bit atomics on 32 bit host.
9195 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9196 MachineBasicBlock *MBB,
9201 bool invSrc) const {
9202 // For the atomic bitwise operator, we generate
9203 // thisMBB (instructions are in pairs, except cmpxchg8b)
9204 // ld t1,t2 = [bitinstr.addr]
9206 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9207 // op t5, t6 <- out1, out2, [bitinstr.val]
9208 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
9209 // mov ECX, EBX <- t5, t6
9210 // mov EAX, EDX <- t1, t2
9211 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
9212 // mov t3, t4 <- EAX, EDX
9214 // result in out1, out2
9215 // fallthrough -->nextMBB
9217 const TargetRegisterClass *RC = X86::GR32RegisterClass;
9218 const unsigned LoadOpc = X86::MOV32rm;
9219 const unsigned NotOpc = X86::NOT32r;
9220 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9221 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9222 MachineFunction::iterator MBBIter = MBB;
9225 /// First build the CFG
9226 MachineFunction *F = MBB->getParent();
9227 MachineBasicBlock *thisMBB = MBB;
9228 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9229 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9230 F->insert(MBBIter, newMBB);
9231 F->insert(MBBIter, nextMBB);
9233 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9234 nextMBB->splice(nextMBB->begin(), thisMBB,
9235 llvm::next(MachineBasicBlock::iterator(bInstr)),
9237 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9239 // Update thisMBB to fall through to newMBB
9240 thisMBB->addSuccessor(newMBB);
9242 // newMBB jumps to itself and fall through to nextMBB
9243 newMBB->addSuccessor(nextMBB);
9244 newMBB->addSuccessor(newMBB);
9246 DebugLoc dl = bInstr->getDebugLoc();
9247 // Insert instructions into newMBB based on incoming instruction
9248 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9249 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9250 "unexpected number of operands");
9251 MachineOperand& dest1Oper = bInstr->getOperand(0);
9252 MachineOperand& dest2Oper = bInstr->getOperand(1);
9253 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9254 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9255 argOpers[i] = &bInstr->getOperand(i+2);
9257 // We use some of the operands multiple times, so conservatively just
9258 // clear any kill flags that might be present.
9259 if (argOpers[i]->isReg() && argOpers[i]->isUse())
9260 argOpers[i]->setIsKill(false);
9263 // x86 address has 5 operands: base, index, scale, displacement, and segment.
9264 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9266 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9267 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9268 for (int i=0; i <= lastAddrIndx; ++i)
9269 (*MIB).addOperand(*argOpers[i]);
9270 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9271 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9272 // add 4 to displacement.
9273 for (int i=0; i <= lastAddrIndx-2; ++i)
9274 (*MIB).addOperand(*argOpers[i]);
9275 MachineOperand newOp3 = *(argOpers[3]);
9277 newOp3.setImm(newOp3.getImm()+4);
9279 newOp3.setOffset(newOp3.getOffset()+4);
9280 (*MIB).addOperand(newOp3);
9281 (*MIB).addOperand(*argOpers[lastAddrIndx]);
9283 // t3/4 are defined later, at the bottom of the loop
9284 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9285 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9286 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9287 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9288 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9289 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9291 // The subsequent operations should be using the destination registers of
9292 //the PHI instructions.
9294 t1 = F->getRegInfo().createVirtualRegister(RC);
9295 t2 = F->getRegInfo().createVirtualRegister(RC);
9296 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9297 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9299 t1 = dest1Oper.getReg();
9300 t2 = dest2Oper.getReg();
9303 int valArgIndx = lastAddrIndx + 1;
9304 assert((argOpers[valArgIndx]->isReg() ||
9305 argOpers[valArgIndx]->isImm()) &&
9307 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9308 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9309 if (argOpers[valArgIndx]->isReg())
9310 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9312 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9313 if (regOpcL != X86::MOV32rr)
9315 (*MIB).addOperand(*argOpers[valArgIndx]);
9316 assert(argOpers[valArgIndx + 1]->isReg() ==
9317 argOpers[valArgIndx]->isReg());
9318 assert(argOpers[valArgIndx + 1]->isImm() ==
9319 argOpers[valArgIndx]->isImm());
9320 if (argOpers[valArgIndx + 1]->isReg())
9321 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9323 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9324 if (regOpcH != X86::MOV32rr)
9326 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9328 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9330 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9333 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9335 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9338 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9339 for (int i=0; i <= lastAddrIndx; ++i)
9340 (*MIB).addOperand(*argOpers[i]);
9342 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9343 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9344 bInstr->memoperands_end());
9346 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9347 MIB.addReg(X86::EAX);
9348 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9349 MIB.addReg(X86::EDX);
9352 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9354 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9358 // private utility function
9360 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9361 MachineBasicBlock *MBB,
9362 unsigned cmovOpc) const {
9363 // For the atomic min/max operator, we generate
9366 // ld t1 = [min/max.addr]
9367 // mov t2 = [min/max.val]
9369 // cmov[cond] t2 = t1
9371 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9373 // fallthrough -->nextMBB
9375 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9376 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9377 MachineFunction::iterator MBBIter = MBB;
9380 /// First build the CFG
9381 MachineFunction *F = MBB->getParent();
9382 MachineBasicBlock *thisMBB = MBB;
9383 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9384 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9385 F->insert(MBBIter, newMBB);
9386 F->insert(MBBIter, nextMBB);
9388 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9389 nextMBB->splice(nextMBB->begin(), thisMBB,
9390 llvm::next(MachineBasicBlock::iterator(mInstr)),
9392 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9394 // Update thisMBB to fall through to newMBB
9395 thisMBB->addSuccessor(newMBB);
9397 // newMBB jumps to newMBB and fall through to nextMBB
9398 newMBB->addSuccessor(nextMBB);
9399 newMBB->addSuccessor(newMBB);
9401 DebugLoc dl = mInstr->getDebugLoc();
9402 // Insert instructions into newMBB based on incoming instruction
9403 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9404 "unexpected number of operands");
9405 MachineOperand& destOper = mInstr->getOperand(0);
9406 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9407 int numArgs = mInstr->getNumOperands() - 1;
9408 for (int i=0; i < numArgs; ++i)
9409 argOpers[i] = &mInstr->getOperand(i+1);
9411 // x86 address has 4 operands: base, index, scale, and displacement
9412 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9413 int valArgIndx = lastAddrIndx + 1;
9415 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9416 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9417 for (int i=0; i <= lastAddrIndx; ++i)
9418 (*MIB).addOperand(*argOpers[i]);
9420 // We only support register and immediate values
9421 assert((argOpers[valArgIndx]->isReg() ||
9422 argOpers[valArgIndx]->isImm()) &&
9425 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9426 if (argOpers[valArgIndx]->isReg())
9427 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9429 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9430 (*MIB).addOperand(*argOpers[valArgIndx]);
9432 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9435 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
9440 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9441 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
9445 // Cmp and exchange if none has modified the memory location
9446 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
9447 for (int i=0; i <= lastAddrIndx; ++i)
9448 (*MIB).addOperand(*argOpers[i]);
9450 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9451 (*MIB).setMemRefs(mInstr->memoperands_begin(),
9452 mInstr->memoperands_end());
9454 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9455 MIB.addReg(X86::EAX);
9458 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9460 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
9464 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
9465 // or XMM0_V32I8 in AVX all of this code can be replaced with that
9468 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
9469 unsigned numArgs, bool memArg) const {
9470 assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
9471 "Target must have SSE4.2 or AVX features enabled");
9473 DebugLoc dl = MI->getDebugLoc();
9474 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9476 if (!Subtarget->hasAVX()) {
9478 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
9480 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
9483 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
9485 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
9488 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
9489 for (unsigned i = 0; i < numArgs; ++i) {
9490 MachineOperand &Op = MI->getOperand(i+1);
9491 if (!(Op.isReg() && Op.isImplicit()))
9494 BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
9497 MI->eraseFromParent();
9502 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
9503 DebugLoc dl = MI->getDebugLoc();
9504 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9506 // Address into RAX/EAX, other two args into ECX, EDX.
9507 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
9508 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
9509 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
9510 for (int i = 0; i < X86::AddrNumOperands; ++i)
9511 MIB.addOperand(MI->getOperand(i));
9513 unsigned ValOps = X86::AddrNumOperands;
9514 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9515 .addReg(MI->getOperand(ValOps).getReg());
9516 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
9517 .addReg(MI->getOperand(ValOps+1).getReg());
9519 // The instruction doesn't actually take any operands though.
9520 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
9522 MI->eraseFromParent(); // The pseudo is gone now.
9527 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
9528 DebugLoc dl = MI->getDebugLoc();
9529 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9531 // First arg in ECX, the second in EAX.
9532 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9533 .addReg(MI->getOperand(0).getReg());
9534 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
9535 .addReg(MI->getOperand(1).getReg());
9537 // The instruction doesn't actually take any operands though.
9538 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
9540 MI->eraseFromParent(); // The pseudo is gone now.
9545 X86TargetLowering::EmitVAARG64WithCustomInserter(
9547 MachineBasicBlock *MBB) const {
9548 // Emit va_arg instruction on X86-64.
9550 // Operands to this pseudo-instruction:
9551 // 0 ) Output : destination address (reg)
9552 // 1-5) Input : va_list address (addr, i64mem)
9553 // 6 ) ArgSize : Size (in bytes) of vararg type
9554 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
9555 // 8 ) Align : Alignment of type
9556 // 9 ) EFLAGS (implicit-def)
9558 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
9559 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
9561 unsigned DestReg = MI->getOperand(0).getReg();
9562 MachineOperand &Base = MI->getOperand(1);
9563 MachineOperand &Scale = MI->getOperand(2);
9564 MachineOperand &Index = MI->getOperand(3);
9565 MachineOperand &Disp = MI->getOperand(4);
9566 MachineOperand &Segment = MI->getOperand(5);
9567 unsigned ArgSize = MI->getOperand(6).getImm();
9568 unsigned ArgMode = MI->getOperand(7).getImm();
9569 unsigned Align = MI->getOperand(8).getImm();
9572 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
9573 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
9574 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
9576 // Machine Information
9577 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9578 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
9579 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
9580 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
9581 DebugLoc DL = MI->getDebugLoc();
9586 // i64 overflow_area (address)
9587 // i64 reg_save_area (address)
9589 // sizeof(va_list) = 24
9590 // alignment(va_list) = 8
9592 unsigned TotalNumIntRegs = 6;
9593 unsigned TotalNumXMMRegs = 8;
9594 bool UseGPOffset = (ArgMode == 1);
9595 bool UseFPOffset = (ArgMode == 2);
9596 unsigned MaxOffset = TotalNumIntRegs * 8 +
9597 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
9599 /* Align ArgSize to a multiple of 8 */
9600 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
9601 bool NeedsAlign = (Align > 8);
9603 MachineBasicBlock *thisMBB = MBB;
9604 MachineBasicBlock *overflowMBB;
9605 MachineBasicBlock *offsetMBB;
9606 MachineBasicBlock *endMBB;
9608 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
9609 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
9610 unsigned OffsetReg = 0;
9612 if (!UseGPOffset && !UseFPOffset) {
9613 // If we only pull from the overflow region, we don't create a branch.
9614 // We don't need to alter control flow.
9615 OffsetDestReg = 0; // unused
9616 OverflowDestReg = DestReg;
9619 overflowMBB = thisMBB;
9622 // First emit code to check if gp_offset (or fp_offset) is below the bound.
9623 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
9624 // If not, pull from overflow_area. (branch to overflowMBB)
9629 // offsetMBB overflowMBB
9634 // Registers for the PHI in endMBB
9635 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
9636 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
9638 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9639 MachineFunction *MF = MBB->getParent();
9640 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9641 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9642 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9644 MachineFunction::iterator MBBIter = MBB;
9647 // Insert the new basic blocks
9648 MF->insert(MBBIter, offsetMBB);
9649 MF->insert(MBBIter, overflowMBB);
9650 MF->insert(MBBIter, endMBB);
9652 // Transfer the remainder of MBB and its successor edges to endMBB.
9653 endMBB->splice(endMBB->begin(), thisMBB,
9654 llvm::next(MachineBasicBlock::iterator(MI)),
9656 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9658 // Make offsetMBB and overflowMBB successors of thisMBB
9659 thisMBB->addSuccessor(offsetMBB);
9660 thisMBB->addSuccessor(overflowMBB);
9662 // endMBB is a successor of both offsetMBB and overflowMBB
9663 offsetMBB->addSuccessor(endMBB);
9664 overflowMBB->addSuccessor(endMBB);
9666 // Load the offset value into a register
9667 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
9668 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
9672 .addDisp(Disp, UseFPOffset ? 4 : 0)
9673 .addOperand(Segment)
9674 .setMemRefs(MMOBegin, MMOEnd);
9676 // Check if there is enough room left to pull this argument.
9677 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
9679 .addImm(MaxOffset + 8 - ArgSizeA8);
9681 // Branch to "overflowMBB" if offset >= max
9682 // Fall through to "offsetMBB" otherwise
9683 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
9684 .addMBB(overflowMBB);
9687 // In offsetMBB, emit code to use the reg_save_area.
9689 assert(OffsetReg != 0);
9691 // Read the reg_save_area address.
9692 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
9693 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
9698 .addOperand(Segment)
9699 .setMemRefs(MMOBegin, MMOEnd);
9701 // Zero-extend the offset
9702 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
9703 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
9706 .addImm(X86::sub_32bit);
9708 // Add the offset to the reg_save_area to get the final address.
9709 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
9710 .addReg(OffsetReg64)
9711 .addReg(RegSaveReg);
9713 // Compute the offset for the next argument
9714 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
9715 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
9717 .addImm(UseFPOffset ? 16 : 8);
9719 // Store it back into the va_list.
9720 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
9724 .addDisp(Disp, UseFPOffset ? 4 : 0)
9725 .addOperand(Segment)
9726 .addReg(NextOffsetReg)
9727 .setMemRefs(MMOBegin, MMOEnd);
9730 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
9735 // Emit code to use overflow area
9738 // Load the overflow_area address into a register.
9739 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
9740 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
9745 .addOperand(Segment)
9746 .setMemRefs(MMOBegin, MMOEnd);
9748 // If we need to align it, do so. Otherwise, just copy the address
9749 // to OverflowDestReg.
9751 // Align the overflow address
9752 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
9753 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
9755 // aligned_addr = (addr + (align-1)) & ~(align-1)
9756 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
9757 .addReg(OverflowAddrReg)
9760 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
9762 .addImm(~(uint64_t)(Align-1));
9764 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
9765 .addReg(OverflowAddrReg);
9768 // Compute the next overflow address after this argument.
9769 // (the overflow address should be kept 8-byte aligned)
9770 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
9771 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
9772 .addReg(OverflowDestReg)
9775 // Store the new overflow address.
9776 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
9781 .addOperand(Segment)
9782 .addReg(NextAddrReg)
9783 .setMemRefs(MMOBegin, MMOEnd);
9785 // If we branched, emit the PHI to the front of endMBB.
9787 BuildMI(*endMBB, endMBB->begin(), DL,
9788 TII->get(X86::PHI), DestReg)
9789 .addReg(OffsetDestReg).addMBB(offsetMBB)
9790 .addReg(OverflowDestReg).addMBB(overflowMBB);
9793 // Erase the pseudo instruction
9794 MI->eraseFromParent();
9800 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
9802 MachineBasicBlock *MBB) const {
9803 // Emit code to save XMM registers to the stack. The ABI says that the
9804 // number of registers to save is given in %al, so it's theoretically
9805 // possible to do an indirect jump trick to avoid saving all of them,
9806 // however this code takes a simpler approach and just executes all
9807 // of the stores if %al is non-zero. It's less code, and it's probably
9808 // easier on the hardware branch predictor, and stores aren't all that
9809 // expensive anyway.
9811 // Create the new basic blocks. One block contains all the XMM stores,
9812 // and one block is the final destination regardless of whether any
9813 // stores were performed.
9814 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9815 MachineFunction *F = MBB->getParent();
9816 MachineFunction::iterator MBBIter = MBB;
9818 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
9819 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
9820 F->insert(MBBIter, XMMSaveMBB);
9821 F->insert(MBBIter, EndMBB);
9823 // Transfer the remainder of MBB and its successor edges to EndMBB.
9824 EndMBB->splice(EndMBB->begin(), MBB,
9825 llvm::next(MachineBasicBlock::iterator(MI)),
9827 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
9829 // The original block will now fall through to the XMM save block.
9830 MBB->addSuccessor(XMMSaveMBB);
9831 // The XMMSaveMBB will fall through to the end block.
9832 XMMSaveMBB->addSuccessor(EndMBB);
9834 // Now add the instructions.
9835 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9836 DebugLoc DL = MI->getDebugLoc();
9838 unsigned CountReg = MI->getOperand(0).getReg();
9839 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
9840 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
9842 if (!Subtarget->isTargetWin64()) {
9843 // If %al is 0, branch around the XMM save block.
9844 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
9845 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
9846 MBB->addSuccessor(EndMBB);
9849 // In the XMM save block, save all the XMM argument registers.
9850 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
9851 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
9852 MachineMemOperand *MMO =
9853 F->getMachineMemOperand(
9854 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
9855 MachineMemOperand::MOStore,
9856 /*Size=*/16, /*Align=*/16);
9857 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
9858 .addFrameIndex(RegSaveFrameIndex)
9859 .addImm(/*Scale=*/1)
9860 .addReg(/*IndexReg=*/0)
9861 .addImm(/*Disp=*/Offset)
9862 .addReg(/*Segment=*/0)
9863 .addReg(MI->getOperand(i).getReg())
9864 .addMemOperand(MMO);
9867 MI->eraseFromParent(); // The pseudo instruction is gone now.
9873 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
9874 MachineBasicBlock *BB) const {
9875 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9876 DebugLoc DL = MI->getDebugLoc();
9878 // To "insert" a SELECT_CC instruction, we actually have to insert the
9879 // diamond control-flow pattern. The incoming instruction knows the
9880 // destination vreg to set, the condition code register to branch on, the
9881 // true/false values to select between, and a branch opcode to use.
9882 const BasicBlock *LLVM_BB = BB->getBasicBlock();
9883 MachineFunction::iterator It = BB;
9889 // cmpTY ccX, r1, r2
9891 // fallthrough --> copy0MBB
9892 MachineBasicBlock *thisMBB = BB;
9893 MachineFunction *F = BB->getParent();
9894 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9895 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9896 F->insert(It, copy0MBB);
9897 F->insert(It, sinkMBB);
9899 // If the EFLAGS register isn't dead in the terminator, then claim that it's
9900 // live into the sink and copy blocks.
9901 const MachineFunction *MF = BB->getParent();
9902 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
9903 BitVector ReservedRegs = TRI->getReservedRegs(*MF);
9905 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
9906 const MachineOperand &MO = MI->getOperand(I);
9907 if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
9908 unsigned Reg = MO.getReg();
9909 if (Reg != X86::EFLAGS) continue;
9910 copy0MBB->addLiveIn(Reg);
9911 sinkMBB->addLiveIn(Reg);
9914 // Transfer the remainder of BB and its successor edges to sinkMBB.
9915 sinkMBB->splice(sinkMBB->begin(), BB,
9916 llvm::next(MachineBasicBlock::iterator(MI)),
9918 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9920 // Add the true and fallthrough blocks as its successors.
9921 BB->addSuccessor(copy0MBB);
9922 BB->addSuccessor(sinkMBB);
9924 // Create the conditional branch instruction.
9926 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
9927 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
9930 // %FalseValue = ...
9931 // # fallthrough to sinkMBB
9932 copy0MBB->addSuccessor(sinkMBB);
9935 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9937 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
9938 TII->get(X86::PHI), MI->getOperand(0).getReg())
9939 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
9940 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
9942 MI->eraseFromParent(); // The pseudo instruction is gone now.
9947 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
9948 MachineBasicBlock *BB) const {
9949 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9950 DebugLoc DL = MI->getDebugLoc();
9952 // The lowering is pretty easy: we're just emitting the call to _alloca. The
9953 // non-trivial part is impdef of ESP.
9954 // FIXME: The code should be tweaked as soon as we'll try to do codegen for
9957 const char *StackProbeSymbol =
9958 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
9960 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
9961 .addExternalSymbol(StackProbeSymbol)
9962 .addReg(X86::EAX, RegState::Implicit)
9963 .addReg(X86::ESP, RegState::Implicit)
9964 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
9965 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
9966 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
9968 MI->eraseFromParent(); // The pseudo instruction is gone now.
9973 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
9974 MachineBasicBlock *BB) const {
9975 // This is pretty easy. We're taking the value that we received from
9976 // our load from the relocation, sticking it in either RDI (x86-64)
9977 // or EAX and doing an indirect call. The return value will then
9978 // be in the normal return register.
9979 const X86InstrInfo *TII
9980 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
9981 DebugLoc DL = MI->getDebugLoc();
9982 MachineFunction *F = BB->getParent();
9984 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
9985 assert(MI->getOperand(3).isGlobal() && "This should be a global");
9987 if (Subtarget->is64Bit()) {
9988 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9989 TII->get(X86::MOV64rm), X86::RDI)
9991 .addImm(0).addReg(0)
9992 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
9993 MI->getOperand(3).getTargetFlags())
9995 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
9996 addDirectMem(MIB, X86::RDI);
9997 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
9998 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9999 TII->get(X86::MOV32rm), X86::EAX)
10001 .addImm(0).addReg(0)
10002 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10003 MI->getOperand(3).getTargetFlags())
10005 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10006 addDirectMem(MIB, X86::EAX);
10008 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10009 TII->get(X86::MOV32rm), X86::EAX)
10010 .addReg(TII->getGlobalBaseReg(F))
10011 .addImm(0).addReg(0)
10012 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10013 MI->getOperand(3).getTargetFlags())
10015 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10016 addDirectMem(MIB, X86::EAX);
10019 MI->eraseFromParent(); // The pseudo instruction is gone now.
10023 MachineBasicBlock *
10024 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10025 MachineBasicBlock *BB) const {
10026 switch (MI->getOpcode()) {
10027 default: assert(false && "Unexpected instr type to insert");
10028 case X86::WIN_ALLOCA:
10029 return EmitLoweredWinAlloca(MI, BB);
10030 case X86::TLSCall_32:
10031 case X86::TLSCall_64:
10032 return EmitLoweredTLSCall(MI, BB);
10033 case X86::CMOV_GR8:
10034 case X86::CMOV_FR32:
10035 case X86::CMOV_FR64:
10036 case X86::CMOV_V4F32:
10037 case X86::CMOV_V2F64:
10038 case X86::CMOV_V2I64:
10039 case X86::CMOV_GR16:
10040 case X86::CMOV_GR32:
10041 case X86::CMOV_RFP32:
10042 case X86::CMOV_RFP64:
10043 case X86::CMOV_RFP80:
10044 return EmitLoweredSelect(MI, BB);
10046 case X86::FP32_TO_INT16_IN_MEM:
10047 case X86::FP32_TO_INT32_IN_MEM:
10048 case X86::FP32_TO_INT64_IN_MEM:
10049 case X86::FP64_TO_INT16_IN_MEM:
10050 case X86::FP64_TO_INT32_IN_MEM:
10051 case X86::FP64_TO_INT64_IN_MEM:
10052 case X86::FP80_TO_INT16_IN_MEM:
10053 case X86::FP80_TO_INT32_IN_MEM:
10054 case X86::FP80_TO_INT64_IN_MEM: {
10055 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10056 DebugLoc DL = MI->getDebugLoc();
10058 // Change the floating point control register to use "round towards zero"
10059 // mode when truncating to an integer value.
10060 MachineFunction *F = BB->getParent();
10061 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10062 addFrameReference(BuildMI(*BB, MI, DL,
10063 TII->get(X86::FNSTCW16m)), CWFrameIdx);
10065 // Load the old value of the high byte of the control word...
10067 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10068 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10071 // Set the high part to be round to zero...
10072 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10075 // Reload the modified control word now...
10076 addFrameReference(BuildMI(*BB, MI, DL,
10077 TII->get(X86::FLDCW16m)), CWFrameIdx);
10079 // Restore the memory image of control word to original value
10080 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10083 // Get the X86 opcode to use.
10085 switch (MI->getOpcode()) {
10086 default: llvm_unreachable("illegal opcode!");
10087 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10088 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10089 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10090 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10091 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10092 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10093 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10094 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10095 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10099 MachineOperand &Op = MI->getOperand(0);
10101 AM.BaseType = X86AddressMode::RegBase;
10102 AM.Base.Reg = Op.getReg();
10104 AM.BaseType = X86AddressMode::FrameIndexBase;
10105 AM.Base.FrameIndex = Op.getIndex();
10107 Op = MI->getOperand(1);
10109 AM.Scale = Op.getImm();
10110 Op = MI->getOperand(2);
10112 AM.IndexReg = Op.getImm();
10113 Op = MI->getOperand(3);
10114 if (Op.isGlobal()) {
10115 AM.GV = Op.getGlobal();
10117 AM.Disp = Op.getImm();
10119 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10120 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10122 // Reload the original control word now.
10123 addFrameReference(BuildMI(*BB, MI, DL,
10124 TII->get(X86::FLDCW16m)), CWFrameIdx);
10126 MI->eraseFromParent(); // The pseudo instruction is gone now.
10129 // String/text processing lowering.
10130 case X86::PCMPISTRM128REG:
10131 case X86::VPCMPISTRM128REG:
10132 return EmitPCMP(MI, BB, 3, false /* in-mem */);
10133 case X86::PCMPISTRM128MEM:
10134 case X86::VPCMPISTRM128MEM:
10135 return EmitPCMP(MI, BB, 3, true /* in-mem */);
10136 case X86::PCMPESTRM128REG:
10137 case X86::VPCMPESTRM128REG:
10138 return EmitPCMP(MI, BB, 5, false /* in mem */);
10139 case X86::PCMPESTRM128MEM:
10140 case X86::VPCMPESTRM128MEM:
10141 return EmitPCMP(MI, BB, 5, true /* in mem */);
10143 // Thread synchronization.
10145 return EmitMonitor(MI, BB);
10147 return EmitMwait(MI, BB);
10149 // Atomic Lowering.
10150 case X86::ATOMAND32:
10151 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10152 X86::AND32ri, X86::MOV32rm,
10154 X86::NOT32r, X86::EAX,
10155 X86::GR32RegisterClass);
10156 case X86::ATOMOR32:
10157 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10158 X86::OR32ri, X86::MOV32rm,
10160 X86::NOT32r, X86::EAX,
10161 X86::GR32RegisterClass);
10162 case X86::ATOMXOR32:
10163 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10164 X86::XOR32ri, X86::MOV32rm,
10166 X86::NOT32r, X86::EAX,
10167 X86::GR32RegisterClass);
10168 case X86::ATOMNAND32:
10169 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10170 X86::AND32ri, X86::MOV32rm,
10172 X86::NOT32r, X86::EAX,
10173 X86::GR32RegisterClass, true);
10174 case X86::ATOMMIN32:
10175 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10176 case X86::ATOMMAX32:
10177 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10178 case X86::ATOMUMIN32:
10179 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10180 case X86::ATOMUMAX32:
10181 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10183 case X86::ATOMAND16:
10184 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10185 X86::AND16ri, X86::MOV16rm,
10187 X86::NOT16r, X86::AX,
10188 X86::GR16RegisterClass);
10189 case X86::ATOMOR16:
10190 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10191 X86::OR16ri, X86::MOV16rm,
10193 X86::NOT16r, X86::AX,
10194 X86::GR16RegisterClass);
10195 case X86::ATOMXOR16:
10196 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10197 X86::XOR16ri, X86::MOV16rm,
10199 X86::NOT16r, X86::AX,
10200 X86::GR16RegisterClass);
10201 case X86::ATOMNAND16:
10202 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10203 X86::AND16ri, X86::MOV16rm,
10205 X86::NOT16r, X86::AX,
10206 X86::GR16RegisterClass, true);
10207 case X86::ATOMMIN16:
10208 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10209 case X86::ATOMMAX16:
10210 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10211 case X86::ATOMUMIN16:
10212 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10213 case X86::ATOMUMAX16:
10214 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10216 case X86::ATOMAND8:
10217 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10218 X86::AND8ri, X86::MOV8rm,
10220 X86::NOT8r, X86::AL,
10221 X86::GR8RegisterClass);
10223 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10224 X86::OR8ri, X86::MOV8rm,
10226 X86::NOT8r, X86::AL,
10227 X86::GR8RegisterClass);
10228 case X86::ATOMXOR8:
10229 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10230 X86::XOR8ri, X86::MOV8rm,
10232 X86::NOT8r, X86::AL,
10233 X86::GR8RegisterClass);
10234 case X86::ATOMNAND8:
10235 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10236 X86::AND8ri, X86::MOV8rm,
10238 X86::NOT8r, X86::AL,
10239 X86::GR8RegisterClass, true);
10240 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10241 // This group is for 64-bit host.
10242 case X86::ATOMAND64:
10243 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10244 X86::AND64ri32, X86::MOV64rm,
10246 X86::NOT64r, X86::RAX,
10247 X86::GR64RegisterClass);
10248 case X86::ATOMOR64:
10249 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10250 X86::OR64ri32, X86::MOV64rm,
10252 X86::NOT64r, X86::RAX,
10253 X86::GR64RegisterClass);
10254 case X86::ATOMXOR64:
10255 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10256 X86::XOR64ri32, X86::MOV64rm,
10258 X86::NOT64r, X86::RAX,
10259 X86::GR64RegisterClass);
10260 case X86::ATOMNAND64:
10261 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10262 X86::AND64ri32, X86::MOV64rm,
10264 X86::NOT64r, X86::RAX,
10265 X86::GR64RegisterClass, true);
10266 case X86::ATOMMIN64:
10267 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10268 case X86::ATOMMAX64:
10269 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10270 case X86::ATOMUMIN64:
10271 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10272 case X86::ATOMUMAX64:
10273 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10275 // This group does 64-bit operations on a 32-bit host.
10276 case X86::ATOMAND6432:
10277 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10278 X86::AND32rr, X86::AND32rr,
10279 X86::AND32ri, X86::AND32ri,
10281 case X86::ATOMOR6432:
10282 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10283 X86::OR32rr, X86::OR32rr,
10284 X86::OR32ri, X86::OR32ri,
10286 case X86::ATOMXOR6432:
10287 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10288 X86::XOR32rr, X86::XOR32rr,
10289 X86::XOR32ri, X86::XOR32ri,
10291 case X86::ATOMNAND6432:
10292 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10293 X86::AND32rr, X86::AND32rr,
10294 X86::AND32ri, X86::AND32ri,
10296 case X86::ATOMADD6432:
10297 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10298 X86::ADD32rr, X86::ADC32rr,
10299 X86::ADD32ri, X86::ADC32ri,
10301 case X86::ATOMSUB6432:
10302 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10303 X86::SUB32rr, X86::SBB32rr,
10304 X86::SUB32ri, X86::SBB32ri,
10306 case X86::ATOMSWAP6432:
10307 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10308 X86::MOV32rr, X86::MOV32rr,
10309 X86::MOV32ri, X86::MOV32ri,
10311 case X86::VASTART_SAVE_XMM_REGS:
10312 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10314 case X86::VAARG_64:
10315 return EmitVAARG64WithCustomInserter(MI, BB);
10319 //===----------------------------------------------------------------------===//
10320 // X86 Optimization Hooks
10321 //===----------------------------------------------------------------------===//
10323 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10327 const SelectionDAG &DAG,
10328 unsigned Depth) const {
10329 unsigned Opc = Op.getOpcode();
10330 assert((Opc >= ISD::BUILTIN_OP_END ||
10331 Opc == ISD::INTRINSIC_WO_CHAIN ||
10332 Opc == ISD::INTRINSIC_W_CHAIN ||
10333 Opc == ISD::INTRINSIC_VOID) &&
10334 "Should use MaskedValueIsZero if you don't know whether Op"
10335 " is a target node!");
10337 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
10349 // These nodes' second result is a boolean.
10350 if (Op.getResNo() == 0)
10353 case X86ISD::SETCC:
10354 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
10355 Mask.getBitWidth() - 1);
10360 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
10361 unsigned Depth) const {
10362 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
10363 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
10364 return Op.getValueType().getScalarType().getSizeInBits();
10370 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
10371 /// node is a GlobalAddress + offset.
10372 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
10373 const GlobalValue* &GA,
10374 int64_t &Offset) const {
10375 if (N->getOpcode() == X86ISD::Wrapper) {
10376 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
10377 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
10378 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
10382 return TargetLowering::isGAPlusOffset(N, GA, Offset);
10385 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
10386 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
10387 /// if the load addresses are consecutive, non-overlapping, and in the right
10389 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
10390 const TargetLowering &TLI) {
10391 DebugLoc dl = N->getDebugLoc();
10392 EVT VT = N->getValueType(0);
10394 if (VT.getSizeInBits() != 128)
10397 SmallVector<SDValue, 16> Elts;
10398 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
10399 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
10401 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
10404 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
10405 /// generation and convert it from being a bunch of shuffles and extracts
10406 /// to a simple store and scalar loads to extract the elements.
10407 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
10408 const TargetLowering &TLI) {
10409 SDValue InputVector = N->getOperand(0);
10411 // Only operate on vectors of 4 elements, where the alternative shuffling
10412 // gets to be more expensive.
10413 if (InputVector.getValueType() != MVT::v4i32)
10416 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
10417 // single use which is a sign-extend or zero-extend, and all elements are
10419 SmallVector<SDNode *, 4> Uses;
10420 unsigned ExtractedElements = 0;
10421 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
10422 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
10423 if (UI.getUse().getResNo() != InputVector.getResNo())
10426 SDNode *Extract = *UI;
10427 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10430 if (Extract->getValueType(0) != MVT::i32)
10432 if (!Extract->hasOneUse())
10434 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
10435 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
10437 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
10440 // Record which element was extracted.
10441 ExtractedElements |=
10442 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
10444 Uses.push_back(Extract);
10447 // If not all the elements were used, this may not be worthwhile.
10448 if (ExtractedElements != 15)
10451 // Ok, we've now decided to do the transformation.
10452 DebugLoc dl = InputVector.getDebugLoc();
10454 // Store the value to a temporary stack slot.
10455 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
10456 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
10457 MachinePointerInfo(), false, false, 0);
10459 // Replace each use (extract) with a load of the appropriate element.
10460 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
10461 UE = Uses.end(); UI != UE; ++UI) {
10462 SDNode *Extract = *UI;
10464 // Compute the element's address.
10465 SDValue Idx = Extract->getOperand(1);
10467 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
10468 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
10469 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
10471 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(),
10472 StackPtr, OffsetVal);
10474 // Load the scalar.
10475 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
10476 ScalarAddr, MachinePointerInfo(),
10479 // Replace the exact with the load.
10480 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
10483 // The replacement was made in place; don't return anything.
10487 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
10488 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
10489 const X86Subtarget *Subtarget) {
10490 DebugLoc DL = N->getDebugLoc();
10491 SDValue Cond = N->getOperand(0);
10492 // Get the LHS/RHS of the select.
10493 SDValue LHS = N->getOperand(1);
10494 SDValue RHS = N->getOperand(2);
10496 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
10497 // instructions match the semantics of the common C idiom x<y?x:y but not
10498 // x<=y?x:y, because of how they handle negative zero (which can be
10499 // ignored in unsafe-math mode).
10500 if (Subtarget->hasSSE2() &&
10501 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
10502 Cond.getOpcode() == ISD::SETCC) {
10503 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
10505 unsigned Opcode = 0;
10506 // Check for x CC y ? x : y.
10507 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
10508 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
10512 // Converting this to a min would handle NaNs incorrectly, and swapping
10513 // the operands would cause it to handle comparisons between positive
10514 // and negative zero incorrectly.
10515 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10516 if (!UnsafeFPMath &&
10517 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10519 std::swap(LHS, RHS);
10521 Opcode = X86ISD::FMIN;
10524 // Converting this to a min would handle comparisons between positive
10525 // and negative zero incorrectly.
10526 if (!UnsafeFPMath &&
10527 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
10529 Opcode = X86ISD::FMIN;
10532 // Converting this to a min would handle both negative zeros and NaNs
10533 // incorrectly, but we can swap the operands to fix both.
10534 std::swap(LHS, RHS);
10538 Opcode = X86ISD::FMIN;
10542 // Converting this to a max would handle comparisons between positive
10543 // and negative zero incorrectly.
10544 if (!UnsafeFPMath &&
10545 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
10547 Opcode = X86ISD::FMAX;
10550 // Converting this to a max would handle NaNs incorrectly, and swapping
10551 // the operands would cause it to handle comparisons between positive
10552 // and negative zero incorrectly.
10553 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10554 if (!UnsafeFPMath &&
10555 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10557 std::swap(LHS, RHS);
10559 Opcode = X86ISD::FMAX;
10562 // Converting this to a max would handle both negative zeros and NaNs
10563 // incorrectly, but we can swap the operands to fix both.
10564 std::swap(LHS, RHS);
10568 Opcode = X86ISD::FMAX;
10571 // Check for x CC y ? y : x -- a min/max with reversed arms.
10572 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
10573 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
10577 // Converting this to a min would handle comparisons between positive
10578 // and negative zero incorrectly, and swapping the operands would
10579 // cause it to handle NaNs incorrectly.
10580 if (!UnsafeFPMath &&
10581 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
10582 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10584 std::swap(LHS, RHS);
10586 Opcode = X86ISD::FMIN;
10589 // Converting this to a min would handle NaNs incorrectly.
10590 if (!UnsafeFPMath &&
10591 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
10593 Opcode = X86ISD::FMIN;
10596 // Converting this to a min would handle both negative zeros and NaNs
10597 // incorrectly, but we can swap the operands to fix both.
10598 std::swap(LHS, RHS);
10602 Opcode = X86ISD::FMIN;
10606 // Converting this to a max would handle NaNs incorrectly.
10607 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10609 Opcode = X86ISD::FMAX;
10612 // Converting this to a max would handle comparisons between positive
10613 // and negative zero incorrectly, and swapping the operands would
10614 // cause it to handle NaNs incorrectly.
10615 if (!UnsafeFPMath &&
10616 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
10617 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10619 std::swap(LHS, RHS);
10621 Opcode = X86ISD::FMAX;
10624 // Converting this to a max would handle both negative zeros and NaNs
10625 // incorrectly, but we can swap the operands to fix both.
10626 std::swap(LHS, RHS);
10630 Opcode = X86ISD::FMAX;
10636 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
10639 // If this is a select between two integer constants, try to do some
10641 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
10642 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
10643 // Don't do this for crazy integer types.
10644 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
10645 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
10646 // so that TrueC (the true value) is larger than FalseC.
10647 bool NeedsCondInvert = false;
10649 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
10650 // Efficiently invertible.
10651 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
10652 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
10653 isa<ConstantSDNode>(Cond.getOperand(1))))) {
10654 NeedsCondInvert = true;
10655 std::swap(TrueC, FalseC);
10658 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
10659 if (FalseC->getAPIntValue() == 0 &&
10660 TrueC->getAPIntValue().isPowerOf2()) {
10661 if (NeedsCondInvert) // Invert the condition if needed.
10662 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10663 DAG.getConstant(1, Cond.getValueType()));
10665 // Zero extend the condition if needed.
10666 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
10668 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10669 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
10670 DAG.getConstant(ShAmt, MVT::i8));
10673 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
10674 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10675 if (NeedsCondInvert) // Invert the condition if needed.
10676 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10677 DAG.getConstant(1, Cond.getValueType()));
10679 // Zero extend the condition if needed.
10680 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10681 FalseC->getValueType(0), Cond);
10682 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10683 SDValue(FalseC, 0));
10686 // Optimize cases that will turn into an LEA instruction. This requires
10687 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10688 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10689 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10690 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10692 bool isFastMultiplier = false;
10694 switch ((unsigned char)Diff) {
10696 case 1: // result = add base, cond
10697 case 2: // result = lea base( , cond*2)
10698 case 3: // result = lea base(cond, cond*2)
10699 case 4: // result = lea base( , cond*4)
10700 case 5: // result = lea base(cond, cond*4)
10701 case 8: // result = lea base( , cond*8)
10702 case 9: // result = lea base(cond, cond*8)
10703 isFastMultiplier = true;
10708 if (isFastMultiplier) {
10709 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10710 if (NeedsCondInvert) // Invert the condition if needed.
10711 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10712 DAG.getConstant(1, Cond.getValueType()));
10714 // Zero extend the condition if needed.
10715 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10717 // Scale the condition by the difference.
10719 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10720 DAG.getConstant(Diff, Cond.getValueType()));
10722 // Add the base if non-zero.
10723 if (FalseC->getAPIntValue() != 0)
10724 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10725 SDValue(FalseC, 0));
10735 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
10736 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
10737 TargetLowering::DAGCombinerInfo &DCI) {
10738 DebugLoc DL = N->getDebugLoc();
10740 // If the flag operand isn't dead, don't touch this CMOV.
10741 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
10744 // If this is a select between two integer constants, try to do some
10745 // optimizations. Note that the operands are ordered the opposite of SELECT
10747 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
10748 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10749 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
10750 // larger than FalseC (the false value).
10751 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
10753 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
10754 CC = X86::GetOppositeBranchCondition(CC);
10755 std::swap(TrueC, FalseC);
10758 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
10759 // This is efficient for any integer data type (including i8/i16) and
10761 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
10762 SDValue Cond = N->getOperand(3);
10763 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10764 DAG.getConstant(CC, MVT::i8), Cond);
10766 // Zero extend the condition if needed.
10767 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
10769 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10770 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
10771 DAG.getConstant(ShAmt, MVT::i8));
10772 if (N->getNumValues() == 2) // Dead flag value?
10773 return DCI.CombineTo(N, Cond, SDValue());
10777 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
10778 // for any integer data type, including i8/i16.
10779 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10780 SDValue Cond = N->getOperand(3);
10781 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10782 DAG.getConstant(CC, MVT::i8), Cond);
10784 // Zero extend the condition if needed.
10785 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10786 FalseC->getValueType(0), Cond);
10787 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10788 SDValue(FalseC, 0));
10790 if (N->getNumValues() == 2) // Dead flag value?
10791 return DCI.CombineTo(N, Cond, SDValue());
10795 // Optimize cases that will turn into an LEA instruction. This requires
10796 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10797 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10798 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10799 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10801 bool isFastMultiplier = false;
10803 switch ((unsigned char)Diff) {
10805 case 1: // result = add base, cond
10806 case 2: // result = lea base( , cond*2)
10807 case 3: // result = lea base(cond, cond*2)
10808 case 4: // result = lea base( , cond*4)
10809 case 5: // result = lea base(cond, cond*4)
10810 case 8: // result = lea base( , cond*8)
10811 case 9: // result = lea base(cond, cond*8)
10812 isFastMultiplier = true;
10817 if (isFastMultiplier) {
10818 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10819 SDValue Cond = N->getOperand(3);
10820 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10821 DAG.getConstant(CC, MVT::i8), Cond);
10822 // Zero extend the condition if needed.
10823 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10825 // Scale the condition by the difference.
10827 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10828 DAG.getConstant(Diff, Cond.getValueType()));
10830 // Add the base if non-zero.
10831 if (FalseC->getAPIntValue() != 0)
10832 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10833 SDValue(FalseC, 0));
10834 if (N->getNumValues() == 2) // Dead flag value?
10835 return DCI.CombineTo(N, Cond, SDValue());
10845 /// PerformMulCombine - Optimize a single multiply with constant into two
10846 /// in order to implement it with two cheaper instructions, e.g.
10847 /// LEA + SHL, LEA + LEA.
10848 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
10849 TargetLowering::DAGCombinerInfo &DCI) {
10850 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10853 EVT VT = N->getValueType(0);
10854 if (VT != MVT::i64)
10857 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10860 uint64_t MulAmt = C->getZExtValue();
10861 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
10864 uint64_t MulAmt1 = 0;
10865 uint64_t MulAmt2 = 0;
10866 if ((MulAmt % 9) == 0) {
10868 MulAmt2 = MulAmt / 9;
10869 } else if ((MulAmt % 5) == 0) {
10871 MulAmt2 = MulAmt / 5;
10872 } else if ((MulAmt % 3) == 0) {
10874 MulAmt2 = MulAmt / 3;
10877 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
10878 DebugLoc DL = N->getDebugLoc();
10880 if (isPowerOf2_64(MulAmt2) &&
10881 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
10882 // If second multiplifer is pow2, issue it first. We want the multiply by
10883 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
10885 std::swap(MulAmt1, MulAmt2);
10888 if (isPowerOf2_64(MulAmt1))
10889 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
10890 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
10892 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
10893 DAG.getConstant(MulAmt1, VT));
10895 if (isPowerOf2_64(MulAmt2))
10896 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
10897 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
10899 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
10900 DAG.getConstant(MulAmt2, VT));
10902 // Do not add new nodes to DAG combiner worklist.
10903 DCI.CombineTo(N, NewMul, false);
10908 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
10909 SDValue N0 = N->getOperand(0);
10910 SDValue N1 = N->getOperand(1);
10911 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
10912 EVT VT = N0.getValueType();
10914 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
10915 // since the result of setcc_c is all zero's or all ones.
10916 if (N1C && N0.getOpcode() == ISD::AND &&
10917 N0.getOperand(1).getOpcode() == ISD::Constant) {
10918 SDValue N00 = N0.getOperand(0);
10919 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
10920 ((N00.getOpcode() == ISD::ANY_EXTEND ||
10921 N00.getOpcode() == ISD::ZERO_EXTEND) &&
10922 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
10923 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
10924 APInt ShAmt = N1C->getAPIntValue();
10925 Mask = Mask.shl(ShAmt);
10927 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
10928 N00, DAG.getConstant(Mask, VT));
10935 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
10937 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
10938 const X86Subtarget *Subtarget) {
10939 EVT VT = N->getValueType(0);
10940 if (!VT.isVector() && VT.isInteger() &&
10941 N->getOpcode() == ISD::SHL)
10942 return PerformSHLCombine(N, DAG);
10944 // On X86 with SSE2 support, we can transform this to a vector shift if
10945 // all elements are shifted by the same amount. We can't do this in legalize
10946 // because the a constant vector is typically transformed to a constant pool
10947 // so we have no knowledge of the shift amount.
10948 if (!Subtarget->hasSSE2())
10951 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
10954 SDValue ShAmtOp = N->getOperand(1);
10955 EVT EltVT = VT.getVectorElementType();
10956 DebugLoc DL = N->getDebugLoc();
10957 SDValue BaseShAmt = SDValue();
10958 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
10959 unsigned NumElts = VT.getVectorNumElements();
10961 for (; i != NumElts; ++i) {
10962 SDValue Arg = ShAmtOp.getOperand(i);
10963 if (Arg.getOpcode() == ISD::UNDEF) continue;
10967 for (; i != NumElts; ++i) {
10968 SDValue Arg = ShAmtOp.getOperand(i);
10969 if (Arg.getOpcode() == ISD::UNDEF) continue;
10970 if (Arg != BaseShAmt) {
10974 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
10975 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
10976 SDValue InVec = ShAmtOp.getOperand(0);
10977 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
10978 unsigned NumElts = InVec.getValueType().getVectorNumElements();
10980 for (; i != NumElts; ++i) {
10981 SDValue Arg = InVec.getOperand(i);
10982 if (Arg.getOpcode() == ISD::UNDEF) continue;
10986 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
10987 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
10988 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
10989 if (C->getZExtValue() == SplatIdx)
10990 BaseShAmt = InVec.getOperand(1);
10993 if (BaseShAmt.getNode() == 0)
10994 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
10995 DAG.getIntPtrConstant(0));
10999 // The shift amount is an i32.
11000 if (EltVT.bitsGT(MVT::i32))
11001 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11002 else if (EltVT.bitsLT(MVT::i32))
11003 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11005 // The shift amount is identical so we can do a vector shift.
11006 SDValue ValOp = N->getOperand(0);
11007 switch (N->getOpcode()) {
11009 llvm_unreachable("Unknown shift opcode!");
11012 if (VT == MVT::v2i64)
11013 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11014 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11016 if (VT == MVT::v4i32)
11017 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11018 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11020 if (VT == MVT::v8i16)
11021 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11022 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11026 if (VT == MVT::v4i32)
11027 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11028 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11030 if (VT == MVT::v8i16)
11031 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11032 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11036 if (VT == MVT::v2i64)
11037 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11038 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11040 if (VT == MVT::v4i32)
11041 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11042 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11044 if (VT == MVT::v8i16)
11045 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11046 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11053 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11054 TargetLowering::DAGCombinerInfo &DCI,
11055 const X86Subtarget *Subtarget) {
11056 if (DCI.isBeforeLegalizeOps())
11059 EVT VT = N->getValueType(0);
11060 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
11063 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11064 SDValue N0 = N->getOperand(0);
11065 SDValue N1 = N->getOperand(1);
11066 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11068 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11070 if (!N0.hasOneUse() || !N1.hasOneUse())
11073 SDValue ShAmt0 = N0.getOperand(1);
11074 if (ShAmt0.getValueType() != MVT::i8)
11076 SDValue ShAmt1 = N1.getOperand(1);
11077 if (ShAmt1.getValueType() != MVT::i8)
11079 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
11080 ShAmt0 = ShAmt0.getOperand(0);
11081 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
11082 ShAmt1 = ShAmt1.getOperand(0);
11084 DebugLoc DL = N->getDebugLoc();
11085 unsigned Opc = X86ISD::SHLD;
11086 SDValue Op0 = N0.getOperand(0);
11087 SDValue Op1 = N1.getOperand(0);
11088 if (ShAmt0.getOpcode() == ISD::SUB) {
11089 Opc = X86ISD::SHRD;
11090 std::swap(Op0, Op1);
11091 std::swap(ShAmt0, ShAmt1);
11094 unsigned Bits = VT.getSizeInBits();
11095 if (ShAmt1.getOpcode() == ISD::SUB) {
11096 SDValue Sum = ShAmt1.getOperand(0);
11097 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11098 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11099 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11100 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11101 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11102 return DAG.getNode(Opc, DL, VT,
11104 DAG.getNode(ISD::TRUNCATE, DL,
11107 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11108 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11110 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11111 return DAG.getNode(Opc, DL, VT,
11112 N0.getOperand(0), N1.getOperand(0),
11113 DAG.getNode(ISD::TRUNCATE, DL,
11120 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
11121 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
11122 const X86Subtarget *Subtarget) {
11123 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
11124 // the FP state in cases where an emms may be missing.
11125 // A preferable solution to the general problem is to figure out the right
11126 // places to insert EMMS. This qualifies as a quick hack.
11128 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
11129 StoreSDNode *St = cast<StoreSDNode>(N);
11130 EVT VT = St->getValue().getValueType();
11131 if (VT.getSizeInBits() != 64)
11134 const Function *F = DAG.getMachineFunction().getFunction();
11135 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
11136 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
11137 && Subtarget->hasSSE2();
11138 if ((VT.isVector() ||
11139 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
11140 isa<LoadSDNode>(St->getValue()) &&
11141 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
11142 St->getChain().hasOneUse() && !St->isVolatile()) {
11143 SDNode* LdVal = St->getValue().getNode();
11144 LoadSDNode *Ld = 0;
11145 int TokenFactorIndex = -1;
11146 SmallVector<SDValue, 8> Ops;
11147 SDNode* ChainVal = St->getChain().getNode();
11148 // Must be a store of a load. We currently handle two cases: the load
11149 // is a direct child, and it's under an intervening TokenFactor. It is
11150 // possible to dig deeper under nested TokenFactors.
11151 if (ChainVal == LdVal)
11152 Ld = cast<LoadSDNode>(St->getChain());
11153 else if (St->getValue().hasOneUse() &&
11154 ChainVal->getOpcode() == ISD::TokenFactor) {
11155 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
11156 if (ChainVal->getOperand(i).getNode() == LdVal) {
11157 TokenFactorIndex = i;
11158 Ld = cast<LoadSDNode>(St->getValue());
11160 Ops.push_back(ChainVal->getOperand(i));
11164 if (!Ld || !ISD::isNormalLoad(Ld))
11167 // If this is not the MMX case, i.e. we are just turning i64 load/store
11168 // into f64 load/store, avoid the transformation if there are multiple
11169 // uses of the loaded value.
11170 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
11173 DebugLoc LdDL = Ld->getDebugLoc();
11174 DebugLoc StDL = N->getDebugLoc();
11175 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
11176 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
11178 if (Subtarget->is64Bit() || F64IsLegal) {
11179 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
11180 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
11181 Ld->getPointerInfo(), Ld->isVolatile(),
11182 Ld->isNonTemporal(), Ld->getAlignment());
11183 SDValue NewChain = NewLd.getValue(1);
11184 if (TokenFactorIndex != -1) {
11185 Ops.push_back(NewChain);
11186 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11189 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
11190 St->getPointerInfo(),
11191 St->isVolatile(), St->isNonTemporal(),
11192 St->getAlignment());
11195 // Otherwise, lower to two pairs of 32-bit loads / stores.
11196 SDValue LoAddr = Ld->getBasePtr();
11197 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
11198 DAG.getConstant(4, MVT::i32));
11200 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
11201 Ld->getPointerInfo(),
11202 Ld->isVolatile(), Ld->isNonTemporal(),
11203 Ld->getAlignment());
11204 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
11205 Ld->getPointerInfo().getWithOffset(4),
11206 Ld->isVolatile(), Ld->isNonTemporal(),
11207 MinAlign(Ld->getAlignment(), 4));
11209 SDValue NewChain = LoLd.getValue(1);
11210 if (TokenFactorIndex != -1) {
11211 Ops.push_back(LoLd);
11212 Ops.push_back(HiLd);
11213 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11217 LoAddr = St->getBasePtr();
11218 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
11219 DAG.getConstant(4, MVT::i32));
11221 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
11222 St->getPointerInfo(),
11223 St->isVolatile(), St->isNonTemporal(),
11224 St->getAlignment());
11225 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
11226 St->getPointerInfo().getWithOffset(4),
11228 St->isNonTemporal(),
11229 MinAlign(St->getAlignment(), 4));
11230 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
11235 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
11236 /// X86ISD::FXOR nodes.
11237 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
11238 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
11239 // F[X]OR(0.0, x) -> x
11240 // F[X]OR(x, 0.0) -> x
11241 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11242 if (C->getValueAPF().isPosZero())
11243 return N->getOperand(1);
11244 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11245 if (C->getValueAPF().isPosZero())
11246 return N->getOperand(0);
11250 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
11251 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
11252 // FAND(0.0, x) -> 0.0
11253 // FAND(x, 0.0) -> 0.0
11254 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11255 if (C->getValueAPF().isPosZero())
11256 return N->getOperand(0);
11257 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11258 if (C->getValueAPF().isPosZero())
11259 return N->getOperand(1);
11263 static SDValue PerformBTCombine(SDNode *N,
11265 TargetLowering::DAGCombinerInfo &DCI) {
11266 // BT ignores high bits in the bit index operand.
11267 SDValue Op1 = N->getOperand(1);
11268 if (Op1.hasOneUse()) {
11269 unsigned BitWidth = Op1.getValueSizeInBits();
11270 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
11271 APInt KnownZero, KnownOne;
11272 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
11273 !DCI.isBeforeLegalizeOps());
11274 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11275 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
11276 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
11277 DCI.CommitTargetLoweringOpt(TLO);
11282 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
11283 SDValue Op = N->getOperand(0);
11284 if (Op.getOpcode() == ISD::BITCAST)
11285 Op = Op.getOperand(0);
11286 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
11287 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
11288 VT.getVectorElementType().getSizeInBits() ==
11289 OpVT.getVectorElementType().getSizeInBits()) {
11290 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
11295 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
11296 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
11297 // (and (i32 x86isd::setcc_carry), 1)
11298 // This eliminates the zext. This transformation is necessary because
11299 // ISD::SETCC is always legalized to i8.
11300 DebugLoc dl = N->getDebugLoc();
11301 SDValue N0 = N->getOperand(0);
11302 EVT VT = N->getValueType(0);
11303 if (N0.getOpcode() == ISD::AND &&
11305 N0.getOperand(0).hasOneUse()) {
11306 SDValue N00 = N0.getOperand(0);
11307 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
11309 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
11310 if (!C || C->getZExtValue() != 1)
11312 return DAG.getNode(ISD::AND, dl, VT,
11313 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
11314 N00.getOperand(0), N00.getOperand(1)),
11315 DAG.getConstant(1, VT));
11321 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
11322 DAGCombinerInfo &DCI) const {
11323 SelectionDAG &DAG = DCI.DAG;
11324 switch (N->getOpcode()) {
11326 case ISD::EXTRACT_VECTOR_ELT:
11327 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
11328 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
11329 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
11330 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
11333 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
11334 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
11335 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
11337 case X86ISD::FOR: return PerformFORCombine(N, DAG);
11338 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
11339 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
11340 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
11341 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
11342 case X86ISD::SHUFPS: // Handle all target specific shuffles
11343 case X86ISD::SHUFPD:
11344 case X86ISD::PALIGN:
11345 case X86ISD::PUNPCKHBW:
11346 case X86ISD::PUNPCKHWD:
11347 case X86ISD::PUNPCKHDQ:
11348 case X86ISD::PUNPCKHQDQ:
11349 case X86ISD::UNPCKHPS:
11350 case X86ISD::UNPCKHPD:
11351 case X86ISD::PUNPCKLBW:
11352 case X86ISD::PUNPCKLWD:
11353 case X86ISD::PUNPCKLDQ:
11354 case X86ISD::PUNPCKLQDQ:
11355 case X86ISD::UNPCKLPS:
11356 case X86ISD::UNPCKLPD:
11357 case X86ISD::MOVHLPS:
11358 case X86ISD::MOVLHPS:
11359 case X86ISD::PSHUFD:
11360 case X86ISD::PSHUFHW:
11361 case X86ISD::PSHUFLW:
11362 case X86ISD::MOVSS:
11363 case X86ISD::MOVSD:
11364 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
11370 /// isTypeDesirableForOp - Return true if the target has native support for
11371 /// the specified value type and it is 'desirable' to use the type for the
11372 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
11373 /// instruction encodings are longer and some i16 instructions are slow.
11374 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
11375 if (!isTypeLegal(VT))
11377 if (VT != MVT::i16)
11384 case ISD::SIGN_EXTEND:
11385 case ISD::ZERO_EXTEND:
11386 case ISD::ANY_EXTEND:
11399 /// IsDesirableToPromoteOp - This method query the target whether it is
11400 /// beneficial for dag combiner to promote the specified node. If true, it
11401 /// should return the desired promotion type by reference.
11402 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
11403 EVT VT = Op.getValueType();
11404 if (VT != MVT::i16)
11407 bool Promote = false;
11408 bool Commute = false;
11409 switch (Op.getOpcode()) {
11412 LoadSDNode *LD = cast<LoadSDNode>(Op);
11413 // If the non-extending load has a single use and it's not live out, then it
11414 // might be folded.
11415 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
11416 Op.hasOneUse()*/) {
11417 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11418 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
11419 // The only case where we'd want to promote LOAD (rather then it being
11420 // promoted as an operand is when it's only use is liveout.
11421 if (UI->getOpcode() != ISD::CopyToReg)
11428 case ISD::SIGN_EXTEND:
11429 case ISD::ZERO_EXTEND:
11430 case ISD::ANY_EXTEND:
11435 SDValue N0 = Op.getOperand(0);
11436 // Look out for (store (shl (load), x)).
11437 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
11450 SDValue N0 = Op.getOperand(0);
11451 SDValue N1 = Op.getOperand(1);
11452 if (!Commute && MayFoldLoad(N1))
11454 // Avoid disabling potential load folding opportunities.
11455 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
11457 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
11467 //===----------------------------------------------------------------------===//
11468 // X86 Inline Assembly Support
11469 //===----------------------------------------------------------------------===//
11471 static bool LowerToBSwap(CallInst *CI) {
11472 // FIXME: this should verify that we are targetting a 486 or better. If not,
11473 // we will turn this bswap into something that will be lowered to logical ops
11474 // instead of emitting the bswap asm. For now, we don't support 486 or lower
11475 // so don't worry about this.
11477 // Verify this is a simple bswap.
11478 if (CI->getNumArgOperands() != 1 ||
11479 CI->getType() != CI->getArgOperand(0)->getType() ||
11480 !CI->getType()->isIntegerTy())
11483 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11484 if (!Ty || Ty->getBitWidth() % 16 != 0)
11487 // Okay, we can do this xform, do so now.
11488 const Type *Tys[] = { Ty };
11489 Module *M = CI->getParent()->getParent()->getParent();
11490 Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
11492 Value *Op = CI->getArgOperand(0);
11493 Op = CallInst::Create(Int, Op, CI->getName(), CI);
11495 CI->replaceAllUsesWith(Op);
11496 CI->eraseFromParent();
11500 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
11501 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
11502 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
11504 std::string AsmStr = IA->getAsmString();
11506 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
11507 SmallVector<StringRef, 4> AsmPieces;
11508 SplitString(AsmStr, AsmPieces, ";\n");
11510 switch (AsmPieces.size()) {
11511 default: return false;
11513 AsmStr = AsmPieces[0];
11515 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
11518 if (AsmPieces.size() == 2 &&
11519 (AsmPieces[0] == "bswap" ||
11520 AsmPieces[0] == "bswapq" ||
11521 AsmPieces[0] == "bswapl") &&
11522 (AsmPieces[1] == "$0" ||
11523 AsmPieces[1] == "${0:q}")) {
11524 // No need to check constraints, nothing other than the equivalent of
11525 // "=r,0" would be valid here.
11526 return LowerToBSwap(CI);
11528 // rorw $$8, ${0:w} --> llvm.bswap.i16
11529 if (CI->getType()->isIntegerTy(16) &&
11530 AsmPieces.size() == 3 &&
11531 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
11532 AsmPieces[1] == "$$8," &&
11533 AsmPieces[2] == "${0:w}" &&
11534 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
11536 const std::string &Constraints = IA->getConstraintString();
11537 SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
11538 std::sort(AsmPieces.begin(), AsmPieces.end());
11539 if (AsmPieces.size() == 4 &&
11540 AsmPieces[0] == "~{cc}" &&
11541 AsmPieces[1] == "~{dirflag}" &&
11542 AsmPieces[2] == "~{flags}" &&
11543 AsmPieces[3] == "~{fpsr}") {
11544 return LowerToBSwap(CI);
11549 if (CI->getType()->isIntegerTy(32) &&
11550 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
11551 SmallVector<StringRef, 4> Words;
11552 SplitString(AsmPieces[0], Words, " \t,");
11553 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
11554 Words[2] == "${0:w}") {
11556 SplitString(AsmPieces[1], Words, " \t,");
11557 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
11558 Words[2] == "$0") {
11560 SplitString(AsmPieces[2], Words, " \t,");
11561 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
11562 Words[2] == "${0:w}") {
11564 const std::string &Constraints = IA->getConstraintString();
11565 SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
11566 std::sort(AsmPieces.begin(), AsmPieces.end());
11567 if (AsmPieces.size() == 4 &&
11568 AsmPieces[0] == "~{cc}" &&
11569 AsmPieces[1] == "~{dirflag}" &&
11570 AsmPieces[2] == "~{flags}" &&
11571 AsmPieces[3] == "~{fpsr}") {
11572 return LowerToBSwap(CI);
11578 if (CI->getType()->isIntegerTy(64) &&
11579 Constraints.size() >= 2 &&
11580 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
11581 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
11582 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
11583 SmallVector<StringRef, 4> Words;
11584 SplitString(AsmPieces[0], Words, " \t");
11585 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
11587 SplitString(AsmPieces[1], Words, " \t");
11588 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
11590 SplitString(AsmPieces[2], Words, " \t,");
11591 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
11592 Words[2] == "%edx") {
11593 return LowerToBSwap(CI);
11605 /// getConstraintType - Given a constraint letter, return the type of
11606 /// constraint it is for this target.
11607 X86TargetLowering::ConstraintType
11608 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
11609 if (Constraint.size() == 1) {
11610 switch (Constraint[0]) {
11620 return C_RegisterClass;
11644 return TargetLowering::getConstraintType(Constraint);
11647 /// Examine constraint type and operand type and determine a weight value.
11648 /// This object must already have been set up with the operand type
11649 /// and the current alternative constraint selected.
11650 TargetLowering::ConstraintWeight
11651 X86TargetLowering::getSingleConstraintMatchWeight(
11652 AsmOperandInfo &info, const char *constraint) const {
11653 ConstraintWeight weight = CW_Invalid;
11654 Value *CallOperandVal = info.CallOperandVal;
11655 // If we don't have a value, we can't do a match,
11656 // but allow it at the lowest weight.
11657 if (CallOperandVal == NULL)
11659 const Type *type = CallOperandVal->getType();
11660 // Look at the constraint type.
11661 switch (*constraint) {
11663 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11674 if (CallOperandVal->getType()->isIntegerTy())
11675 weight = CW_SpecificReg;
11680 if (type->isFloatingPointTy())
11681 weight = CW_SpecificReg;
11684 if (type->isX86_MMXTy() && !DisableMMX && Subtarget->hasMMX())
11685 weight = CW_SpecificReg;
11689 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1())
11690 weight = CW_Register;
11693 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
11694 if (C->getZExtValue() <= 31)
11695 weight = CW_Constant;
11699 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11700 if (C->getZExtValue() <= 63)
11701 weight = CW_Constant;
11705 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11706 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
11707 weight = CW_Constant;
11711 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11712 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
11713 weight = CW_Constant;
11717 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11718 if (C->getZExtValue() <= 3)
11719 weight = CW_Constant;
11723 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11724 if (C->getZExtValue() <= 0xff)
11725 weight = CW_Constant;
11730 if (dyn_cast<ConstantFP>(CallOperandVal)) {
11731 weight = CW_Constant;
11735 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11736 if ((C->getSExtValue() >= -0x80000000LL) &&
11737 (C->getSExtValue() <= 0x7fffffffLL))
11738 weight = CW_Constant;
11742 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11743 if (C->getZExtValue() <= 0xffffffff)
11744 weight = CW_Constant;
11751 /// LowerXConstraint - try to replace an X constraint, which matches anything,
11752 /// with another that has more specific requirements based on the type of the
11753 /// corresponding operand.
11754 const char *X86TargetLowering::
11755 LowerXConstraint(EVT ConstraintVT) const {
11756 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
11757 // 'f' like normal targets.
11758 if (ConstraintVT.isFloatingPoint()) {
11759 if (Subtarget->hasSSE2())
11761 if (Subtarget->hasSSE1())
11765 return TargetLowering::LowerXConstraint(ConstraintVT);
11768 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11769 /// vector. If it is invalid, don't add anything to Ops.
11770 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11772 std::vector<SDValue>&Ops,
11773 SelectionDAG &DAG) const {
11774 SDValue Result(0, 0);
11776 switch (Constraint) {
11779 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11780 if (C->getZExtValue() <= 31) {
11781 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11787 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11788 if (C->getZExtValue() <= 63) {
11789 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11795 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11796 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
11797 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11803 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11804 if (C->getZExtValue() <= 255) {
11805 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11811 // 32-bit signed value
11812 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11813 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
11814 C->getSExtValue())) {
11815 // Widen to 64 bits here to get it sign extended.
11816 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
11819 // FIXME gcc accepts some relocatable values here too, but only in certain
11820 // memory models; it's complicated.
11825 // 32-bit unsigned value
11826 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11827 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
11828 C->getZExtValue())) {
11829 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11833 // FIXME gcc accepts some relocatable values here too, but only in certain
11834 // memory models; it's complicated.
11838 // Literal immediates are always ok.
11839 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
11840 // Widen to 64 bits here to get it sign extended.
11841 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
11845 // In any sort of PIC mode addresses need to be computed at runtime by
11846 // adding in a register or some sort of table lookup. These can't
11847 // be used as immediates.
11848 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
11851 // If we are in non-pic codegen mode, we allow the address of a global (with
11852 // an optional displacement) to be used with 'i'.
11853 GlobalAddressSDNode *GA = 0;
11854 int64_t Offset = 0;
11856 // Match either (GA), (GA+C), (GA+C1+C2), etc.
11858 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
11859 Offset += GA->getOffset();
11861 } else if (Op.getOpcode() == ISD::ADD) {
11862 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
11863 Offset += C->getZExtValue();
11864 Op = Op.getOperand(0);
11867 } else if (Op.getOpcode() == ISD::SUB) {
11868 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
11869 Offset += -C->getZExtValue();
11870 Op = Op.getOperand(0);
11875 // Otherwise, this isn't something we can handle, reject it.
11879 const GlobalValue *GV = GA->getGlobal();
11880 // If we require an extra load to get this address, as in PIC mode, we
11881 // can't accept it.
11882 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
11883 getTargetMachine())))
11886 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
11887 GA->getValueType(0), Offset);
11892 if (Result.getNode()) {
11893 Ops.push_back(Result);
11896 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11899 std::vector<unsigned> X86TargetLowering::
11900 getRegClassForInlineAsmConstraint(const std::string &Constraint,
11902 if (Constraint.size() == 1) {
11903 // FIXME: not handling fp-stack yet!
11904 switch (Constraint[0]) { // GCC X86 Constraint Letters
11905 default: break; // Unknown constraint letter
11906 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
11907 if (Subtarget->is64Bit()) {
11908 if (VT == MVT::i32)
11909 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
11910 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
11911 X86::R10D,X86::R11D,X86::R12D,
11912 X86::R13D,X86::R14D,X86::R15D,
11913 X86::EBP, X86::ESP, 0);
11914 else if (VT == MVT::i16)
11915 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
11916 X86::SI, X86::DI, X86::R8W,X86::R9W,
11917 X86::R10W,X86::R11W,X86::R12W,
11918 X86::R13W,X86::R14W,X86::R15W,
11919 X86::BP, X86::SP, 0);
11920 else if (VT == MVT::i8)
11921 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
11922 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
11923 X86::R10B,X86::R11B,X86::R12B,
11924 X86::R13B,X86::R14B,X86::R15B,
11925 X86::BPL, X86::SPL, 0);
11927 else if (VT == MVT::i64)
11928 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
11929 X86::RSI, X86::RDI, X86::R8, X86::R9,
11930 X86::R10, X86::R11, X86::R12,
11931 X86::R13, X86::R14, X86::R15,
11932 X86::RBP, X86::RSP, 0);
11936 // 32-bit fallthrough
11937 case 'Q': // Q_REGS
11938 if (VT == MVT::i32)
11939 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
11940 else if (VT == MVT::i16)
11941 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
11942 else if (VT == MVT::i8)
11943 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
11944 else if (VT == MVT::i64)
11945 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
11950 return std::vector<unsigned>();
11953 std::pair<unsigned, const TargetRegisterClass*>
11954 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
11956 // First, see if this is a constraint that directly corresponds to an LLVM
11958 if (Constraint.size() == 1) {
11959 // GCC Constraint Letters
11960 switch (Constraint[0]) {
11962 case 'r': // GENERAL_REGS
11963 case 'l': // INDEX_REGS
11965 return std::make_pair(0U, X86::GR8RegisterClass);
11966 if (VT == MVT::i16)
11967 return std::make_pair(0U, X86::GR16RegisterClass);
11968 if (VT == MVT::i32 || !Subtarget->is64Bit())
11969 return std::make_pair(0U, X86::GR32RegisterClass);
11970 return std::make_pair(0U, X86::GR64RegisterClass);
11971 case 'R': // LEGACY_REGS
11973 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
11974 if (VT == MVT::i16)
11975 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
11976 if (VT == MVT::i32 || !Subtarget->is64Bit())
11977 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
11978 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
11979 case 'f': // FP Stack registers.
11980 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
11981 // value to the correct fpstack register class.
11982 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
11983 return std::make_pair(0U, X86::RFP32RegisterClass);
11984 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
11985 return std::make_pair(0U, X86::RFP64RegisterClass);
11986 return std::make_pair(0U, X86::RFP80RegisterClass);
11987 case 'y': // MMX_REGS if MMX allowed.
11988 if (!Subtarget->hasMMX()) break;
11989 return std::make_pair(0U, X86::VR64RegisterClass);
11990 case 'Y': // SSE_REGS if SSE2 allowed
11991 if (!Subtarget->hasSSE2()) break;
11993 case 'x': // SSE_REGS if SSE1 allowed
11994 if (!Subtarget->hasSSE1()) break;
11996 switch (VT.getSimpleVT().SimpleTy) {
11998 // Scalar SSE types.
12001 return std::make_pair(0U, X86::FR32RegisterClass);
12004 return std::make_pair(0U, X86::FR64RegisterClass);
12012 return std::make_pair(0U, X86::VR128RegisterClass);
12018 // Use the default implementation in TargetLowering to convert the register
12019 // constraint into a member of a register class.
12020 std::pair<unsigned, const TargetRegisterClass*> Res;
12021 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
12023 // Not found as a standard register?
12024 if (Res.second == 0) {
12025 // Map st(0) -> st(7) -> ST0
12026 if (Constraint.size() == 7 && Constraint[0] == '{' &&
12027 tolower(Constraint[1]) == 's' &&
12028 tolower(Constraint[2]) == 't' &&
12029 Constraint[3] == '(' &&
12030 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
12031 Constraint[5] == ')' &&
12032 Constraint[6] == '}') {
12034 Res.first = X86::ST0+Constraint[4]-'0';
12035 Res.second = X86::RFP80RegisterClass;
12039 // GCC allows "st(0)" to be called just plain "st".
12040 if (StringRef("{st}").equals_lower(Constraint)) {
12041 Res.first = X86::ST0;
12042 Res.second = X86::RFP80RegisterClass;
12047 if (StringRef("{flags}").equals_lower(Constraint)) {
12048 Res.first = X86::EFLAGS;
12049 Res.second = X86::CCRRegisterClass;
12053 // 'A' means EAX + EDX.
12054 if (Constraint == "A") {
12055 Res.first = X86::EAX;
12056 Res.second = X86::GR32_ADRegisterClass;
12062 // Otherwise, check to see if this is a register class of the wrong value
12063 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
12064 // turn into {ax},{dx}.
12065 if (Res.second->hasType(VT))
12066 return Res; // Correct type already, nothing to do.
12068 // All of the single-register GCC register classes map their values onto
12069 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
12070 // really want an 8-bit or 32-bit register, map to the appropriate register
12071 // class and return the appropriate register.
12072 if (Res.second == X86::GR16RegisterClass) {
12073 if (VT == MVT::i8) {
12074 unsigned DestReg = 0;
12075 switch (Res.first) {
12077 case X86::AX: DestReg = X86::AL; break;
12078 case X86::DX: DestReg = X86::DL; break;
12079 case X86::CX: DestReg = X86::CL; break;
12080 case X86::BX: DestReg = X86::BL; break;
12083 Res.first = DestReg;
12084 Res.second = X86::GR8RegisterClass;
12086 } else if (VT == MVT::i32) {
12087 unsigned DestReg = 0;
12088 switch (Res.first) {
12090 case X86::AX: DestReg = X86::EAX; break;
12091 case X86::DX: DestReg = X86::EDX; break;
12092 case X86::CX: DestReg = X86::ECX; break;
12093 case X86::BX: DestReg = X86::EBX; break;
12094 case X86::SI: DestReg = X86::ESI; break;
12095 case X86::DI: DestReg = X86::EDI; break;
12096 case X86::BP: DestReg = X86::EBP; break;
12097 case X86::SP: DestReg = X86::ESP; break;
12100 Res.first = DestReg;
12101 Res.second = X86::GR32RegisterClass;
12103 } else if (VT == MVT::i64) {
12104 unsigned DestReg = 0;
12105 switch (Res.first) {
12107 case X86::AX: DestReg = X86::RAX; break;
12108 case X86::DX: DestReg = X86::RDX; break;
12109 case X86::CX: DestReg = X86::RCX; break;
12110 case X86::BX: DestReg = X86::RBX; break;
12111 case X86::SI: DestReg = X86::RSI; break;
12112 case X86::DI: DestReg = X86::RDI; break;
12113 case X86::BP: DestReg = X86::RBP; break;
12114 case X86::SP: DestReg = X86::RSP; break;
12117 Res.first = DestReg;
12118 Res.second = X86::GR64RegisterClass;
12121 } else if (Res.second == X86::FR32RegisterClass ||
12122 Res.second == X86::FR64RegisterClass ||
12123 Res.second == X86::VR128RegisterClass) {
12124 // Handle references to XMM physical registers that got mapped into the
12125 // wrong class. This can happen with constraints like {xmm0} where the
12126 // target independent register mapper will just pick the first match it can
12127 // find, ignoring the required type.
12128 if (VT == MVT::f32)
12129 Res.second = X86::FR32RegisterClass;
12130 else if (VT == MVT::f64)
12131 Res.second = X86::FR64RegisterClass;
12132 else if (X86::VR128RegisterClass->hasType(VT))
12133 Res.second = X86::VR128RegisterClass;