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->hasXMMInt();
85 X86ScalarSSEf32 = Subtarget->hasXMM();
86 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
88 RegInfo = TM.getRegisterInfo();
91 // Set up the TargetLowering object.
92 static MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
94 // X86 is weird, it always uses i8 for shift amounts and setcc results.
95 setShiftAmountType(MVT::i8);
96 setBooleanContents(ZeroOrOneBooleanContent);
97 setSchedulingPreference(Sched::RegPressure);
98 setStackPointerRegisterToSaveRestore(X86StackPtr);
100 if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing()) {
101 // Setup Windows compiler runtime calls.
102 setLibcallName(RTLIB::SDIV_I64, "_alldiv");
103 setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
104 setLibcallName(RTLIB::FPTOUINT_F64_I64, "_ftol2");
105 setLibcallName(RTLIB::FPTOUINT_F32_I64, "_ftol2");
106 setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
107 setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
108 setLibcallCallingConv(RTLIB::FPTOUINT_F64_I64, CallingConv::C);
109 setLibcallCallingConv(RTLIB::FPTOUINT_F32_I64, CallingConv::C);
112 if (Subtarget->isTargetDarwin()) {
113 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
114 setUseUnderscoreSetJmp(false);
115 setUseUnderscoreLongJmp(false);
116 } else if (Subtarget->isTargetMingw()) {
117 // MS runtime is weird: it exports _setjmp, but longjmp!
118 setUseUnderscoreSetJmp(true);
119 setUseUnderscoreLongJmp(false);
121 setUseUnderscoreSetJmp(true);
122 setUseUnderscoreLongJmp(true);
125 // Set up the register classes.
126 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
127 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
128 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
129 if (Subtarget->is64Bit())
130 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
132 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
134 // We don't accept any truncstore of integer registers.
135 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
136 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
137 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
138 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
139 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
140 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
142 // SETOEQ and SETUNE require checking two conditions.
143 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
144 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
145 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
146 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
147 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
148 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
150 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
152 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
153 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
154 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
156 if (Subtarget->is64Bit()) {
157 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
158 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
159 } else if (!UseSoftFloat) {
160 // We have an algorithm for SSE2->double, and we turn this into a
161 // 64-bit FILD followed by conditional FADD for other targets.
162 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
163 // We have an algorithm for SSE2, and we turn this into a 64-bit
164 // FILD for other targets.
165 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
168 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
170 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
171 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
174 // SSE has no i16 to fp conversion, only i32
175 if (X86ScalarSSEf32) {
176 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
177 // f32 and f64 cases are Legal, f80 case is not
178 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
180 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
181 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
184 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
185 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
188 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
189 // are Legal, f80 is custom lowered.
190 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
191 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
193 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
195 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
196 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
198 if (X86ScalarSSEf32) {
199 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
200 // f32 and f64 cases are Legal, f80 case is not
201 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
203 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
204 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
207 // Handle FP_TO_UINT by promoting the destination to a larger signed
209 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
210 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
211 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
213 if (Subtarget->is64Bit()) {
214 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
215 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
216 } else if (!UseSoftFloat) {
217 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
218 // Expand FP_TO_UINT into a select.
219 // FIXME: We would like to use a Custom expander here eventually to do
220 // the optimal thing for SSE vs. the default expansion in the legalizer.
221 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
223 // With SSE3 we can use fisttpll to convert to a signed i64; without
224 // SSE, we're stuck with a fistpll.
225 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
228 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
229 if (!X86ScalarSSEf64) {
230 setOperationAction(ISD::BITCAST , MVT::f32 , Expand);
231 setOperationAction(ISD::BITCAST , MVT::i32 , Expand);
232 if (Subtarget->is64Bit()) {
233 setOperationAction(ISD::BITCAST , MVT::f64 , Expand);
234 // Without SSE, i64->f64 goes through memory.
235 setOperationAction(ISD::BITCAST , MVT::i64 , Expand);
239 // Scalar integer divide and remainder are lowered to use operations that
240 // produce two results, to match the available instructions. This exposes
241 // the two-result form to trivial CSE, which is able to combine x/y and x%y
242 // into a single instruction.
244 // Scalar integer multiply-high is also lowered to use two-result
245 // operations, to match the available instructions. However, plain multiply
246 // (low) operations are left as Legal, as there are single-result
247 // instructions for this in x86. Using the two-result multiply instructions
248 // when both high and low results are needed must be arranged by dagcombine.
249 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
250 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
251 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
252 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
253 setOperationAction(ISD::SREM , MVT::i8 , Expand);
254 setOperationAction(ISD::UREM , MVT::i8 , Expand);
255 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
256 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
257 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
258 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
259 setOperationAction(ISD::SREM , MVT::i16 , Expand);
260 setOperationAction(ISD::UREM , MVT::i16 , Expand);
261 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
262 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
263 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
264 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
265 setOperationAction(ISD::SREM , MVT::i32 , Expand);
266 setOperationAction(ISD::UREM , MVT::i32 , Expand);
267 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
268 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
269 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
270 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
271 setOperationAction(ISD::SREM , MVT::i64 , Expand);
272 setOperationAction(ISD::UREM , MVT::i64 , Expand);
274 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
275 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
276 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
277 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
278 if (Subtarget->is64Bit())
279 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
280 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
281 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
282 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
283 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
284 setOperationAction(ISD::FREM , MVT::f32 , Expand);
285 setOperationAction(ISD::FREM , MVT::f64 , Expand);
286 setOperationAction(ISD::FREM , MVT::f80 , Expand);
287 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
289 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
290 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
291 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
292 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
293 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
294 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
295 if (Subtarget->is64Bit()) {
296 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
297 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
300 if (Subtarget->hasPOPCNT()) {
301 setOperationAction(ISD::CTPOP , MVT::i8 , Promote);
303 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
304 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
305 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
306 if (Subtarget->is64Bit())
307 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
310 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
311 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
313 // These should be promoted to a larger select which is supported.
314 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
315 // X86 wants to expand cmov itself.
316 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
317 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
318 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
319 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
320 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
321 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
322 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
323 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
324 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
325 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
326 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
327 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
328 if (Subtarget->is64Bit()) {
329 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
330 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
332 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
335 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
336 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
337 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
338 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
339 if (Subtarget->is64Bit())
340 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
341 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
342 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
343 if (Subtarget->is64Bit()) {
344 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
345 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
346 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
347 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
348 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
350 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
351 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
352 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
353 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
354 if (Subtarget->is64Bit()) {
355 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
356 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
357 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
360 if (Subtarget->hasXMM())
361 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
363 // We may not have a libcall for MEMBARRIER so we should lower this.
364 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
366 // On X86 and X86-64, atomic operations are lowered to locked instructions.
367 // Locked instructions, in turn, have implicit fence semantics (all memory
368 // operations are flushed before issuing the locked instruction, and they
369 // are not buffered), so we can fold away the common pattern of
370 // fence-atomic-fence.
371 setShouldFoldAtomicFences(true);
373 // Expand certain atomics
374 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
375 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
376 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
377 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
379 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
380 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
381 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
382 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
384 if (!Subtarget->is64Bit()) {
385 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
386 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
387 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
388 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
389 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
390 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
391 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
394 // FIXME - use subtarget debug flags
395 if (!Subtarget->isTargetDarwin() &&
396 !Subtarget->isTargetELF() &&
397 !Subtarget->isTargetCygMing()) {
398 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
401 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
402 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
403 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
404 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
405 if (Subtarget->is64Bit()) {
406 setExceptionPointerRegister(X86::RAX);
407 setExceptionSelectorRegister(X86::RDX);
409 setExceptionPointerRegister(X86::EAX);
410 setExceptionSelectorRegister(X86::EDX);
412 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
413 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
415 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
417 setOperationAction(ISD::TRAP, MVT::Other, Legal);
419 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
420 setOperationAction(ISD::VASTART , MVT::Other, Custom);
421 setOperationAction(ISD::VAEND , MVT::Other, Expand);
422 if (Subtarget->is64Bit()) {
423 setOperationAction(ISD::VAARG , MVT::Other, Custom);
424 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
426 setOperationAction(ISD::VAARG , MVT::Other, Expand);
427 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
430 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
431 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
432 if (Subtarget->is64Bit())
433 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
434 if (Subtarget->isTargetCygMing() || Subtarget->isTargetWindows())
435 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
437 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
439 if (!UseSoftFloat && X86ScalarSSEf64) {
440 // f32 and f64 use SSE.
441 // Set up the FP register classes.
442 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
443 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
445 // Use ANDPD to simulate FABS.
446 setOperationAction(ISD::FABS , MVT::f64, Custom);
447 setOperationAction(ISD::FABS , MVT::f32, Custom);
449 // Use XORP to simulate FNEG.
450 setOperationAction(ISD::FNEG , MVT::f64, Custom);
451 setOperationAction(ISD::FNEG , MVT::f32, Custom);
453 // Use ANDPD and ORPD to simulate FCOPYSIGN.
454 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
455 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
457 // We don't support sin/cos/fmod
458 setOperationAction(ISD::FSIN , MVT::f64, Expand);
459 setOperationAction(ISD::FCOS , MVT::f64, Expand);
460 setOperationAction(ISD::FSIN , MVT::f32, Expand);
461 setOperationAction(ISD::FCOS , MVT::f32, Expand);
463 // Expand FP immediates into loads from the stack, except for the special
465 addLegalFPImmediate(APFloat(+0.0)); // xorpd
466 addLegalFPImmediate(APFloat(+0.0f)); // xorps
467 } else if (!UseSoftFloat && X86ScalarSSEf32) {
468 // Use SSE for f32, x87 for f64.
469 // Set up the FP register classes.
470 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
471 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
473 // Use ANDPS to simulate FABS.
474 setOperationAction(ISD::FABS , MVT::f32, Custom);
476 // Use XORP to simulate FNEG.
477 setOperationAction(ISD::FNEG , MVT::f32, Custom);
479 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
481 // Use ANDPS and ORPS to simulate FCOPYSIGN.
482 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
483 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
485 // We don't support sin/cos/fmod
486 setOperationAction(ISD::FSIN , MVT::f32, Expand);
487 setOperationAction(ISD::FCOS , MVT::f32, Expand);
489 // Special cases we handle for FP constants.
490 addLegalFPImmediate(APFloat(+0.0f)); // xorps
491 addLegalFPImmediate(APFloat(+0.0)); // FLD0
492 addLegalFPImmediate(APFloat(+1.0)); // FLD1
493 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
494 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
497 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
498 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
500 } else if (!UseSoftFloat) {
501 // f32 and f64 in x87.
502 // Set up the FP register classes.
503 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
504 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
506 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
507 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
508 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
509 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
512 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
513 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
515 addLegalFPImmediate(APFloat(+0.0)); // FLD0
516 addLegalFPImmediate(APFloat(+1.0)); // FLD1
517 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
518 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
519 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
520 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
521 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
522 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
525 // Long double always uses X87.
527 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
528 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
529 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
531 APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
532 addLegalFPImmediate(TmpFlt); // FLD0
534 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
537 APFloat TmpFlt2(+1.0);
538 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
540 addLegalFPImmediate(TmpFlt2); // FLD1
541 TmpFlt2.changeSign();
542 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
546 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
547 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
551 // Always use a library call for pow.
552 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
553 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
554 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
556 setOperationAction(ISD::FLOG, MVT::f80, Expand);
557 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
558 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
559 setOperationAction(ISD::FEXP, MVT::f80, Expand);
560 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
562 // First set operation action for all vector types to either promote
563 // (for widening) or expand (for scalarization). Then we will selectively
564 // turn on ones that can be effectively codegen'd.
565 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
566 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
567 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
568 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
569 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
570 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
571 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
572 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
573 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
574 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
575 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
576 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
577 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
578 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
579 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
580 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
581 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
582 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
583 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
584 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
585 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
586 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
587 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
588 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
589 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
590 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
591 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
592 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
593 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
594 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
595 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
596 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
597 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
598 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
599 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
600 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
601 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
602 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
603 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
604 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
605 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
606 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
607 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
608 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
609 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
610 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
611 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
612 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
613 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
614 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
615 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
616 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
617 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
618 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
619 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
620 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
621 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
622 setTruncStoreAction((MVT::SimpleValueType)VT,
623 (MVT::SimpleValueType)InnerVT, Expand);
624 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
625 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
626 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
629 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
630 // with -msoft-float, disable use of MMX as well.
631 if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
632 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass);
633 // No operations on x86mmx supported, everything uses intrinsics.
636 // MMX-sized vectors (other than x86mmx) are expected to be expanded
637 // into smaller operations.
638 setOperationAction(ISD::MULHS, MVT::v8i8, Expand);
639 setOperationAction(ISD::MULHS, MVT::v4i16, Expand);
640 setOperationAction(ISD::MULHS, MVT::v2i32, Expand);
641 setOperationAction(ISD::MULHS, MVT::v1i64, Expand);
642 setOperationAction(ISD::AND, MVT::v8i8, Expand);
643 setOperationAction(ISD::AND, MVT::v4i16, Expand);
644 setOperationAction(ISD::AND, MVT::v2i32, Expand);
645 setOperationAction(ISD::AND, MVT::v1i64, Expand);
646 setOperationAction(ISD::OR, MVT::v8i8, Expand);
647 setOperationAction(ISD::OR, MVT::v4i16, Expand);
648 setOperationAction(ISD::OR, MVT::v2i32, Expand);
649 setOperationAction(ISD::OR, MVT::v1i64, Expand);
650 setOperationAction(ISD::XOR, MVT::v8i8, Expand);
651 setOperationAction(ISD::XOR, MVT::v4i16, Expand);
652 setOperationAction(ISD::XOR, MVT::v2i32, Expand);
653 setOperationAction(ISD::XOR, MVT::v1i64, Expand);
654 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Expand);
655 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Expand);
656 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Expand);
657 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Expand);
658 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v1i64, Expand);
659 setOperationAction(ISD::SELECT, MVT::v8i8, Expand);
660 setOperationAction(ISD::SELECT, MVT::v4i16, Expand);
661 setOperationAction(ISD::SELECT, MVT::v2i32, Expand);
662 setOperationAction(ISD::SELECT, MVT::v1i64, Expand);
663 setOperationAction(ISD::BITCAST, MVT::v8i8, Expand);
664 setOperationAction(ISD::BITCAST, MVT::v4i16, Expand);
665 setOperationAction(ISD::BITCAST, MVT::v2i32, Expand);
666 setOperationAction(ISD::BITCAST, MVT::v1i64, Expand);
668 if (!UseSoftFloat && Subtarget->hasXMM()) {
669 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
671 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
672 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
673 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
674 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
675 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
676 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
677 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
678 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
679 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
680 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
681 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
682 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
685 if (!UseSoftFloat && Subtarget->hasXMMInt()) {
686 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
688 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
689 // registers cannot be used even for integer operations.
690 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
691 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
692 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
693 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
695 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
696 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
697 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
698 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
699 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
700 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
701 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
702 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
703 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
704 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
705 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
706 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
707 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
708 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
709 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
710 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
712 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
713 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
714 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
715 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
717 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
718 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
719 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
720 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
721 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
723 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
724 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
725 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
726 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
727 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
729 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
730 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
731 EVT VT = (MVT::SimpleValueType)i;
732 // Do not attempt to custom lower non-power-of-2 vectors
733 if (!isPowerOf2_32(VT.getVectorNumElements()))
735 // Do not attempt to custom lower non-128-bit vectors
736 if (!VT.is128BitVector())
738 setOperationAction(ISD::BUILD_VECTOR,
739 VT.getSimpleVT().SimpleTy, Custom);
740 setOperationAction(ISD::VECTOR_SHUFFLE,
741 VT.getSimpleVT().SimpleTy, Custom);
742 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
743 VT.getSimpleVT().SimpleTy, Custom);
746 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
747 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
748 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
749 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
750 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
751 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
753 if (Subtarget->is64Bit()) {
754 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
755 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
758 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
759 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
760 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
763 // Do not attempt to promote non-128-bit vectors
764 if (!VT.is128BitVector())
767 setOperationAction(ISD::AND, SVT, Promote);
768 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
769 setOperationAction(ISD::OR, SVT, Promote);
770 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
771 setOperationAction(ISD::XOR, SVT, Promote);
772 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
773 setOperationAction(ISD::LOAD, SVT, Promote);
774 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
775 setOperationAction(ISD::SELECT, SVT, Promote);
776 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
779 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
781 // Custom lower v2i64 and v2f64 selects.
782 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
783 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
784 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
785 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
787 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
788 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
791 if (Subtarget->hasSSE41()) {
792 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
793 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
794 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
795 setOperationAction(ISD::FRINT, MVT::f32, Legal);
796 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
797 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
798 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
799 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
800 setOperationAction(ISD::FRINT, MVT::f64, Legal);
801 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
803 // FIXME: Do we need to handle scalar-to-vector here?
804 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
806 // Can turn SHL into an integer multiply.
807 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
808 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
810 // i8 and i16 vectors are custom , because the source register and source
811 // source memory operand types are not the same width. f32 vectors are
812 // custom since the immediate controlling the insert encodes additional
814 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
815 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
816 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
817 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
819 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
820 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
821 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
822 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
824 if (Subtarget->is64Bit()) {
825 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
826 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
830 if (Subtarget->hasSSE42())
831 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);
946 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
947 // handle type legalization for these operations here.
949 // FIXME: We really should do custom legalization for addition and
950 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
951 // than generic legalization for 64-bit multiplication-with-overflow, though.
952 for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
953 // Add/Sub/Mul with overflow operations are custom lowered.
955 setOperationAction(ISD::SADDO, VT, Custom);
956 setOperationAction(ISD::UADDO, VT, Custom);
957 setOperationAction(ISD::SSUBO, VT, Custom);
958 setOperationAction(ISD::USUBO, VT, Custom);
959 setOperationAction(ISD::SMULO, VT, Custom);
960 setOperationAction(ISD::UMULO, VT, Custom);
963 // There are no 8-bit 3-address imul/mul instructions
964 setOperationAction(ISD::SMULO, MVT::i8, Expand);
965 setOperationAction(ISD::UMULO, MVT::i8, Expand);
967 if (!Subtarget->is64Bit()) {
968 // These libcalls are not available in 32-bit.
969 setLibcallName(RTLIB::SHL_I128, 0);
970 setLibcallName(RTLIB::SRL_I128, 0);
971 setLibcallName(RTLIB::SRA_I128, 0);
974 // We have target-specific dag combine patterns for the following nodes:
975 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
976 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
977 setTargetDAGCombine(ISD::BUILD_VECTOR);
978 setTargetDAGCombine(ISD::SELECT);
979 setTargetDAGCombine(ISD::SHL);
980 setTargetDAGCombine(ISD::SRA);
981 setTargetDAGCombine(ISD::SRL);
982 setTargetDAGCombine(ISD::OR);
983 setTargetDAGCombine(ISD::AND);
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->hasXMM())
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->hasXMMInt()) {
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->hasXMM())) {
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->hasXMMInt()))
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->hasXMM())) {
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->hasXMM()) &&
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->hasXMM())
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->hasXMM() || !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,
6184 GA->getValueType(0),
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 Chain = DAG.getEntryNode();
6198 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6199 SDValue Args[] = { Chain, Offset };
6200 Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args, 2);
6202 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6203 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6204 MFI->setAdjustsStack(true);
6206 // And our return value (tls address) is in the standard call return value
6208 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6209 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6213 "TLS not implemented for this target.");
6215 llvm_unreachable("Unreachable");
6220 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
6221 /// take a 2 x i32 value to shift plus a shift amount.
6222 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
6223 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6224 EVT VT = Op.getValueType();
6225 unsigned VTBits = VT.getSizeInBits();
6226 DebugLoc dl = Op.getDebugLoc();
6227 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6228 SDValue ShOpLo = Op.getOperand(0);
6229 SDValue ShOpHi = Op.getOperand(1);
6230 SDValue ShAmt = Op.getOperand(2);
6231 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6232 DAG.getConstant(VTBits - 1, MVT::i8))
6233 : DAG.getConstant(0, VT);
6236 if (Op.getOpcode() == ISD::SHL_PARTS) {
6237 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6238 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6240 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6241 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6244 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6245 DAG.getConstant(VTBits, MVT::i8));
6246 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6247 AndNode, DAG.getConstant(0, MVT::i8));
6250 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6251 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6252 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6254 if (Op.getOpcode() == ISD::SHL_PARTS) {
6255 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6256 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6258 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6259 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6262 SDValue Ops[2] = { Lo, Hi };
6263 return DAG.getMergeValues(Ops, 2, dl);
6266 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6267 SelectionDAG &DAG) const {
6268 EVT SrcVT = Op.getOperand(0).getValueType();
6270 if (SrcVT.isVector())
6273 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6274 "Unknown SINT_TO_FP to lower!");
6276 // These are really Legal; return the operand so the caller accepts it as
6278 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6280 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6281 Subtarget->is64Bit()) {
6285 DebugLoc dl = Op.getDebugLoc();
6286 unsigned Size = SrcVT.getSizeInBits()/8;
6287 MachineFunction &MF = DAG.getMachineFunction();
6288 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6289 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6290 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6292 MachinePointerInfo::getFixedStack(SSFI),
6294 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6297 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6299 SelectionDAG &DAG) const {
6301 DebugLoc DL = Op.getDebugLoc();
6303 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6305 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
6307 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6309 unsigned ByteSize = SrcVT.getSizeInBits()/8;
6311 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6312 MachineMemOperand *MMO =
6313 DAG.getMachineFunction()
6314 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6315 MachineMemOperand::MOLoad, ByteSize, ByteSize);
6317 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6318 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6320 Tys, Ops, array_lengthof(Ops),
6324 Chain = Result.getValue(1);
6325 SDValue InFlag = Result.getValue(2);
6327 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6328 // shouldn't be necessary except that RFP cannot be live across
6329 // multiple blocks. When stackifier is fixed, they can be uncoupled.
6330 MachineFunction &MF = DAG.getMachineFunction();
6331 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6332 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6333 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6334 Tys = DAG.getVTList(MVT::Other);
6336 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6338 MachineMemOperand *MMO =
6339 DAG.getMachineFunction()
6340 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6341 MachineMemOperand::MOStore, SSFISize, SSFISize);
6343 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6344 Ops, array_lengthof(Ops),
6345 Op.getValueType(), MMO);
6346 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6347 MachinePointerInfo::getFixedStack(SSFI),
6354 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6355 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6356 SelectionDAG &DAG) const {
6357 // This algorithm is not obvious. Here it is in C code, more or less:
6359 double uint64_to_double( uint32_t hi, uint32_t lo ) {
6360 static const __m128i exp = { 0x4330000045300000ULL, 0 };
6361 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6363 // Copy ints to xmm registers.
6364 __m128i xh = _mm_cvtsi32_si128( hi );
6365 __m128i xl = _mm_cvtsi32_si128( lo );
6367 // Combine into low half of a single xmm register.
6368 __m128i x = _mm_unpacklo_epi32( xh, xl );
6372 // Merge in appropriate exponents to give the integer bits the right
6374 x = _mm_unpacklo_epi32( x, exp );
6376 // Subtract away the biases to deal with the IEEE-754 double precision
6378 d = _mm_sub_pd( (__m128d) x, bias );
6380 // All conversions up to here are exact. The correctly rounded result is
6381 // calculated using the current rounding mode using the following
6383 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6384 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
6385 // store doesn't really need to be here (except
6386 // maybe to zero the other double)
6391 DebugLoc dl = Op.getDebugLoc();
6392 LLVMContext *Context = DAG.getContext();
6394 // Build some magic constants.
6395 std::vector<Constant*> CV0;
6396 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6397 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6398 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6399 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6400 Constant *C0 = ConstantVector::get(CV0);
6401 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6403 std::vector<Constant*> CV1;
6405 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6407 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6408 Constant *C1 = ConstantVector::get(CV1);
6409 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6411 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6412 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6414 DAG.getIntPtrConstant(1)));
6415 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6416 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6418 DAG.getIntPtrConstant(0)));
6419 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6420 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6421 MachinePointerInfo::getConstantPool(),
6423 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6424 SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck2);
6425 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6426 MachinePointerInfo::getConstantPool(),
6428 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6430 // Add the halves; easiest way is to swap them into another reg first.
6431 int ShufMask[2] = { 1, -1 };
6432 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6433 DAG.getUNDEF(MVT::v2f64), ShufMask);
6434 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6435 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6436 DAG.getIntPtrConstant(0));
6439 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6440 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6441 SelectionDAG &DAG) const {
6442 DebugLoc dl = Op.getDebugLoc();
6443 // FP constant to bias correct the final result.
6444 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6447 // Load the 32-bit value into an XMM register.
6448 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6449 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6451 DAG.getIntPtrConstant(0)));
6453 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6454 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
6455 DAG.getIntPtrConstant(0));
6457 // Or the load with the bias.
6458 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6459 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6460 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6462 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6463 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6464 MVT::v2f64, Bias)));
6465 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6466 DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
6467 DAG.getIntPtrConstant(0));
6469 // Subtract the bias.
6470 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6472 // Handle final rounding.
6473 EVT DestVT = Op.getValueType();
6475 if (DestVT.bitsLT(MVT::f64)) {
6476 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6477 DAG.getIntPtrConstant(0));
6478 } else if (DestVT.bitsGT(MVT::f64)) {
6479 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6482 // Handle final rounding.
6486 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6487 SelectionDAG &DAG) const {
6488 SDValue N0 = Op.getOperand(0);
6489 DebugLoc dl = Op.getDebugLoc();
6491 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6492 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6493 // the optimization here.
6494 if (DAG.SignBitIsZero(N0))
6495 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6497 EVT SrcVT = N0.getValueType();
6498 EVT DstVT = Op.getValueType();
6499 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6500 return LowerUINT_TO_FP_i64(Op, DAG);
6501 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6502 return LowerUINT_TO_FP_i32(Op, DAG);
6504 // Make a 64-bit buffer, and use it to build an FILD.
6505 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6506 if (SrcVT == MVT::i32) {
6507 SDValue WordOff = DAG.getConstant(4, getPointerTy());
6508 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6509 getPointerTy(), StackSlot, WordOff);
6510 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6511 StackSlot, MachinePointerInfo(),
6513 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6514 OffsetSlot, MachinePointerInfo(),
6516 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6520 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6521 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6522 StackSlot, MachinePointerInfo(),
6524 // For i64 source, we need to add the appropriate power of 2 if the input
6525 // was negative. This is the same as the optimization in
6526 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6527 // we must be careful to do the computation in x87 extended precision, not
6528 // in SSE. (The generic code can't know it's OK to do this, or how to.)
6529 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6530 MachineMemOperand *MMO =
6531 DAG.getMachineFunction()
6532 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6533 MachineMemOperand::MOLoad, 8, 8);
6535 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6536 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6537 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
6540 APInt FF(32, 0x5F800000ULL);
6542 // Check whether the sign bit is set.
6543 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6544 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6547 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6548 SDValue FudgePtr = DAG.getConstantPool(
6549 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6552 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6553 SDValue Zero = DAG.getIntPtrConstant(0);
6554 SDValue Four = DAG.getIntPtrConstant(4);
6555 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6557 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6559 // Load the value out, extending it from f32 to f80.
6560 // FIXME: Avoid the extend by constructing the right constant pool?
6561 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, MVT::f80, dl, DAG.getEntryNode(),
6562 FudgePtr, MachinePointerInfo::getConstantPool(),
6563 MVT::f32, false, false, 4);
6564 // Extend everything to 80 bits to force it to be done on x87.
6565 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6566 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6569 std::pair<SDValue,SDValue> X86TargetLowering::
6570 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6571 DebugLoc DL = Op.getDebugLoc();
6573 EVT DstTy = Op.getValueType();
6576 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
6580 assert(DstTy.getSimpleVT() <= MVT::i64 &&
6581 DstTy.getSimpleVT() >= MVT::i16 &&
6582 "Unknown FP_TO_SINT to lower!");
6584 // These are really Legal.
6585 if (DstTy == MVT::i32 &&
6586 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6587 return std::make_pair(SDValue(), SDValue());
6588 if (Subtarget->is64Bit() &&
6589 DstTy == MVT::i64 &&
6590 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6591 return std::make_pair(SDValue(), SDValue());
6593 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
6595 MachineFunction &MF = DAG.getMachineFunction();
6596 unsigned MemSize = DstTy.getSizeInBits()/8;
6597 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6598 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6603 switch (DstTy.getSimpleVT().SimpleTy) {
6604 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
6605 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
6606 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
6607 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
6610 SDValue Chain = DAG.getEntryNode();
6611 SDValue Value = Op.getOperand(0);
6612 EVT TheVT = Op.getOperand(0).getValueType();
6613 if (isScalarFPTypeInSSEReg(TheVT)) {
6614 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
6615 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
6616 MachinePointerInfo::getFixedStack(SSFI),
6618 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
6620 Chain, StackSlot, DAG.getValueType(TheVT)
6623 MachineMemOperand *MMO =
6624 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6625 MachineMemOperand::MOLoad, MemSize, MemSize);
6626 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
6628 Chain = Value.getValue(1);
6629 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6630 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6633 MachineMemOperand *MMO =
6634 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6635 MachineMemOperand::MOStore, MemSize, MemSize);
6637 // Build the FP_TO_INT*_IN_MEM
6638 SDValue Ops[] = { Chain, Value, StackSlot };
6639 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
6640 Ops, 3, DstTy, MMO);
6642 return std::make_pair(FIST, StackSlot);
6645 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
6646 SelectionDAG &DAG) const {
6647 if (Op.getValueType().isVector())
6650 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
6651 SDValue FIST = Vals.first, StackSlot = Vals.second;
6652 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
6653 if (FIST.getNode() == 0) return Op;
6656 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6657 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6660 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
6661 SelectionDAG &DAG) const {
6662 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
6663 SDValue FIST = Vals.first, StackSlot = Vals.second;
6664 assert(FIST.getNode() && "Unexpected failure");
6667 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6668 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6671 SDValue X86TargetLowering::LowerFABS(SDValue Op,
6672 SelectionDAG &DAG) const {
6673 LLVMContext *Context = DAG.getContext();
6674 DebugLoc dl = Op.getDebugLoc();
6675 EVT VT = Op.getValueType();
6678 EltVT = VT.getVectorElementType();
6679 std::vector<Constant*> CV;
6680 if (EltVT == MVT::f64) {
6681 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
6685 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
6691 Constant *C = ConstantVector::get(CV);
6692 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6693 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6694 MachinePointerInfo::getConstantPool(),
6696 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
6699 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
6700 LLVMContext *Context = DAG.getContext();
6701 DebugLoc dl = Op.getDebugLoc();
6702 EVT VT = Op.getValueType();
6705 EltVT = VT.getVectorElementType();
6706 std::vector<Constant*> CV;
6707 if (EltVT == MVT::f64) {
6708 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
6712 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
6718 Constant *C = ConstantVector::get(CV);
6719 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6720 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6721 MachinePointerInfo::getConstantPool(),
6723 if (VT.isVector()) {
6724 return DAG.getNode(ISD::BITCAST, dl, VT,
6725 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
6726 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
6728 DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, Mask)));
6730 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
6734 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
6735 LLVMContext *Context = DAG.getContext();
6736 SDValue Op0 = Op.getOperand(0);
6737 SDValue Op1 = Op.getOperand(1);
6738 DebugLoc dl = Op.getDebugLoc();
6739 EVT VT = Op.getValueType();
6740 EVT SrcVT = Op1.getValueType();
6742 // If second operand is smaller, extend it first.
6743 if (SrcVT.bitsLT(VT)) {
6744 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
6747 // And if it is bigger, shrink it first.
6748 if (SrcVT.bitsGT(VT)) {
6749 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
6753 // At this point the operands and the result should have the same
6754 // type, and that won't be f80 since that is not custom lowered.
6756 // First get the sign bit of second operand.
6757 std::vector<Constant*> CV;
6758 if (SrcVT == MVT::f64) {
6759 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
6760 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6762 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
6763 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6764 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6765 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6767 Constant *C = ConstantVector::get(CV);
6768 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6769 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
6770 MachinePointerInfo::getConstantPool(),
6772 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
6774 // Shift sign bit right or left if the two operands have different types.
6775 if (SrcVT.bitsGT(VT)) {
6776 // Op0 is MVT::f32, Op1 is MVT::f64.
6777 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
6778 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
6779 DAG.getConstant(32, MVT::i32));
6780 SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
6781 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
6782 DAG.getIntPtrConstant(0));
6785 // Clear first operand sign bit.
6787 if (VT == MVT::f64) {
6788 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
6789 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6791 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
6792 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6793 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6794 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6796 C = ConstantVector::get(CV);
6797 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6798 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6799 MachinePointerInfo::getConstantPool(),
6801 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
6803 // Or the value with the sign bit.
6804 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
6807 /// Emit nodes that will be selected as "test Op0,Op0", or something
6809 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
6810 SelectionDAG &DAG) const {
6811 DebugLoc dl = Op.getDebugLoc();
6813 // CF and OF aren't always set the way we want. Determine which
6814 // of these we need.
6815 bool NeedCF = false;
6816 bool NeedOF = false;
6819 case X86::COND_A: case X86::COND_AE:
6820 case X86::COND_B: case X86::COND_BE:
6823 case X86::COND_G: case X86::COND_GE:
6824 case X86::COND_L: case X86::COND_LE:
6825 case X86::COND_O: case X86::COND_NO:
6830 // See if we can use the EFLAGS value from the operand instead of
6831 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
6832 // we prove that the arithmetic won't overflow, we can't use OF or CF.
6833 if (Op.getResNo() != 0 || NeedOF || NeedCF)
6834 // Emit a CMP with 0, which is the TEST pattern.
6835 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6836 DAG.getConstant(0, Op.getValueType()));
6838 unsigned Opcode = 0;
6839 unsigned NumOperands = 0;
6840 switch (Op.getNode()->getOpcode()) {
6842 // Due to an isel shortcoming, be conservative if this add is likely to be
6843 // selected as part of a load-modify-store instruction. When the root node
6844 // in a match is a store, isel doesn't know how to remap non-chain non-flag
6845 // uses of other nodes in the match, such as the ADD in this case. This
6846 // leads to the ADD being left around and reselected, with the result being
6847 // two adds in the output. Alas, even if none our users are stores, that
6848 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
6849 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
6850 // climbing the DAG back to the root, and it doesn't seem to be worth the
6852 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6853 UE = Op.getNode()->use_end(); UI != UE; ++UI)
6854 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
6857 if (ConstantSDNode *C =
6858 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
6859 // An add of one will be selected as an INC.
6860 if (C->getAPIntValue() == 1) {
6861 Opcode = X86ISD::INC;
6866 // An add of negative one (subtract of one) will be selected as a DEC.
6867 if (C->getAPIntValue().isAllOnesValue()) {
6868 Opcode = X86ISD::DEC;
6874 // Otherwise use a regular EFLAGS-setting add.
6875 Opcode = X86ISD::ADD;
6879 // If the primary and result isn't used, don't bother using X86ISD::AND,
6880 // because a TEST instruction will be better.
6881 bool NonFlagUse = false;
6882 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6883 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
6885 unsigned UOpNo = UI.getOperandNo();
6886 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
6887 // Look pass truncate.
6888 UOpNo = User->use_begin().getOperandNo();
6889 User = *User->use_begin();
6892 if (User->getOpcode() != ISD::BRCOND &&
6893 User->getOpcode() != ISD::SETCC &&
6894 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
6907 // Due to the ISEL shortcoming noted above, be conservative if this op is
6908 // likely to be selected as part of a load-modify-store instruction.
6909 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6910 UE = Op.getNode()->use_end(); UI != UE; ++UI)
6911 if (UI->getOpcode() == ISD::STORE)
6914 // Otherwise use a regular EFLAGS-setting instruction.
6915 switch (Op.getNode()->getOpcode()) {
6916 default: llvm_unreachable("unexpected operator!");
6917 case ISD::SUB: Opcode = X86ISD::SUB; break;
6918 case ISD::OR: Opcode = X86ISD::OR; break;
6919 case ISD::XOR: Opcode = X86ISD::XOR; break;
6920 case ISD::AND: Opcode = X86ISD::AND; break;
6932 return SDValue(Op.getNode(), 1);
6939 // Emit a CMP with 0, which is the TEST pattern.
6940 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6941 DAG.getConstant(0, Op.getValueType()));
6943 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
6944 SmallVector<SDValue, 4> Ops;
6945 for (unsigned i = 0; i != NumOperands; ++i)
6946 Ops.push_back(Op.getOperand(i));
6948 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
6949 DAG.ReplaceAllUsesWith(Op, New);
6950 return SDValue(New.getNode(), 1);
6953 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
6955 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
6956 SelectionDAG &DAG) const {
6957 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
6958 if (C->getAPIntValue() == 0)
6959 return EmitTest(Op0, X86CC, DAG);
6961 DebugLoc dl = Op0.getDebugLoc();
6962 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
6965 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
6966 /// if it's possible.
6967 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
6968 DebugLoc dl, SelectionDAG &DAG) const {
6969 SDValue Op0 = And.getOperand(0);
6970 SDValue Op1 = And.getOperand(1);
6971 if (Op0.getOpcode() == ISD::TRUNCATE)
6972 Op0 = Op0.getOperand(0);
6973 if (Op1.getOpcode() == ISD::TRUNCATE)
6974 Op1 = Op1.getOperand(0);
6977 if (Op1.getOpcode() == ISD::SHL)
6978 std::swap(Op0, Op1);
6979 if (Op0.getOpcode() == ISD::SHL) {
6980 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
6981 if (And00C->getZExtValue() == 1) {
6982 // If we looked past a truncate, check that it's only truncating away
6984 unsigned BitWidth = Op0.getValueSizeInBits();
6985 unsigned AndBitWidth = And.getValueSizeInBits();
6986 if (BitWidth > AndBitWidth) {
6987 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
6988 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
6989 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
6993 RHS = Op0.getOperand(1);
6995 } else if (Op1.getOpcode() == ISD::Constant) {
6996 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
6997 SDValue AndLHS = Op0;
6998 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
6999 LHS = AndLHS.getOperand(0);
7000 RHS = AndLHS.getOperand(1);
7004 if (LHS.getNode()) {
7005 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
7006 // instruction. Since the shift amount is in-range-or-undefined, we know
7007 // that doing a bittest on the i32 value is ok. We extend to i32 because
7008 // the encoding for the i16 version is larger than the i32 version.
7009 // Also promote i16 to i32 for performance / code size reason.
7010 if (LHS.getValueType() == MVT::i8 ||
7011 LHS.getValueType() == MVT::i16)
7012 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7014 // If the operand types disagree, extend the shift amount to match. Since
7015 // BT ignores high bits (like shifts) we can use anyextend.
7016 if (LHS.getValueType() != RHS.getValueType())
7017 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7019 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7020 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7021 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7022 DAG.getConstant(Cond, MVT::i8), BT);
7028 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7029 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7030 SDValue Op0 = Op.getOperand(0);
7031 SDValue Op1 = Op.getOperand(1);
7032 DebugLoc dl = Op.getDebugLoc();
7033 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7035 // Optimize to BT if possible.
7036 // Lower (X & (1 << N)) == 0 to BT(X, N).
7037 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7038 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7039 if (Op0.getOpcode() == ISD::AND &&
7041 Op1.getOpcode() == ISD::Constant &&
7042 cast<ConstantSDNode>(Op1)->isNullValue() &&
7043 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7044 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7045 if (NewSetCC.getNode())
7049 // Look for "(setcc) == / != 1" to avoid unnecessary setcc.
7050 if (Op0.getOpcode() == X86ISD::SETCC &&
7051 Op1.getOpcode() == ISD::Constant &&
7052 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7053 cast<ConstantSDNode>(Op1)->isNullValue()) &&
7054 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7055 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7056 bool Invert = (CC == ISD::SETNE) ^
7057 cast<ConstantSDNode>(Op1)->isNullValue();
7059 CCode = X86::GetOppositeBranchCondition(CCode);
7060 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7061 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7064 bool isFP = Op1.getValueType().isFloatingPoint();
7065 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7066 if (X86CC == X86::COND_INVALID)
7069 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
7071 // Use sbb x, x to materialize carry bit into a GPR.
7072 if (X86CC == X86::COND_B)
7073 return DAG.getNode(ISD::AND, dl, MVT::i8,
7074 DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
7075 DAG.getConstant(X86CC, MVT::i8), Cond),
7076 DAG.getConstant(1, MVT::i8));
7078 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7079 DAG.getConstant(X86CC, MVT::i8), Cond);
7082 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7084 SDValue Op0 = Op.getOperand(0);
7085 SDValue Op1 = Op.getOperand(1);
7086 SDValue CC = Op.getOperand(2);
7087 EVT VT = Op.getValueType();
7088 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7089 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7090 DebugLoc dl = Op.getDebugLoc();
7094 EVT VT0 = Op0.getValueType();
7095 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7096 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7099 switch (SetCCOpcode) {
7102 case ISD::SETEQ: SSECC = 0; break;
7104 case ISD::SETGT: Swap = true; // Fallthrough
7106 case ISD::SETOLT: SSECC = 1; break;
7108 case ISD::SETGE: Swap = true; // Fallthrough
7110 case ISD::SETOLE: SSECC = 2; break;
7111 case ISD::SETUO: SSECC = 3; break;
7113 case ISD::SETNE: SSECC = 4; break;
7114 case ISD::SETULE: Swap = true;
7115 case ISD::SETUGE: SSECC = 5; break;
7116 case ISD::SETULT: Swap = true;
7117 case ISD::SETUGT: SSECC = 6; break;
7118 case ISD::SETO: SSECC = 7; break;
7121 std::swap(Op0, Op1);
7123 // In the two special cases we can't handle, emit two comparisons.
7125 if (SetCCOpcode == ISD::SETUEQ) {
7127 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7128 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7129 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7131 else if (SetCCOpcode == ISD::SETONE) {
7133 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7134 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7135 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7137 llvm_unreachable("Illegal FP comparison");
7139 // Handle all other FP comparisons here.
7140 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7143 // We are handling one of the integer comparisons here. Since SSE only has
7144 // GT and EQ comparisons for integer, swapping operands and multiple
7145 // operations may be required for some comparisons.
7146 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7147 bool Swap = false, Invert = false, FlipSigns = false;
7149 switch (VT.getSimpleVT().SimpleTy) {
7151 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7152 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7153 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7154 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7157 switch (SetCCOpcode) {
7159 case ISD::SETNE: Invert = true;
7160 case ISD::SETEQ: Opc = EQOpc; break;
7161 case ISD::SETLT: Swap = true;
7162 case ISD::SETGT: Opc = GTOpc; break;
7163 case ISD::SETGE: Swap = true;
7164 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
7165 case ISD::SETULT: Swap = true;
7166 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7167 case ISD::SETUGE: Swap = true;
7168 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7171 std::swap(Op0, Op1);
7173 // Since SSE has no unsigned integer comparisons, we need to flip the sign
7174 // bits of the inputs before performing those operations.
7176 EVT EltVT = VT.getVectorElementType();
7177 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7179 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7180 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7182 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7183 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7186 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7188 // If the logical-not of the result is required, perform that now.
7190 Result = DAG.getNOT(dl, Result, VT);
7195 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7196 static bool isX86LogicalCmp(SDValue Op) {
7197 unsigned Opc = Op.getNode()->getOpcode();
7198 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7200 if (Op.getResNo() == 1 &&
7201 (Opc == X86ISD::ADD ||
7202 Opc == X86ISD::SUB ||
7203 Opc == X86ISD::SMUL ||
7204 Opc == X86ISD::UMUL ||
7205 Opc == X86ISD::INC ||
7206 Opc == X86ISD::DEC ||
7207 Opc == X86ISD::OR ||
7208 Opc == X86ISD::XOR ||
7209 Opc == X86ISD::AND))
7212 if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
7218 static bool isZero(SDValue V) {
7219 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7220 return C && C->isNullValue();
7223 static bool isAllOnes(SDValue V) {
7224 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
7225 return C && C->isAllOnesValue();
7228 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7229 bool addTest = true;
7230 SDValue Cond = Op.getOperand(0);
7231 SDValue Op1 = Op.getOperand(1);
7232 SDValue Op2 = Op.getOperand(2);
7233 DebugLoc DL = Op.getDebugLoc();
7236 if (Cond.getOpcode() == ISD::SETCC) {
7237 SDValue NewCond = LowerSETCC(Cond, DAG);
7238 if (NewCond.getNode())
7242 // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
7243 // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
7244 // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
7245 // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
7246 if (Cond.getOpcode() == X86ISD::SETCC &&
7247 Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
7248 isZero(Cond.getOperand(1).getOperand(1))) {
7249 SDValue Cmp = Cond.getOperand(1);
7251 unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
7253 if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
7254 (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
7255 SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
7257 SDValue CmpOp0 = Cmp.getOperand(0);
7258 Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
7259 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7261 SDValue Res = // Res = 0 or -1.
7262 DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
7263 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7265 if (isAllOnes(Op1) != (CondCode == X86::COND_E))
7266 Res = DAG.getNOT(DL, Res, Res.getValueType());
7268 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7269 if (N2C == 0 || !N2C->isNullValue())
7270 Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
7275 // Look past (and (setcc_carry (cmp ...)), 1).
7276 if (Cond.getOpcode() == ISD::AND &&
7277 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7278 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7279 if (C && C->getAPIntValue() == 1)
7280 Cond = Cond.getOperand(0);
7283 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7284 // setting operand in place of the X86ISD::SETCC.
7285 if (Cond.getOpcode() == X86ISD::SETCC ||
7286 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7287 CC = Cond.getOperand(0);
7289 SDValue Cmp = Cond.getOperand(1);
7290 unsigned Opc = Cmp.getOpcode();
7291 EVT VT = Op.getValueType();
7293 bool IllegalFPCMov = false;
7294 if (VT.isFloatingPoint() && !VT.isVector() &&
7295 !isScalarFPTypeInSSEReg(VT)) // FPStack?
7296 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7298 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7299 Opc == X86ISD::BT) { // FIXME
7306 // Look pass the truncate.
7307 if (Cond.getOpcode() == ISD::TRUNCATE)
7308 Cond = Cond.getOperand(0);
7310 // We know the result of AND is compared against zero. Try to match
7312 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7313 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
7314 if (NewSetCC.getNode()) {
7315 CC = NewSetCC.getOperand(0);
7316 Cond = NewSetCC.getOperand(1);
7323 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7324 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7327 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7328 // condition is true.
7329 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
7330 SDValue Ops[] = { Op2, Op1, CC, Cond };
7331 return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops, array_lengthof(Ops));
7334 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7335 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7336 // from the AND / OR.
7337 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7338 Opc = Op.getOpcode();
7339 if (Opc != ISD::OR && Opc != ISD::AND)
7341 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7342 Op.getOperand(0).hasOneUse() &&
7343 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7344 Op.getOperand(1).hasOneUse());
7347 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7348 // 1 and that the SETCC node has a single use.
7349 static bool isXor1OfSetCC(SDValue Op) {
7350 if (Op.getOpcode() != ISD::XOR)
7352 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7353 if (N1C && N1C->getAPIntValue() == 1) {
7354 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7355 Op.getOperand(0).hasOneUse();
7360 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7361 bool addTest = true;
7362 SDValue Chain = Op.getOperand(0);
7363 SDValue Cond = Op.getOperand(1);
7364 SDValue Dest = Op.getOperand(2);
7365 DebugLoc dl = Op.getDebugLoc();
7368 if (Cond.getOpcode() == ISD::SETCC) {
7369 SDValue NewCond = LowerSETCC(Cond, DAG);
7370 if (NewCond.getNode())
7374 // FIXME: LowerXALUO doesn't handle these!!
7375 else if (Cond.getOpcode() == X86ISD::ADD ||
7376 Cond.getOpcode() == X86ISD::SUB ||
7377 Cond.getOpcode() == X86ISD::SMUL ||
7378 Cond.getOpcode() == X86ISD::UMUL)
7379 Cond = LowerXALUO(Cond, DAG);
7382 // Look pass (and (setcc_carry (cmp ...)), 1).
7383 if (Cond.getOpcode() == ISD::AND &&
7384 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7385 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7386 if (C && C->getAPIntValue() == 1)
7387 Cond = Cond.getOperand(0);
7390 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7391 // setting operand in place of the X86ISD::SETCC.
7392 if (Cond.getOpcode() == X86ISD::SETCC ||
7393 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7394 CC = Cond.getOperand(0);
7396 SDValue Cmp = Cond.getOperand(1);
7397 unsigned Opc = Cmp.getOpcode();
7398 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7399 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7403 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7407 // These can only come from an arithmetic instruction with overflow,
7408 // e.g. SADDO, UADDO.
7409 Cond = Cond.getNode()->getOperand(1);
7416 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7417 SDValue Cmp = Cond.getOperand(0).getOperand(1);
7418 if (CondOpc == ISD::OR) {
7419 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7420 // two branches instead of an explicit OR instruction with a
7422 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7423 isX86LogicalCmp(Cmp)) {
7424 CC = Cond.getOperand(0).getOperand(0);
7425 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7426 Chain, Dest, CC, Cmp);
7427 CC = Cond.getOperand(1).getOperand(0);
7431 } else { // ISD::AND
7432 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7433 // two branches instead of an explicit AND instruction with a
7434 // separate test. However, we only do this if this block doesn't
7435 // have a fall-through edge, because this requires an explicit
7436 // jmp when the condition is false.
7437 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7438 isX86LogicalCmp(Cmp) &&
7439 Op.getNode()->hasOneUse()) {
7440 X86::CondCode CCode =
7441 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7442 CCode = X86::GetOppositeBranchCondition(CCode);
7443 CC = DAG.getConstant(CCode, MVT::i8);
7444 SDNode *User = *Op.getNode()->use_begin();
7445 // Look for an unconditional branch following this conditional branch.
7446 // We need this because we need to reverse the successors in order
7447 // to implement FCMP_OEQ.
7448 if (User->getOpcode() == ISD::BR) {
7449 SDValue FalseBB = User->getOperand(1);
7451 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7452 assert(NewBR == User);
7456 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7457 Chain, Dest, CC, Cmp);
7458 X86::CondCode CCode =
7459 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7460 CCode = X86::GetOppositeBranchCondition(CCode);
7461 CC = DAG.getConstant(CCode, MVT::i8);
7467 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7468 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7469 // It should be transformed during dag combiner except when the condition
7470 // is set by a arithmetics with overflow node.
7471 X86::CondCode CCode =
7472 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7473 CCode = X86::GetOppositeBranchCondition(CCode);
7474 CC = DAG.getConstant(CCode, MVT::i8);
7475 Cond = Cond.getOperand(0).getOperand(1);
7481 // Look pass the truncate.
7482 if (Cond.getOpcode() == ISD::TRUNCATE)
7483 Cond = Cond.getOperand(0);
7485 // We know the result of AND is compared against zero. Try to match
7487 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7488 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7489 if (NewSetCC.getNode()) {
7490 CC = NewSetCC.getOperand(0);
7491 Cond = NewSetCC.getOperand(1);
7498 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7499 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7501 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7502 Chain, Dest, CC, Cond);
7506 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7507 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7508 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7509 // that the guard pages used by the OS virtual memory manager are allocated in
7510 // correct sequence.
7512 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7513 SelectionDAG &DAG) const {
7514 assert((Subtarget->isTargetCygMing() || Subtarget->isTargetWindows()) &&
7515 "This should be used only on Windows targets");
7516 DebugLoc dl = Op.getDebugLoc();
7519 SDValue Chain = Op.getOperand(0);
7520 SDValue Size = Op.getOperand(1);
7521 // FIXME: Ensure alignment here
7525 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7527 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
7528 Flag = Chain.getValue(1);
7530 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
7532 Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
7533 Flag = Chain.getValue(1);
7535 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
7537 SDValue Ops1[2] = { Chain.getValue(0), Chain };
7538 return DAG.getMergeValues(Ops1, 2, dl);
7541 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
7542 MachineFunction &MF = DAG.getMachineFunction();
7543 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
7545 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7546 DebugLoc DL = Op.getDebugLoc();
7548 if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
7549 // vastart just stores the address of the VarArgsFrameIndex slot into the
7550 // memory location argument.
7551 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7553 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7554 MachinePointerInfo(SV), false, false, 0);
7558 // gp_offset (0 - 6 * 8)
7559 // fp_offset (48 - 48 + 8 * 16)
7560 // overflow_arg_area (point to parameters coming in memory).
7562 SmallVector<SDValue, 8> MemOps;
7563 SDValue FIN = Op.getOperand(1);
7565 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
7566 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
7568 FIN, MachinePointerInfo(SV), false, false, 0);
7569 MemOps.push_back(Store);
7572 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7573 FIN, DAG.getIntPtrConstant(4));
7574 Store = DAG.getStore(Op.getOperand(0), DL,
7575 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
7577 FIN, MachinePointerInfo(SV, 4), false, false, 0);
7578 MemOps.push_back(Store);
7580 // Store ptr to overflow_arg_area
7581 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7582 FIN, DAG.getIntPtrConstant(4));
7583 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7585 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
7586 MachinePointerInfo(SV, 8),
7588 MemOps.push_back(Store);
7590 // Store ptr to reg_save_area.
7591 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7592 FIN, DAG.getIntPtrConstant(8));
7593 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
7595 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
7596 MachinePointerInfo(SV, 16), false, false, 0);
7597 MemOps.push_back(Store);
7598 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
7599 &MemOps[0], MemOps.size());
7602 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
7603 assert(Subtarget->is64Bit() &&
7604 "LowerVAARG only handles 64-bit va_arg!");
7605 assert((Subtarget->isTargetLinux() ||
7606 Subtarget->isTargetDarwin()) &&
7607 "Unhandled target in LowerVAARG");
7608 assert(Op.getNode()->getNumOperands() == 4);
7609 SDValue Chain = Op.getOperand(0);
7610 SDValue SrcPtr = Op.getOperand(1);
7611 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7612 unsigned Align = Op.getConstantOperandVal(3);
7613 DebugLoc dl = Op.getDebugLoc();
7615 EVT ArgVT = Op.getNode()->getValueType(0);
7616 const Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7617 uint32_t ArgSize = getTargetData()->getTypeAllocSize(ArgTy);
7620 // Decide which area this value should be read from.
7621 // TODO: Implement the AMD64 ABI in its entirety. This simple
7622 // selection mechanism works only for the basic types.
7623 if (ArgVT == MVT::f80) {
7624 llvm_unreachable("va_arg for f80 not yet implemented");
7625 } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
7626 ArgMode = 2; // Argument passed in XMM register. Use fp_offset.
7627 } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
7628 ArgMode = 1; // Argument passed in GPR64 register(s). Use gp_offset.
7630 llvm_unreachable("Unhandled argument type in LowerVAARG");
7634 // Sanity Check: Make sure using fp_offset makes sense.
7635 assert(!UseSoftFloat &&
7636 !(DAG.getMachineFunction()
7637 .getFunction()->hasFnAttr(Attribute::NoImplicitFloat)) &&
7638 Subtarget->hasXMM());
7641 // Insert VAARG_64 node into the DAG
7642 // VAARG_64 returns two values: Variable Argument Address, Chain
7643 SmallVector<SDValue, 11> InstOps;
7644 InstOps.push_back(Chain);
7645 InstOps.push_back(SrcPtr);
7646 InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
7647 InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
7648 InstOps.push_back(DAG.getConstant(Align, MVT::i32));
7649 SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
7650 SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
7651 VTs, &InstOps[0], InstOps.size(),
7653 MachinePointerInfo(SV),
7658 Chain = VAARG.getValue(1);
7660 // Load the next argument and return it
7661 return DAG.getLoad(ArgVT, dl,
7664 MachinePointerInfo(),
7668 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
7669 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
7670 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
7671 SDValue Chain = Op.getOperand(0);
7672 SDValue DstPtr = Op.getOperand(1);
7673 SDValue SrcPtr = Op.getOperand(2);
7674 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
7675 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7676 DebugLoc DL = Op.getDebugLoc();
7678 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
7679 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
7681 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
7685 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
7686 DebugLoc dl = Op.getDebugLoc();
7687 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7689 default: return SDValue(); // Don't custom lower most intrinsics.
7690 // Comparison intrinsics.
7691 case Intrinsic::x86_sse_comieq_ss:
7692 case Intrinsic::x86_sse_comilt_ss:
7693 case Intrinsic::x86_sse_comile_ss:
7694 case Intrinsic::x86_sse_comigt_ss:
7695 case Intrinsic::x86_sse_comige_ss:
7696 case Intrinsic::x86_sse_comineq_ss:
7697 case Intrinsic::x86_sse_ucomieq_ss:
7698 case Intrinsic::x86_sse_ucomilt_ss:
7699 case Intrinsic::x86_sse_ucomile_ss:
7700 case Intrinsic::x86_sse_ucomigt_ss:
7701 case Intrinsic::x86_sse_ucomige_ss:
7702 case Intrinsic::x86_sse_ucomineq_ss:
7703 case Intrinsic::x86_sse2_comieq_sd:
7704 case Intrinsic::x86_sse2_comilt_sd:
7705 case Intrinsic::x86_sse2_comile_sd:
7706 case Intrinsic::x86_sse2_comigt_sd:
7707 case Intrinsic::x86_sse2_comige_sd:
7708 case Intrinsic::x86_sse2_comineq_sd:
7709 case Intrinsic::x86_sse2_ucomieq_sd:
7710 case Intrinsic::x86_sse2_ucomilt_sd:
7711 case Intrinsic::x86_sse2_ucomile_sd:
7712 case Intrinsic::x86_sse2_ucomigt_sd:
7713 case Intrinsic::x86_sse2_ucomige_sd:
7714 case Intrinsic::x86_sse2_ucomineq_sd: {
7716 ISD::CondCode CC = ISD::SETCC_INVALID;
7719 case Intrinsic::x86_sse_comieq_ss:
7720 case Intrinsic::x86_sse2_comieq_sd:
7724 case Intrinsic::x86_sse_comilt_ss:
7725 case Intrinsic::x86_sse2_comilt_sd:
7729 case Intrinsic::x86_sse_comile_ss:
7730 case Intrinsic::x86_sse2_comile_sd:
7734 case Intrinsic::x86_sse_comigt_ss:
7735 case Intrinsic::x86_sse2_comigt_sd:
7739 case Intrinsic::x86_sse_comige_ss:
7740 case Intrinsic::x86_sse2_comige_sd:
7744 case Intrinsic::x86_sse_comineq_ss:
7745 case Intrinsic::x86_sse2_comineq_sd:
7749 case Intrinsic::x86_sse_ucomieq_ss:
7750 case Intrinsic::x86_sse2_ucomieq_sd:
7751 Opc = X86ISD::UCOMI;
7754 case Intrinsic::x86_sse_ucomilt_ss:
7755 case Intrinsic::x86_sse2_ucomilt_sd:
7756 Opc = X86ISD::UCOMI;
7759 case Intrinsic::x86_sse_ucomile_ss:
7760 case Intrinsic::x86_sse2_ucomile_sd:
7761 Opc = X86ISD::UCOMI;
7764 case Intrinsic::x86_sse_ucomigt_ss:
7765 case Intrinsic::x86_sse2_ucomigt_sd:
7766 Opc = X86ISD::UCOMI;
7769 case Intrinsic::x86_sse_ucomige_ss:
7770 case Intrinsic::x86_sse2_ucomige_sd:
7771 Opc = X86ISD::UCOMI;
7774 case Intrinsic::x86_sse_ucomineq_ss:
7775 case Intrinsic::x86_sse2_ucomineq_sd:
7776 Opc = X86ISD::UCOMI;
7781 SDValue LHS = Op.getOperand(1);
7782 SDValue RHS = Op.getOperand(2);
7783 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
7784 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
7785 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
7786 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7787 DAG.getConstant(X86CC, MVT::i8), Cond);
7788 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7790 // ptest and testp intrinsics. The intrinsic these come from are designed to
7791 // return an integer value, not just an instruction so lower it to the ptest
7792 // or testp pattern and a setcc for the result.
7793 case Intrinsic::x86_sse41_ptestz:
7794 case Intrinsic::x86_sse41_ptestc:
7795 case Intrinsic::x86_sse41_ptestnzc:
7796 case Intrinsic::x86_avx_ptestz_256:
7797 case Intrinsic::x86_avx_ptestc_256:
7798 case Intrinsic::x86_avx_ptestnzc_256:
7799 case Intrinsic::x86_avx_vtestz_ps:
7800 case Intrinsic::x86_avx_vtestc_ps:
7801 case Intrinsic::x86_avx_vtestnzc_ps:
7802 case Intrinsic::x86_avx_vtestz_pd:
7803 case Intrinsic::x86_avx_vtestc_pd:
7804 case Intrinsic::x86_avx_vtestnzc_pd:
7805 case Intrinsic::x86_avx_vtestz_ps_256:
7806 case Intrinsic::x86_avx_vtestc_ps_256:
7807 case Intrinsic::x86_avx_vtestnzc_ps_256:
7808 case Intrinsic::x86_avx_vtestz_pd_256:
7809 case Intrinsic::x86_avx_vtestc_pd_256:
7810 case Intrinsic::x86_avx_vtestnzc_pd_256: {
7811 bool IsTestPacked = false;
7814 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
7815 case Intrinsic::x86_avx_vtestz_ps:
7816 case Intrinsic::x86_avx_vtestz_pd:
7817 case Intrinsic::x86_avx_vtestz_ps_256:
7818 case Intrinsic::x86_avx_vtestz_pd_256:
7819 IsTestPacked = true; // Fallthrough
7820 case Intrinsic::x86_sse41_ptestz:
7821 case Intrinsic::x86_avx_ptestz_256:
7823 X86CC = X86::COND_E;
7825 case Intrinsic::x86_avx_vtestc_ps:
7826 case Intrinsic::x86_avx_vtestc_pd:
7827 case Intrinsic::x86_avx_vtestc_ps_256:
7828 case Intrinsic::x86_avx_vtestc_pd_256:
7829 IsTestPacked = true; // Fallthrough
7830 case Intrinsic::x86_sse41_ptestc:
7831 case Intrinsic::x86_avx_ptestc_256:
7833 X86CC = X86::COND_B;
7835 case Intrinsic::x86_avx_vtestnzc_ps:
7836 case Intrinsic::x86_avx_vtestnzc_pd:
7837 case Intrinsic::x86_avx_vtestnzc_ps_256:
7838 case Intrinsic::x86_avx_vtestnzc_pd_256:
7839 IsTestPacked = true; // Fallthrough
7840 case Intrinsic::x86_sse41_ptestnzc:
7841 case Intrinsic::x86_avx_ptestnzc_256:
7843 X86CC = X86::COND_A;
7847 SDValue LHS = Op.getOperand(1);
7848 SDValue RHS = Op.getOperand(2);
7849 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
7850 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
7851 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
7852 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
7853 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7856 // Fix vector shift instructions where the last operand is a non-immediate
7858 case Intrinsic::x86_sse2_pslli_w:
7859 case Intrinsic::x86_sse2_pslli_d:
7860 case Intrinsic::x86_sse2_pslli_q:
7861 case Intrinsic::x86_sse2_psrli_w:
7862 case Intrinsic::x86_sse2_psrli_d:
7863 case Intrinsic::x86_sse2_psrli_q:
7864 case Intrinsic::x86_sse2_psrai_w:
7865 case Intrinsic::x86_sse2_psrai_d:
7866 case Intrinsic::x86_mmx_pslli_w:
7867 case Intrinsic::x86_mmx_pslli_d:
7868 case Intrinsic::x86_mmx_pslli_q:
7869 case Intrinsic::x86_mmx_psrli_w:
7870 case Intrinsic::x86_mmx_psrli_d:
7871 case Intrinsic::x86_mmx_psrli_q:
7872 case Intrinsic::x86_mmx_psrai_w:
7873 case Intrinsic::x86_mmx_psrai_d: {
7874 SDValue ShAmt = Op.getOperand(2);
7875 if (isa<ConstantSDNode>(ShAmt))
7878 unsigned NewIntNo = 0;
7879 EVT ShAmtVT = MVT::v4i32;
7881 case Intrinsic::x86_sse2_pslli_w:
7882 NewIntNo = Intrinsic::x86_sse2_psll_w;
7884 case Intrinsic::x86_sse2_pslli_d:
7885 NewIntNo = Intrinsic::x86_sse2_psll_d;
7887 case Intrinsic::x86_sse2_pslli_q:
7888 NewIntNo = Intrinsic::x86_sse2_psll_q;
7890 case Intrinsic::x86_sse2_psrli_w:
7891 NewIntNo = Intrinsic::x86_sse2_psrl_w;
7893 case Intrinsic::x86_sse2_psrli_d:
7894 NewIntNo = Intrinsic::x86_sse2_psrl_d;
7896 case Intrinsic::x86_sse2_psrli_q:
7897 NewIntNo = Intrinsic::x86_sse2_psrl_q;
7899 case Intrinsic::x86_sse2_psrai_w:
7900 NewIntNo = Intrinsic::x86_sse2_psra_w;
7902 case Intrinsic::x86_sse2_psrai_d:
7903 NewIntNo = Intrinsic::x86_sse2_psra_d;
7906 ShAmtVT = MVT::v2i32;
7908 case Intrinsic::x86_mmx_pslli_w:
7909 NewIntNo = Intrinsic::x86_mmx_psll_w;
7911 case Intrinsic::x86_mmx_pslli_d:
7912 NewIntNo = Intrinsic::x86_mmx_psll_d;
7914 case Intrinsic::x86_mmx_pslli_q:
7915 NewIntNo = Intrinsic::x86_mmx_psll_q;
7917 case Intrinsic::x86_mmx_psrli_w:
7918 NewIntNo = Intrinsic::x86_mmx_psrl_w;
7920 case Intrinsic::x86_mmx_psrli_d:
7921 NewIntNo = Intrinsic::x86_mmx_psrl_d;
7923 case Intrinsic::x86_mmx_psrli_q:
7924 NewIntNo = Intrinsic::x86_mmx_psrl_q;
7926 case Intrinsic::x86_mmx_psrai_w:
7927 NewIntNo = Intrinsic::x86_mmx_psra_w;
7929 case Intrinsic::x86_mmx_psrai_d:
7930 NewIntNo = Intrinsic::x86_mmx_psra_d;
7932 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7938 // The vector shift intrinsics with scalars uses 32b shift amounts but
7939 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
7943 ShOps[1] = DAG.getConstant(0, MVT::i32);
7944 if (ShAmtVT == MVT::v4i32) {
7945 ShOps[2] = DAG.getUNDEF(MVT::i32);
7946 ShOps[3] = DAG.getUNDEF(MVT::i32);
7947 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
7949 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
7950 // FIXME this must be lowered to get rid of the invalid type.
7953 EVT VT = Op.getValueType();
7954 ShAmt = DAG.getNode(ISD::BITCAST, dl, VT, ShAmt);
7955 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7956 DAG.getConstant(NewIntNo, MVT::i32),
7957 Op.getOperand(1), ShAmt);
7962 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
7963 SelectionDAG &DAG) const {
7964 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7965 MFI->setReturnAddressIsTaken(true);
7967 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7968 DebugLoc dl = Op.getDebugLoc();
7971 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7973 DAG.getConstant(TD->getPointerSize(),
7974 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
7975 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7976 DAG.getNode(ISD::ADD, dl, getPointerTy(),
7978 MachinePointerInfo(), false, false, 0);
7981 // Just load the return address.
7982 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
7983 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7984 RetAddrFI, MachinePointerInfo(), false, false, 0);
7987 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
7988 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7989 MFI->setFrameAddressIsTaken(true);
7991 EVT VT = Op.getValueType();
7992 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
7993 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7994 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
7995 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
7997 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
7998 MachinePointerInfo(),
8003 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
8004 SelectionDAG &DAG) const {
8005 return DAG.getIntPtrConstant(2*TD->getPointerSize());
8008 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
8009 MachineFunction &MF = DAG.getMachineFunction();
8010 SDValue Chain = Op.getOperand(0);
8011 SDValue Offset = Op.getOperand(1);
8012 SDValue Handler = Op.getOperand(2);
8013 DebugLoc dl = Op.getDebugLoc();
8015 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
8016 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8018 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8020 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8021 DAG.getIntPtrConstant(TD->getPointerSize()));
8022 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8023 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8025 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8026 MF.getRegInfo().addLiveOut(StoreAddrReg);
8028 return DAG.getNode(X86ISD::EH_RETURN, dl,
8030 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8033 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8034 SelectionDAG &DAG) const {
8035 SDValue Root = Op.getOperand(0);
8036 SDValue Trmp = Op.getOperand(1); // trampoline
8037 SDValue FPtr = Op.getOperand(2); // nested function
8038 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8039 DebugLoc dl = Op.getDebugLoc();
8041 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8043 if (Subtarget->is64Bit()) {
8044 SDValue OutChains[6];
8046 // Large code-model.
8047 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
8048 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8050 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8051 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8053 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8055 // Load the pointer to the nested function into R11.
8056 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8057 SDValue Addr = Trmp;
8058 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8059 Addr, MachinePointerInfo(TrmpAddr),
8062 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8063 DAG.getConstant(2, MVT::i64));
8064 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8065 MachinePointerInfo(TrmpAddr, 2),
8068 // Load the 'nest' parameter value into R10.
8069 // R10 is specified in X86CallingConv.td
8070 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8071 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8072 DAG.getConstant(10, MVT::i64));
8073 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8074 Addr, MachinePointerInfo(TrmpAddr, 10),
8077 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8078 DAG.getConstant(12, MVT::i64));
8079 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8080 MachinePointerInfo(TrmpAddr, 12),
8083 // Jump to the nested function.
8084 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8085 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8086 DAG.getConstant(20, MVT::i64));
8087 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8088 Addr, MachinePointerInfo(TrmpAddr, 20),
8091 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8092 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8093 DAG.getConstant(22, MVT::i64));
8094 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8095 MachinePointerInfo(TrmpAddr, 22),
8099 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8100 return DAG.getMergeValues(Ops, 2, dl);
8102 const Function *Func =
8103 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8104 CallingConv::ID CC = Func->getCallingConv();
8109 llvm_unreachable("Unsupported calling convention");
8110 case CallingConv::C:
8111 case CallingConv::X86_StdCall: {
8112 // Pass 'nest' parameter in ECX.
8113 // Must be kept in sync with X86CallingConv.td
8116 // Check that ECX wasn't needed by an 'inreg' parameter.
8117 const FunctionType *FTy = Func->getFunctionType();
8118 const AttrListPtr &Attrs = Func->getAttributes();
8120 if (!Attrs.isEmpty() && !Func->isVarArg()) {
8121 unsigned InRegCount = 0;
8124 for (FunctionType::param_iterator I = FTy->param_begin(),
8125 E = FTy->param_end(); I != E; ++I, ++Idx)
8126 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8127 // FIXME: should only count parameters that are lowered to integers.
8128 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8130 if (InRegCount > 2) {
8131 report_fatal_error("Nest register in use - reduce number of inreg"
8137 case CallingConv::X86_FastCall:
8138 case CallingConv::X86_ThisCall:
8139 case CallingConv::Fast:
8140 // Pass 'nest' parameter in EAX.
8141 // Must be kept in sync with X86CallingConv.td
8146 SDValue OutChains[4];
8149 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8150 DAG.getConstant(10, MVT::i32));
8151 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8153 // This is storing the opcode for MOV32ri.
8154 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8155 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8156 OutChains[0] = DAG.getStore(Root, dl,
8157 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8158 Trmp, MachinePointerInfo(TrmpAddr),
8161 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8162 DAG.getConstant(1, MVT::i32));
8163 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8164 MachinePointerInfo(TrmpAddr, 1),
8167 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8168 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8169 DAG.getConstant(5, MVT::i32));
8170 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8171 MachinePointerInfo(TrmpAddr, 5),
8174 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8175 DAG.getConstant(6, MVT::i32));
8176 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8177 MachinePointerInfo(TrmpAddr, 6),
8181 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8182 return DAG.getMergeValues(Ops, 2, dl);
8186 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8187 SelectionDAG &DAG) const {
8189 The rounding mode is in bits 11:10 of FPSR, and has the following
8196 FLT_ROUNDS, on the other hand, expects the following:
8203 To perform the conversion, we do:
8204 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8207 MachineFunction &MF = DAG.getMachineFunction();
8208 const TargetMachine &TM = MF.getTarget();
8209 const TargetFrameInfo &TFI = *TM.getFrameInfo();
8210 unsigned StackAlignment = TFI.getStackAlignment();
8211 EVT VT = Op.getValueType();
8212 DebugLoc DL = Op.getDebugLoc();
8214 // Save FP Control Word to stack slot
8215 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8216 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8219 MachineMemOperand *MMO =
8220 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8221 MachineMemOperand::MOStore, 2, 2);
8223 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8224 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8225 DAG.getVTList(MVT::Other),
8226 Ops, 2, MVT::i16, MMO);
8228 // Load FP Control Word from stack slot
8229 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8230 MachinePointerInfo(), false, false, 0);
8232 // Transform as necessary
8234 DAG.getNode(ISD::SRL, DL, MVT::i16,
8235 DAG.getNode(ISD::AND, DL, MVT::i16,
8236 CWD, DAG.getConstant(0x800, MVT::i16)),
8237 DAG.getConstant(11, MVT::i8));
8239 DAG.getNode(ISD::SRL, DL, MVT::i16,
8240 DAG.getNode(ISD::AND, DL, MVT::i16,
8241 CWD, DAG.getConstant(0x400, MVT::i16)),
8242 DAG.getConstant(9, MVT::i8));
8245 DAG.getNode(ISD::AND, DL, MVT::i16,
8246 DAG.getNode(ISD::ADD, DL, MVT::i16,
8247 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8248 DAG.getConstant(1, MVT::i16)),
8249 DAG.getConstant(3, MVT::i16));
8252 return DAG.getNode((VT.getSizeInBits() < 16 ?
8253 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8256 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8257 EVT VT = Op.getValueType();
8259 unsigned NumBits = VT.getSizeInBits();
8260 DebugLoc dl = Op.getDebugLoc();
8262 Op = Op.getOperand(0);
8263 if (VT == MVT::i8) {
8264 // Zero extend to i32 since there is not an i8 bsr.
8266 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8269 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8270 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8271 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8273 // If src is zero (i.e. bsr sets ZF), returns NumBits.
8276 DAG.getConstant(NumBits+NumBits-1, OpVT),
8277 DAG.getConstant(X86::COND_E, MVT::i8),
8280 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8282 // Finally xor with NumBits-1.
8283 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8286 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8290 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8291 EVT VT = Op.getValueType();
8293 unsigned NumBits = VT.getSizeInBits();
8294 DebugLoc dl = Op.getDebugLoc();
8296 Op = Op.getOperand(0);
8297 if (VT == MVT::i8) {
8299 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8302 // Issue a bsf (scan bits forward) which also sets EFLAGS.
8303 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8304 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8306 // If src is zero (i.e. bsf sets ZF), returns NumBits.
8309 DAG.getConstant(NumBits, OpVT),
8310 DAG.getConstant(X86::COND_E, MVT::i8),
8313 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8316 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8320 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8321 EVT VT = Op.getValueType();
8322 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8323 DebugLoc dl = Op.getDebugLoc();
8325 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8326 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8327 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8328 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8329 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8331 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8332 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8333 // return AloBlo + AloBhi + AhiBlo;
8335 SDValue A = Op.getOperand(0);
8336 SDValue B = Op.getOperand(1);
8338 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8339 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8340 A, DAG.getConstant(32, MVT::i32));
8341 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8342 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8343 B, DAG.getConstant(32, MVT::i32));
8344 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8345 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8347 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8348 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8350 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8351 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8353 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8354 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8355 AloBhi, DAG.getConstant(32, MVT::i32));
8356 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8357 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8358 AhiBlo, DAG.getConstant(32, MVT::i32));
8359 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8360 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8364 SDValue X86TargetLowering::LowerSHL(SDValue Op, SelectionDAG &DAG) const {
8365 EVT VT = Op.getValueType();
8366 DebugLoc dl = Op.getDebugLoc();
8367 SDValue R = Op.getOperand(0);
8369 LLVMContext *Context = DAG.getContext();
8371 assert(Subtarget->hasSSE41() && "Cannot lower SHL without SSE4.1 or later");
8373 if (VT == MVT::v4i32) {
8374 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8375 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8376 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8378 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8380 std::vector<Constant*> CV(4, CI);
8381 Constant *C = ConstantVector::get(CV);
8382 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8383 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8384 MachinePointerInfo::getConstantPool(),
8387 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8388 Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
8389 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8390 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8392 if (VT == MVT::v16i8) {
8394 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8395 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8396 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8398 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8399 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8401 std::vector<Constant*> CVM1(16, CM1);
8402 std::vector<Constant*> CVM2(16, CM2);
8403 Constant *C = ConstantVector::get(CVM1);
8404 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8405 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8406 MachinePointerInfo::getConstantPool(),
8409 // r = pblendv(r, psllw(r & (char16)15, 4), a);
8410 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8411 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8412 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8413 DAG.getConstant(4, MVT::i32));
8414 R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8415 DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8418 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8420 C = ConstantVector::get(CVM2);
8421 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8422 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8423 MachinePointerInfo::getConstantPool(),
8426 // r = pblendv(r, psllw(r & (char16)63, 2), a);
8427 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8428 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8429 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8430 DAG.getConstant(2, MVT::i32));
8431 R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8432 DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8435 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8437 // return pblendv(r, r+r, a);
8438 R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8439 DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8440 R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8446 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8447 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8448 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8449 // looks for this combo and may remove the "setcc" instruction if the "setcc"
8450 // has only one use.
8451 SDNode *N = Op.getNode();
8452 SDValue LHS = N->getOperand(0);
8453 SDValue RHS = N->getOperand(1);
8454 unsigned BaseOp = 0;
8456 DebugLoc DL = Op.getDebugLoc();
8457 switch (Op.getOpcode()) {
8458 default: llvm_unreachable("Unknown ovf instruction!");
8460 // A subtract of one will be selected as a INC. Note that INC doesn't
8461 // set CF, so we can't do this for UADDO.
8462 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8463 if (C->getAPIntValue() == 1) {
8464 BaseOp = X86ISD::INC;
8468 BaseOp = X86ISD::ADD;
8472 BaseOp = X86ISD::ADD;
8476 // A subtract of one will be selected as a DEC. Note that DEC doesn't
8477 // set CF, so we can't do this for USUBO.
8478 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8479 if (C->getAPIntValue() == 1) {
8480 BaseOp = X86ISD::DEC;
8484 BaseOp = X86ISD::SUB;
8488 BaseOp = X86ISD::SUB;
8492 BaseOp = X86ISD::SMUL;
8495 case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
8496 SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
8498 SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
8501 DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8502 DAG.getConstant(X86::COND_O, MVT::i32),
8503 SDValue(Sum.getNode(), 2));
8505 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8510 // Also sets EFLAGS.
8511 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
8512 SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
8515 DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
8516 DAG.getConstant(Cond, MVT::i32),
8517 SDValue(Sum.getNode(), 1));
8519 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8523 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
8524 DebugLoc dl = Op.getDebugLoc();
8526 if (!Subtarget->hasSSE2()) {
8527 SDValue Chain = Op.getOperand(0);
8528 SDValue Zero = DAG.getConstant(0,
8529 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8531 DAG.getRegister(X86::ESP, MVT::i32), // Base
8532 DAG.getTargetConstant(1, MVT::i8), // Scale
8533 DAG.getRegister(0, MVT::i32), // Index
8534 DAG.getTargetConstant(0, MVT::i32), // Disp
8535 DAG.getRegister(0, MVT::i32), // Segment.
8540 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
8541 array_lengthof(Ops));
8542 return SDValue(Res, 0);
8545 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
8547 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
8549 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8550 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8551 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
8552 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
8554 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
8555 if (!Op1 && !Op2 && !Op3 && Op4)
8556 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
8558 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
8559 if (Op1 && !Op2 && !Op3 && !Op4)
8560 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
8562 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
8564 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
8567 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8568 EVT T = Op.getValueType();
8569 DebugLoc DL = Op.getDebugLoc();
8572 switch(T.getSimpleVT().SimpleTy) {
8574 assert(false && "Invalid value type!");
8575 case MVT::i8: Reg = X86::AL; size = 1; break;
8576 case MVT::i16: Reg = X86::AX; size = 2; break;
8577 case MVT::i32: Reg = X86::EAX; size = 4; break;
8579 assert(Subtarget->is64Bit() && "Node not type legal!");
8580 Reg = X86::RAX; size = 8;
8583 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
8584 Op.getOperand(2), SDValue());
8585 SDValue Ops[] = { cpIn.getValue(0),
8588 DAG.getTargetConstant(size, MVT::i8),
8590 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8591 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
8592 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
8595 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
8599 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
8600 SelectionDAG &DAG) const {
8601 assert(Subtarget->is64Bit() && "Result not type legalized?");
8602 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8603 SDValue TheChain = Op.getOperand(0);
8604 DebugLoc dl = Op.getDebugLoc();
8605 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8606 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
8607 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
8609 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
8610 DAG.getConstant(32, MVT::i8));
8612 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
8615 return DAG.getMergeValues(Ops, 2, dl);
8618 SDValue X86TargetLowering::LowerBITCAST(SDValue Op,
8619 SelectionDAG &DAG) const {
8620 EVT SrcVT = Op.getOperand(0).getValueType();
8621 EVT DstVT = Op.getValueType();
8622 assert((Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
8623 Subtarget->hasMMX() && !DisableMMX) &&
8624 "Unexpected custom BITCAST");
8625 assert((DstVT == MVT::i64 ||
8626 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
8627 "Unexpected custom BITCAST");
8628 // i64 <=> MMX conversions are Legal.
8629 if (SrcVT==MVT::i64 && DstVT.isVector())
8631 if (DstVT==MVT::i64 && SrcVT.isVector())
8633 // MMX <=> MMX conversions are Legal.
8634 if (SrcVT.isVector() && DstVT.isVector())
8636 // All other conversions need to be expanded.
8639 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
8640 SDNode *Node = Op.getNode();
8641 DebugLoc dl = Node->getDebugLoc();
8642 EVT T = Node->getValueType(0);
8643 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
8644 DAG.getConstant(0, T), Node->getOperand(2));
8645 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
8646 cast<AtomicSDNode>(Node)->getMemoryVT(),
8647 Node->getOperand(0),
8648 Node->getOperand(1), negOp,
8649 cast<AtomicSDNode>(Node)->getSrcValue(),
8650 cast<AtomicSDNode>(Node)->getAlignment());
8653 /// LowerOperation - Provide custom lowering hooks for some operations.
8655 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8656 switch (Op.getOpcode()) {
8657 default: llvm_unreachable("Should not custom lower this!");
8658 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
8659 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
8660 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
8661 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
8662 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
8663 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
8664 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8665 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
8666 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
8667 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
8668 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
8669 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
8670 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
8671 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
8672 case ISD::SHL_PARTS:
8673 case ISD::SRA_PARTS:
8674 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
8675 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
8676 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
8677 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
8678 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
8679 case ISD::FABS: return LowerFABS(Op, DAG);
8680 case ISD::FNEG: return LowerFNEG(Op, DAG);
8681 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
8682 case ISD::SETCC: return LowerSETCC(Op, DAG);
8683 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
8684 case ISD::SELECT: return LowerSELECT(Op, DAG);
8685 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
8686 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
8687 case ISD::VASTART: return LowerVASTART(Op, DAG);
8688 case ISD::VAARG: return LowerVAARG(Op, DAG);
8689 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
8690 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8691 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
8692 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
8693 case ISD::FRAME_TO_ARGS_OFFSET:
8694 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
8695 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
8696 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
8697 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
8698 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
8699 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
8700 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
8701 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
8702 case ISD::SHL: return LowerSHL(Op, DAG);
8708 case ISD::UMULO: return LowerXALUO(Op, DAG);
8709 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
8710 case ISD::BITCAST: return LowerBITCAST(Op, DAG);
8714 void X86TargetLowering::
8715 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
8716 SelectionDAG &DAG, unsigned NewOp) const {
8717 EVT T = Node->getValueType(0);
8718 DebugLoc dl = Node->getDebugLoc();
8719 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
8721 SDValue Chain = Node->getOperand(0);
8722 SDValue In1 = Node->getOperand(1);
8723 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8724 Node->getOperand(2), DAG.getIntPtrConstant(0));
8725 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8726 Node->getOperand(2), DAG.getIntPtrConstant(1));
8727 SDValue Ops[] = { Chain, In1, In2L, In2H };
8728 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8730 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
8731 cast<MemSDNode>(Node)->getMemOperand());
8732 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
8733 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8734 Results.push_back(Result.getValue(2));
8737 /// ReplaceNodeResults - Replace a node with an illegal result type
8738 /// with a new node built out of custom code.
8739 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
8740 SmallVectorImpl<SDValue>&Results,
8741 SelectionDAG &DAG) const {
8742 DebugLoc dl = N->getDebugLoc();
8743 switch (N->getOpcode()) {
8745 assert(false && "Do not know how to custom type legalize this operation!");
8747 case ISD::FP_TO_SINT: {
8748 std::pair<SDValue,SDValue> Vals =
8749 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
8750 SDValue FIST = Vals.first, StackSlot = Vals.second;
8751 if (FIST.getNode() != 0) {
8752 EVT VT = N->getValueType(0);
8753 // Return a load from the stack slot.
8754 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
8755 MachinePointerInfo(), false, false, 0));
8759 case ISD::READCYCLECOUNTER: {
8760 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8761 SDValue TheChain = N->getOperand(0);
8762 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8763 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
8765 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
8767 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
8768 SDValue Ops[] = { eax, edx };
8769 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
8770 Results.push_back(edx.getValue(1));
8773 case ISD::ATOMIC_CMP_SWAP: {
8774 EVT T = N->getValueType(0);
8775 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
8776 SDValue cpInL, cpInH;
8777 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8778 DAG.getConstant(0, MVT::i32));
8779 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8780 DAG.getConstant(1, MVT::i32));
8781 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
8782 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
8784 SDValue swapInL, swapInH;
8785 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8786 DAG.getConstant(0, MVT::i32));
8787 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8788 DAG.getConstant(1, MVT::i32));
8789 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
8791 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
8792 swapInL.getValue(1));
8793 SDValue Ops[] = { swapInH.getValue(0),
8795 swapInH.getValue(1) };
8796 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8797 MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
8798 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG8_DAG, dl, Tys,
8800 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
8801 MVT::i32, Result.getValue(1));
8802 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
8803 MVT::i32, cpOutL.getValue(2));
8804 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
8805 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8806 Results.push_back(cpOutH.getValue(1));
8809 case ISD::ATOMIC_LOAD_ADD:
8810 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
8812 case ISD::ATOMIC_LOAD_AND:
8813 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
8815 case ISD::ATOMIC_LOAD_NAND:
8816 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
8818 case ISD::ATOMIC_LOAD_OR:
8819 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
8821 case ISD::ATOMIC_LOAD_SUB:
8822 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
8824 case ISD::ATOMIC_LOAD_XOR:
8825 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
8827 case ISD::ATOMIC_SWAP:
8828 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
8833 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
8835 default: return NULL;
8836 case X86ISD::BSF: return "X86ISD::BSF";
8837 case X86ISD::BSR: return "X86ISD::BSR";
8838 case X86ISD::SHLD: return "X86ISD::SHLD";
8839 case X86ISD::SHRD: return "X86ISD::SHRD";
8840 case X86ISD::FAND: return "X86ISD::FAND";
8841 case X86ISD::FOR: return "X86ISD::FOR";
8842 case X86ISD::FXOR: return "X86ISD::FXOR";
8843 case X86ISD::FSRL: return "X86ISD::FSRL";
8844 case X86ISD::FILD: return "X86ISD::FILD";
8845 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
8846 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
8847 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
8848 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
8849 case X86ISD::FLD: return "X86ISD::FLD";
8850 case X86ISD::FST: return "X86ISD::FST";
8851 case X86ISD::CALL: return "X86ISD::CALL";
8852 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
8853 case X86ISD::BT: return "X86ISD::BT";
8854 case X86ISD::CMP: return "X86ISD::CMP";
8855 case X86ISD::COMI: return "X86ISD::COMI";
8856 case X86ISD::UCOMI: return "X86ISD::UCOMI";
8857 case X86ISD::SETCC: return "X86ISD::SETCC";
8858 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
8859 case X86ISD::CMOV: return "X86ISD::CMOV";
8860 case X86ISD::BRCOND: return "X86ISD::BRCOND";
8861 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
8862 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
8863 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
8864 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
8865 case X86ISD::Wrapper: return "X86ISD::Wrapper";
8866 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
8867 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
8868 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
8869 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
8870 case X86ISD::PINSRB: return "X86ISD::PINSRB";
8871 case X86ISD::PINSRW: return "X86ISD::PINSRW";
8872 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
8873 case X86ISD::PANDN: return "X86ISD::PANDN";
8874 case X86ISD::PSIGNB: return "X86ISD::PSIGNB";
8875 case X86ISD::PSIGNW: return "X86ISD::PSIGNW";
8876 case X86ISD::PSIGND: return "X86ISD::PSIGND";
8877 case X86ISD::FMAX: return "X86ISD::FMAX";
8878 case X86ISD::FMIN: return "X86ISD::FMIN";
8879 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
8880 case X86ISD::FRCP: return "X86ISD::FRCP";
8881 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
8882 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
8883 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
8884 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
8885 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
8886 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
8887 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
8888 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
8889 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
8890 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
8891 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
8892 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
8893 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
8894 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
8895 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
8896 case X86ISD::VSHL: return "X86ISD::VSHL";
8897 case X86ISD::VSRL: return "X86ISD::VSRL";
8898 case X86ISD::CMPPD: return "X86ISD::CMPPD";
8899 case X86ISD::CMPPS: return "X86ISD::CMPPS";
8900 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
8901 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
8902 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
8903 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
8904 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
8905 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
8906 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
8907 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
8908 case X86ISD::ADD: return "X86ISD::ADD";
8909 case X86ISD::SUB: return "X86ISD::SUB";
8910 case X86ISD::SMUL: return "X86ISD::SMUL";
8911 case X86ISD::UMUL: return "X86ISD::UMUL";
8912 case X86ISD::INC: return "X86ISD::INC";
8913 case X86ISD::DEC: return "X86ISD::DEC";
8914 case X86ISD::OR: return "X86ISD::OR";
8915 case X86ISD::XOR: return "X86ISD::XOR";
8916 case X86ISD::AND: return "X86ISD::AND";
8917 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
8918 case X86ISD::PTEST: return "X86ISD::PTEST";
8919 case X86ISD::TESTP: return "X86ISD::TESTP";
8920 case X86ISD::PALIGN: return "X86ISD::PALIGN";
8921 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
8922 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
8923 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
8924 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
8925 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
8926 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
8927 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
8928 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
8929 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
8930 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
8931 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD";
8932 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
8933 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
8934 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
8935 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
8936 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
8937 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
8938 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
8939 case X86ISD::MOVSD: return "X86ISD::MOVSD";
8940 case X86ISD::MOVSS: return "X86ISD::MOVSS";
8941 case X86ISD::UNPCKLPS: return "X86ISD::UNPCKLPS";
8942 case X86ISD::UNPCKLPD: return "X86ISD::UNPCKLPD";
8943 case X86ISD::UNPCKHPS: return "X86ISD::UNPCKHPS";
8944 case X86ISD::UNPCKHPD: return "X86ISD::UNPCKHPD";
8945 case X86ISD::PUNPCKLBW: return "X86ISD::PUNPCKLBW";
8946 case X86ISD::PUNPCKLWD: return "X86ISD::PUNPCKLWD";
8947 case X86ISD::PUNPCKLDQ: return "X86ISD::PUNPCKLDQ";
8948 case X86ISD::PUNPCKLQDQ: return "X86ISD::PUNPCKLQDQ";
8949 case X86ISD::PUNPCKHBW: return "X86ISD::PUNPCKHBW";
8950 case X86ISD::PUNPCKHWD: return "X86ISD::PUNPCKHWD";
8951 case X86ISD::PUNPCKHDQ: return "X86ISD::PUNPCKHDQ";
8952 case X86ISD::PUNPCKHQDQ: return "X86ISD::PUNPCKHQDQ";
8953 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
8954 case X86ISD::VAARG_64: return "X86ISD::VAARG_64";
8955 case X86ISD::WIN_ALLOCA: return "X86ISD::WIN_ALLOCA";
8959 // isLegalAddressingMode - Return true if the addressing mode represented
8960 // by AM is legal for this target, for a load/store of the specified type.
8961 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
8962 const Type *Ty) const {
8963 // X86 supports extremely general addressing modes.
8964 CodeModel::Model M = getTargetMachine().getCodeModel();
8965 Reloc::Model R = getTargetMachine().getRelocationModel();
8967 // X86 allows a sign-extended 32-bit immediate field as a displacement.
8968 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
8973 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
8975 // If a reference to this global requires an extra load, we can't fold it.
8976 if (isGlobalStubReference(GVFlags))
8979 // If BaseGV requires a register for the PIC base, we cannot also have a
8980 // BaseReg specified.
8981 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
8984 // If lower 4G is not available, then we must use rip-relative addressing.
8985 if ((M != CodeModel::Small || R != Reloc::Static) &&
8986 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
8996 // These scales always work.
9001 // These scales are formed with basereg+scalereg. Only accept if there is
9006 default: // Other stuff never works.
9014 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
9015 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
9017 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
9018 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
9019 if (NumBits1 <= NumBits2)
9024 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
9025 if (!VT1.isInteger() || !VT2.isInteger())
9027 unsigned NumBits1 = VT1.getSizeInBits();
9028 unsigned NumBits2 = VT2.getSizeInBits();
9029 if (NumBits1 <= NumBits2)
9034 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9035 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9036 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9039 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9040 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9041 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9044 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9045 // i16 instructions are longer (0x66 prefix) and potentially slower.
9046 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9049 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9050 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9051 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9052 /// are assumed to be legal.
9054 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9056 // Very little shuffling can be done for 64-bit vectors right now.
9057 if (VT.getSizeInBits() == 64)
9058 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9060 // FIXME: pshufb, blends, shifts.
9061 return (VT.getVectorNumElements() == 2 ||
9062 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9063 isMOVLMask(M, VT) ||
9064 isSHUFPMask(M, VT) ||
9065 isPSHUFDMask(M, VT) ||
9066 isPSHUFHWMask(M, VT) ||
9067 isPSHUFLWMask(M, VT) ||
9068 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9069 isUNPCKLMask(M, VT) ||
9070 isUNPCKHMask(M, VT) ||
9071 isUNPCKL_v_undef_Mask(M, VT) ||
9072 isUNPCKH_v_undef_Mask(M, VT));
9076 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9078 unsigned NumElts = VT.getVectorNumElements();
9079 // FIXME: This collection of masks seems suspect.
9082 if (NumElts == 4 && VT.getSizeInBits() == 128) {
9083 return (isMOVLMask(Mask, VT) ||
9084 isCommutedMOVLMask(Mask, VT, true) ||
9085 isSHUFPMask(Mask, VT) ||
9086 isCommutedSHUFPMask(Mask, VT));
9091 //===----------------------------------------------------------------------===//
9092 // X86 Scheduler Hooks
9093 //===----------------------------------------------------------------------===//
9095 // private utility function
9097 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9098 MachineBasicBlock *MBB,
9105 TargetRegisterClass *RC,
9106 bool invSrc) const {
9107 // For the atomic bitwise operator, we generate
9110 // ld t1 = [bitinstr.addr]
9111 // op t2 = t1, [bitinstr.val]
9113 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9115 // fallthrough -->nextMBB
9116 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9117 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9118 MachineFunction::iterator MBBIter = MBB;
9121 /// First build the CFG
9122 MachineFunction *F = MBB->getParent();
9123 MachineBasicBlock *thisMBB = MBB;
9124 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9125 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9126 F->insert(MBBIter, newMBB);
9127 F->insert(MBBIter, nextMBB);
9129 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9130 nextMBB->splice(nextMBB->begin(), thisMBB,
9131 llvm::next(MachineBasicBlock::iterator(bInstr)),
9133 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9135 // Update thisMBB to fall through to newMBB
9136 thisMBB->addSuccessor(newMBB);
9138 // newMBB jumps to itself and fall through to nextMBB
9139 newMBB->addSuccessor(nextMBB);
9140 newMBB->addSuccessor(newMBB);
9142 // Insert instructions into newMBB based on incoming instruction
9143 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9144 "unexpected number of operands");
9145 DebugLoc dl = bInstr->getDebugLoc();
9146 MachineOperand& destOper = bInstr->getOperand(0);
9147 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9148 int numArgs = bInstr->getNumOperands() - 1;
9149 for (int i=0; i < numArgs; ++i)
9150 argOpers[i] = &bInstr->getOperand(i+1);
9152 // x86 address has 4 operands: base, index, scale, and displacement
9153 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9154 int valArgIndx = lastAddrIndx + 1;
9156 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9157 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9158 for (int i=0; i <= lastAddrIndx; ++i)
9159 (*MIB).addOperand(*argOpers[i]);
9161 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9163 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9168 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9169 assert((argOpers[valArgIndx]->isReg() ||
9170 argOpers[valArgIndx]->isImm()) &&
9172 if (argOpers[valArgIndx]->isReg())
9173 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9175 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9177 (*MIB).addOperand(*argOpers[valArgIndx]);
9179 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9182 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9183 for (int i=0; i <= lastAddrIndx; ++i)
9184 (*MIB).addOperand(*argOpers[i]);
9186 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9187 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9188 bInstr->memoperands_end());
9190 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9194 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9196 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9200 // private utility function: 64 bit atomics on 32 bit host.
9202 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9203 MachineBasicBlock *MBB,
9208 bool invSrc) const {
9209 // For the atomic bitwise operator, we generate
9210 // thisMBB (instructions are in pairs, except cmpxchg8b)
9211 // ld t1,t2 = [bitinstr.addr]
9213 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9214 // op t5, t6 <- out1, out2, [bitinstr.val]
9215 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
9216 // mov ECX, EBX <- t5, t6
9217 // mov EAX, EDX <- t1, t2
9218 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
9219 // mov t3, t4 <- EAX, EDX
9221 // result in out1, out2
9222 // fallthrough -->nextMBB
9224 const TargetRegisterClass *RC = X86::GR32RegisterClass;
9225 const unsigned LoadOpc = X86::MOV32rm;
9226 const unsigned NotOpc = X86::NOT32r;
9227 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9228 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9229 MachineFunction::iterator MBBIter = MBB;
9232 /// First build the CFG
9233 MachineFunction *F = MBB->getParent();
9234 MachineBasicBlock *thisMBB = MBB;
9235 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9236 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9237 F->insert(MBBIter, newMBB);
9238 F->insert(MBBIter, nextMBB);
9240 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9241 nextMBB->splice(nextMBB->begin(), thisMBB,
9242 llvm::next(MachineBasicBlock::iterator(bInstr)),
9244 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9246 // Update thisMBB to fall through to newMBB
9247 thisMBB->addSuccessor(newMBB);
9249 // newMBB jumps to itself and fall through to nextMBB
9250 newMBB->addSuccessor(nextMBB);
9251 newMBB->addSuccessor(newMBB);
9253 DebugLoc dl = bInstr->getDebugLoc();
9254 // Insert instructions into newMBB based on incoming instruction
9255 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9256 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9257 "unexpected number of operands");
9258 MachineOperand& dest1Oper = bInstr->getOperand(0);
9259 MachineOperand& dest2Oper = bInstr->getOperand(1);
9260 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9261 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9262 argOpers[i] = &bInstr->getOperand(i+2);
9264 // We use some of the operands multiple times, so conservatively just
9265 // clear any kill flags that might be present.
9266 if (argOpers[i]->isReg() && argOpers[i]->isUse())
9267 argOpers[i]->setIsKill(false);
9270 // x86 address has 5 operands: base, index, scale, displacement, and segment.
9271 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9273 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9274 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9275 for (int i=0; i <= lastAddrIndx; ++i)
9276 (*MIB).addOperand(*argOpers[i]);
9277 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9278 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9279 // add 4 to displacement.
9280 for (int i=0; i <= lastAddrIndx-2; ++i)
9281 (*MIB).addOperand(*argOpers[i]);
9282 MachineOperand newOp3 = *(argOpers[3]);
9284 newOp3.setImm(newOp3.getImm()+4);
9286 newOp3.setOffset(newOp3.getOffset()+4);
9287 (*MIB).addOperand(newOp3);
9288 (*MIB).addOperand(*argOpers[lastAddrIndx]);
9290 // t3/4 are defined later, at the bottom of the loop
9291 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9292 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9293 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9294 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9295 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9296 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9298 // The subsequent operations should be using the destination registers of
9299 //the PHI instructions.
9301 t1 = F->getRegInfo().createVirtualRegister(RC);
9302 t2 = F->getRegInfo().createVirtualRegister(RC);
9303 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9304 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9306 t1 = dest1Oper.getReg();
9307 t2 = dest2Oper.getReg();
9310 int valArgIndx = lastAddrIndx + 1;
9311 assert((argOpers[valArgIndx]->isReg() ||
9312 argOpers[valArgIndx]->isImm()) &&
9314 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9315 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9316 if (argOpers[valArgIndx]->isReg())
9317 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9319 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9320 if (regOpcL != X86::MOV32rr)
9322 (*MIB).addOperand(*argOpers[valArgIndx]);
9323 assert(argOpers[valArgIndx + 1]->isReg() ==
9324 argOpers[valArgIndx]->isReg());
9325 assert(argOpers[valArgIndx + 1]->isImm() ==
9326 argOpers[valArgIndx]->isImm());
9327 if (argOpers[valArgIndx + 1]->isReg())
9328 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9330 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9331 if (regOpcH != X86::MOV32rr)
9333 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9335 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9337 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9340 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9342 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9345 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9346 for (int i=0; i <= lastAddrIndx; ++i)
9347 (*MIB).addOperand(*argOpers[i]);
9349 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9350 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9351 bInstr->memoperands_end());
9353 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9354 MIB.addReg(X86::EAX);
9355 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9356 MIB.addReg(X86::EDX);
9359 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9361 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9365 // private utility function
9367 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9368 MachineBasicBlock *MBB,
9369 unsigned cmovOpc) const {
9370 // For the atomic min/max operator, we generate
9373 // ld t1 = [min/max.addr]
9374 // mov t2 = [min/max.val]
9376 // cmov[cond] t2 = t1
9378 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9380 // fallthrough -->nextMBB
9382 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9383 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9384 MachineFunction::iterator MBBIter = MBB;
9387 /// First build the CFG
9388 MachineFunction *F = MBB->getParent();
9389 MachineBasicBlock *thisMBB = MBB;
9390 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9391 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9392 F->insert(MBBIter, newMBB);
9393 F->insert(MBBIter, nextMBB);
9395 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9396 nextMBB->splice(nextMBB->begin(), thisMBB,
9397 llvm::next(MachineBasicBlock::iterator(mInstr)),
9399 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9401 // Update thisMBB to fall through to newMBB
9402 thisMBB->addSuccessor(newMBB);
9404 // newMBB jumps to newMBB and fall through to nextMBB
9405 newMBB->addSuccessor(nextMBB);
9406 newMBB->addSuccessor(newMBB);
9408 DebugLoc dl = mInstr->getDebugLoc();
9409 // Insert instructions into newMBB based on incoming instruction
9410 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9411 "unexpected number of operands");
9412 MachineOperand& destOper = mInstr->getOperand(0);
9413 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9414 int numArgs = mInstr->getNumOperands() - 1;
9415 for (int i=0; i < numArgs; ++i)
9416 argOpers[i] = &mInstr->getOperand(i+1);
9418 // x86 address has 4 operands: base, index, scale, and displacement
9419 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9420 int valArgIndx = lastAddrIndx + 1;
9422 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9423 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9424 for (int i=0; i <= lastAddrIndx; ++i)
9425 (*MIB).addOperand(*argOpers[i]);
9427 // We only support register and immediate values
9428 assert((argOpers[valArgIndx]->isReg() ||
9429 argOpers[valArgIndx]->isImm()) &&
9432 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9433 if (argOpers[valArgIndx]->isReg())
9434 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9436 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9437 (*MIB).addOperand(*argOpers[valArgIndx]);
9439 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9442 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
9447 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9448 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
9452 // Cmp and exchange if none has modified the memory location
9453 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
9454 for (int i=0; i <= lastAddrIndx; ++i)
9455 (*MIB).addOperand(*argOpers[i]);
9457 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9458 (*MIB).setMemRefs(mInstr->memoperands_begin(),
9459 mInstr->memoperands_end());
9461 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9462 MIB.addReg(X86::EAX);
9465 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9467 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
9471 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
9472 // or XMM0_V32I8 in AVX all of this code can be replaced with that
9475 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
9476 unsigned numArgs, bool memArg) const {
9477 assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
9478 "Target must have SSE4.2 or AVX features enabled");
9480 DebugLoc dl = MI->getDebugLoc();
9481 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9483 if (!Subtarget->hasAVX()) {
9485 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
9487 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
9490 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
9492 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
9495 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
9496 for (unsigned i = 0; i < numArgs; ++i) {
9497 MachineOperand &Op = MI->getOperand(i+1);
9498 if (!(Op.isReg() && Op.isImplicit()))
9501 BuildMI(*BB, MI, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
9504 MI->eraseFromParent();
9509 X86TargetLowering::EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB) const {
9510 DebugLoc dl = MI->getDebugLoc();
9511 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9513 // Address into RAX/EAX, other two args into ECX, EDX.
9514 unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
9515 unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
9516 MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
9517 for (int i = 0; i < X86::AddrNumOperands; ++i)
9518 MIB.addOperand(MI->getOperand(i));
9520 unsigned ValOps = X86::AddrNumOperands;
9521 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9522 .addReg(MI->getOperand(ValOps).getReg());
9523 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
9524 .addReg(MI->getOperand(ValOps+1).getReg());
9526 // The instruction doesn't actually take any operands though.
9527 BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
9529 MI->eraseFromParent(); // The pseudo is gone now.
9534 X86TargetLowering::EmitMwait(MachineInstr *MI, MachineBasicBlock *BB) const {
9535 DebugLoc dl = MI->getDebugLoc();
9536 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9538 // First arg in ECX, the second in EAX.
9539 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
9540 .addReg(MI->getOperand(0).getReg());
9541 BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EAX)
9542 .addReg(MI->getOperand(1).getReg());
9544 // The instruction doesn't actually take any operands though.
9545 BuildMI(*BB, MI, dl, TII->get(X86::MWAITrr));
9547 MI->eraseFromParent(); // The pseudo is gone now.
9552 X86TargetLowering::EmitVAARG64WithCustomInserter(
9554 MachineBasicBlock *MBB) const {
9555 // Emit va_arg instruction on X86-64.
9557 // Operands to this pseudo-instruction:
9558 // 0 ) Output : destination address (reg)
9559 // 1-5) Input : va_list address (addr, i64mem)
9560 // 6 ) ArgSize : Size (in bytes) of vararg type
9561 // 7 ) ArgMode : 0=overflow only, 1=use gp_offset, 2=use fp_offset
9562 // 8 ) Align : Alignment of type
9563 // 9 ) EFLAGS (implicit-def)
9565 assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
9566 assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
9568 unsigned DestReg = MI->getOperand(0).getReg();
9569 MachineOperand &Base = MI->getOperand(1);
9570 MachineOperand &Scale = MI->getOperand(2);
9571 MachineOperand &Index = MI->getOperand(3);
9572 MachineOperand &Disp = MI->getOperand(4);
9573 MachineOperand &Segment = MI->getOperand(5);
9574 unsigned ArgSize = MI->getOperand(6).getImm();
9575 unsigned ArgMode = MI->getOperand(7).getImm();
9576 unsigned Align = MI->getOperand(8).getImm();
9579 assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
9580 MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
9581 MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
9583 // Machine Information
9584 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9585 MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
9586 const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
9587 const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
9588 DebugLoc DL = MI->getDebugLoc();
9593 // i64 overflow_area (address)
9594 // i64 reg_save_area (address)
9596 // sizeof(va_list) = 24
9597 // alignment(va_list) = 8
9599 unsigned TotalNumIntRegs = 6;
9600 unsigned TotalNumXMMRegs = 8;
9601 bool UseGPOffset = (ArgMode == 1);
9602 bool UseFPOffset = (ArgMode == 2);
9603 unsigned MaxOffset = TotalNumIntRegs * 8 +
9604 (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
9606 /* Align ArgSize to a multiple of 8 */
9607 unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
9608 bool NeedsAlign = (Align > 8);
9610 MachineBasicBlock *thisMBB = MBB;
9611 MachineBasicBlock *overflowMBB;
9612 MachineBasicBlock *offsetMBB;
9613 MachineBasicBlock *endMBB;
9615 unsigned OffsetDestReg = 0; // Argument address computed by offsetMBB
9616 unsigned OverflowDestReg = 0; // Argument address computed by overflowMBB
9617 unsigned OffsetReg = 0;
9619 if (!UseGPOffset && !UseFPOffset) {
9620 // If we only pull from the overflow region, we don't create a branch.
9621 // We don't need to alter control flow.
9622 OffsetDestReg = 0; // unused
9623 OverflowDestReg = DestReg;
9626 overflowMBB = thisMBB;
9629 // First emit code to check if gp_offset (or fp_offset) is below the bound.
9630 // If so, pull the argument from reg_save_area. (branch to offsetMBB)
9631 // If not, pull from overflow_area. (branch to overflowMBB)
9636 // offsetMBB overflowMBB
9641 // Registers for the PHI in endMBB
9642 OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
9643 OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
9645 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9646 MachineFunction *MF = MBB->getParent();
9647 overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9648 offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9649 endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9651 MachineFunction::iterator MBBIter = MBB;
9654 // Insert the new basic blocks
9655 MF->insert(MBBIter, offsetMBB);
9656 MF->insert(MBBIter, overflowMBB);
9657 MF->insert(MBBIter, endMBB);
9659 // Transfer the remainder of MBB and its successor edges to endMBB.
9660 endMBB->splice(endMBB->begin(), thisMBB,
9661 llvm::next(MachineBasicBlock::iterator(MI)),
9663 endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9665 // Make offsetMBB and overflowMBB successors of thisMBB
9666 thisMBB->addSuccessor(offsetMBB);
9667 thisMBB->addSuccessor(overflowMBB);
9669 // endMBB is a successor of both offsetMBB and overflowMBB
9670 offsetMBB->addSuccessor(endMBB);
9671 overflowMBB->addSuccessor(endMBB);
9673 // Load the offset value into a register
9674 OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
9675 BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
9679 .addDisp(Disp, UseFPOffset ? 4 : 0)
9680 .addOperand(Segment)
9681 .setMemRefs(MMOBegin, MMOEnd);
9683 // Check if there is enough room left to pull this argument.
9684 BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
9686 .addImm(MaxOffset + 8 - ArgSizeA8);
9688 // Branch to "overflowMBB" if offset >= max
9689 // Fall through to "offsetMBB" otherwise
9690 BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
9691 .addMBB(overflowMBB);
9694 // In offsetMBB, emit code to use the reg_save_area.
9696 assert(OffsetReg != 0);
9698 // Read the reg_save_area address.
9699 unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
9700 BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
9705 .addOperand(Segment)
9706 .setMemRefs(MMOBegin, MMOEnd);
9708 // Zero-extend the offset
9709 unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
9710 BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
9713 .addImm(X86::sub_32bit);
9715 // Add the offset to the reg_save_area to get the final address.
9716 BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
9717 .addReg(OffsetReg64)
9718 .addReg(RegSaveReg);
9720 // Compute the offset for the next argument
9721 unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
9722 BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
9724 .addImm(UseFPOffset ? 16 : 8);
9726 // Store it back into the va_list.
9727 BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
9731 .addDisp(Disp, UseFPOffset ? 4 : 0)
9732 .addOperand(Segment)
9733 .addReg(NextOffsetReg)
9734 .setMemRefs(MMOBegin, MMOEnd);
9737 BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
9742 // Emit code to use overflow area
9745 // Load the overflow_area address into a register.
9746 unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
9747 BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
9752 .addOperand(Segment)
9753 .setMemRefs(MMOBegin, MMOEnd);
9755 // If we need to align it, do so. Otherwise, just copy the address
9756 // to OverflowDestReg.
9758 // Align the overflow address
9759 assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
9760 unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
9762 // aligned_addr = (addr + (align-1)) & ~(align-1)
9763 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
9764 .addReg(OverflowAddrReg)
9767 BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
9769 .addImm(~(uint64_t)(Align-1));
9771 BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
9772 .addReg(OverflowAddrReg);
9775 // Compute the next overflow address after this argument.
9776 // (the overflow address should be kept 8-byte aligned)
9777 unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
9778 BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
9779 .addReg(OverflowDestReg)
9782 // Store the new overflow address.
9783 BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
9788 .addOperand(Segment)
9789 .addReg(NextAddrReg)
9790 .setMemRefs(MMOBegin, MMOEnd);
9792 // If we branched, emit the PHI to the front of endMBB.
9794 BuildMI(*endMBB, endMBB->begin(), DL,
9795 TII->get(X86::PHI), DestReg)
9796 .addReg(OffsetDestReg).addMBB(offsetMBB)
9797 .addReg(OverflowDestReg).addMBB(overflowMBB);
9800 // Erase the pseudo instruction
9801 MI->eraseFromParent();
9807 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
9809 MachineBasicBlock *MBB) const {
9810 // Emit code to save XMM registers to the stack. The ABI says that the
9811 // number of registers to save is given in %al, so it's theoretically
9812 // possible to do an indirect jump trick to avoid saving all of them,
9813 // however this code takes a simpler approach and just executes all
9814 // of the stores if %al is non-zero. It's less code, and it's probably
9815 // easier on the hardware branch predictor, and stores aren't all that
9816 // expensive anyway.
9818 // Create the new basic blocks. One block contains all the XMM stores,
9819 // and one block is the final destination regardless of whether any
9820 // stores were performed.
9821 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9822 MachineFunction *F = MBB->getParent();
9823 MachineFunction::iterator MBBIter = MBB;
9825 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
9826 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
9827 F->insert(MBBIter, XMMSaveMBB);
9828 F->insert(MBBIter, EndMBB);
9830 // Transfer the remainder of MBB and its successor edges to EndMBB.
9831 EndMBB->splice(EndMBB->begin(), MBB,
9832 llvm::next(MachineBasicBlock::iterator(MI)),
9834 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
9836 // The original block will now fall through to the XMM save block.
9837 MBB->addSuccessor(XMMSaveMBB);
9838 // The XMMSaveMBB will fall through to the end block.
9839 XMMSaveMBB->addSuccessor(EndMBB);
9841 // Now add the instructions.
9842 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9843 DebugLoc DL = MI->getDebugLoc();
9845 unsigned CountReg = MI->getOperand(0).getReg();
9846 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
9847 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
9849 if (!Subtarget->isTargetWin64()) {
9850 // If %al is 0, branch around the XMM save block.
9851 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
9852 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
9853 MBB->addSuccessor(EndMBB);
9856 // In the XMM save block, save all the XMM argument registers.
9857 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
9858 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
9859 MachineMemOperand *MMO =
9860 F->getMachineMemOperand(
9861 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
9862 MachineMemOperand::MOStore,
9863 /*Size=*/16, /*Align=*/16);
9864 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
9865 .addFrameIndex(RegSaveFrameIndex)
9866 .addImm(/*Scale=*/1)
9867 .addReg(/*IndexReg=*/0)
9868 .addImm(/*Disp=*/Offset)
9869 .addReg(/*Segment=*/0)
9870 .addReg(MI->getOperand(i).getReg())
9871 .addMemOperand(MMO);
9874 MI->eraseFromParent(); // The pseudo instruction is gone now.
9880 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
9881 MachineBasicBlock *BB) const {
9882 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9883 DebugLoc DL = MI->getDebugLoc();
9885 // To "insert" a SELECT_CC instruction, we actually have to insert the
9886 // diamond control-flow pattern. The incoming instruction knows the
9887 // destination vreg to set, the condition code register to branch on, the
9888 // true/false values to select between, and a branch opcode to use.
9889 const BasicBlock *LLVM_BB = BB->getBasicBlock();
9890 MachineFunction::iterator It = BB;
9896 // cmpTY ccX, r1, r2
9898 // fallthrough --> copy0MBB
9899 MachineBasicBlock *thisMBB = BB;
9900 MachineFunction *F = BB->getParent();
9901 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9902 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9903 F->insert(It, copy0MBB);
9904 F->insert(It, sinkMBB);
9906 // If the EFLAGS register isn't dead in the terminator, then claim that it's
9907 // live into the sink and copy blocks.
9908 const MachineFunction *MF = BB->getParent();
9909 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
9910 BitVector ReservedRegs = TRI->getReservedRegs(*MF);
9912 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
9913 const MachineOperand &MO = MI->getOperand(I);
9914 if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
9915 unsigned Reg = MO.getReg();
9916 if (Reg != X86::EFLAGS) continue;
9917 copy0MBB->addLiveIn(Reg);
9918 sinkMBB->addLiveIn(Reg);
9921 // Transfer the remainder of BB and its successor edges to sinkMBB.
9922 sinkMBB->splice(sinkMBB->begin(), BB,
9923 llvm::next(MachineBasicBlock::iterator(MI)),
9925 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9927 // Add the true and fallthrough blocks as its successors.
9928 BB->addSuccessor(copy0MBB);
9929 BB->addSuccessor(sinkMBB);
9931 // Create the conditional branch instruction.
9933 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
9934 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
9937 // %FalseValue = ...
9938 // # fallthrough to sinkMBB
9939 copy0MBB->addSuccessor(sinkMBB);
9942 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9944 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
9945 TII->get(X86::PHI), MI->getOperand(0).getReg())
9946 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
9947 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
9949 MI->eraseFromParent(); // The pseudo instruction is gone now.
9954 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
9955 MachineBasicBlock *BB) const {
9956 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9957 DebugLoc DL = MI->getDebugLoc();
9959 // The lowering is pretty easy: we're just emitting the call to _alloca. The
9960 // non-trivial part is impdef of ESP.
9961 // FIXME: The code should be tweaked as soon as we'll try to do codegen for
9964 const char *StackProbeSymbol =
9965 Subtarget->isTargetWindows() ? "_chkstk" : "_alloca";
9967 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
9968 .addExternalSymbol(StackProbeSymbol)
9969 .addReg(X86::EAX, RegState::Implicit)
9970 .addReg(X86::ESP, RegState::Implicit)
9971 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
9972 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
9973 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
9975 MI->eraseFromParent(); // The pseudo instruction is gone now.
9980 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
9981 MachineBasicBlock *BB) const {
9982 // This is pretty easy. We're taking the value that we received from
9983 // our load from the relocation, sticking it in either RDI (x86-64)
9984 // or EAX and doing an indirect call. The return value will then
9985 // be in the normal return register.
9986 const X86InstrInfo *TII
9987 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
9988 DebugLoc DL = MI->getDebugLoc();
9989 MachineFunction *F = BB->getParent();
9991 assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
9992 assert(MI->getOperand(3).isGlobal() && "This should be a global");
9994 if (Subtarget->is64Bit()) {
9995 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9996 TII->get(X86::MOV64rm), X86::RDI)
9998 .addImm(0).addReg(0)
9999 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10000 MI->getOperand(3).getTargetFlags())
10002 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
10003 addDirectMem(MIB, X86::RDI);
10004 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
10005 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10006 TII->get(X86::MOV32rm), X86::EAX)
10008 .addImm(0).addReg(0)
10009 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10010 MI->getOperand(3).getTargetFlags())
10012 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10013 addDirectMem(MIB, X86::EAX);
10015 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
10016 TII->get(X86::MOV32rm), X86::EAX)
10017 .addReg(TII->getGlobalBaseReg(F))
10018 .addImm(0).addReg(0)
10019 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
10020 MI->getOperand(3).getTargetFlags())
10022 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
10023 addDirectMem(MIB, X86::EAX);
10026 MI->eraseFromParent(); // The pseudo instruction is gone now.
10030 MachineBasicBlock *
10031 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
10032 MachineBasicBlock *BB) const {
10033 switch (MI->getOpcode()) {
10034 default: assert(false && "Unexpected instr type to insert");
10035 case X86::WIN_ALLOCA:
10036 return EmitLoweredWinAlloca(MI, BB);
10037 case X86::TLSCall_32:
10038 case X86::TLSCall_64:
10039 return EmitLoweredTLSCall(MI, BB);
10040 case X86::CMOV_GR8:
10041 case X86::CMOV_FR32:
10042 case X86::CMOV_FR64:
10043 case X86::CMOV_V4F32:
10044 case X86::CMOV_V2F64:
10045 case X86::CMOV_V2I64:
10046 case X86::CMOV_GR16:
10047 case X86::CMOV_GR32:
10048 case X86::CMOV_RFP32:
10049 case X86::CMOV_RFP64:
10050 case X86::CMOV_RFP80:
10051 return EmitLoweredSelect(MI, BB);
10053 case X86::FP32_TO_INT16_IN_MEM:
10054 case X86::FP32_TO_INT32_IN_MEM:
10055 case X86::FP32_TO_INT64_IN_MEM:
10056 case X86::FP64_TO_INT16_IN_MEM:
10057 case X86::FP64_TO_INT32_IN_MEM:
10058 case X86::FP64_TO_INT64_IN_MEM:
10059 case X86::FP80_TO_INT16_IN_MEM:
10060 case X86::FP80_TO_INT32_IN_MEM:
10061 case X86::FP80_TO_INT64_IN_MEM: {
10062 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
10063 DebugLoc DL = MI->getDebugLoc();
10065 // Change the floating point control register to use "round towards zero"
10066 // mode when truncating to an integer value.
10067 MachineFunction *F = BB->getParent();
10068 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
10069 addFrameReference(BuildMI(*BB, MI, DL,
10070 TII->get(X86::FNSTCW16m)), CWFrameIdx);
10072 // Load the old value of the high byte of the control word...
10074 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
10075 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
10078 // Set the high part to be round to zero...
10079 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
10082 // Reload the modified control word now...
10083 addFrameReference(BuildMI(*BB, MI, DL,
10084 TII->get(X86::FLDCW16m)), CWFrameIdx);
10086 // Restore the memory image of control word to original value
10087 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
10090 // Get the X86 opcode to use.
10092 switch (MI->getOpcode()) {
10093 default: llvm_unreachable("illegal opcode!");
10094 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
10095 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
10096 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
10097 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
10098 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
10099 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
10100 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
10101 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
10102 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
10106 MachineOperand &Op = MI->getOperand(0);
10108 AM.BaseType = X86AddressMode::RegBase;
10109 AM.Base.Reg = Op.getReg();
10111 AM.BaseType = X86AddressMode::FrameIndexBase;
10112 AM.Base.FrameIndex = Op.getIndex();
10114 Op = MI->getOperand(1);
10116 AM.Scale = Op.getImm();
10117 Op = MI->getOperand(2);
10119 AM.IndexReg = Op.getImm();
10120 Op = MI->getOperand(3);
10121 if (Op.isGlobal()) {
10122 AM.GV = Op.getGlobal();
10124 AM.Disp = Op.getImm();
10126 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
10127 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
10129 // Reload the original control word now.
10130 addFrameReference(BuildMI(*BB, MI, DL,
10131 TII->get(X86::FLDCW16m)), CWFrameIdx);
10133 MI->eraseFromParent(); // The pseudo instruction is gone now.
10136 // String/text processing lowering.
10137 case X86::PCMPISTRM128REG:
10138 case X86::VPCMPISTRM128REG:
10139 return EmitPCMP(MI, BB, 3, false /* in-mem */);
10140 case X86::PCMPISTRM128MEM:
10141 case X86::VPCMPISTRM128MEM:
10142 return EmitPCMP(MI, BB, 3, true /* in-mem */);
10143 case X86::PCMPESTRM128REG:
10144 case X86::VPCMPESTRM128REG:
10145 return EmitPCMP(MI, BB, 5, false /* in mem */);
10146 case X86::PCMPESTRM128MEM:
10147 case X86::VPCMPESTRM128MEM:
10148 return EmitPCMP(MI, BB, 5, true /* in mem */);
10150 // Thread synchronization.
10152 return EmitMonitor(MI, BB);
10154 return EmitMwait(MI, BB);
10156 // Atomic Lowering.
10157 case X86::ATOMAND32:
10158 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10159 X86::AND32ri, X86::MOV32rm,
10161 X86::NOT32r, X86::EAX,
10162 X86::GR32RegisterClass);
10163 case X86::ATOMOR32:
10164 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
10165 X86::OR32ri, X86::MOV32rm,
10167 X86::NOT32r, X86::EAX,
10168 X86::GR32RegisterClass);
10169 case X86::ATOMXOR32:
10170 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
10171 X86::XOR32ri, X86::MOV32rm,
10173 X86::NOT32r, X86::EAX,
10174 X86::GR32RegisterClass);
10175 case X86::ATOMNAND32:
10176 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
10177 X86::AND32ri, X86::MOV32rm,
10179 X86::NOT32r, X86::EAX,
10180 X86::GR32RegisterClass, true);
10181 case X86::ATOMMIN32:
10182 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
10183 case X86::ATOMMAX32:
10184 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
10185 case X86::ATOMUMIN32:
10186 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
10187 case X86::ATOMUMAX32:
10188 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
10190 case X86::ATOMAND16:
10191 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10192 X86::AND16ri, X86::MOV16rm,
10194 X86::NOT16r, X86::AX,
10195 X86::GR16RegisterClass);
10196 case X86::ATOMOR16:
10197 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
10198 X86::OR16ri, X86::MOV16rm,
10200 X86::NOT16r, X86::AX,
10201 X86::GR16RegisterClass);
10202 case X86::ATOMXOR16:
10203 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
10204 X86::XOR16ri, X86::MOV16rm,
10206 X86::NOT16r, X86::AX,
10207 X86::GR16RegisterClass);
10208 case X86::ATOMNAND16:
10209 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
10210 X86::AND16ri, X86::MOV16rm,
10212 X86::NOT16r, X86::AX,
10213 X86::GR16RegisterClass, true);
10214 case X86::ATOMMIN16:
10215 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
10216 case X86::ATOMMAX16:
10217 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
10218 case X86::ATOMUMIN16:
10219 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
10220 case X86::ATOMUMAX16:
10221 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
10223 case X86::ATOMAND8:
10224 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10225 X86::AND8ri, X86::MOV8rm,
10227 X86::NOT8r, X86::AL,
10228 X86::GR8RegisterClass);
10230 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
10231 X86::OR8ri, X86::MOV8rm,
10233 X86::NOT8r, X86::AL,
10234 X86::GR8RegisterClass);
10235 case X86::ATOMXOR8:
10236 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
10237 X86::XOR8ri, X86::MOV8rm,
10239 X86::NOT8r, X86::AL,
10240 X86::GR8RegisterClass);
10241 case X86::ATOMNAND8:
10242 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
10243 X86::AND8ri, X86::MOV8rm,
10245 X86::NOT8r, X86::AL,
10246 X86::GR8RegisterClass, true);
10247 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
10248 // This group is for 64-bit host.
10249 case X86::ATOMAND64:
10250 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10251 X86::AND64ri32, X86::MOV64rm,
10253 X86::NOT64r, X86::RAX,
10254 X86::GR64RegisterClass);
10255 case X86::ATOMOR64:
10256 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
10257 X86::OR64ri32, X86::MOV64rm,
10259 X86::NOT64r, X86::RAX,
10260 X86::GR64RegisterClass);
10261 case X86::ATOMXOR64:
10262 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
10263 X86::XOR64ri32, X86::MOV64rm,
10265 X86::NOT64r, X86::RAX,
10266 X86::GR64RegisterClass);
10267 case X86::ATOMNAND64:
10268 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
10269 X86::AND64ri32, X86::MOV64rm,
10271 X86::NOT64r, X86::RAX,
10272 X86::GR64RegisterClass, true);
10273 case X86::ATOMMIN64:
10274 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
10275 case X86::ATOMMAX64:
10276 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
10277 case X86::ATOMUMIN64:
10278 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
10279 case X86::ATOMUMAX64:
10280 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
10282 // This group does 64-bit operations on a 32-bit host.
10283 case X86::ATOMAND6432:
10284 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10285 X86::AND32rr, X86::AND32rr,
10286 X86::AND32ri, X86::AND32ri,
10288 case X86::ATOMOR6432:
10289 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10290 X86::OR32rr, X86::OR32rr,
10291 X86::OR32ri, X86::OR32ri,
10293 case X86::ATOMXOR6432:
10294 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10295 X86::XOR32rr, X86::XOR32rr,
10296 X86::XOR32ri, X86::XOR32ri,
10298 case X86::ATOMNAND6432:
10299 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10300 X86::AND32rr, X86::AND32rr,
10301 X86::AND32ri, X86::AND32ri,
10303 case X86::ATOMADD6432:
10304 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10305 X86::ADD32rr, X86::ADC32rr,
10306 X86::ADD32ri, X86::ADC32ri,
10308 case X86::ATOMSUB6432:
10309 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10310 X86::SUB32rr, X86::SBB32rr,
10311 X86::SUB32ri, X86::SBB32ri,
10313 case X86::ATOMSWAP6432:
10314 return EmitAtomicBit6432WithCustomInserter(MI, BB,
10315 X86::MOV32rr, X86::MOV32rr,
10316 X86::MOV32ri, X86::MOV32ri,
10318 case X86::VASTART_SAVE_XMM_REGS:
10319 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
10321 case X86::VAARG_64:
10322 return EmitVAARG64WithCustomInserter(MI, BB);
10326 //===----------------------------------------------------------------------===//
10327 // X86 Optimization Hooks
10328 //===----------------------------------------------------------------------===//
10330 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
10334 const SelectionDAG &DAG,
10335 unsigned Depth) const {
10336 unsigned Opc = Op.getOpcode();
10337 assert((Opc >= ISD::BUILTIN_OP_END ||
10338 Opc == ISD::INTRINSIC_WO_CHAIN ||
10339 Opc == ISD::INTRINSIC_W_CHAIN ||
10340 Opc == ISD::INTRINSIC_VOID) &&
10341 "Should use MaskedValueIsZero if you don't know whether Op"
10342 " is a target node!");
10344 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
10356 // These nodes' second result is a boolean.
10357 if (Op.getResNo() == 0)
10360 case X86ISD::SETCC:
10361 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
10362 Mask.getBitWidth() - 1);
10367 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
10368 unsigned Depth) const {
10369 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
10370 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
10371 return Op.getValueType().getScalarType().getSizeInBits();
10377 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
10378 /// node is a GlobalAddress + offset.
10379 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
10380 const GlobalValue* &GA,
10381 int64_t &Offset) const {
10382 if (N->getOpcode() == X86ISD::Wrapper) {
10383 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
10384 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
10385 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
10389 return TargetLowering::isGAPlusOffset(N, GA, Offset);
10392 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
10393 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
10394 /// if the load addresses are consecutive, non-overlapping, and in the right
10396 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
10397 const TargetLowering &TLI) {
10398 DebugLoc dl = N->getDebugLoc();
10399 EVT VT = N->getValueType(0);
10401 if (VT.getSizeInBits() != 128)
10404 SmallVector<SDValue, 16> Elts;
10405 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
10406 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
10408 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
10411 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
10412 /// generation and convert it from being a bunch of shuffles and extracts
10413 /// to a simple store and scalar loads to extract the elements.
10414 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
10415 const TargetLowering &TLI) {
10416 SDValue InputVector = N->getOperand(0);
10418 // Only operate on vectors of 4 elements, where the alternative shuffling
10419 // gets to be more expensive.
10420 if (InputVector.getValueType() != MVT::v4i32)
10423 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
10424 // single use which is a sign-extend or zero-extend, and all elements are
10426 SmallVector<SDNode *, 4> Uses;
10427 unsigned ExtractedElements = 0;
10428 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
10429 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
10430 if (UI.getUse().getResNo() != InputVector.getResNo())
10433 SDNode *Extract = *UI;
10434 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10437 if (Extract->getValueType(0) != MVT::i32)
10439 if (!Extract->hasOneUse())
10441 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
10442 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
10444 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
10447 // Record which element was extracted.
10448 ExtractedElements |=
10449 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
10451 Uses.push_back(Extract);
10454 // If not all the elements were used, this may not be worthwhile.
10455 if (ExtractedElements != 15)
10458 // Ok, we've now decided to do the transformation.
10459 DebugLoc dl = InputVector.getDebugLoc();
10461 // Store the value to a temporary stack slot.
10462 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
10463 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
10464 MachinePointerInfo(), false, false, 0);
10466 // Replace each use (extract) with a load of the appropriate element.
10467 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
10468 UE = Uses.end(); UI != UE; ++UI) {
10469 SDNode *Extract = *UI;
10471 // Compute the element's address.
10472 SDValue Idx = Extract->getOperand(1);
10474 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
10475 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
10476 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
10478 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(),
10479 StackPtr, OffsetVal);
10481 // Load the scalar.
10482 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
10483 ScalarAddr, MachinePointerInfo(),
10486 // Replace the exact with the load.
10487 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
10490 // The replacement was made in place; don't return anything.
10494 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
10495 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
10496 const X86Subtarget *Subtarget) {
10497 DebugLoc DL = N->getDebugLoc();
10498 SDValue Cond = N->getOperand(0);
10499 // Get the LHS/RHS of the select.
10500 SDValue LHS = N->getOperand(1);
10501 SDValue RHS = N->getOperand(2);
10503 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
10504 // instructions match the semantics of the common C idiom x<y?x:y but not
10505 // x<=y?x:y, because of how they handle negative zero (which can be
10506 // ignored in unsafe-math mode).
10507 if (Subtarget->hasSSE2() &&
10508 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
10509 Cond.getOpcode() == ISD::SETCC) {
10510 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
10512 unsigned Opcode = 0;
10513 // Check for x CC y ? x : y.
10514 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
10515 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
10519 // Converting this to a min would handle NaNs incorrectly, and swapping
10520 // the operands would cause it to handle comparisons between positive
10521 // and negative zero incorrectly.
10522 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10523 if (!UnsafeFPMath &&
10524 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10526 std::swap(LHS, RHS);
10528 Opcode = X86ISD::FMIN;
10531 // Converting this to a min would handle comparisons between positive
10532 // and negative zero incorrectly.
10533 if (!UnsafeFPMath &&
10534 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
10536 Opcode = X86ISD::FMIN;
10539 // Converting this to a min would handle both negative zeros and NaNs
10540 // incorrectly, but we can swap the operands to fix both.
10541 std::swap(LHS, RHS);
10545 Opcode = X86ISD::FMIN;
10549 // Converting this to a max would handle comparisons between positive
10550 // and negative zero incorrectly.
10551 if (!UnsafeFPMath &&
10552 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
10554 Opcode = X86ISD::FMAX;
10557 // Converting this to a max would handle NaNs incorrectly, and swapping
10558 // the operands would cause it to handle comparisons between positive
10559 // and negative zero incorrectly.
10560 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10561 if (!UnsafeFPMath &&
10562 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10564 std::swap(LHS, RHS);
10566 Opcode = X86ISD::FMAX;
10569 // Converting this to a max would handle both negative zeros and NaNs
10570 // incorrectly, but we can swap the operands to fix both.
10571 std::swap(LHS, RHS);
10575 Opcode = X86ISD::FMAX;
10578 // Check for x CC y ? y : x -- a min/max with reversed arms.
10579 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
10580 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
10584 // Converting this to a min would handle comparisons between positive
10585 // and negative zero incorrectly, and swapping the operands would
10586 // cause it to handle NaNs incorrectly.
10587 if (!UnsafeFPMath &&
10588 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
10589 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10591 std::swap(LHS, RHS);
10593 Opcode = X86ISD::FMIN;
10596 // Converting this to a min would handle NaNs incorrectly.
10597 if (!UnsafeFPMath &&
10598 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
10600 Opcode = X86ISD::FMIN;
10603 // Converting this to a min would handle both negative zeros and NaNs
10604 // incorrectly, but we can swap the operands to fix both.
10605 std::swap(LHS, RHS);
10609 Opcode = X86ISD::FMIN;
10613 // Converting this to a max would handle NaNs incorrectly.
10614 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10616 Opcode = X86ISD::FMAX;
10619 // Converting this to a max would handle comparisons between positive
10620 // and negative zero incorrectly, and swapping the operands would
10621 // cause it to handle NaNs incorrectly.
10622 if (!UnsafeFPMath &&
10623 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
10624 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10626 std::swap(LHS, RHS);
10628 Opcode = X86ISD::FMAX;
10631 // Converting this to a max would handle both negative zeros and NaNs
10632 // incorrectly, but we can swap the operands to fix both.
10633 std::swap(LHS, RHS);
10637 Opcode = X86ISD::FMAX;
10643 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
10646 // If this is a select between two integer constants, try to do some
10648 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
10649 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
10650 // Don't do this for crazy integer types.
10651 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
10652 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
10653 // so that TrueC (the true value) is larger than FalseC.
10654 bool NeedsCondInvert = false;
10656 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
10657 // Efficiently invertible.
10658 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
10659 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
10660 isa<ConstantSDNode>(Cond.getOperand(1))))) {
10661 NeedsCondInvert = true;
10662 std::swap(TrueC, FalseC);
10665 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
10666 if (FalseC->getAPIntValue() == 0 &&
10667 TrueC->getAPIntValue().isPowerOf2()) {
10668 if (NeedsCondInvert) // Invert the condition if needed.
10669 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10670 DAG.getConstant(1, Cond.getValueType()));
10672 // Zero extend the condition if needed.
10673 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
10675 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10676 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
10677 DAG.getConstant(ShAmt, MVT::i8));
10680 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
10681 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10682 if (NeedsCondInvert) // Invert the condition if needed.
10683 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10684 DAG.getConstant(1, Cond.getValueType()));
10686 // Zero extend the condition if needed.
10687 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10688 FalseC->getValueType(0), Cond);
10689 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10690 SDValue(FalseC, 0));
10693 // Optimize cases that will turn into an LEA instruction. This requires
10694 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10695 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10696 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10697 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10699 bool isFastMultiplier = false;
10701 switch ((unsigned char)Diff) {
10703 case 1: // result = add base, cond
10704 case 2: // result = lea base( , cond*2)
10705 case 3: // result = lea base(cond, cond*2)
10706 case 4: // result = lea base( , cond*4)
10707 case 5: // result = lea base(cond, cond*4)
10708 case 8: // result = lea base( , cond*8)
10709 case 9: // result = lea base(cond, cond*8)
10710 isFastMultiplier = true;
10715 if (isFastMultiplier) {
10716 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10717 if (NeedsCondInvert) // Invert the condition if needed.
10718 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10719 DAG.getConstant(1, Cond.getValueType()));
10721 // Zero extend the condition if needed.
10722 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10724 // Scale the condition by the difference.
10726 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10727 DAG.getConstant(Diff, Cond.getValueType()));
10729 // Add the base if non-zero.
10730 if (FalseC->getAPIntValue() != 0)
10731 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10732 SDValue(FalseC, 0));
10742 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
10743 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
10744 TargetLowering::DAGCombinerInfo &DCI) {
10745 DebugLoc DL = N->getDebugLoc();
10747 // If the flag operand isn't dead, don't touch this CMOV.
10748 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
10751 // If this is a select between two integer constants, try to do some
10752 // optimizations. Note that the operands are ordered the opposite of SELECT
10754 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
10755 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10756 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
10757 // larger than FalseC (the false value).
10758 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
10760 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
10761 CC = X86::GetOppositeBranchCondition(CC);
10762 std::swap(TrueC, FalseC);
10765 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
10766 // This is efficient for any integer data type (including i8/i16) and
10768 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
10769 SDValue Cond = N->getOperand(3);
10770 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10771 DAG.getConstant(CC, MVT::i8), Cond);
10773 // Zero extend the condition if needed.
10774 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
10776 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10777 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
10778 DAG.getConstant(ShAmt, MVT::i8));
10779 if (N->getNumValues() == 2) // Dead flag value?
10780 return DCI.CombineTo(N, Cond, SDValue());
10784 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
10785 // for any integer data type, including i8/i16.
10786 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10787 SDValue Cond = N->getOperand(3);
10788 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10789 DAG.getConstant(CC, MVT::i8), Cond);
10791 // Zero extend the condition if needed.
10792 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10793 FalseC->getValueType(0), Cond);
10794 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10795 SDValue(FalseC, 0));
10797 if (N->getNumValues() == 2) // Dead flag value?
10798 return DCI.CombineTo(N, Cond, SDValue());
10802 // Optimize cases that will turn into an LEA instruction. This requires
10803 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10804 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10805 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10806 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10808 bool isFastMultiplier = false;
10810 switch ((unsigned char)Diff) {
10812 case 1: // result = add base, cond
10813 case 2: // result = lea base( , cond*2)
10814 case 3: // result = lea base(cond, cond*2)
10815 case 4: // result = lea base( , cond*4)
10816 case 5: // result = lea base(cond, cond*4)
10817 case 8: // result = lea base( , cond*8)
10818 case 9: // result = lea base(cond, cond*8)
10819 isFastMultiplier = true;
10824 if (isFastMultiplier) {
10825 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10826 SDValue Cond = N->getOperand(3);
10827 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10828 DAG.getConstant(CC, MVT::i8), Cond);
10829 // Zero extend the condition if needed.
10830 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10832 // Scale the condition by the difference.
10834 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10835 DAG.getConstant(Diff, Cond.getValueType()));
10837 // Add the base if non-zero.
10838 if (FalseC->getAPIntValue() != 0)
10839 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10840 SDValue(FalseC, 0));
10841 if (N->getNumValues() == 2) // Dead flag value?
10842 return DCI.CombineTo(N, Cond, SDValue());
10852 /// PerformMulCombine - Optimize a single multiply with constant into two
10853 /// in order to implement it with two cheaper instructions, e.g.
10854 /// LEA + SHL, LEA + LEA.
10855 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
10856 TargetLowering::DAGCombinerInfo &DCI) {
10857 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10860 EVT VT = N->getValueType(0);
10861 if (VT != MVT::i64)
10864 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10867 uint64_t MulAmt = C->getZExtValue();
10868 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
10871 uint64_t MulAmt1 = 0;
10872 uint64_t MulAmt2 = 0;
10873 if ((MulAmt % 9) == 0) {
10875 MulAmt2 = MulAmt / 9;
10876 } else if ((MulAmt % 5) == 0) {
10878 MulAmt2 = MulAmt / 5;
10879 } else if ((MulAmt % 3) == 0) {
10881 MulAmt2 = MulAmt / 3;
10884 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
10885 DebugLoc DL = N->getDebugLoc();
10887 if (isPowerOf2_64(MulAmt2) &&
10888 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
10889 // If second multiplifer is pow2, issue it first. We want the multiply by
10890 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
10892 std::swap(MulAmt1, MulAmt2);
10895 if (isPowerOf2_64(MulAmt1))
10896 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
10897 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
10899 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
10900 DAG.getConstant(MulAmt1, VT));
10902 if (isPowerOf2_64(MulAmt2))
10903 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
10904 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
10906 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
10907 DAG.getConstant(MulAmt2, VT));
10909 // Do not add new nodes to DAG combiner worklist.
10910 DCI.CombineTo(N, NewMul, false);
10915 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
10916 SDValue N0 = N->getOperand(0);
10917 SDValue N1 = N->getOperand(1);
10918 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
10919 EVT VT = N0.getValueType();
10921 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
10922 // since the result of setcc_c is all zero's or all ones.
10923 if (N1C && N0.getOpcode() == ISD::AND &&
10924 N0.getOperand(1).getOpcode() == ISD::Constant) {
10925 SDValue N00 = N0.getOperand(0);
10926 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
10927 ((N00.getOpcode() == ISD::ANY_EXTEND ||
10928 N00.getOpcode() == ISD::ZERO_EXTEND) &&
10929 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
10930 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
10931 APInt ShAmt = N1C->getAPIntValue();
10932 Mask = Mask.shl(ShAmt);
10934 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
10935 N00, DAG.getConstant(Mask, VT));
10942 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
10944 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
10945 const X86Subtarget *Subtarget) {
10946 EVT VT = N->getValueType(0);
10947 if (!VT.isVector() && VT.isInteger() &&
10948 N->getOpcode() == ISD::SHL)
10949 return PerformSHLCombine(N, DAG);
10951 // On X86 with SSE2 support, we can transform this to a vector shift if
10952 // all elements are shifted by the same amount. We can't do this in legalize
10953 // because the a constant vector is typically transformed to a constant pool
10954 // so we have no knowledge of the shift amount.
10955 if (!Subtarget->hasSSE2())
10958 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
10961 SDValue ShAmtOp = N->getOperand(1);
10962 EVT EltVT = VT.getVectorElementType();
10963 DebugLoc DL = N->getDebugLoc();
10964 SDValue BaseShAmt = SDValue();
10965 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
10966 unsigned NumElts = VT.getVectorNumElements();
10968 for (; i != NumElts; ++i) {
10969 SDValue Arg = ShAmtOp.getOperand(i);
10970 if (Arg.getOpcode() == ISD::UNDEF) continue;
10974 for (; i != NumElts; ++i) {
10975 SDValue Arg = ShAmtOp.getOperand(i);
10976 if (Arg.getOpcode() == ISD::UNDEF) continue;
10977 if (Arg != BaseShAmt) {
10981 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
10982 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
10983 SDValue InVec = ShAmtOp.getOperand(0);
10984 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
10985 unsigned NumElts = InVec.getValueType().getVectorNumElements();
10987 for (; i != NumElts; ++i) {
10988 SDValue Arg = InVec.getOperand(i);
10989 if (Arg.getOpcode() == ISD::UNDEF) continue;
10993 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
10994 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
10995 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
10996 if (C->getZExtValue() == SplatIdx)
10997 BaseShAmt = InVec.getOperand(1);
11000 if (BaseShAmt.getNode() == 0)
11001 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
11002 DAG.getIntPtrConstant(0));
11006 // The shift amount is an i32.
11007 if (EltVT.bitsGT(MVT::i32))
11008 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
11009 else if (EltVT.bitsLT(MVT::i32))
11010 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
11012 // The shift amount is identical so we can do a vector shift.
11013 SDValue ValOp = N->getOperand(0);
11014 switch (N->getOpcode()) {
11016 llvm_unreachable("Unknown shift opcode!");
11019 if (VT == MVT::v2i64)
11020 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11021 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
11023 if (VT == MVT::v4i32)
11024 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11025 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
11027 if (VT == MVT::v8i16)
11028 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11029 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
11033 if (VT == MVT::v4i32)
11034 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11035 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
11037 if (VT == MVT::v8i16)
11038 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11039 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
11043 if (VT == MVT::v2i64)
11044 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11045 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
11047 if (VT == MVT::v4i32)
11048 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11049 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
11051 if (VT == MVT::v8i16)
11052 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
11053 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
11061 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
11062 TargetLowering::DAGCombinerInfo &DCI,
11063 const X86Subtarget *Subtarget) {
11064 if (DCI.isBeforeLegalizeOps())
11067 // Want to form PANDN nodes, in the hopes of then easily combining them with
11068 // OR and AND nodes to form PBLEND/PSIGN.
11069 EVT VT = N->getValueType(0);
11070 if (VT != MVT::v2i64)
11073 SDValue N0 = N->getOperand(0);
11074 SDValue N1 = N->getOperand(1);
11075 DebugLoc DL = N->getDebugLoc();
11077 // Check LHS for vnot
11078 if (N0.getOpcode() == ISD::XOR &&
11079 ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
11080 return DAG.getNode(X86ISD::PANDN, DL, VT, N0.getOperand(0), N1);
11082 // Check RHS for vnot
11083 if (N1.getOpcode() == ISD::XOR &&
11084 ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
11085 return DAG.getNode(X86ISD::PANDN, DL, VT, N1.getOperand(0), N0);
11090 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
11091 TargetLowering::DAGCombinerInfo &DCI,
11092 const X86Subtarget *Subtarget) {
11093 if (DCI.isBeforeLegalizeOps())
11096 EVT VT = N->getValueType(0);
11097 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64 && VT != MVT::v2i64)
11100 SDValue N0 = N->getOperand(0);
11101 SDValue N1 = N->getOperand(1);
11103 // look for psign/blend
11104 if (Subtarget->hasSSSE3()) {
11105 if (VT == MVT::v2i64) {
11106 // Canonicalize pandn to RHS
11107 if (N0.getOpcode() == X86ISD::PANDN)
11109 // or (and (m, x), (pandn m, y))
11110 if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::PANDN) {
11111 SDValue Mask = N1.getOperand(0);
11112 SDValue X = N1.getOperand(1);
11114 if (N0.getOperand(0) == Mask)
11115 Y = N0.getOperand(1);
11116 if (N0.getOperand(1) == Mask)
11117 Y = N0.getOperand(0);
11119 // Check to see if the mask appeared in both the AND and PANDN and
11123 // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
11124 if (Mask.getOpcode() != ISD::BITCAST ||
11125 X.getOpcode() != ISD::BITCAST ||
11126 Y.getOpcode() != ISD::BITCAST)
11129 // Look through mask bitcast.
11130 Mask = Mask.getOperand(0);
11131 EVT MaskVT = Mask.getValueType();
11133 // Validate that the Mask operand is a vector sra node. The sra node
11134 // will be an intrinsic.
11135 if (Mask.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
11138 // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
11139 // there is no psrai.b
11140 switch (cast<ConstantSDNode>(Mask.getOperand(0))->getZExtValue()) {
11141 case Intrinsic::x86_sse2_psrai_w:
11142 case Intrinsic::x86_sse2_psrai_d:
11144 default: return SDValue();
11147 // Check that the SRA is all signbits.
11148 SDValue SraC = Mask.getOperand(2);
11149 unsigned SraAmt = cast<ConstantSDNode>(SraC)->getZExtValue();
11150 unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
11151 if ((SraAmt + 1) != EltBits)
11154 DebugLoc DL = N->getDebugLoc();
11156 // Now we know we at least have a plendvb with the mask val. See if
11157 // we can form a psignb/w/d.
11158 // psign = x.type == y.type == mask.type && y = sub(0, x);
11159 X = X.getOperand(0);
11160 Y = Y.getOperand(0);
11161 if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
11162 ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
11163 X.getValueType() == MaskVT && X.getValueType() == Y.getValueType()){
11166 case 8: Opc = X86ISD::PSIGNB; break;
11167 case 16: Opc = X86ISD::PSIGNW; break;
11168 case 32: Opc = X86ISD::PSIGND; break;
11172 SDValue Sign = DAG.getNode(Opc, DL, MaskVT, X, Mask.getOperand(1));
11173 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Sign);
11176 // PBLENDVB only available on SSE 4.1
11177 if (!Subtarget->hasSSE41())
11180 unsigned IID = Intrinsic::x86_sse41_pblendvb;
11181 X = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, X);
11182 Y = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Y);
11183 Mask = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Mask);
11184 Mask = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::v16i8,
11185 DAG.getConstant(IID, MVT::i32), X, Y, Mask);
11186 return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, Mask);
11191 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
11192 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
11194 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
11196 if (!N0.hasOneUse() || !N1.hasOneUse())
11199 SDValue ShAmt0 = N0.getOperand(1);
11200 if (ShAmt0.getValueType() != MVT::i8)
11202 SDValue ShAmt1 = N1.getOperand(1);
11203 if (ShAmt1.getValueType() != MVT::i8)
11205 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
11206 ShAmt0 = ShAmt0.getOperand(0);
11207 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
11208 ShAmt1 = ShAmt1.getOperand(0);
11210 DebugLoc DL = N->getDebugLoc();
11211 unsigned Opc = X86ISD::SHLD;
11212 SDValue Op0 = N0.getOperand(0);
11213 SDValue Op1 = N1.getOperand(0);
11214 if (ShAmt0.getOpcode() == ISD::SUB) {
11215 Opc = X86ISD::SHRD;
11216 std::swap(Op0, Op1);
11217 std::swap(ShAmt0, ShAmt1);
11220 unsigned Bits = VT.getSizeInBits();
11221 if (ShAmt1.getOpcode() == ISD::SUB) {
11222 SDValue Sum = ShAmt1.getOperand(0);
11223 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
11224 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
11225 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
11226 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
11227 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
11228 return DAG.getNode(Opc, DL, VT,
11230 DAG.getNode(ISD::TRUNCATE, DL,
11233 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
11234 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
11236 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
11237 return DAG.getNode(Opc, DL, VT,
11238 N0.getOperand(0), N1.getOperand(0),
11239 DAG.getNode(ISD::TRUNCATE, DL,
11246 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
11247 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
11248 const X86Subtarget *Subtarget) {
11249 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
11250 // the FP state in cases where an emms may be missing.
11251 // A preferable solution to the general problem is to figure out the right
11252 // places to insert EMMS. This qualifies as a quick hack.
11254 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
11255 StoreSDNode *St = cast<StoreSDNode>(N);
11256 EVT VT = St->getValue().getValueType();
11257 if (VT.getSizeInBits() != 64)
11260 const Function *F = DAG.getMachineFunction().getFunction();
11261 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
11262 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
11263 && Subtarget->hasSSE2();
11264 if ((VT.isVector() ||
11265 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
11266 isa<LoadSDNode>(St->getValue()) &&
11267 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
11268 St->getChain().hasOneUse() && !St->isVolatile()) {
11269 SDNode* LdVal = St->getValue().getNode();
11270 LoadSDNode *Ld = 0;
11271 int TokenFactorIndex = -1;
11272 SmallVector<SDValue, 8> Ops;
11273 SDNode* ChainVal = St->getChain().getNode();
11274 // Must be a store of a load. We currently handle two cases: the load
11275 // is a direct child, and it's under an intervening TokenFactor. It is
11276 // possible to dig deeper under nested TokenFactors.
11277 if (ChainVal == LdVal)
11278 Ld = cast<LoadSDNode>(St->getChain());
11279 else if (St->getValue().hasOneUse() &&
11280 ChainVal->getOpcode() == ISD::TokenFactor) {
11281 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
11282 if (ChainVal->getOperand(i).getNode() == LdVal) {
11283 TokenFactorIndex = i;
11284 Ld = cast<LoadSDNode>(St->getValue());
11286 Ops.push_back(ChainVal->getOperand(i));
11290 if (!Ld || !ISD::isNormalLoad(Ld))
11293 // If this is not the MMX case, i.e. we are just turning i64 load/store
11294 // into f64 load/store, avoid the transformation if there are multiple
11295 // uses of the loaded value.
11296 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
11299 DebugLoc LdDL = Ld->getDebugLoc();
11300 DebugLoc StDL = N->getDebugLoc();
11301 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
11302 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
11304 if (Subtarget->is64Bit() || F64IsLegal) {
11305 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
11306 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
11307 Ld->getPointerInfo(), Ld->isVolatile(),
11308 Ld->isNonTemporal(), Ld->getAlignment());
11309 SDValue NewChain = NewLd.getValue(1);
11310 if (TokenFactorIndex != -1) {
11311 Ops.push_back(NewChain);
11312 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11315 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
11316 St->getPointerInfo(),
11317 St->isVolatile(), St->isNonTemporal(),
11318 St->getAlignment());
11321 // Otherwise, lower to two pairs of 32-bit loads / stores.
11322 SDValue LoAddr = Ld->getBasePtr();
11323 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
11324 DAG.getConstant(4, MVT::i32));
11326 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
11327 Ld->getPointerInfo(),
11328 Ld->isVolatile(), Ld->isNonTemporal(),
11329 Ld->getAlignment());
11330 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
11331 Ld->getPointerInfo().getWithOffset(4),
11332 Ld->isVolatile(), Ld->isNonTemporal(),
11333 MinAlign(Ld->getAlignment(), 4));
11335 SDValue NewChain = LoLd.getValue(1);
11336 if (TokenFactorIndex != -1) {
11337 Ops.push_back(LoLd);
11338 Ops.push_back(HiLd);
11339 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
11343 LoAddr = St->getBasePtr();
11344 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
11345 DAG.getConstant(4, MVT::i32));
11347 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
11348 St->getPointerInfo(),
11349 St->isVolatile(), St->isNonTemporal(),
11350 St->getAlignment());
11351 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
11352 St->getPointerInfo().getWithOffset(4),
11354 St->isNonTemporal(),
11355 MinAlign(St->getAlignment(), 4));
11356 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
11361 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
11362 /// X86ISD::FXOR nodes.
11363 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
11364 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
11365 // F[X]OR(0.0, x) -> x
11366 // F[X]OR(x, 0.0) -> x
11367 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11368 if (C->getValueAPF().isPosZero())
11369 return N->getOperand(1);
11370 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11371 if (C->getValueAPF().isPosZero())
11372 return N->getOperand(0);
11376 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
11377 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
11378 // FAND(0.0, x) -> 0.0
11379 // FAND(x, 0.0) -> 0.0
11380 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
11381 if (C->getValueAPF().isPosZero())
11382 return N->getOperand(0);
11383 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
11384 if (C->getValueAPF().isPosZero())
11385 return N->getOperand(1);
11389 static SDValue PerformBTCombine(SDNode *N,
11391 TargetLowering::DAGCombinerInfo &DCI) {
11392 // BT ignores high bits in the bit index operand.
11393 SDValue Op1 = N->getOperand(1);
11394 if (Op1.hasOneUse()) {
11395 unsigned BitWidth = Op1.getValueSizeInBits();
11396 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
11397 APInt KnownZero, KnownOne;
11398 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
11399 !DCI.isBeforeLegalizeOps());
11400 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11401 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
11402 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
11403 DCI.CommitTargetLoweringOpt(TLO);
11408 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
11409 SDValue Op = N->getOperand(0);
11410 if (Op.getOpcode() == ISD::BITCAST)
11411 Op = Op.getOperand(0);
11412 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
11413 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
11414 VT.getVectorElementType().getSizeInBits() ==
11415 OpVT.getVectorElementType().getSizeInBits()) {
11416 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, Op);
11421 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
11422 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
11423 // (and (i32 x86isd::setcc_carry), 1)
11424 // This eliminates the zext. This transformation is necessary because
11425 // ISD::SETCC is always legalized to i8.
11426 DebugLoc dl = N->getDebugLoc();
11427 SDValue N0 = N->getOperand(0);
11428 EVT VT = N->getValueType(0);
11429 if (N0.getOpcode() == ISD::AND &&
11431 N0.getOperand(0).hasOneUse()) {
11432 SDValue N00 = N0.getOperand(0);
11433 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
11435 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
11436 if (!C || C->getZExtValue() != 1)
11438 return DAG.getNode(ISD::AND, dl, VT,
11439 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
11440 N00.getOperand(0), N00.getOperand(1)),
11441 DAG.getConstant(1, VT));
11447 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
11448 DAGCombinerInfo &DCI) const {
11449 SelectionDAG &DAG = DCI.DAG;
11450 switch (N->getOpcode()) {
11452 case ISD::EXTRACT_VECTOR_ELT:
11453 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
11454 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
11455 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
11456 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
11459 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
11460 case ISD::AND: return PerformAndCombine(N, DAG, DCI, Subtarget);
11461 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
11462 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
11464 case X86ISD::FOR: return PerformFORCombine(N, DAG);
11465 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
11466 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
11467 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
11468 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
11469 case X86ISD::SHUFPS: // Handle all target specific shuffles
11470 case X86ISD::SHUFPD:
11471 case X86ISD::PALIGN:
11472 case X86ISD::PUNPCKHBW:
11473 case X86ISD::PUNPCKHWD:
11474 case X86ISD::PUNPCKHDQ:
11475 case X86ISD::PUNPCKHQDQ:
11476 case X86ISD::UNPCKHPS:
11477 case X86ISD::UNPCKHPD:
11478 case X86ISD::PUNPCKLBW:
11479 case X86ISD::PUNPCKLWD:
11480 case X86ISD::PUNPCKLDQ:
11481 case X86ISD::PUNPCKLQDQ:
11482 case X86ISD::UNPCKLPS:
11483 case X86ISD::UNPCKLPD:
11484 case X86ISD::MOVHLPS:
11485 case X86ISD::MOVLHPS:
11486 case X86ISD::PSHUFD:
11487 case X86ISD::PSHUFHW:
11488 case X86ISD::PSHUFLW:
11489 case X86ISD::MOVSS:
11490 case X86ISD::MOVSD:
11491 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
11497 /// isTypeDesirableForOp - Return true if the target has native support for
11498 /// the specified value type and it is 'desirable' to use the type for the
11499 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
11500 /// instruction encodings are longer and some i16 instructions are slow.
11501 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
11502 if (!isTypeLegal(VT))
11504 if (VT != MVT::i16)
11511 case ISD::SIGN_EXTEND:
11512 case ISD::ZERO_EXTEND:
11513 case ISD::ANY_EXTEND:
11526 /// IsDesirableToPromoteOp - This method query the target whether it is
11527 /// beneficial for dag combiner to promote the specified node. If true, it
11528 /// should return the desired promotion type by reference.
11529 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
11530 EVT VT = Op.getValueType();
11531 if (VT != MVT::i16)
11534 bool Promote = false;
11535 bool Commute = false;
11536 switch (Op.getOpcode()) {
11539 LoadSDNode *LD = cast<LoadSDNode>(Op);
11540 // If the non-extending load has a single use and it's not live out, then it
11541 // might be folded.
11542 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
11543 Op.hasOneUse()*/) {
11544 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11545 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
11546 // The only case where we'd want to promote LOAD (rather then it being
11547 // promoted as an operand is when it's only use is liveout.
11548 if (UI->getOpcode() != ISD::CopyToReg)
11555 case ISD::SIGN_EXTEND:
11556 case ISD::ZERO_EXTEND:
11557 case ISD::ANY_EXTEND:
11562 SDValue N0 = Op.getOperand(0);
11563 // Look out for (store (shl (load), x)).
11564 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
11577 SDValue N0 = Op.getOperand(0);
11578 SDValue N1 = Op.getOperand(1);
11579 if (!Commute && MayFoldLoad(N1))
11581 // Avoid disabling potential load folding opportunities.
11582 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
11584 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
11594 //===----------------------------------------------------------------------===//
11595 // X86 Inline Assembly Support
11596 //===----------------------------------------------------------------------===//
11598 static bool LowerToBSwap(CallInst *CI) {
11599 // FIXME: this should verify that we are targetting a 486 or better. If not,
11600 // we will turn this bswap into something that will be lowered to logical ops
11601 // instead of emitting the bswap asm. For now, we don't support 486 or lower
11602 // so don't worry about this.
11604 // Verify this is a simple bswap.
11605 if (CI->getNumArgOperands() != 1 ||
11606 CI->getType() != CI->getArgOperand(0)->getType() ||
11607 !CI->getType()->isIntegerTy())
11610 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11611 if (!Ty || Ty->getBitWidth() % 16 != 0)
11614 // Okay, we can do this xform, do so now.
11615 const Type *Tys[] = { Ty };
11616 Module *M = CI->getParent()->getParent()->getParent();
11617 Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
11619 Value *Op = CI->getArgOperand(0);
11620 Op = CallInst::Create(Int, Op, CI->getName(), CI);
11622 CI->replaceAllUsesWith(Op);
11623 CI->eraseFromParent();
11627 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
11628 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
11629 InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
11631 std::string AsmStr = IA->getAsmString();
11633 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
11634 SmallVector<StringRef, 4> AsmPieces;
11635 SplitString(AsmStr, AsmPieces, ";\n");
11637 switch (AsmPieces.size()) {
11638 default: return false;
11640 AsmStr = AsmPieces[0];
11642 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
11645 if (AsmPieces.size() == 2 &&
11646 (AsmPieces[0] == "bswap" ||
11647 AsmPieces[0] == "bswapq" ||
11648 AsmPieces[0] == "bswapl") &&
11649 (AsmPieces[1] == "$0" ||
11650 AsmPieces[1] == "${0:q}")) {
11651 // No need to check constraints, nothing other than the equivalent of
11652 // "=r,0" would be valid here.
11653 return LowerToBSwap(CI);
11655 // rorw $$8, ${0:w} --> llvm.bswap.i16
11656 if (CI->getType()->isIntegerTy(16) &&
11657 AsmPieces.size() == 3 &&
11658 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
11659 AsmPieces[1] == "$$8," &&
11660 AsmPieces[2] == "${0:w}" &&
11661 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
11663 const std::string &Constraints = IA->getConstraintString();
11664 SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
11665 std::sort(AsmPieces.begin(), AsmPieces.end());
11666 if (AsmPieces.size() == 4 &&
11667 AsmPieces[0] == "~{cc}" &&
11668 AsmPieces[1] == "~{dirflag}" &&
11669 AsmPieces[2] == "~{flags}" &&
11670 AsmPieces[3] == "~{fpsr}") {
11671 return LowerToBSwap(CI);
11676 if (CI->getType()->isIntegerTy(32) &&
11677 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
11678 SmallVector<StringRef, 4> Words;
11679 SplitString(AsmPieces[0], Words, " \t,");
11680 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
11681 Words[2] == "${0:w}") {
11683 SplitString(AsmPieces[1], Words, " \t,");
11684 if (Words.size() == 3 && Words[0] == "rorl" && Words[1] == "$$16" &&
11685 Words[2] == "$0") {
11687 SplitString(AsmPieces[2], Words, " \t,");
11688 if (Words.size() == 3 && Words[0] == "rorw" && Words[1] == "$$8" &&
11689 Words[2] == "${0:w}") {
11691 const std::string &Constraints = IA->getConstraintString();
11692 SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
11693 std::sort(AsmPieces.begin(), AsmPieces.end());
11694 if (AsmPieces.size() == 4 &&
11695 AsmPieces[0] == "~{cc}" &&
11696 AsmPieces[1] == "~{dirflag}" &&
11697 AsmPieces[2] == "~{flags}" &&
11698 AsmPieces[3] == "~{fpsr}") {
11699 return LowerToBSwap(CI);
11705 if (CI->getType()->isIntegerTy(64) &&
11706 Constraints.size() >= 2 &&
11707 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
11708 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
11709 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
11710 SmallVector<StringRef, 4> Words;
11711 SplitString(AsmPieces[0], Words, " \t");
11712 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
11714 SplitString(AsmPieces[1], Words, " \t");
11715 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
11717 SplitString(AsmPieces[2], Words, " \t,");
11718 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
11719 Words[2] == "%edx") {
11720 return LowerToBSwap(CI);
11732 /// getConstraintType - Given a constraint letter, return the type of
11733 /// constraint it is for this target.
11734 X86TargetLowering::ConstraintType
11735 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
11736 if (Constraint.size() == 1) {
11737 switch (Constraint[0]) {
11747 return C_RegisterClass;
11771 return TargetLowering::getConstraintType(Constraint);
11774 /// Examine constraint type and operand type and determine a weight value.
11775 /// This object must already have been set up with the operand type
11776 /// and the current alternative constraint selected.
11777 TargetLowering::ConstraintWeight
11778 X86TargetLowering::getSingleConstraintMatchWeight(
11779 AsmOperandInfo &info, const char *constraint) const {
11780 ConstraintWeight weight = CW_Invalid;
11781 Value *CallOperandVal = info.CallOperandVal;
11782 // If we don't have a value, we can't do a match,
11783 // but allow it at the lowest weight.
11784 if (CallOperandVal == NULL)
11786 const Type *type = CallOperandVal->getType();
11787 // Look at the constraint type.
11788 switch (*constraint) {
11790 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11801 if (CallOperandVal->getType()->isIntegerTy())
11802 weight = CW_SpecificReg;
11807 if (type->isFloatingPointTy())
11808 weight = CW_SpecificReg;
11811 if (type->isX86_MMXTy() && !DisableMMX && Subtarget->hasMMX())
11812 weight = CW_SpecificReg;
11816 if ((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasXMM())
11817 weight = CW_Register;
11820 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
11821 if (C->getZExtValue() <= 31)
11822 weight = CW_Constant;
11826 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11827 if (C->getZExtValue() <= 63)
11828 weight = CW_Constant;
11832 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11833 if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
11834 weight = CW_Constant;
11838 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11839 if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
11840 weight = CW_Constant;
11844 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11845 if (C->getZExtValue() <= 3)
11846 weight = CW_Constant;
11850 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11851 if (C->getZExtValue() <= 0xff)
11852 weight = CW_Constant;
11857 if (dyn_cast<ConstantFP>(CallOperandVal)) {
11858 weight = CW_Constant;
11862 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11863 if ((C->getSExtValue() >= -0x80000000LL) &&
11864 (C->getSExtValue() <= 0x7fffffffLL))
11865 weight = CW_Constant;
11869 if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
11870 if (C->getZExtValue() <= 0xffffffff)
11871 weight = CW_Constant;
11878 /// LowerXConstraint - try to replace an X constraint, which matches anything,
11879 /// with another that has more specific requirements based on the type of the
11880 /// corresponding operand.
11881 const char *X86TargetLowering::
11882 LowerXConstraint(EVT ConstraintVT) const {
11883 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
11884 // 'f' like normal targets.
11885 if (ConstraintVT.isFloatingPoint()) {
11886 if (Subtarget->hasXMMInt())
11888 if (Subtarget->hasXMM())
11892 return TargetLowering::LowerXConstraint(ConstraintVT);
11895 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11896 /// vector. If it is invalid, don't add anything to Ops.
11897 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11899 std::vector<SDValue>&Ops,
11900 SelectionDAG &DAG) const {
11901 SDValue Result(0, 0);
11903 switch (Constraint) {
11906 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11907 if (C->getZExtValue() <= 31) {
11908 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11914 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11915 if (C->getZExtValue() <= 63) {
11916 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11922 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11923 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
11924 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11930 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11931 if (C->getZExtValue() <= 255) {
11932 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11938 // 32-bit signed value
11939 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11940 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
11941 C->getSExtValue())) {
11942 // Widen to 64 bits here to get it sign extended.
11943 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
11946 // FIXME gcc accepts some relocatable values here too, but only in certain
11947 // memory models; it's complicated.
11952 // 32-bit unsigned value
11953 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11954 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
11955 C->getZExtValue())) {
11956 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11960 // FIXME gcc accepts some relocatable values here too, but only in certain
11961 // memory models; it's complicated.
11965 // Literal immediates are always ok.
11966 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
11967 // Widen to 64 bits here to get it sign extended.
11968 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
11972 // In any sort of PIC mode addresses need to be computed at runtime by
11973 // adding in a register or some sort of table lookup. These can't
11974 // be used as immediates.
11975 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
11978 // If we are in non-pic codegen mode, we allow the address of a global (with
11979 // an optional displacement) to be used with 'i'.
11980 GlobalAddressSDNode *GA = 0;
11981 int64_t Offset = 0;
11983 // Match either (GA), (GA+C), (GA+C1+C2), etc.
11985 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
11986 Offset += GA->getOffset();
11988 } else if (Op.getOpcode() == ISD::ADD) {
11989 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
11990 Offset += C->getZExtValue();
11991 Op = Op.getOperand(0);
11994 } else if (Op.getOpcode() == ISD::SUB) {
11995 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
11996 Offset += -C->getZExtValue();
11997 Op = Op.getOperand(0);
12002 // Otherwise, this isn't something we can handle, reject it.
12006 const GlobalValue *GV = GA->getGlobal();
12007 // If we require an extra load to get this address, as in PIC mode, we
12008 // can't accept it.
12009 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
12010 getTargetMachine())))
12013 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
12014 GA->getValueType(0), Offset);
12019 if (Result.getNode()) {
12020 Ops.push_back(Result);
12023 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12026 std::vector<unsigned> X86TargetLowering::
12027 getRegClassForInlineAsmConstraint(const std::string &Constraint,
12029 if (Constraint.size() == 1) {
12030 // FIXME: not handling fp-stack yet!
12031 switch (Constraint[0]) { // GCC X86 Constraint Letters
12032 default: break; // Unknown constraint letter
12033 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
12034 if (Subtarget->is64Bit()) {
12035 if (VT == MVT::i32)
12036 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
12037 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
12038 X86::R10D,X86::R11D,X86::R12D,
12039 X86::R13D,X86::R14D,X86::R15D,
12040 X86::EBP, X86::ESP, 0);
12041 else if (VT == MVT::i16)
12042 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
12043 X86::SI, X86::DI, X86::R8W,X86::R9W,
12044 X86::R10W,X86::R11W,X86::R12W,
12045 X86::R13W,X86::R14W,X86::R15W,
12046 X86::BP, X86::SP, 0);
12047 else if (VT == MVT::i8)
12048 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
12049 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
12050 X86::R10B,X86::R11B,X86::R12B,
12051 X86::R13B,X86::R14B,X86::R15B,
12052 X86::BPL, X86::SPL, 0);
12054 else if (VT == MVT::i64)
12055 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
12056 X86::RSI, X86::RDI, X86::R8, X86::R9,
12057 X86::R10, X86::R11, X86::R12,
12058 X86::R13, X86::R14, X86::R15,
12059 X86::RBP, X86::RSP, 0);
12063 // 32-bit fallthrough
12064 case 'Q': // Q_REGS
12065 if (VT == MVT::i32)
12066 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
12067 else if (VT == MVT::i16)
12068 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
12069 else if (VT == MVT::i8)
12070 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
12071 else if (VT == MVT::i64)
12072 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
12077 return std::vector<unsigned>();
12080 std::pair<unsigned, const TargetRegisterClass*>
12081 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
12083 // First, see if this is a constraint that directly corresponds to an LLVM
12085 if (Constraint.size() == 1) {
12086 // GCC Constraint Letters
12087 switch (Constraint[0]) {
12089 case 'r': // GENERAL_REGS
12090 case 'l': // INDEX_REGS
12092 return std::make_pair(0U, X86::GR8RegisterClass);
12093 if (VT == MVT::i16)
12094 return std::make_pair(0U, X86::GR16RegisterClass);
12095 if (VT == MVT::i32 || !Subtarget->is64Bit())
12096 return std::make_pair(0U, X86::GR32RegisterClass);
12097 return std::make_pair(0U, X86::GR64RegisterClass);
12098 case 'R': // LEGACY_REGS
12100 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
12101 if (VT == MVT::i16)
12102 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
12103 if (VT == MVT::i32 || !Subtarget->is64Bit())
12104 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
12105 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
12106 case 'f': // FP Stack registers.
12107 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
12108 // value to the correct fpstack register class.
12109 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
12110 return std::make_pair(0U, X86::RFP32RegisterClass);
12111 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
12112 return std::make_pair(0U, X86::RFP64RegisterClass);
12113 return std::make_pair(0U, X86::RFP80RegisterClass);
12114 case 'y': // MMX_REGS if MMX allowed.
12115 if (!Subtarget->hasMMX()) break;
12116 return std::make_pair(0U, X86::VR64RegisterClass);
12117 case 'Y': // SSE_REGS if SSE2 allowed
12118 if (!Subtarget->hasXMMInt()) break;
12120 case 'x': // SSE_REGS if SSE1 allowed
12121 if (!Subtarget->hasXMM()) break;
12123 switch (VT.getSimpleVT().SimpleTy) {
12125 // Scalar SSE types.
12128 return std::make_pair(0U, X86::FR32RegisterClass);
12131 return std::make_pair(0U, X86::FR64RegisterClass);
12139 return std::make_pair(0U, X86::VR128RegisterClass);
12145 // Use the default implementation in TargetLowering to convert the register
12146 // constraint into a member of a register class.
12147 std::pair<unsigned, const TargetRegisterClass*> Res;
12148 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
12150 // Not found as a standard register?
12151 if (Res.second == 0) {
12152 // Map st(0) -> st(7) -> ST0
12153 if (Constraint.size() == 7 && Constraint[0] == '{' &&
12154 tolower(Constraint[1]) == 's' &&
12155 tolower(Constraint[2]) == 't' &&
12156 Constraint[3] == '(' &&
12157 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
12158 Constraint[5] == ')' &&
12159 Constraint[6] == '}') {
12161 Res.first = X86::ST0+Constraint[4]-'0';
12162 Res.second = X86::RFP80RegisterClass;
12166 // GCC allows "st(0)" to be called just plain "st".
12167 if (StringRef("{st}").equals_lower(Constraint)) {
12168 Res.first = X86::ST0;
12169 Res.second = X86::RFP80RegisterClass;
12174 if (StringRef("{flags}").equals_lower(Constraint)) {
12175 Res.first = X86::EFLAGS;
12176 Res.second = X86::CCRRegisterClass;
12180 // 'A' means EAX + EDX.
12181 if (Constraint == "A") {
12182 Res.first = X86::EAX;
12183 Res.second = X86::GR32_ADRegisterClass;
12189 // Otherwise, check to see if this is a register class of the wrong value
12190 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
12191 // turn into {ax},{dx}.
12192 if (Res.second->hasType(VT))
12193 return Res; // Correct type already, nothing to do.
12195 // All of the single-register GCC register classes map their values onto
12196 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
12197 // really want an 8-bit or 32-bit register, map to the appropriate register
12198 // class and return the appropriate register.
12199 if (Res.second == X86::GR16RegisterClass) {
12200 if (VT == MVT::i8) {
12201 unsigned DestReg = 0;
12202 switch (Res.first) {
12204 case X86::AX: DestReg = X86::AL; break;
12205 case X86::DX: DestReg = X86::DL; break;
12206 case X86::CX: DestReg = X86::CL; break;
12207 case X86::BX: DestReg = X86::BL; break;
12210 Res.first = DestReg;
12211 Res.second = X86::GR8RegisterClass;
12213 } else if (VT == MVT::i32) {
12214 unsigned DestReg = 0;
12215 switch (Res.first) {
12217 case X86::AX: DestReg = X86::EAX; break;
12218 case X86::DX: DestReg = X86::EDX; break;
12219 case X86::CX: DestReg = X86::ECX; break;
12220 case X86::BX: DestReg = X86::EBX; break;
12221 case X86::SI: DestReg = X86::ESI; break;
12222 case X86::DI: DestReg = X86::EDI; break;
12223 case X86::BP: DestReg = X86::EBP; break;
12224 case X86::SP: DestReg = X86::ESP; break;
12227 Res.first = DestReg;
12228 Res.second = X86::GR32RegisterClass;
12230 } else if (VT == MVT::i64) {
12231 unsigned DestReg = 0;
12232 switch (Res.first) {
12234 case X86::AX: DestReg = X86::RAX; break;
12235 case X86::DX: DestReg = X86::RDX; break;
12236 case X86::CX: DestReg = X86::RCX; break;
12237 case X86::BX: DestReg = X86::RBX; break;
12238 case X86::SI: DestReg = X86::RSI; break;
12239 case X86::DI: DestReg = X86::RDI; break;
12240 case X86::BP: DestReg = X86::RBP; break;
12241 case X86::SP: DestReg = X86::RSP; break;
12244 Res.first = DestReg;
12245 Res.second = X86::GR64RegisterClass;
12248 } else if (Res.second == X86::FR32RegisterClass ||
12249 Res.second == X86::FR64RegisterClass ||
12250 Res.second == X86::VR128RegisterClass) {
12251 // Handle references to XMM physical registers that got mapped into the
12252 // wrong class. This can happen with constraints like {xmm0} where the
12253 // target independent register mapper will just pick the first match it can
12254 // find, ignoring the required type.
12255 if (VT == MVT::f32)
12256 Res.second = X86::FR32RegisterClass;
12257 else if (VT == MVT::f64)
12258 Res.second = X86::FR64RegisterClass;
12259 else if (X86::VR128RegisterClass->hasType(VT))
12260 Res.second = X86::VR128RegisterClass;