1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "x86-isel"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/GlobalAlias.h"
25 #include "llvm/GlobalVariable.h"
26 #include "llvm/Function.h"
27 #include "llvm/Instructions.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/LLVMContext.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/PseudoSourceValue.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/MC/MCContext.h"
39 #include "llvm/MC/MCExpr.h"
40 #include "llvm/MC/MCSymbol.h"
41 #include "llvm/ADT/BitVector.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/ADT/VectorExtras.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/Dwarf.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Support/raw_ostream.h"
53 using namespace dwarf;
55 STATISTIC(NumTailCalls, "Number of tail calls");
58 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
60 // Forward declarations.
61 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
64 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
66 bool is64Bit = TM.getSubtarget<X86Subtarget>().is64Bit();
68 if (TM.getSubtarget<X86Subtarget>().isTargetDarwin()) {
69 if (is64Bit) return new X8664_MachoTargetObjectFile();
70 return new TargetLoweringObjectFileMachO();
71 } else if (TM.getSubtarget<X86Subtarget>().isTargetELF() ){
72 if (is64Bit) return new X8664_ELFTargetObjectFile(TM);
73 return new X8632_ELFTargetObjectFile(TM);
74 } else if (TM.getSubtarget<X86Subtarget>().isTargetCOFF()) {
75 return new TargetLoweringObjectFileCOFF();
77 llvm_unreachable("unknown subtarget type");
80 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
81 : TargetLowering(TM, createTLOF(TM)) {
82 Subtarget = &TM.getSubtarget<X86Subtarget>();
83 X86ScalarSSEf64 = Subtarget->hasSSE2();
84 X86ScalarSSEf32 = Subtarget->hasSSE1();
85 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
87 RegInfo = TM.getRegisterInfo();
90 // Set up the TargetLowering object.
92 // X86 is weird, it always uses i8 for shift amounts and setcc results.
93 setShiftAmountType(MVT::i8);
94 setBooleanContents(ZeroOrOneBooleanContent);
95 setSchedulingPreference(Sched::RegPressure);
96 setStackPointerRegisterToSaveRestore(X86StackPtr);
98 if (Subtarget->isTargetDarwin()) {
99 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
100 setUseUnderscoreSetJmp(false);
101 setUseUnderscoreLongJmp(false);
102 } else if (Subtarget->isTargetMingw()) {
103 // MS runtime is weird: it exports _setjmp, but longjmp!
104 setUseUnderscoreSetJmp(true);
105 setUseUnderscoreLongJmp(false);
107 setUseUnderscoreSetJmp(true);
108 setUseUnderscoreLongJmp(true);
111 // Set up the register classes.
112 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
113 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
114 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
115 if (Subtarget->is64Bit())
116 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
118 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
120 // We don't accept any truncstore of integer registers.
121 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
122 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
123 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
124 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
125 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
126 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
128 // SETOEQ and SETUNE require checking two conditions.
129 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
130 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
131 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
132 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
133 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
134 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
136 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
138 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
139 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
140 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
142 if (Subtarget->is64Bit()) {
143 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
144 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
145 } else if (!UseSoftFloat) {
146 // We have an algorithm for SSE2->double, and we turn this into a
147 // 64-bit FILD followed by conditional FADD for other targets.
148 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
149 // We have an algorithm for SSE2, and we turn this into a 64-bit
150 // FILD for other targets.
151 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
154 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
156 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
157 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
160 // SSE has no i16 to fp conversion, only i32
161 if (X86ScalarSSEf32) {
162 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
163 // f32 and f64 cases are Legal, f80 case is not
164 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
166 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
167 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
170 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
171 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
174 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
175 // are Legal, f80 is custom lowered.
176 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
177 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
179 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
181 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
182 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
184 if (X86ScalarSSEf32) {
185 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
186 // f32 and f64 cases are Legal, f80 case is not
187 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
189 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
190 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
193 // Handle FP_TO_UINT by promoting the destination to a larger signed
195 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
196 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
197 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
199 if (Subtarget->is64Bit()) {
200 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
201 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
202 } else if (!UseSoftFloat) {
203 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
204 // Expand FP_TO_UINT into a select.
205 // FIXME: We would like to use a Custom expander here eventually to do
206 // the optimal thing for SSE vs. the default expansion in the legalizer.
207 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
209 // With SSE3 we can use fisttpll to convert to a signed i64; without
210 // SSE, we're stuck with a fistpll.
211 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
214 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
215 if (!X86ScalarSSEf64) {
216 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
217 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
218 if (Subtarget->is64Bit()) {
219 setOperationAction(ISD::BIT_CONVERT , MVT::f64 , Expand);
220 // Without SSE, i64->f64 goes through memory; i64->MMX is Legal.
221 if (Subtarget->hasMMX() && !DisableMMX)
222 setOperationAction(ISD::BIT_CONVERT , MVT::i64 , Custom);
224 setOperationAction(ISD::BIT_CONVERT , MVT::i64 , Expand);
228 // Scalar integer divide and remainder are lowered to use operations that
229 // produce two results, to match the available instructions. This exposes
230 // the two-result form to trivial CSE, which is able to combine x/y and x%y
231 // into a single instruction.
233 // Scalar integer multiply-high is also lowered to use two-result
234 // operations, to match the available instructions. However, plain multiply
235 // (low) operations are left as Legal, as there are single-result
236 // instructions for this in x86. Using the two-result multiply instructions
237 // when both high and low results are needed must be arranged by dagcombine.
238 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
239 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
240 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
241 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
242 setOperationAction(ISD::SREM , MVT::i8 , Expand);
243 setOperationAction(ISD::UREM , MVT::i8 , Expand);
244 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
245 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
246 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
247 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
248 setOperationAction(ISD::SREM , MVT::i16 , Expand);
249 setOperationAction(ISD::UREM , MVT::i16 , Expand);
250 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
251 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
252 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
253 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
254 setOperationAction(ISD::SREM , MVT::i32 , Expand);
255 setOperationAction(ISD::UREM , MVT::i32 , Expand);
256 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
257 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
258 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
259 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
260 setOperationAction(ISD::SREM , MVT::i64 , Expand);
261 setOperationAction(ISD::UREM , MVT::i64 , Expand);
263 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
264 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
265 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
266 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
267 if (Subtarget->is64Bit())
268 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
269 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
270 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
271 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
272 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
273 setOperationAction(ISD::FREM , MVT::f32 , Expand);
274 setOperationAction(ISD::FREM , MVT::f64 , Expand);
275 setOperationAction(ISD::FREM , MVT::f80 , Expand);
276 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
278 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
279 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
280 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
281 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
282 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
283 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
284 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
285 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
286 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
287 if (Subtarget->is64Bit()) {
288 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
289 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
290 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
293 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
294 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
296 // These should be promoted to a larger select which is supported.
297 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
298 // X86 wants to expand cmov itself.
299 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
300 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
301 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
302 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
303 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
304 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
305 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
306 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
307 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
308 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
309 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
310 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
311 if (Subtarget->is64Bit()) {
312 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
313 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
315 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
318 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
319 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
320 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
321 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
322 if (Subtarget->is64Bit())
323 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
324 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
325 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
326 if (Subtarget->is64Bit()) {
327 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
328 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
329 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
330 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
331 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
333 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
334 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
335 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
336 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
337 if (Subtarget->is64Bit()) {
338 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
339 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
340 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
343 if (Subtarget->hasSSE1())
344 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
346 // We may not have a libcall for MEMBARRIER so we should lower this.
347 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
349 // On X86 and X86-64, atomic operations are lowered to locked instructions.
350 // Locked instructions, in turn, have implicit fence semantics (all memory
351 // operations are flushed before issuing the locked instruction, and they
352 // are not buffered), so we can fold away the common pattern of
353 // fence-atomic-fence.
354 setShouldFoldAtomicFences(true);
356 // Expand certain atomics
357 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
358 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
359 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
360 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
362 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
363 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
364 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
365 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
367 if (!Subtarget->is64Bit()) {
368 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
369 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
370 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
371 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
372 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
373 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
374 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
377 // FIXME - use subtarget debug flags
378 if (!Subtarget->isTargetDarwin() &&
379 !Subtarget->isTargetELF() &&
380 !Subtarget->isTargetCygMing()) {
381 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
384 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
385 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
386 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
387 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
388 if (Subtarget->is64Bit()) {
389 setExceptionPointerRegister(X86::RAX);
390 setExceptionSelectorRegister(X86::RDX);
392 setExceptionPointerRegister(X86::EAX);
393 setExceptionSelectorRegister(X86::EDX);
395 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
396 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
398 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
400 setOperationAction(ISD::TRAP, MVT::Other, Legal);
402 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
403 setOperationAction(ISD::VASTART , MVT::Other, Custom);
404 setOperationAction(ISD::VAEND , MVT::Other, Expand);
405 if (Subtarget->is64Bit()) {
406 setOperationAction(ISD::VAARG , MVT::Other, Custom);
407 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
409 setOperationAction(ISD::VAARG , MVT::Other, Expand);
410 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
413 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
414 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
415 if (Subtarget->is64Bit())
416 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
417 if (Subtarget->isTargetCygMing())
418 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
420 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
422 if (!UseSoftFloat && X86ScalarSSEf64) {
423 // f32 and f64 use SSE.
424 // Set up the FP register classes.
425 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
426 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
428 // Use ANDPD to simulate FABS.
429 setOperationAction(ISD::FABS , MVT::f64, Custom);
430 setOperationAction(ISD::FABS , MVT::f32, Custom);
432 // Use XORP to simulate FNEG.
433 setOperationAction(ISD::FNEG , MVT::f64, Custom);
434 setOperationAction(ISD::FNEG , MVT::f32, Custom);
436 // Use ANDPD and ORPD to simulate FCOPYSIGN.
437 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
438 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
440 // We don't support sin/cos/fmod
441 setOperationAction(ISD::FSIN , MVT::f64, Expand);
442 setOperationAction(ISD::FCOS , MVT::f64, Expand);
443 setOperationAction(ISD::FSIN , MVT::f32, Expand);
444 setOperationAction(ISD::FCOS , MVT::f32, Expand);
446 // Expand FP immediates into loads from the stack, except for the special
448 addLegalFPImmediate(APFloat(+0.0)); // xorpd
449 addLegalFPImmediate(APFloat(+0.0f)); // xorps
450 } else if (!UseSoftFloat && X86ScalarSSEf32) {
451 // Use SSE for f32, x87 for f64.
452 // Set up the FP register classes.
453 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
454 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
456 // Use ANDPS to simulate FABS.
457 setOperationAction(ISD::FABS , MVT::f32, Custom);
459 // Use XORP to simulate FNEG.
460 setOperationAction(ISD::FNEG , MVT::f32, Custom);
462 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
464 // Use ANDPS and ORPS to simulate FCOPYSIGN.
465 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
466 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
468 // We don't support sin/cos/fmod
469 setOperationAction(ISD::FSIN , MVT::f32, Expand);
470 setOperationAction(ISD::FCOS , MVT::f32, Expand);
472 // Special cases we handle for FP constants.
473 addLegalFPImmediate(APFloat(+0.0f)); // xorps
474 addLegalFPImmediate(APFloat(+0.0)); // FLD0
475 addLegalFPImmediate(APFloat(+1.0)); // FLD1
476 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
477 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
480 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
481 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
483 } else if (!UseSoftFloat) {
484 // f32 and f64 in x87.
485 // Set up the FP register classes.
486 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
487 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
489 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
490 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
491 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
492 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
495 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
496 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
498 addLegalFPImmediate(APFloat(+0.0)); // FLD0
499 addLegalFPImmediate(APFloat(+1.0)); // FLD1
500 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
501 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
502 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
503 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
504 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
505 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
508 // Long double always uses X87.
510 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
511 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
512 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
515 APFloat TmpFlt(+0.0);
516 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
518 addLegalFPImmediate(TmpFlt); // FLD0
520 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
521 APFloat TmpFlt2(+1.0);
522 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
524 addLegalFPImmediate(TmpFlt2); // FLD1
525 TmpFlt2.changeSign();
526 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
530 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
531 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
535 // Always use a library call for pow.
536 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
537 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
538 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
540 setOperationAction(ISD::FLOG, MVT::f80, Expand);
541 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
542 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
543 setOperationAction(ISD::FEXP, MVT::f80, Expand);
544 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
546 // First set operation action for all vector types to either promote
547 // (for widening) or expand (for scalarization). Then we will selectively
548 // turn on ones that can be effectively codegen'd.
549 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
550 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
551 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
552 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
553 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
554 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
555 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
556 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
557 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
558 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
559 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
560 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
561 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
562 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
563 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
564 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
565 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
566 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
567 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
568 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
569 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
570 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
571 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
572 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
573 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
574 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
575 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
576 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
577 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
578 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
579 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
580 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
581 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
582 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
583 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
584 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
585 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
586 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
587 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
588 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
589 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
590 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
591 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
592 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
593 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
594 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
595 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
596 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
597 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
598 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
599 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
600 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
601 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
602 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
603 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
604 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
605 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
606 setTruncStoreAction((MVT::SimpleValueType)VT,
607 (MVT::SimpleValueType)InnerVT, Expand);
608 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
609 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
610 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
613 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
614 // with -msoft-float, disable use of MMX as well.
615 if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
616 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass, false);
617 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass, false);
618 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass, false);
620 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass, false);
622 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
623 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
624 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
625 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
627 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
628 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
629 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
630 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
632 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
633 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
635 setOperationAction(ISD::AND, MVT::v8i8, Promote);
636 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
637 setOperationAction(ISD::AND, MVT::v4i16, Promote);
638 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
639 setOperationAction(ISD::AND, MVT::v2i32, Promote);
640 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
641 setOperationAction(ISD::AND, MVT::v1i64, Legal);
643 setOperationAction(ISD::OR, MVT::v8i8, Promote);
644 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
645 setOperationAction(ISD::OR, MVT::v4i16, Promote);
646 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
647 setOperationAction(ISD::OR, MVT::v2i32, Promote);
648 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
649 setOperationAction(ISD::OR, MVT::v1i64, Legal);
651 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
652 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
653 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
654 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
655 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
656 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
657 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
659 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
660 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
661 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
662 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
663 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
664 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
665 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
667 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
668 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
669 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
670 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
672 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
673 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
674 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
675 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
677 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
678 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
679 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
681 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
683 setOperationAction(ISD::SELECT, MVT::v8i8, Promote);
684 setOperationAction(ISD::SELECT, MVT::v4i16, Promote);
685 setOperationAction(ISD::SELECT, MVT::v2i32, Promote);
686 setOperationAction(ISD::SELECT, MVT::v1i64, Custom);
687 setOperationAction(ISD::VSETCC, MVT::v8i8, Custom);
688 setOperationAction(ISD::VSETCC, MVT::v4i16, Custom);
689 setOperationAction(ISD::VSETCC, MVT::v2i32, Custom);
691 if (!X86ScalarSSEf64 && Subtarget->is64Bit()) {
692 setOperationAction(ISD::BIT_CONVERT, MVT::v8i8, Custom);
693 setOperationAction(ISD::BIT_CONVERT, MVT::v4i16, Custom);
694 setOperationAction(ISD::BIT_CONVERT, MVT::v2i32, Custom);
695 setOperationAction(ISD::BIT_CONVERT, MVT::v1i64, Custom);
699 if (!UseSoftFloat && Subtarget->hasSSE1()) {
700 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
702 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
703 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
704 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
705 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
706 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
707 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
708 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
709 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
710 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
711 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
712 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
713 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
716 if (!UseSoftFloat && Subtarget->hasSSE2()) {
717 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
719 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
720 // registers cannot be used even for integer operations.
721 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
722 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
723 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
724 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
726 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
727 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
728 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
729 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
730 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
731 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
732 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
733 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
734 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
735 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
736 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
737 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
738 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
739 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
740 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
741 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
743 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
744 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
745 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
746 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
748 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
749 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
750 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
751 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
752 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
754 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
755 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
756 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
757 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
758 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
760 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
761 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
762 EVT VT = (MVT::SimpleValueType)i;
763 // Do not attempt to custom lower non-power-of-2 vectors
764 if (!isPowerOf2_32(VT.getVectorNumElements()))
766 // Do not attempt to custom lower non-128-bit vectors
767 if (!VT.is128BitVector())
769 setOperationAction(ISD::BUILD_VECTOR,
770 VT.getSimpleVT().SimpleTy, Custom);
771 setOperationAction(ISD::VECTOR_SHUFFLE,
772 VT.getSimpleVT().SimpleTy, Custom);
773 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
774 VT.getSimpleVT().SimpleTy, Custom);
777 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
778 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
779 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
780 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
781 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
782 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
784 if (Subtarget->is64Bit()) {
785 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
786 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
789 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
790 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
791 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
794 // Do not attempt to promote non-128-bit vectors
795 if (!VT.is128BitVector())
798 setOperationAction(ISD::AND, SVT, Promote);
799 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
800 setOperationAction(ISD::OR, SVT, Promote);
801 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
802 setOperationAction(ISD::XOR, SVT, Promote);
803 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
804 setOperationAction(ISD::LOAD, SVT, Promote);
805 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
806 setOperationAction(ISD::SELECT, SVT, Promote);
807 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
810 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
812 // Custom lower v2i64 and v2f64 selects.
813 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
814 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
815 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
816 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
818 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
819 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
820 if (!DisableMMX && Subtarget->hasMMX()) {
821 setOperationAction(ISD::FP_TO_SINT, MVT::v2i32, Custom);
822 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
826 if (Subtarget->hasSSE41()) {
827 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
828 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
829 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
830 setOperationAction(ISD::FRINT, MVT::f32, Legal);
831 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
832 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
833 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
834 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
835 setOperationAction(ISD::FRINT, MVT::f64, Legal);
836 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
838 // FIXME: Do we need to handle scalar-to-vector here?
839 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
841 // Can turn SHL into an integer multiply.
842 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
843 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
845 // i8 and i16 vectors are custom , because the source register and source
846 // source memory operand types are not the same width. f32 vectors are
847 // custom since the immediate controlling the insert encodes additional
849 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
850 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
851 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
852 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
854 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
855 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
856 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
857 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
859 if (Subtarget->is64Bit()) {
860 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
861 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
865 if (Subtarget->hasSSE42()) {
866 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
869 if (!UseSoftFloat && Subtarget->hasAVX()) {
870 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
871 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
872 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
873 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
875 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
876 setOperationAction(ISD::LOAD, MVT::v8i32, Legal);
877 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
878 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
879 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
880 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
881 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
882 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
883 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
884 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
885 //setOperationAction(ISD::BUILD_VECTOR, MVT::v8f32, Custom);
886 //setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Custom);
887 //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
888 //setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
889 //setOperationAction(ISD::VSETCC, MVT::v8f32, Custom);
891 // Operations to consider commented out -v16i16 v32i8
892 //setOperationAction(ISD::ADD, MVT::v16i16, Legal);
893 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
894 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
895 //setOperationAction(ISD::SUB, MVT::v32i8, Legal);
896 //setOperationAction(ISD::SUB, MVT::v16i16, Legal);
897 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
898 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
899 //setOperationAction(ISD::MUL, MVT::v16i16, Legal);
900 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
901 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
902 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
903 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
904 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
905 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
907 setOperationAction(ISD::VSETCC, MVT::v4f64, Custom);
908 // setOperationAction(ISD::VSETCC, MVT::v32i8, Custom);
909 // setOperationAction(ISD::VSETCC, MVT::v16i16, Custom);
910 setOperationAction(ISD::VSETCC, MVT::v8i32, Custom);
912 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v32i8, Custom);
913 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i16, Custom);
914 // setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i16, Custom);
915 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i32, Custom);
916 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8f32, Custom);
918 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
919 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i64, Custom);
920 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f64, Custom);
921 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i64, Custom);
922 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f64, Custom);
923 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
926 // Not sure we want to do this since there are no 256-bit integer
929 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
930 // This includes 256-bit vectors
931 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
932 EVT VT = (MVT::SimpleValueType)i;
934 // Do not attempt to custom lower non-power-of-2 vectors
935 if (!isPowerOf2_32(VT.getVectorNumElements()))
938 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
939 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
940 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
943 if (Subtarget->is64Bit()) {
944 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i64, Custom);
945 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
950 // Not sure we want to do this since there are no 256-bit integer
953 // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
954 // Including 256-bit vectors
955 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
956 EVT VT = (MVT::SimpleValueType)i;
958 if (!VT.is256BitVector()) {
961 setOperationAction(ISD::AND, VT, Promote);
962 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
963 setOperationAction(ISD::OR, VT, Promote);
964 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
965 setOperationAction(ISD::XOR, VT, Promote);
966 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
967 setOperationAction(ISD::LOAD, VT, Promote);
968 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
969 setOperationAction(ISD::SELECT, VT, Promote);
970 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
973 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
977 // We want to custom lower some of our intrinsics.
978 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
980 // Add/Sub/Mul with overflow operations are custom lowered.
981 setOperationAction(ISD::SADDO, MVT::i32, Custom);
982 setOperationAction(ISD::UADDO, MVT::i32, Custom);
983 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
984 setOperationAction(ISD::USUBO, MVT::i32, Custom);
985 setOperationAction(ISD::SMULO, MVT::i32, Custom);
987 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
988 // handle type legalization for these operations here.
990 // FIXME: We really should do custom legalization for addition and
991 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
992 // than generic legalization for 64-bit multiplication-with-overflow, though.
993 if (Subtarget->is64Bit()) {
994 setOperationAction(ISD::SADDO, MVT::i64, Custom);
995 setOperationAction(ISD::UADDO, MVT::i64, Custom);
996 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
997 setOperationAction(ISD::USUBO, MVT::i64, Custom);
998 setOperationAction(ISD::SMULO, MVT::i64, Custom);
1001 if (!Subtarget->is64Bit()) {
1002 // These libcalls are not available in 32-bit.
1003 setLibcallName(RTLIB::SHL_I128, 0);
1004 setLibcallName(RTLIB::SRL_I128, 0);
1005 setLibcallName(RTLIB::SRA_I128, 0);
1008 // We have target-specific dag combine patterns for the following nodes:
1009 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1010 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1011 setTargetDAGCombine(ISD::BUILD_VECTOR);
1012 setTargetDAGCombine(ISD::SELECT);
1013 setTargetDAGCombine(ISD::SHL);
1014 setTargetDAGCombine(ISD::SRA);
1015 setTargetDAGCombine(ISD::SRL);
1016 setTargetDAGCombine(ISD::OR);
1017 setTargetDAGCombine(ISD::STORE);
1018 setTargetDAGCombine(ISD::ZERO_EXTEND);
1019 if (Subtarget->is64Bit())
1020 setTargetDAGCombine(ISD::MUL);
1022 computeRegisterProperties();
1024 // FIXME: These should be based on subtarget info. Plus, the values should
1025 // be smaller when we are in optimizing for size mode.
1026 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1027 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1028 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
1029 setPrefLoopAlignment(16);
1030 benefitFromCodePlacementOpt = true;
1034 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1039 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1040 /// the desired ByVal argument alignment.
1041 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1044 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1045 if (VTy->getBitWidth() == 128)
1047 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1048 unsigned EltAlign = 0;
1049 getMaxByValAlign(ATy->getElementType(), EltAlign);
1050 if (EltAlign > MaxAlign)
1051 MaxAlign = EltAlign;
1052 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1053 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1054 unsigned EltAlign = 0;
1055 getMaxByValAlign(STy->getElementType(i), EltAlign);
1056 if (EltAlign > MaxAlign)
1057 MaxAlign = EltAlign;
1065 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1066 /// function arguments in the caller parameter area. For X86, aggregates
1067 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1068 /// are at 4-byte boundaries.
1069 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1070 if (Subtarget->is64Bit()) {
1071 // Max of 8 and alignment of type.
1072 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1079 if (Subtarget->hasSSE1())
1080 getMaxByValAlign(Ty, Align);
1084 /// getOptimalMemOpType - Returns the target specific optimal type for load
1085 /// and store operations as a result of memset, memcpy, and memmove
1086 /// lowering. If DstAlign is zero that means it's safe to destination
1087 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1088 /// means there isn't a need to check it against alignment requirement,
1089 /// probably because the source does not need to be loaded. If
1090 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1091 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1092 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1093 /// constant so it does not need to be loaded.
1094 /// It returns EVT::Other if the type should be determined using generic
1095 /// target-independent logic.
1097 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1098 unsigned DstAlign, unsigned SrcAlign,
1099 bool NonScalarIntSafe,
1101 MachineFunction &MF) const {
1102 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1103 // linux. This is because the stack realignment code can't handle certain
1104 // cases like PR2962. This should be removed when PR2962 is fixed.
1105 const Function *F = MF.getFunction();
1106 if (NonScalarIntSafe &&
1107 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1109 (Subtarget->isUnalignedMemAccessFast() ||
1110 ((DstAlign == 0 || DstAlign >= 16) &&
1111 (SrcAlign == 0 || SrcAlign >= 16))) &&
1112 Subtarget->getStackAlignment() >= 16) {
1113 if (Subtarget->hasSSE2())
1115 if (Subtarget->hasSSE1())
1117 } else if (!MemcpyStrSrc && Size >= 8 &&
1118 !Subtarget->is64Bit() &&
1119 Subtarget->getStackAlignment() >= 8 &&
1120 Subtarget->hasSSE2()) {
1121 // Do not use f64 to lower memcpy if source is string constant. It's
1122 // better to use i32 to avoid the loads.
1126 if (Subtarget->is64Bit() && Size >= 8)
1131 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1132 /// current function. The returned value is a member of the
1133 /// MachineJumpTableInfo::JTEntryKind enum.
1134 unsigned X86TargetLowering::getJumpTableEncoding() const {
1135 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1137 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1138 Subtarget->isPICStyleGOT())
1139 return MachineJumpTableInfo::EK_Custom32;
1141 // Otherwise, use the normal jump table encoding heuristics.
1142 return TargetLowering::getJumpTableEncoding();
1145 /// getPICBaseSymbol - Return the X86-32 PIC base.
1147 X86TargetLowering::getPICBaseSymbol(const MachineFunction *MF,
1148 MCContext &Ctx) const {
1149 const MCAsmInfo &MAI = *getTargetMachine().getMCAsmInfo();
1150 return Ctx.GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix())+
1151 Twine(MF->getFunctionNumber())+"$pb");
1156 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1157 const MachineBasicBlock *MBB,
1158 unsigned uid,MCContext &Ctx) const{
1159 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1160 Subtarget->isPICStyleGOT());
1161 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1163 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1164 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1167 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1169 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1170 SelectionDAG &DAG) const {
1171 if (!Subtarget->is64Bit())
1172 // This doesn't have DebugLoc associated with it, but is not really the
1173 // same as a Register.
1174 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1178 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1179 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1181 const MCExpr *X86TargetLowering::
1182 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1183 MCContext &Ctx) const {
1184 // X86-64 uses RIP relative addressing based on the jump table label.
1185 if (Subtarget->isPICStyleRIPRel())
1186 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1188 // Otherwise, the reference is relative to the PIC base.
1189 return MCSymbolRefExpr::Create(getPICBaseSymbol(MF, Ctx), Ctx);
1192 /// getFunctionAlignment - Return the Log2 alignment of this function.
1193 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1194 return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1197 std::pair<const TargetRegisterClass*, uint8_t>
1198 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1199 const TargetRegisterClass *RRC = 0;
1201 switch (VT.getSimpleVT().SimpleTy) {
1203 return TargetLowering::findRepresentativeClass(VT);
1204 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1205 RRC = (Subtarget->is64Bit()
1206 ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1208 case MVT::v8i8: case MVT::v4i16:
1209 case MVT::v2i32: case MVT::v1i64:
1210 RRC = X86::VR64RegisterClass;
1212 case MVT::f32: case MVT::f64:
1213 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1214 case MVT::v4f32: case MVT::v2f64:
1215 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1217 RRC = X86::VR128RegisterClass;
1220 return std::make_pair(RRC, Cost);
1224 X86TargetLowering::getRegPressureLimit(const TargetRegisterClass *RC,
1225 MachineFunction &MF) const {
1226 unsigned FPDiff = RegInfo->hasFP(MF) ? 1 : 0;
1227 switch (RC->getID()) {
1230 case X86::GR32RegClassID:
1232 case X86::GR64RegClassID:
1234 case X86::VR128RegClassID:
1235 return Subtarget->is64Bit() ? 10 : 4;
1236 case X86::VR64RegClassID:
1241 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1242 unsigned &Offset) const {
1243 if (!Subtarget->isTargetLinux())
1246 if (Subtarget->is64Bit()) {
1247 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1249 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1262 //===----------------------------------------------------------------------===//
1263 // Return Value Calling Convention Implementation
1264 //===----------------------------------------------------------------------===//
1266 #include "X86GenCallingConv.inc"
1269 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1270 const SmallVectorImpl<ISD::OutputArg> &Outs,
1271 LLVMContext &Context) const {
1272 SmallVector<CCValAssign, 16> RVLocs;
1273 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1275 return CCInfo.CheckReturn(Outs, RetCC_X86);
1279 X86TargetLowering::LowerReturn(SDValue Chain,
1280 CallingConv::ID CallConv, bool isVarArg,
1281 const SmallVectorImpl<ISD::OutputArg> &Outs,
1282 const SmallVectorImpl<SDValue> &OutVals,
1283 DebugLoc dl, SelectionDAG &DAG) const {
1284 MachineFunction &MF = DAG.getMachineFunction();
1285 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1287 SmallVector<CCValAssign, 16> RVLocs;
1288 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1289 RVLocs, *DAG.getContext());
1290 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1292 // Add the regs to the liveout set for the function.
1293 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1294 for (unsigned i = 0; i != RVLocs.size(); ++i)
1295 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1296 MRI.addLiveOut(RVLocs[i].getLocReg());
1300 SmallVector<SDValue, 6> RetOps;
1301 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1302 // Operand #1 = Bytes To Pop
1303 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1306 // Copy the result values into the output registers.
1307 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1308 CCValAssign &VA = RVLocs[i];
1309 assert(VA.isRegLoc() && "Can only return in registers!");
1310 SDValue ValToCopy = OutVals[i];
1311 EVT ValVT = ValToCopy.getValueType();
1313 // If this is x86-64, and we disabled SSE, we can't return FP values
1314 if ((ValVT == MVT::f32 || ValVT == MVT::f64) &&
1315 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1316 report_fatal_error("SSE register return with SSE disabled");
1318 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1319 // llvm-gcc has never done it right and no one has noticed, so this
1320 // should be OK for now.
1321 if (ValVT == MVT::f64 &&
1322 (Subtarget->is64Bit() && !Subtarget->hasSSE2())) {
1323 report_fatal_error("SSE2 register return with SSE2 disabled");
1326 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1327 // the RET instruction and handled by the FP Stackifier.
1328 if (VA.getLocReg() == X86::ST0 ||
1329 VA.getLocReg() == X86::ST1) {
1330 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1331 // change the value to the FP stack register class.
1332 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1333 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1334 RetOps.push_back(ValToCopy);
1335 // Don't emit a copytoreg.
1339 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1340 // which is returned in RAX / RDX.
1341 if (Subtarget->is64Bit()) {
1342 if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1343 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1344 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1345 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1350 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1351 Flag = Chain.getValue(1);
1354 // The x86-64 ABI for returning structs by value requires that we copy
1355 // the sret argument into %rax for the return. We saved the argument into
1356 // a virtual register in the entry block, so now we copy the value out
1358 if (Subtarget->is64Bit() &&
1359 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1360 MachineFunction &MF = DAG.getMachineFunction();
1361 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1362 unsigned Reg = FuncInfo->getSRetReturnReg();
1364 "SRetReturnReg should have been set in LowerFormalArguments().");
1365 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1367 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1368 Flag = Chain.getValue(1);
1370 // RAX now acts like a return value.
1371 MRI.addLiveOut(X86::RAX);
1374 RetOps[0] = Chain; // Update chain.
1376 // Add the flag if we have it.
1378 RetOps.push_back(Flag);
1380 return DAG.getNode(X86ISD::RET_FLAG, dl,
1381 MVT::Other, &RetOps[0], RetOps.size());
1384 /// LowerCallResult - Lower the result values of a call into the
1385 /// appropriate copies out of appropriate physical registers.
1388 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1389 CallingConv::ID CallConv, bool isVarArg,
1390 const SmallVectorImpl<ISD::InputArg> &Ins,
1391 DebugLoc dl, SelectionDAG &DAG,
1392 SmallVectorImpl<SDValue> &InVals) const {
1394 // Assign locations to each value returned by this call.
1395 SmallVector<CCValAssign, 16> RVLocs;
1396 bool Is64Bit = Subtarget->is64Bit();
1397 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1398 RVLocs, *DAG.getContext());
1399 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1401 // Copy all of the result registers out of their specified physreg.
1402 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1403 CCValAssign &VA = RVLocs[i];
1404 EVT CopyVT = VA.getValVT();
1406 // If this is x86-64, and we disabled SSE, we can't return FP values
1407 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1408 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1409 report_fatal_error("SSE register return with SSE disabled");
1414 // If this is a call to a function that returns an fp value on the floating
1415 // point stack, we must guarantee the the value is popped from the stack, so
1416 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1417 // if the return value is not used. We use the FpGET_ST0 instructions
1419 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1420 // If we prefer to use the value in xmm registers, copy it out as f80 and
1421 // use a truncate to move it from fp stack reg to xmm reg.
1422 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1423 bool isST0 = VA.getLocReg() == X86::ST0;
1425 if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1426 if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1427 if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1428 SDValue Ops[] = { Chain, InFlag };
1429 Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Flag,
1431 Val = Chain.getValue(0);
1433 // Round the f80 to the right size, which also moves it to the appropriate
1435 if (CopyVT != VA.getValVT())
1436 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1437 // This truncation won't change the value.
1438 DAG.getIntPtrConstant(1));
1439 } else if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1440 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1441 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1442 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1443 MVT::v2i64, InFlag).getValue(1);
1444 Val = Chain.getValue(0);
1445 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1446 Val, DAG.getConstant(0, MVT::i64));
1448 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1449 MVT::i64, InFlag).getValue(1);
1450 Val = Chain.getValue(0);
1452 Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1454 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1455 CopyVT, InFlag).getValue(1);
1456 Val = Chain.getValue(0);
1458 InFlag = Chain.getValue(2);
1459 InVals.push_back(Val);
1466 //===----------------------------------------------------------------------===//
1467 // C & StdCall & Fast Calling Convention implementation
1468 //===----------------------------------------------------------------------===//
1469 // StdCall calling convention seems to be standard for many Windows' API
1470 // routines and around. It differs from C calling convention just a little:
1471 // callee should clean up the stack, not caller. Symbols should be also
1472 // decorated in some fancy way :) It doesn't support any vector arguments.
1473 // For info on fast calling convention see Fast Calling Convention (tail call)
1474 // implementation LowerX86_32FastCCCallTo.
1476 /// CallIsStructReturn - Determines whether a call uses struct return
1478 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1482 return Outs[0].Flags.isSRet();
1485 /// ArgsAreStructReturn - Determines whether a function uses struct
1486 /// return semantics.
1488 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1492 return Ins[0].Flags.isSRet();
1495 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1496 /// given CallingConvention value.
1497 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1498 if (Subtarget->is64Bit()) {
1499 if (CC == CallingConv::GHC)
1500 return CC_X86_64_GHC;
1501 else if (Subtarget->isTargetWin64())
1502 return CC_X86_Win64_C;
1507 if (CC == CallingConv::X86_FastCall)
1508 return CC_X86_32_FastCall;
1509 else if (CC == CallingConv::X86_ThisCall)
1510 return CC_X86_32_ThisCall;
1511 else if (CC == CallingConv::Fast)
1512 return CC_X86_32_FastCC;
1513 else if (CC == CallingConv::GHC)
1514 return CC_X86_32_GHC;
1519 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1520 /// by "Src" to address "Dst" with size and alignment information specified by
1521 /// the specific parameter attribute. The copy will be passed as a byval
1522 /// function parameter.
1524 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1525 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1527 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1528 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1529 /*isVolatile*/false, /*AlwaysInline=*/true,
1533 /// IsTailCallConvention - Return true if the calling convention is one that
1534 /// supports tail call optimization.
1535 static bool IsTailCallConvention(CallingConv::ID CC) {
1536 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1539 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1540 /// a tailcall target by changing its ABI.
1541 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1542 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1546 X86TargetLowering::LowerMemArgument(SDValue Chain,
1547 CallingConv::ID CallConv,
1548 const SmallVectorImpl<ISD::InputArg> &Ins,
1549 DebugLoc dl, SelectionDAG &DAG,
1550 const CCValAssign &VA,
1551 MachineFrameInfo *MFI,
1553 // Create the nodes corresponding to a load from this parameter slot.
1554 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1555 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1556 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1559 // If value is passed by pointer we have address passed instead of the value
1561 if (VA.getLocInfo() == CCValAssign::Indirect)
1562 ValVT = VA.getLocVT();
1564 ValVT = VA.getValVT();
1566 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1567 // changed with more analysis.
1568 // In case of tail call optimization mark all arguments mutable. Since they
1569 // could be overwritten by lowering of arguments in case of a tail call.
1570 if (Flags.isByVal()) {
1571 int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1572 VA.getLocMemOffset(), isImmutable);
1573 return DAG.getFrameIndex(FI, getPointerTy());
1575 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1576 VA.getLocMemOffset(), isImmutable);
1577 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1578 return DAG.getLoad(ValVT, dl, Chain, FIN,
1579 PseudoSourceValue::getFixedStack(FI), 0,
1585 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1586 CallingConv::ID CallConv,
1588 const SmallVectorImpl<ISD::InputArg> &Ins,
1591 SmallVectorImpl<SDValue> &InVals)
1593 MachineFunction &MF = DAG.getMachineFunction();
1594 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1596 const Function* Fn = MF.getFunction();
1597 if (Fn->hasExternalLinkage() &&
1598 Subtarget->isTargetCygMing() &&
1599 Fn->getName() == "main")
1600 FuncInfo->setForceFramePointer(true);
1602 MachineFrameInfo *MFI = MF.getFrameInfo();
1603 bool Is64Bit = Subtarget->is64Bit();
1604 bool IsWin64 = Subtarget->isTargetWin64();
1606 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1607 "Var args not supported with calling convention fastcc or ghc");
1609 // Assign locations to all of the incoming arguments.
1610 SmallVector<CCValAssign, 16> ArgLocs;
1611 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1612 ArgLocs, *DAG.getContext());
1613 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1615 unsigned LastVal = ~0U;
1617 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1618 CCValAssign &VA = ArgLocs[i];
1619 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1621 assert(VA.getValNo() != LastVal &&
1622 "Don't support value assigned to multiple locs yet");
1623 LastVal = VA.getValNo();
1625 if (VA.isRegLoc()) {
1626 EVT RegVT = VA.getLocVT();
1627 TargetRegisterClass *RC = NULL;
1628 if (RegVT == MVT::i32)
1629 RC = X86::GR32RegisterClass;
1630 else if (Is64Bit && RegVT == MVT::i64)
1631 RC = X86::GR64RegisterClass;
1632 else if (RegVT == MVT::f32)
1633 RC = X86::FR32RegisterClass;
1634 else if (RegVT == MVT::f64)
1635 RC = X86::FR64RegisterClass;
1636 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1637 RC = X86::VR128RegisterClass;
1638 else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1639 RC = X86::VR64RegisterClass;
1641 llvm_unreachable("Unknown argument type!");
1643 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1644 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1646 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1647 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1649 if (VA.getLocInfo() == CCValAssign::SExt)
1650 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1651 DAG.getValueType(VA.getValVT()));
1652 else if (VA.getLocInfo() == CCValAssign::ZExt)
1653 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1654 DAG.getValueType(VA.getValVT()));
1655 else if (VA.getLocInfo() == CCValAssign::BCvt)
1656 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1658 if (VA.isExtInLoc()) {
1659 // Handle MMX values passed in XMM regs.
1660 if (RegVT.isVector()) {
1661 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1662 ArgValue, DAG.getConstant(0, MVT::i64));
1663 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1665 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1668 assert(VA.isMemLoc());
1669 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1672 // If value is passed via pointer - do a load.
1673 if (VA.getLocInfo() == CCValAssign::Indirect)
1674 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0,
1677 InVals.push_back(ArgValue);
1680 // The x86-64 ABI for returning structs by value requires that we copy
1681 // the sret argument into %rax for the return. Save the argument into
1682 // a virtual register so that we can access it from the return points.
1683 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1684 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1685 unsigned Reg = FuncInfo->getSRetReturnReg();
1687 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1688 FuncInfo->setSRetReturnReg(Reg);
1690 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1691 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1694 unsigned StackSize = CCInfo.getNextStackOffset();
1695 // Align stack specially for tail calls.
1696 if (FuncIsMadeTailCallSafe(CallConv))
1697 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1699 // If the function takes variable number of arguments, make a frame index for
1700 // the start of the first vararg value... for expansion of llvm.va_start.
1702 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1703 CallConv != CallingConv::X86_ThisCall)) {
1704 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1707 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1709 // FIXME: We should really autogenerate these arrays
1710 static const unsigned GPR64ArgRegsWin64[] = {
1711 X86::RCX, X86::RDX, X86::R8, X86::R9
1713 static const unsigned XMMArgRegsWin64[] = {
1714 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1716 static const unsigned GPR64ArgRegs64Bit[] = {
1717 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1719 static const unsigned XMMArgRegs64Bit[] = {
1720 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1721 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1723 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1726 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1727 GPR64ArgRegs = GPR64ArgRegsWin64;
1728 XMMArgRegs = XMMArgRegsWin64;
1730 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1731 GPR64ArgRegs = GPR64ArgRegs64Bit;
1732 XMMArgRegs = XMMArgRegs64Bit;
1734 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1736 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1739 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1740 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1741 "SSE register cannot be used when SSE is disabled!");
1742 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1743 "SSE register cannot be used when SSE is disabled!");
1744 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1745 // Kernel mode asks for SSE to be disabled, so don't push them
1747 TotalNumXMMRegs = 0;
1749 // For X86-64, if there are vararg parameters that are passed via
1750 // registers, then we must store them to their spots on the stack so they
1751 // may be loaded by deferencing the result of va_next.
1752 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1753 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1754 FuncInfo->setRegSaveFrameIndex(
1755 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1758 // Store the integer parameter registers.
1759 SmallVector<SDValue, 8> MemOps;
1760 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1762 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1763 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1764 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1765 DAG.getIntPtrConstant(Offset));
1766 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1767 X86::GR64RegisterClass);
1768 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1770 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1771 PseudoSourceValue::getFixedStack(
1772 FuncInfo->getRegSaveFrameIndex()),
1773 Offset, false, false, 0);
1774 MemOps.push_back(Store);
1778 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1779 // Now store the XMM (fp + vector) parameter registers.
1780 SmallVector<SDValue, 11> SaveXMMOps;
1781 SaveXMMOps.push_back(Chain);
1783 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1784 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1785 SaveXMMOps.push_back(ALVal);
1787 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1788 FuncInfo->getRegSaveFrameIndex()));
1789 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1790 FuncInfo->getVarArgsFPOffset()));
1792 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1793 unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1794 X86::VR128RegisterClass);
1795 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1796 SaveXMMOps.push_back(Val);
1798 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1800 &SaveXMMOps[0], SaveXMMOps.size()));
1803 if (!MemOps.empty())
1804 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1805 &MemOps[0], MemOps.size());
1809 // Some CCs need callee pop.
1810 if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1811 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1813 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1814 // If this is an sret function, the return should pop the hidden pointer.
1815 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1816 FuncInfo->setBytesToPopOnReturn(4);
1820 // RegSaveFrameIndex is X86-64 only.
1821 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1822 if (CallConv == CallingConv::X86_FastCall ||
1823 CallConv == CallingConv::X86_ThisCall)
1824 // fastcc functions can't have varargs.
1825 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1832 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1833 SDValue StackPtr, SDValue Arg,
1834 DebugLoc dl, SelectionDAG &DAG,
1835 const CCValAssign &VA,
1836 ISD::ArgFlagsTy Flags) const {
1837 const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1838 unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1839 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1840 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1841 if (Flags.isByVal()) {
1842 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1844 return DAG.getStore(Chain, dl, Arg, PtrOff,
1845 PseudoSourceValue::getStack(), LocMemOffset,
1849 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1850 /// optimization is performed and it is required.
1852 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1853 SDValue &OutRetAddr, SDValue Chain,
1854 bool IsTailCall, bool Is64Bit,
1855 int FPDiff, DebugLoc dl) const {
1856 // Adjust the Return address stack slot.
1857 EVT VT = getPointerTy();
1858 OutRetAddr = getReturnAddressFrameIndex(DAG);
1860 // Load the "old" Return address.
1861 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0, false, false, 0);
1862 return SDValue(OutRetAddr.getNode(), 1);
1865 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1866 /// optimization is performed and it is required (FPDiff!=0).
1868 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1869 SDValue Chain, SDValue RetAddrFrIdx,
1870 bool Is64Bit, int FPDiff, DebugLoc dl) {
1871 // Store the return address to the appropriate stack slot.
1872 if (!FPDiff) return Chain;
1873 // Calculate the new stack slot for the return address.
1874 int SlotSize = Is64Bit ? 8 : 4;
1875 int NewReturnAddrFI =
1876 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1877 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1878 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1879 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1880 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0,
1886 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1887 CallingConv::ID CallConv, bool isVarArg,
1889 const SmallVectorImpl<ISD::OutputArg> &Outs,
1890 const SmallVectorImpl<SDValue> &OutVals,
1891 const SmallVectorImpl<ISD::InputArg> &Ins,
1892 DebugLoc dl, SelectionDAG &DAG,
1893 SmallVectorImpl<SDValue> &InVals) const {
1894 MachineFunction &MF = DAG.getMachineFunction();
1895 bool Is64Bit = Subtarget->is64Bit();
1896 bool IsStructRet = CallIsStructReturn(Outs);
1897 bool IsSibcall = false;
1900 // Check if it's really possible to do a tail call.
1901 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1902 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1903 Outs, OutVals, Ins, DAG);
1905 // Sibcalls are automatically detected tailcalls which do not require
1907 if (!GuaranteedTailCallOpt && isTailCall)
1914 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1915 "Var args not supported with calling convention fastcc or ghc");
1917 // Analyze operands of the call, assigning locations to each operand.
1918 SmallVector<CCValAssign, 16> ArgLocs;
1919 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1920 ArgLocs, *DAG.getContext());
1921 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1923 // Get a count of how many bytes are to be pushed on the stack.
1924 unsigned NumBytes = CCInfo.getNextStackOffset();
1926 // This is a sibcall. The memory operands are available in caller's
1927 // own caller's stack.
1929 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1930 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1933 if (isTailCall && !IsSibcall) {
1934 // Lower arguments at fp - stackoffset + fpdiff.
1935 unsigned NumBytesCallerPushed =
1936 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1937 FPDiff = NumBytesCallerPushed - NumBytes;
1939 // Set the delta of movement of the returnaddr stackslot.
1940 // But only set if delta is greater than previous delta.
1941 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1942 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1946 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1948 SDValue RetAddrFrIdx;
1949 // Load return adress for tail calls.
1950 if (isTailCall && FPDiff)
1951 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1952 Is64Bit, FPDiff, dl);
1954 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1955 SmallVector<SDValue, 8> MemOpChains;
1958 // Walk the register/memloc assignments, inserting copies/loads. In the case
1959 // of tail call optimization arguments are handle later.
1960 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1961 CCValAssign &VA = ArgLocs[i];
1962 EVT RegVT = VA.getLocVT();
1963 SDValue Arg = OutVals[i];
1964 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1965 bool isByVal = Flags.isByVal();
1967 // Promote the value if needed.
1968 switch (VA.getLocInfo()) {
1969 default: llvm_unreachable("Unknown loc info!");
1970 case CCValAssign::Full: break;
1971 case CCValAssign::SExt:
1972 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1974 case CCValAssign::ZExt:
1975 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1977 case CCValAssign::AExt:
1978 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1979 // Special case: passing MMX values in XMM registers.
1980 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1981 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1982 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1984 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1986 case CCValAssign::BCvt:
1987 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1989 case CCValAssign::Indirect: {
1990 // Store the argument.
1991 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1992 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1993 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1994 PseudoSourceValue::getFixedStack(FI), 0,
2001 if (VA.isRegLoc()) {
2002 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2003 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2004 assert(VA.isMemLoc());
2005 if (StackPtr.getNode() == 0)
2006 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2007 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2008 dl, DAG, VA, Flags));
2012 if (!MemOpChains.empty())
2013 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2014 &MemOpChains[0], MemOpChains.size());
2016 // Build a sequence of copy-to-reg nodes chained together with token chain
2017 // and flag operands which copy the outgoing args into registers.
2019 // Tail call byval lowering might overwrite argument registers so in case of
2020 // tail call optimization the copies to registers are lowered later.
2022 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2023 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2024 RegsToPass[i].second, InFlag);
2025 InFlag = Chain.getValue(1);
2028 if (Subtarget->isPICStyleGOT()) {
2029 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2032 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2033 DAG.getNode(X86ISD::GlobalBaseReg,
2034 DebugLoc(), getPointerTy()),
2036 InFlag = Chain.getValue(1);
2038 // If we are tail calling and generating PIC/GOT style code load the
2039 // address of the callee into ECX. The value in ecx is used as target of
2040 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2041 // for tail calls on PIC/GOT architectures. Normally we would just put the
2042 // address of GOT into ebx and then call target@PLT. But for tail calls
2043 // ebx would be restored (since ebx is callee saved) before jumping to the
2046 // Note: The actual moving to ECX is done further down.
2047 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2048 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2049 !G->getGlobal()->hasProtectedVisibility())
2050 Callee = LowerGlobalAddress(Callee, DAG);
2051 else if (isa<ExternalSymbolSDNode>(Callee))
2052 Callee = LowerExternalSymbol(Callee, DAG);
2056 if (Is64Bit && isVarArg && !Subtarget->isTargetWin64()) {
2057 // From AMD64 ABI document:
2058 // For calls that may call functions that use varargs or stdargs
2059 // (prototype-less calls or calls to functions containing ellipsis (...) in
2060 // the declaration) %al is used as hidden argument to specify the number
2061 // of SSE registers used. The contents of %al do not need to match exactly
2062 // the number of registers, but must be an ubound on the number of SSE
2063 // registers used and is in the range 0 - 8 inclusive.
2065 // Count the number of XMM registers allocated.
2066 static const unsigned XMMArgRegs[] = {
2067 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2068 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2070 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2071 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2072 && "SSE registers cannot be used when SSE is disabled");
2074 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2075 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2076 InFlag = Chain.getValue(1);
2080 // For tail calls lower the arguments to the 'real' stack slot.
2082 // Force all the incoming stack arguments to be loaded from the stack
2083 // before any new outgoing arguments are stored to the stack, because the
2084 // outgoing stack slots may alias the incoming argument stack slots, and
2085 // the alias isn't otherwise explicit. This is slightly more conservative
2086 // than necessary, because it means that each store effectively depends
2087 // on every argument instead of just those arguments it would clobber.
2088 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2090 SmallVector<SDValue, 8> MemOpChains2;
2093 // Do not flag preceeding copytoreg stuff together with the following stuff.
2095 if (GuaranteedTailCallOpt) {
2096 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2097 CCValAssign &VA = ArgLocs[i];
2100 assert(VA.isMemLoc());
2101 SDValue Arg = OutVals[i];
2102 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2103 // Create frame index.
2104 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2105 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2106 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2107 FIN = DAG.getFrameIndex(FI, getPointerTy());
2109 if (Flags.isByVal()) {
2110 // Copy relative to framepointer.
2111 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2112 if (StackPtr.getNode() == 0)
2113 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2115 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2117 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2121 // Store relative to framepointer.
2122 MemOpChains2.push_back(
2123 DAG.getStore(ArgChain, dl, Arg, FIN,
2124 PseudoSourceValue::getFixedStack(FI), 0,
2130 if (!MemOpChains2.empty())
2131 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2132 &MemOpChains2[0], MemOpChains2.size());
2134 // Copy arguments to their registers.
2135 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2136 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2137 RegsToPass[i].second, InFlag);
2138 InFlag = Chain.getValue(1);
2142 // Store the return address to the appropriate stack slot.
2143 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2147 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2148 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2149 // In the 64-bit large code model, we have to make all calls
2150 // through a register, since the call instruction's 32-bit
2151 // pc-relative offset may not be large enough to hold the whole
2153 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2154 // If the callee is a GlobalAddress node (quite common, every direct call
2155 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2158 // We should use extra load for direct calls to dllimported functions in
2160 const GlobalValue *GV = G->getGlobal();
2161 if (!GV->hasDLLImportLinkage()) {
2162 unsigned char OpFlags = 0;
2164 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2165 // external symbols most go through the PLT in PIC mode. If the symbol
2166 // has hidden or protected visibility, or if it is static or local, then
2167 // we don't need to use the PLT - we can directly call it.
2168 if (Subtarget->isTargetELF() &&
2169 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2170 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2171 OpFlags = X86II::MO_PLT;
2172 } else if (Subtarget->isPICStyleStubAny() &&
2173 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2174 Subtarget->getDarwinVers() < 9) {
2175 // PC-relative references to external symbols should go through $stub,
2176 // unless we're building with the leopard linker or later, which
2177 // automatically synthesizes these stubs.
2178 OpFlags = X86II::MO_DARWIN_STUB;
2181 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2182 G->getOffset(), OpFlags);
2184 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2185 unsigned char OpFlags = 0;
2187 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2188 // symbols should go through the PLT.
2189 if (Subtarget->isTargetELF() &&
2190 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2191 OpFlags = X86II::MO_PLT;
2192 } else if (Subtarget->isPICStyleStubAny() &&
2193 Subtarget->getDarwinVers() < 9) {
2194 // PC-relative references to external symbols should go through $stub,
2195 // unless we're building with the leopard linker or later, which
2196 // automatically synthesizes these stubs.
2197 OpFlags = X86II::MO_DARWIN_STUB;
2200 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2204 // Returns a chain & a flag for retval copy to use.
2205 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2206 SmallVector<SDValue, 8> Ops;
2208 if (!IsSibcall && isTailCall) {
2209 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2210 DAG.getIntPtrConstant(0, true), InFlag);
2211 InFlag = Chain.getValue(1);
2214 Ops.push_back(Chain);
2215 Ops.push_back(Callee);
2218 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2220 // Add argument registers to the end of the list so that they are known live
2222 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2223 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2224 RegsToPass[i].second.getValueType()));
2226 // Add an implicit use GOT pointer in EBX.
2227 if (!isTailCall && Subtarget->isPICStyleGOT())
2228 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2230 // Add an implicit use of AL for x86 vararg functions.
2231 if (Is64Bit && isVarArg)
2232 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2234 if (InFlag.getNode())
2235 Ops.push_back(InFlag);
2239 //// If this is the first return lowered for this function, add the regs
2240 //// to the liveout set for the function.
2241 // This isn't right, although it's probably harmless on x86; liveouts
2242 // should be computed from returns not tail calls. Consider a void
2243 // function making a tail call to a function returning int.
2244 return DAG.getNode(X86ISD::TC_RETURN, dl,
2245 NodeTys, &Ops[0], Ops.size());
2248 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2249 InFlag = Chain.getValue(1);
2251 // Create the CALLSEQ_END node.
2252 unsigned NumBytesForCalleeToPush;
2253 if (Subtarget->IsCalleePop(isVarArg, CallConv))
2254 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2255 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2256 // If this is a call to a struct-return function, the callee
2257 // pops the hidden struct pointer, so we have to push it back.
2258 // This is common for Darwin/X86, Linux & Mingw32 targets.
2259 NumBytesForCalleeToPush = 4;
2261 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2263 // Returns a flag for retval copy to use.
2265 Chain = DAG.getCALLSEQ_END(Chain,
2266 DAG.getIntPtrConstant(NumBytes, true),
2267 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2270 InFlag = Chain.getValue(1);
2273 // Handle result values, copying them out of physregs into vregs that we
2275 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2276 Ins, dl, DAG, InVals);
2280 //===----------------------------------------------------------------------===//
2281 // Fast Calling Convention (tail call) implementation
2282 //===----------------------------------------------------------------------===//
2284 // Like std call, callee cleans arguments, convention except that ECX is
2285 // reserved for storing the tail called function address. Only 2 registers are
2286 // free for argument passing (inreg). Tail call optimization is performed
2288 // * tailcallopt is enabled
2289 // * caller/callee are fastcc
2290 // On X86_64 architecture with GOT-style position independent code only local
2291 // (within module) calls are supported at the moment.
2292 // To keep the stack aligned according to platform abi the function
2293 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2294 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2295 // If a tail called function callee has more arguments than the caller the
2296 // caller needs to make sure that there is room to move the RETADDR to. This is
2297 // achieved by reserving an area the size of the argument delta right after the
2298 // original REtADDR, but before the saved framepointer or the spilled registers
2299 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2311 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2312 /// for a 16 byte align requirement.
2314 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2315 SelectionDAG& DAG) const {
2316 MachineFunction &MF = DAG.getMachineFunction();
2317 const TargetMachine &TM = MF.getTarget();
2318 const TargetFrameInfo &TFI = *TM.getFrameInfo();
2319 unsigned StackAlignment = TFI.getStackAlignment();
2320 uint64_t AlignMask = StackAlignment - 1;
2321 int64_t Offset = StackSize;
2322 uint64_t SlotSize = TD->getPointerSize();
2323 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2324 // Number smaller than 12 so just add the difference.
2325 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2327 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2328 Offset = ((~AlignMask) & Offset) + StackAlignment +
2329 (StackAlignment-SlotSize);
2334 /// MatchingStackOffset - Return true if the given stack call argument is
2335 /// already available in the same position (relatively) of the caller's
2336 /// incoming argument stack.
2338 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2339 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2340 const X86InstrInfo *TII) {
2341 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2343 if (Arg.getOpcode() == ISD::CopyFromReg) {
2344 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2345 if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2347 MachineInstr *Def = MRI->getVRegDef(VR);
2350 if (!Flags.isByVal()) {
2351 if (!TII->isLoadFromStackSlot(Def, FI))
2354 unsigned Opcode = Def->getOpcode();
2355 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2356 Def->getOperand(1).isFI()) {
2357 FI = Def->getOperand(1).getIndex();
2358 Bytes = Flags.getByValSize();
2362 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2363 if (Flags.isByVal())
2364 // ByVal argument is passed in as a pointer but it's now being
2365 // dereferenced. e.g.
2366 // define @foo(%struct.X* %A) {
2367 // tail call @bar(%struct.X* byval %A)
2370 SDValue Ptr = Ld->getBasePtr();
2371 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2374 FI = FINode->getIndex();
2378 assert(FI != INT_MAX);
2379 if (!MFI->isFixedObjectIndex(FI))
2381 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2384 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2385 /// for tail call optimization. Targets which want to do tail call
2386 /// optimization should implement this function.
2388 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2389 CallingConv::ID CalleeCC,
2391 bool isCalleeStructRet,
2392 bool isCallerStructRet,
2393 const SmallVectorImpl<ISD::OutputArg> &Outs,
2394 const SmallVectorImpl<SDValue> &OutVals,
2395 const SmallVectorImpl<ISD::InputArg> &Ins,
2396 SelectionDAG& DAG) const {
2397 if (!IsTailCallConvention(CalleeCC) &&
2398 CalleeCC != CallingConv::C)
2401 // If -tailcallopt is specified, make fastcc functions tail-callable.
2402 const MachineFunction &MF = DAG.getMachineFunction();
2403 const Function *CallerF = DAG.getMachineFunction().getFunction();
2404 CallingConv::ID CallerCC = CallerF->getCallingConv();
2405 bool CCMatch = CallerCC == CalleeCC;
2407 if (GuaranteedTailCallOpt) {
2408 if (IsTailCallConvention(CalleeCC) && CCMatch)
2413 // Look for obvious safe cases to perform tail call optimization that do not
2414 // require ABI changes. This is what gcc calls sibcall.
2416 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2417 // emit a special epilogue.
2418 if (RegInfo->needsStackRealignment(MF))
2421 // Do not sibcall optimize vararg calls unless the call site is not passing
2423 if (isVarArg && !Outs.empty())
2426 // Also avoid sibcall optimization if either caller or callee uses struct
2427 // return semantics.
2428 if (isCalleeStructRet || isCallerStructRet)
2431 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2432 // Therefore if it's not used by the call it is not safe to optimize this into
2434 bool Unused = false;
2435 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2442 SmallVector<CCValAssign, 16> RVLocs;
2443 CCState CCInfo(CalleeCC, false, getTargetMachine(),
2444 RVLocs, *DAG.getContext());
2445 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2446 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2447 CCValAssign &VA = RVLocs[i];
2448 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2453 // If the calling conventions do not match, then we'd better make sure the
2454 // results are returned in the same way as what the caller expects.
2456 SmallVector<CCValAssign, 16> RVLocs1;
2457 CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2458 RVLocs1, *DAG.getContext());
2459 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2461 SmallVector<CCValAssign, 16> RVLocs2;
2462 CCState CCInfo2(CallerCC, false, getTargetMachine(),
2463 RVLocs2, *DAG.getContext());
2464 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2466 if (RVLocs1.size() != RVLocs2.size())
2468 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2469 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2471 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2473 if (RVLocs1[i].isRegLoc()) {
2474 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2477 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2483 // If the callee takes no arguments then go on to check the results of the
2485 if (!Outs.empty()) {
2486 // Check if stack adjustment is needed. For now, do not do this if any
2487 // argument is passed on the stack.
2488 SmallVector<CCValAssign, 16> ArgLocs;
2489 CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2490 ArgLocs, *DAG.getContext());
2491 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
2492 if (CCInfo.getNextStackOffset()) {
2493 MachineFunction &MF = DAG.getMachineFunction();
2494 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2496 if (Subtarget->isTargetWin64())
2497 // Win64 ABI has additional complications.
2500 // Check if the arguments are already laid out in the right way as
2501 // the caller's fixed stack objects.
2502 MachineFrameInfo *MFI = MF.getFrameInfo();
2503 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2504 const X86InstrInfo *TII =
2505 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2506 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2507 CCValAssign &VA = ArgLocs[i];
2508 SDValue Arg = OutVals[i];
2509 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2510 if (VA.getLocInfo() == CCValAssign::Indirect)
2512 if (!VA.isRegLoc()) {
2513 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2520 // If the tailcall address may be in a register, then make sure it's
2521 // possible to register allocate for it. In 32-bit, the call address can
2522 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2523 // callee-saved registers are restored. These happen to be the same
2524 // registers used to pass 'inreg' arguments so watch out for those.
2525 if (!Subtarget->is64Bit() &&
2526 !isa<GlobalAddressSDNode>(Callee) &&
2527 !isa<ExternalSymbolSDNode>(Callee)) {
2528 unsigned NumInRegs = 0;
2529 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2530 CCValAssign &VA = ArgLocs[i];
2533 unsigned Reg = VA.getLocReg();
2536 case X86::EAX: case X86::EDX: case X86::ECX:
2537 if (++NumInRegs == 3)
2549 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2550 return X86::createFastISel(funcInfo);
2554 //===----------------------------------------------------------------------===//
2555 // Other Lowering Hooks
2556 //===----------------------------------------------------------------------===//
2559 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2560 MachineFunction &MF = DAG.getMachineFunction();
2561 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2562 int ReturnAddrIndex = FuncInfo->getRAIndex();
2564 if (ReturnAddrIndex == 0) {
2565 // Set up a frame object for the return address.
2566 uint64_t SlotSize = TD->getPointerSize();
2567 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2569 FuncInfo->setRAIndex(ReturnAddrIndex);
2572 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2576 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2577 bool hasSymbolicDisplacement) {
2578 // Offset should fit into 32 bit immediate field.
2579 if (!isInt<32>(Offset))
2582 // If we don't have a symbolic displacement - we don't have any extra
2584 if (!hasSymbolicDisplacement)
2587 // FIXME: Some tweaks might be needed for medium code model.
2588 if (M != CodeModel::Small && M != CodeModel::Kernel)
2591 // For small code model we assume that latest object is 16MB before end of 31
2592 // bits boundary. We may also accept pretty large negative constants knowing
2593 // that all objects are in the positive half of address space.
2594 if (M == CodeModel::Small && Offset < 16*1024*1024)
2597 // For kernel code model we know that all object resist in the negative half
2598 // of 32bits address space. We may not accept negative offsets, since they may
2599 // be just off and we may accept pretty large positive ones.
2600 if (M == CodeModel::Kernel && Offset > 0)
2606 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2607 /// specific condition code, returning the condition code and the LHS/RHS of the
2608 /// comparison to make.
2609 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2610 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2612 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2613 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2614 // X > -1 -> X == 0, jump !sign.
2615 RHS = DAG.getConstant(0, RHS.getValueType());
2616 return X86::COND_NS;
2617 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2618 // X < 0 -> X == 0, jump on sign.
2620 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2622 RHS = DAG.getConstant(0, RHS.getValueType());
2623 return X86::COND_LE;
2627 switch (SetCCOpcode) {
2628 default: llvm_unreachable("Invalid integer condition!");
2629 case ISD::SETEQ: return X86::COND_E;
2630 case ISD::SETGT: return X86::COND_G;
2631 case ISD::SETGE: return X86::COND_GE;
2632 case ISD::SETLT: return X86::COND_L;
2633 case ISD::SETLE: return X86::COND_LE;
2634 case ISD::SETNE: return X86::COND_NE;
2635 case ISD::SETULT: return X86::COND_B;
2636 case ISD::SETUGT: return X86::COND_A;
2637 case ISD::SETULE: return X86::COND_BE;
2638 case ISD::SETUGE: return X86::COND_AE;
2642 // First determine if it is required or is profitable to flip the operands.
2644 // If LHS is a foldable load, but RHS is not, flip the condition.
2645 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2646 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2647 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2648 std::swap(LHS, RHS);
2651 switch (SetCCOpcode) {
2657 std::swap(LHS, RHS);
2661 // On a floating point condition, the flags are set as follows:
2663 // 0 | 0 | 0 | X > Y
2664 // 0 | 0 | 1 | X < Y
2665 // 1 | 0 | 0 | X == Y
2666 // 1 | 1 | 1 | unordered
2667 switch (SetCCOpcode) {
2668 default: llvm_unreachable("Condcode should be pre-legalized away");
2670 case ISD::SETEQ: return X86::COND_E;
2671 case ISD::SETOLT: // flipped
2673 case ISD::SETGT: return X86::COND_A;
2674 case ISD::SETOLE: // flipped
2676 case ISD::SETGE: return X86::COND_AE;
2677 case ISD::SETUGT: // flipped
2679 case ISD::SETLT: return X86::COND_B;
2680 case ISD::SETUGE: // flipped
2682 case ISD::SETLE: return X86::COND_BE;
2684 case ISD::SETNE: return X86::COND_NE;
2685 case ISD::SETUO: return X86::COND_P;
2686 case ISD::SETO: return X86::COND_NP;
2688 case ISD::SETUNE: return X86::COND_INVALID;
2692 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2693 /// code. Current x86 isa includes the following FP cmov instructions:
2694 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2695 static bool hasFPCMov(unsigned X86CC) {
2711 /// isFPImmLegal - Returns true if the target can instruction select the
2712 /// specified FP immediate natively. If false, the legalizer will
2713 /// materialize the FP immediate as a load from a constant pool.
2714 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2715 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2716 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2722 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2723 /// the specified range (L, H].
2724 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2725 return (Val < 0) || (Val >= Low && Val < Hi);
2728 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2729 /// specified value.
2730 static bool isUndefOrEqual(int Val, int CmpVal) {
2731 if (Val < 0 || Val == CmpVal)
2736 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2737 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2738 /// the second operand.
2739 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2740 if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2741 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2742 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2743 return (Mask[0] < 2 && Mask[1] < 2);
2747 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2748 SmallVector<int, 8> M;
2750 return ::isPSHUFDMask(M, N->getValueType(0));
2753 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2754 /// is suitable for input to PSHUFHW.
2755 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2756 if (VT != MVT::v8i16)
2759 // Lower quadword copied in order or undef.
2760 for (int i = 0; i != 4; ++i)
2761 if (Mask[i] >= 0 && Mask[i] != i)
2764 // Upper quadword shuffled.
2765 for (int i = 4; i != 8; ++i)
2766 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2772 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2773 SmallVector<int, 8> M;
2775 return ::isPSHUFHWMask(M, N->getValueType(0));
2778 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2779 /// is suitable for input to PSHUFLW.
2780 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2781 if (VT != MVT::v8i16)
2784 // Upper quadword copied in order.
2785 for (int i = 4; i != 8; ++i)
2786 if (Mask[i] >= 0 && Mask[i] != i)
2789 // Lower quadword shuffled.
2790 for (int i = 0; i != 4; ++i)
2797 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2798 SmallVector<int, 8> M;
2800 return ::isPSHUFLWMask(M, N->getValueType(0));
2803 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2804 /// is suitable for input to PALIGNR.
2805 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2807 int i, e = VT.getVectorNumElements();
2809 // Do not handle v2i64 / v2f64 shuffles with palignr.
2810 if (e < 4 || !hasSSSE3)
2813 for (i = 0; i != e; ++i)
2817 // All undef, not a palignr.
2821 // Determine if it's ok to perform a palignr with only the LHS, since we
2822 // don't have access to the actual shuffle elements to see if RHS is undef.
2823 bool Unary = Mask[i] < (int)e;
2824 bool NeedsUnary = false;
2826 int s = Mask[i] - i;
2828 // Check the rest of the elements to see if they are consecutive.
2829 for (++i; i != e; ++i) {
2834 Unary = Unary && (m < (int)e);
2835 NeedsUnary = NeedsUnary || (m < s);
2837 if (NeedsUnary && !Unary)
2839 if (Unary && m != ((s+i) & (e-1)))
2841 if (!Unary && m != (s+i))
2847 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2848 SmallVector<int, 8> M;
2850 return ::isPALIGNRMask(M, N->getValueType(0), true);
2853 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2854 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2855 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2856 int NumElems = VT.getVectorNumElements();
2857 if (NumElems != 2 && NumElems != 4)
2860 int Half = NumElems / 2;
2861 for (int i = 0; i < Half; ++i)
2862 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2864 for (int i = Half; i < NumElems; ++i)
2865 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2871 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2872 SmallVector<int, 8> M;
2874 return ::isSHUFPMask(M, N->getValueType(0));
2877 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2878 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2879 /// half elements to come from vector 1 (which would equal the dest.) and
2880 /// the upper half to come from vector 2.
2881 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2882 int NumElems = VT.getVectorNumElements();
2884 if (NumElems != 2 && NumElems != 4)
2887 int Half = NumElems / 2;
2888 for (int i = 0; i < Half; ++i)
2889 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2891 for (int i = Half; i < NumElems; ++i)
2892 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2897 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2898 SmallVector<int, 8> M;
2900 return isCommutedSHUFPMask(M, N->getValueType(0));
2903 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2904 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2905 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2906 if (N->getValueType(0).getVectorNumElements() != 4)
2909 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2910 return isUndefOrEqual(N->getMaskElt(0), 6) &&
2911 isUndefOrEqual(N->getMaskElt(1), 7) &&
2912 isUndefOrEqual(N->getMaskElt(2), 2) &&
2913 isUndefOrEqual(N->getMaskElt(3), 3);
2916 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2917 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2919 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2920 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2925 return isUndefOrEqual(N->getMaskElt(0), 2) &&
2926 isUndefOrEqual(N->getMaskElt(1), 3) &&
2927 isUndefOrEqual(N->getMaskElt(2), 2) &&
2928 isUndefOrEqual(N->getMaskElt(3), 3);
2931 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2932 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2933 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2934 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2936 if (NumElems != 2 && NumElems != 4)
2939 for (unsigned i = 0; i < NumElems/2; ++i)
2940 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2943 for (unsigned i = NumElems/2; i < NumElems; ++i)
2944 if (!isUndefOrEqual(N->getMaskElt(i), i))
2950 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
2951 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
2952 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
2953 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2955 if (NumElems != 2 && NumElems != 4)
2958 for (unsigned i = 0; i < NumElems/2; ++i)
2959 if (!isUndefOrEqual(N->getMaskElt(i), i))
2962 for (unsigned i = 0; i < NumElems/2; ++i)
2963 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2969 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2970 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2971 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2972 bool V2IsSplat = false) {
2973 int NumElts = VT.getVectorNumElements();
2974 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2977 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2979 int BitI1 = Mask[i+1];
2980 if (!isUndefOrEqual(BitI, j))
2983 if (!isUndefOrEqual(BitI1, NumElts))
2986 if (!isUndefOrEqual(BitI1, j + NumElts))
2993 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2994 SmallVector<int, 8> M;
2996 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2999 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3000 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3001 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3002 bool V2IsSplat = false) {
3003 int NumElts = VT.getVectorNumElements();
3004 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3007 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3009 int BitI1 = Mask[i+1];
3010 if (!isUndefOrEqual(BitI, j + NumElts/2))
3013 if (isUndefOrEqual(BitI1, NumElts))
3016 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3023 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3024 SmallVector<int, 8> M;
3026 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3029 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3030 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3032 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3033 int NumElems = VT.getVectorNumElements();
3034 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3037 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
3039 int BitI1 = Mask[i+1];
3040 if (!isUndefOrEqual(BitI, j))
3042 if (!isUndefOrEqual(BitI1, j))
3048 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3049 SmallVector<int, 8> M;
3051 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3054 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3055 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3057 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3058 int NumElems = VT.getVectorNumElements();
3059 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3062 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3064 int BitI1 = Mask[i+1];
3065 if (!isUndefOrEqual(BitI, j))
3067 if (!isUndefOrEqual(BitI1, j))
3073 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3074 SmallVector<int, 8> M;
3076 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3079 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3080 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3081 /// MOVSD, and MOVD, i.e. setting the lowest element.
3082 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3083 if (VT.getVectorElementType().getSizeInBits() < 32)
3086 int NumElts = VT.getVectorNumElements();
3088 if (!isUndefOrEqual(Mask[0], NumElts))
3091 for (int i = 1; i < NumElts; ++i)
3092 if (!isUndefOrEqual(Mask[i], i))
3098 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3099 SmallVector<int, 8> M;
3101 return ::isMOVLMask(M, N->getValueType(0));
3104 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3105 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3106 /// element of vector 2 and the other elements to come from vector 1 in order.
3107 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3108 bool V2IsSplat = false, bool V2IsUndef = false) {
3109 int NumOps = VT.getVectorNumElements();
3110 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3113 if (!isUndefOrEqual(Mask[0], 0))
3116 for (int i = 1; i < NumOps; ++i)
3117 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3118 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3119 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3125 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3126 bool V2IsUndef = false) {
3127 SmallVector<int, 8> M;
3129 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3132 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3133 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3134 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3135 if (N->getValueType(0).getVectorNumElements() != 4)
3138 // Expect 1, 1, 3, 3
3139 for (unsigned i = 0; i < 2; ++i) {
3140 int Elt = N->getMaskElt(i);
3141 if (Elt >= 0 && Elt != 1)
3146 for (unsigned i = 2; i < 4; ++i) {
3147 int Elt = N->getMaskElt(i);
3148 if (Elt >= 0 && Elt != 3)
3153 // Don't use movshdup if it can be done with a shufps.
3154 // FIXME: verify that matching u, u, 3, 3 is what we want.
3158 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3159 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3160 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3161 if (N->getValueType(0).getVectorNumElements() != 4)
3164 // Expect 0, 0, 2, 2
3165 for (unsigned i = 0; i < 2; ++i)
3166 if (N->getMaskElt(i) > 0)
3170 for (unsigned i = 2; i < 4; ++i) {
3171 int Elt = N->getMaskElt(i);
3172 if (Elt >= 0 && Elt != 2)
3177 // Don't use movsldup if it can be done with a shufps.
3181 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3182 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3183 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3184 int e = N->getValueType(0).getVectorNumElements() / 2;
3186 for (int i = 0; i < e; ++i)
3187 if (!isUndefOrEqual(N->getMaskElt(i), i))
3189 for (int i = 0; i < e; ++i)
3190 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3195 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3196 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3197 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3198 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3199 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3201 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3203 for (int i = 0; i < NumOperands; ++i) {
3204 int Val = SVOp->getMaskElt(NumOperands-i-1);
3205 if (Val < 0) Val = 0;
3206 if (Val >= NumOperands) Val -= NumOperands;
3208 if (i != NumOperands - 1)
3214 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3215 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3216 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3217 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3219 // 8 nodes, but we only care about the last 4.
3220 for (unsigned i = 7; i >= 4; --i) {
3221 int Val = SVOp->getMaskElt(i);
3230 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3231 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3232 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3233 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3235 // 8 nodes, but we only care about the first 4.
3236 for (int i = 3; i >= 0; --i) {
3237 int Val = SVOp->getMaskElt(i);
3246 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3247 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3248 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3249 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3250 EVT VVT = N->getValueType(0);
3251 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3255 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3256 Val = SVOp->getMaskElt(i);
3260 return (Val - i) * EltSize;
3263 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3265 bool X86::isZeroNode(SDValue Elt) {
3266 return ((isa<ConstantSDNode>(Elt) &&
3267 cast<ConstantSDNode>(Elt)->isNullValue()) ||
3268 (isa<ConstantFPSDNode>(Elt) &&
3269 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3272 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3273 /// their permute mask.
3274 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3275 SelectionDAG &DAG) {
3276 EVT VT = SVOp->getValueType(0);
3277 unsigned NumElems = VT.getVectorNumElements();
3278 SmallVector<int, 8> MaskVec;
3280 for (unsigned i = 0; i != NumElems; ++i) {
3281 int idx = SVOp->getMaskElt(i);
3283 MaskVec.push_back(idx);
3284 else if (idx < (int)NumElems)
3285 MaskVec.push_back(idx + NumElems);
3287 MaskVec.push_back(idx - NumElems);
3289 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3290 SVOp->getOperand(0), &MaskVec[0]);
3293 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3294 /// the two vector operands have swapped position.
3295 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3296 unsigned NumElems = VT.getVectorNumElements();
3297 for (unsigned i = 0; i != NumElems; ++i) {
3301 else if (idx < (int)NumElems)
3302 Mask[i] = idx + NumElems;
3304 Mask[i] = idx - NumElems;
3308 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3309 /// match movhlps. The lower half elements should come from upper half of
3310 /// V1 (and in order), and the upper half elements should come from the upper
3311 /// half of V2 (and in order).
3312 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3313 if (Op->getValueType(0).getVectorNumElements() != 4)
3315 for (unsigned i = 0, e = 2; i != e; ++i)
3316 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3318 for (unsigned i = 2; i != 4; ++i)
3319 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3324 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3325 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3327 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3328 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3330 N = N->getOperand(0).getNode();
3331 if (!ISD::isNON_EXTLoad(N))
3334 *LD = cast<LoadSDNode>(N);
3338 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3339 /// match movlp{s|d}. The lower half elements should come from lower half of
3340 /// V1 (and in order), and the upper half elements should come from the upper
3341 /// half of V2 (and in order). And since V1 will become the source of the
3342 /// MOVLP, it must be either a vector load or a scalar load to vector.
3343 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3344 ShuffleVectorSDNode *Op) {
3345 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3347 // Is V2 is a vector load, don't do this transformation. We will try to use
3348 // load folding shufps op.
3349 if (ISD::isNON_EXTLoad(V2))
3352 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3354 if (NumElems != 2 && NumElems != 4)
3356 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3357 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3359 for (unsigned i = NumElems/2; i != NumElems; ++i)
3360 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3365 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3367 static bool isSplatVector(SDNode *N) {
3368 if (N->getOpcode() != ISD::BUILD_VECTOR)
3371 SDValue SplatValue = N->getOperand(0);
3372 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3373 if (N->getOperand(i) != SplatValue)
3378 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3379 /// to an zero vector.
3380 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3381 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3382 SDValue V1 = N->getOperand(0);
3383 SDValue V2 = N->getOperand(1);
3384 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3385 for (unsigned i = 0; i != NumElems; ++i) {
3386 int Idx = N->getMaskElt(i);
3387 if (Idx >= (int)NumElems) {
3388 unsigned Opc = V2.getOpcode();
3389 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3391 if (Opc != ISD::BUILD_VECTOR ||
3392 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3394 } else if (Idx >= 0) {
3395 unsigned Opc = V1.getOpcode();
3396 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3398 if (Opc != ISD::BUILD_VECTOR ||
3399 !X86::isZeroNode(V1.getOperand(Idx)))
3406 /// getZeroVector - Returns a vector of specified type with all zero elements.
3408 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3410 assert(VT.isVector() && "Expected a vector type");
3412 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3413 // type. This ensures they get CSE'd.
3415 if (VT.getSizeInBits() == 64) { // MMX
3416 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3417 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3418 } else if (HasSSE2) { // SSE2
3419 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3420 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3422 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3423 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3425 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3428 /// getOnesVector - Returns a vector of specified type with all bits set.
3430 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3431 assert(VT.isVector() && "Expected a vector type");
3433 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3434 // type. This ensures they get CSE'd.
3435 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3437 if (VT.getSizeInBits() == 64) // MMX
3438 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3440 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3441 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3445 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3446 /// that point to V2 points to its first element.
3447 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3448 EVT VT = SVOp->getValueType(0);
3449 unsigned NumElems = VT.getVectorNumElements();
3451 bool Changed = false;
3452 SmallVector<int, 8> MaskVec;
3453 SVOp->getMask(MaskVec);
3455 for (unsigned i = 0; i != NumElems; ++i) {
3456 if (MaskVec[i] > (int)NumElems) {
3457 MaskVec[i] = NumElems;
3462 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3463 SVOp->getOperand(1), &MaskVec[0]);
3464 return SDValue(SVOp, 0);
3467 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3468 /// operation of specified width.
3469 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3471 unsigned NumElems = VT.getVectorNumElements();
3472 SmallVector<int, 8> Mask;
3473 Mask.push_back(NumElems);
3474 for (unsigned i = 1; i != NumElems; ++i)
3476 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3479 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3480 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3482 unsigned NumElems = VT.getVectorNumElements();
3483 SmallVector<int, 8> Mask;
3484 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3486 Mask.push_back(i + NumElems);
3488 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3491 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3492 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3494 unsigned NumElems = VT.getVectorNumElements();
3495 unsigned Half = NumElems/2;
3496 SmallVector<int, 8> Mask;
3497 for (unsigned i = 0; i != Half; ++i) {
3498 Mask.push_back(i + Half);
3499 Mask.push_back(i + NumElems + Half);
3501 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3504 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3505 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3507 if (SV->getValueType(0).getVectorNumElements() <= 4)
3508 return SDValue(SV, 0);
3510 EVT PVT = MVT::v4f32;
3511 EVT VT = SV->getValueType(0);
3512 DebugLoc dl = SV->getDebugLoc();
3513 SDValue V1 = SV->getOperand(0);
3514 int NumElems = VT.getVectorNumElements();
3515 int EltNo = SV->getSplatIndex();
3517 // unpack elements to the correct location
3518 while (NumElems > 4) {
3519 if (EltNo < NumElems/2) {
3520 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3522 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3523 EltNo -= NumElems/2;
3528 // Perform the splat.
3529 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3530 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3531 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3532 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3535 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3536 /// vector of zero or undef vector. This produces a shuffle where the low
3537 /// element of V2 is swizzled into the zero/undef vector, landing at element
3538 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3539 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3540 bool isZero, bool HasSSE2,
3541 SelectionDAG &DAG) {
3542 EVT VT = V2.getValueType();
3544 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3545 unsigned NumElems = VT.getVectorNumElements();
3546 SmallVector<int, 16> MaskVec;
3547 for (unsigned i = 0; i != NumElems; ++i)
3548 // If this is the insertion idx, put the low elt of V2 here.
3549 MaskVec.push_back(i == Idx ? NumElems : i);
3550 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3553 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3554 /// a shuffle that is zero.
3556 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3557 bool Low, SelectionDAG &DAG) {
3558 unsigned NumZeros = 0;
3559 for (int i = 0; i < NumElems; ++i) {
3560 unsigned Index = Low ? i : NumElems-i-1;
3561 int Idx = SVOp->getMaskElt(Index);
3566 SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3567 if (Elt.getNode() && X86::isZeroNode(Elt))
3575 /// isVectorShift - Returns true if the shuffle can be implemented as a
3576 /// logical left or right shift of a vector.
3577 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3578 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3579 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3580 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3583 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3586 NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3590 bool SeenV1 = false;
3591 bool SeenV2 = false;
3592 for (unsigned i = NumZeros; i < NumElems; ++i) {
3593 unsigned Val = isLeft ? (i - NumZeros) : i;
3594 int Idx_ = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3597 unsigned Idx = (unsigned) Idx_;
3607 if (SeenV1 && SeenV2)
3610 ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3616 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3618 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3619 unsigned NumNonZero, unsigned NumZero,
3621 const TargetLowering &TLI) {
3625 DebugLoc dl = Op.getDebugLoc();
3628 for (unsigned i = 0; i < 16; ++i) {
3629 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3630 if (ThisIsNonZero && First) {
3632 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3634 V = DAG.getUNDEF(MVT::v8i16);
3639 SDValue ThisElt(0, 0), LastElt(0, 0);
3640 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3641 if (LastIsNonZero) {
3642 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3643 MVT::i16, Op.getOperand(i-1));
3645 if (ThisIsNonZero) {
3646 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3647 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3648 ThisElt, DAG.getConstant(8, MVT::i8));
3650 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3654 if (ThisElt.getNode())
3655 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3656 DAG.getIntPtrConstant(i/2));
3660 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3663 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3665 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3666 unsigned NumNonZero, unsigned NumZero,
3668 const TargetLowering &TLI) {
3672 DebugLoc dl = Op.getDebugLoc();
3675 for (unsigned i = 0; i < 8; ++i) {
3676 bool isNonZero = (NonZeros & (1 << i)) != 0;
3680 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3682 V = DAG.getUNDEF(MVT::v8i16);
3685 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3686 MVT::v8i16, V, Op.getOperand(i),
3687 DAG.getIntPtrConstant(i));
3694 /// getVShift - Return a vector logical shift node.
3696 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3697 unsigned NumBits, SelectionDAG &DAG,
3698 const TargetLowering &TLI, DebugLoc dl) {
3699 bool isMMX = VT.getSizeInBits() == 64;
3700 EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3701 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3702 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3703 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3704 DAG.getNode(Opc, dl, ShVT, SrcOp,
3705 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3709 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3710 SelectionDAG &DAG) const {
3712 // Check if the scalar load can be widened into a vector load. And if
3713 // the address is "base + cst" see if the cst can be "absorbed" into
3714 // the shuffle mask.
3715 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3716 SDValue Ptr = LD->getBasePtr();
3717 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3719 EVT PVT = LD->getValueType(0);
3720 if (PVT != MVT::i32 && PVT != MVT::f32)
3725 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3726 FI = FINode->getIndex();
3728 } else if (Ptr.getOpcode() == ISD::ADD &&
3729 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
3730 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
3731 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
3732 Offset = Ptr.getConstantOperandVal(1);
3733 Ptr = Ptr.getOperand(0);
3738 SDValue Chain = LD->getChain();
3739 // Make sure the stack object alignment is at least 16.
3740 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3741 if (DAG.InferPtrAlignment(Ptr) < 16) {
3742 if (MFI->isFixedObjectIndex(FI)) {
3743 // Can't change the alignment. FIXME: It's possible to compute
3744 // the exact stack offset and reference FI + adjust offset instead.
3745 // If someone *really* cares about this. That's the way to implement it.
3748 MFI->setObjectAlignment(FI, 16);
3752 // (Offset % 16) must be multiple of 4. Then address is then
3753 // Ptr + (Offset & ~15).
3756 if ((Offset % 16) & 3)
3758 int64_t StartOffset = Offset & ~15;
3760 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
3761 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
3763 int EltNo = (Offset - StartOffset) >> 2;
3764 int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
3765 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
3766 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,LD->getSrcValue(),0,
3768 // Canonicalize it to a v4i32 shuffle.
3769 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
3770 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3771 DAG.getVectorShuffle(MVT::v4i32, dl, V1,
3772 DAG.getUNDEF(MVT::v4i32), &Mask[0]));
3778 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
3779 /// vector of type 'VT', see if the elements can be replaced by a single large
3780 /// load which has the same value as a build_vector whose operands are 'elts'.
3782 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
3784 /// FIXME: we'd also like to handle the case where the last elements are zero
3785 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
3786 /// There's even a handy isZeroNode for that purpose.
3787 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
3788 DebugLoc &dl, SelectionDAG &DAG) {
3789 EVT EltVT = VT.getVectorElementType();
3790 unsigned NumElems = Elts.size();
3792 LoadSDNode *LDBase = NULL;
3793 unsigned LastLoadedElt = -1U;
3795 // For each element in the initializer, see if we've found a load or an undef.
3796 // If we don't find an initial load element, or later load elements are
3797 // non-consecutive, bail out.
3798 for (unsigned i = 0; i < NumElems; ++i) {
3799 SDValue Elt = Elts[i];
3801 if (!Elt.getNode() ||
3802 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
3805 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
3807 LDBase = cast<LoadSDNode>(Elt.getNode());
3811 if (Elt.getOpcode() == ISD::UNDEF)
3814 LoadSDNode *LD = cast<LoadSDNode>(Elt);
3815 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
3820 // If we have found an entire vector of loads and undefs, then return a large
3821 // load of the entire vector width starting at the base pointer. If we found
3822 // consecutive loads for the low half, generate a vzext_load node.
3823 if (LastLoadedElt == NumElems - 1) {
3824 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
3825 return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3826 LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3827 LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
3828 return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3829 LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3830 LDBase->isVolatile(), LDBase->isNonTemporal(),
3831 LDBase->getAlignment());
3832 } else if (NumElems == 4 && LastLoadedElt == 1) {
3833 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
3834 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
3835 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
3836 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
3842 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
3843 DebugLoc dl = Op.getDebugLoc();
3844 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3845 if (ISD::isBuildVectorAllZeros(Op.getNode())
3846 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3847 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3848 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3849 // eliminated on x86-32 hosts.
3850 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3853 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3854 return getOnesVector(Op.getValueType(), DAG, dl);
3855 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3858 EVT VT = Op.getValueType();
3859 EVT ExtVT = VT.getVectorElementType();
3860 unsigned EVTBits = ExtVT.getSizeInBits();
3862 unsigned NumElems = Op.getNumOperands();
3863 unsigned NumZero = 0;
3864 unsigned NumNonZero = 0;
3865 unsigned NonZeros = 0;
3866 bool IsAllConstants = true;
3867 SmallSet<SDValue, 8> Values;
3868 for (unsigned i = 0; i < NumElems; ++i) {
3869 SDValue Elt = Op.getOperand(i);
3870 if (Elt.getOpcode() == ISD::UNDEF)
3873 if (Elt.getOpcode() != ISD::Constant &&
3874 Elt.getOpcode() != ISD::ConstantFP)
3875 IsAllConstants = false;
3876 if (X86::isZeroNode(Elt))
3879 NonZeros |= (1 << i);
3884 if (NumNonZero == 0) {
3885 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3886 return DAG.getUNDEF(VT);
3889 // Special case for single non-zero, non-undef, element.
3890 if (NumNonZero == 1) {
3891 unsigned Idx = CountTrailingZeros_32(NonZeros);
3892 SDValue Item = Op.getOperand(Idx);
3894 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3895 // the value are obviously zero, truncate the value to i32 and do the
3896 // insertion that way. Only do this if the value is non-constant or if the
3897 // value is a constant being inserted into element 0. It is cheaper to do
3898 // a constant pool load than it is to do a movd + shuffle.
3899 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3900 (!IsAllConstants || Idx == 0)) {
3901 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3902 // Handle MMX and SSE both.
3903 EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3904 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3906 // Truncate the value (which may itself be a constant) to i32, and
3907 // convert it to a vector with movd (S2V+shuffle to zero extend).
3908 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3909 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3910 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3911 Subtarget->hasSSE2(), DAG);
3913 // Now we have our 32-bit value zero extended in the low element of
3914 // a vector. If Idx != 0, swizzle it into place.
3916 SmallVector<int, 4> Mask;
3917 Mask.push_back(Idx);
3918 for (unsigned i = 1; i != VecElts; ++i)
3920 Item = DAG.getVectorShuffle(VecVT, dl, Item,
3921 DAG.getUNDEF(Item.getValueType()),
3924 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3928 // If we have a constant or non-constant insertion into the low element of
3929 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3930 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3931 // depending on what the source datatype is.
3934 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3935 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3936 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3937 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3938 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3939 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3941 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3942 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3943 EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3944 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3945 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3946 Subtarget->hasSSE2(), DAG);
3947 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3951 // Is it a vector logical left shift?
3952 if (NumElems == 2 && Idx == 1 &&
3953 X86::isZeroNode(Op.getOperand(0)) &&
3954 !X86::isZeroNode(Op.getOperand(1))) {
3955 unsigned NumBits = VT.getSizeInBits();
3956 return getVShift(true, VT,
3957 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3958 VT, Op.getOperand(1)),
3959 NumBits/2, DAG, *this, dl);
3962 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3965 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3966 // is a non-constant being inserted into an element other than the low one,
3967 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3968 // movd/movss) to move this into the low element, then shuffle it into
3970 if (EVTBits == 32) {
3971 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3973 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3974 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3975 Subtarget->hasSSE2(), DAG);
3976 SmallVector<int, 8> MaskVec;
3977 for (unsigned i = 0; i < NumElems; i++)
3978 MaskVec.push_back(i == Idx ? 0 : 1);
3979 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3983 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3984 if (Values.size() == 1) {
3985 if (EVTBits == 32) {
3986 // Instead of a shuffle like this:
3987 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
3988 // Check if it's possible to issue this instead.
3989 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
3990 unsigned Idx = CountTrailingZeros_32(NonZeros);
3991 SDValue Item = Op.getOperand(Idx);
3992 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
3993 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
3998 // A vector full of immediates; various special cases are already
3999 // handled, so this is best done with a single constant-pool load.
4003 // Let legalizer expand 2-wide build_vectors.
4004 if (EVTBits == 64) {
4005 if (NumNonZero == 1) {
4006 // One half is zero or undef.
4007 unsigned Idx = CountTrailingZeros_32(NonZeros);
4008 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4009 Op.getOperand(Idx));
4010 return getShuffleVectorZeroOrUndef(V2, Idx, true,
4011 Subtarget->hasSSE2(), DAG);
4016 // If element VT is < 32 bits, convert it to inserts into a zero vector.
4017 if (EVTBits == 8 && NumElems == 16) {
4018 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4020 if (V.getNode()) return V;
4023 if (EVTBits == 16 && NumElems == 8) {
4024 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4026 if (V.getNode()) return V;
4029 // If element VT is == 32 bits, turn it into a number of shuffles.
4030 SmallVector<SDValue, 8> V;
4032 if (NumElems == 4 && NumZero > 0) {
4033 for (unsigned i = 0; i < 4; ++i) {
4034 bool isZero = !(NonZeros & (1 << i));
4036 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4038 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4041 for (unsigned i = 0; i < 2; ++i) {
4042 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4045 V[i] = V[i*2]; // Must be a zero vector.
4048 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4051 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4054 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4059 SmallVector<int, 8> MaskVec;
4060 bool Reverse = (NonZeros & 0x3) == 2;
4061 for (unsigned i = 0; i < 2; ++i)
4062 MaskVec.push_back(Reverse ? 1-i : i);
4063 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4064 for (unsigned i = 0; i < 2; ++i)
4065 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4066 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4069 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4070 // Check for a build vector of consecutive loads.
4071 for (unsigned i = 0; i < NumElems; ++i)
4072 V[i] = Op.getOperand(i);
4074 // Check for elements which are consecutive loads.
4075 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4079 // For SSE 4.1, use inserts into undef.
4080 if (getSubtarget()->hasSSE41()) {
4081 V[0] = DAG.getUNDEF(VT);
4082 for (unsigned i = 0; i < NumElems; ++i)
4083 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4084 V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
4085 Op.getOperand(i), DAG.getIntPtrConstant(i));
4089 // Otherwise, expand into a number of unpckl*
4091 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4092 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4093 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
4094 for (unsigned i = 0; i < NumElems; ++i)
4095 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4097 while (NumElems != 0) {
4098 for (unsigned i = 0; i < NumElems; ++i)
4099 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
4108 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4109 // We support concatenate two MMX registers and place them in a MMX
4110 // register. This is better than doing a stack convert.
4111 DebugLoc dl = Op.getDebugLoc();
4112 EVT ResVT = Op.getValueType();
4113 assert(Op.getNumOperands() == 2);
4114 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4115 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4117 SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
4118 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4119 InVec = Op.getOperand(1);
4120 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4121 unsigned NumElts = ResVT.getVectorNumElements();
4122 VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4123 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4124 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4126 InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
4127 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4128 Mask[0] = 0; Mask[1] = 2;
4129 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4131 return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4134 // v8i16 shuffles - Prefer shuffles in the following order:
4135 // 1. [all] pshuflw, pshufhw, optional move
4136 // 2. [ssse3] 1 x pshufb
4137 // 3. [ssse3] 2 x pshufb + 1 x por
4138 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4140 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
4142 const X86TargetLowering &TLI) {
4143 SDValue V1 = SVOp->getOperand(0);
4144 SDValue V2 = SVOp->getOperand(1);
4145 DebugLoc dl = SVOp->getDebugLoc();
4146 SmallVector<int, 8> MaskVals;
4148 // Determine if more than 1 of the words in each of the low and high quadwords
4149 // of the result come from the same quadword of one of the two inputs. Undef
4150 // mask values count as coming from any quadword, for better codegen.
4151 SmallVector<unsigned, 4> LoQuad(4);
4152 SmallVector<unsigned, 4> HiQuad(4);
4153 BitVector InputQuads(4);
4154 for (unsigned i = 0; i < 8; ++i) {
4155 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4156 int EltIdx = SVOp->getMaskElt(i);
4157 MaskVals.push_back(EltIdx);
4166 InputQuads.set(EltIdx / 4);
4169 int BestLoQuad = -1;
4170 unsigned MaxQuad = 1;
4171 for (unsigned i = 0; i < 4; ++i) {
4172 if (LoQuad[i] > MaxQuad) {
4174 MaxQuad = LoQuad[i];
4178 int BestHiQuad = -1;
4180 for (unsigned i = 0; i < 4; ++i) {
4181 if (HiQuad[i] > MaxQuad) {
4183 MaxQuad = HiQuad[i];
4187 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4188 // of the two input vectors, shuffle them into one input vector so only a
4189 // single pshufb instruction is necessary. If There are more than 2 input
4190 // quads, disable the next transformation since it does not help SSSE3.
4191 bool V1Used = InputQuads[0] || InputQuads[1];
4192 bool V2Used = InputQuads[2] || InputQuads[3];
4193 if (TLI.getSubtarget()->hasSSSE3()) {
4194 if (InputQuads.count() == 2 && V1Used && V2Used) {
4195 BestLoQuad = InputQuads.find_first();
4196 BestHiQuad = InputQuads.find_next(BestLoQuad);
4198 if (InputQuads.count() > 2) {
4204 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4205 // the shuffle mask. If a quad is scored as -1, that means that it contains
4206 // words from all 4 input quadwords.
4208 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4209 SmallVector<int, 8> MaskV;
4210 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4211 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4212 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4213 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
4214 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
4215 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
4217 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4218 // source words for the shuffle, to aid later transformations.
4219 bool AllWordsInNewV = true;
4220 bool InOrder[2] = { true, true };
4221 for (unsigned i = 0; i != 8; ++i) {
4222 int idx = MaskVals[i];
4224 InOrder[i/4] = false;
4225 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4227 AllWordsInNewV = false;
4231 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4232 if (AllWordsInNewV) {
4233 for (int i = 0; i != 8; ++i) {
4234 int idx = MaskVals[i];
4237 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4238 if ((idx != i) && idx < 4)
4240 if ((idx != i) && idx > 3)
4249 // If we've eliminated the use of V2, and the new mask is a pshuflw or
4250 // pshufhw, that's as cheap as it gets. Return the new shuffle.
4251 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4252 return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4253 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4257 // If we have SSSE3, and all words of the result are from 1 input vector,
4258 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
4259 // is present, fall back to case 4.
4260 if (TLI.getSubtarget()->hasSSSE3()) {
4261 SmallVector<SDValue,16> pshufbMask;
4263 // If we have elements from both input vectors, set the high bit of the
4264 // shuffle mask element to zero out elements that come from V2 in the V1
4265 // mask, and elements that come from V1 in the V2 mask, so that the two
4266 // results can be OR'd together.
4267 bool TwoInputs = V1Used && V2Used;
4268 for (unsigned i = 0; i != 8; ++i) {
4269 int EltIdx = MaskVals[i] * 2;
4270 if (TwoInputs && (EltIdx >= 16)) {
4271 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4272 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4275 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4276 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4278 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
4279 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4280 DAG.getNode(ISD::BUILD_VECTOR, dl,
4281 MVT::v16i8, &pshufbMask[0], 16));
4283 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4285 // Calculate the shuffle mask for the second input, shuffle it, and
4286 // OR it with the first shuffled input.
4288 for (unsigned i = 0; i != 8; ++i) {
4289 int EltIdx = MaskVals[i] * 2;
4291 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4292 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4295 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4296 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4298 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
4299 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4300 DAG.getNode(ISD::BUILD_VECTOR, dl,
4301 MVT::v16i8, &pshufbMask[0], 16));
4302 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4303 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4306 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4307 // and update MaskVals with new element order.
4308 BitVector InOrder(8);
4309 if (BestLoQuad >= 0) {
4310 SmallVector<int, 8> MaskV;
4311 for (int i = 0; i != 4; ++i) {
4312 int idx = MaskVals[i];
4314 MaskV.push_back(-1);
4316 } else if ((idx / 4) == BestLoQuad) {
4317 MaskV.push_back(idx & 3);
4320 MaskV.push_back(-1);
4323 for (unsigned i = 4; i != 8; ++i)
4325 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4329 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4330 // and update MaskVals with the new element order.
4331 if (BestHiQuad >= 0) {
4332 SmallVector<int, 8> MaskV;
4333 for (unsigned i = 0; i != 4; ++i)
4335 for (unsigned i = 4; i != 8; ++i) {
4336 int idx = MaskVals[i];
4338 MaskV.push_back(-1);
4340 } else if ((idx / 4) == BestHiQuad) {
4341 MaskV.push_back((idx & 3) + 4);
4344 MaskV.push_back(-1);
4347 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4351 // In case BestHi & BestLo were both -1, which means each quadword has a word
4352 // from each of the four input quadwords, calculate the InOrder bitvector now
4353 // before falling through to the insert/extract cleanup.
4354 if (BestLoQuad == -1 && BestHiQuad == -1) {
4356 for (int i = 0; i != 8; ++i)
4357 if (MaskVals[i] < 0 || MaskVals[i] == i)
4361 // The other elements are put in the right place using pextrw and pinsrw.
4362 for (unsigned i = 0; i != 8; ++i) {
4365 int EltIdx = MaskVals[i];
4368 SDValue ExtOp = (EltIdx < 8)
4369 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4370 DAG.getIntPtrConstant(EltIdx))
4371 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4372 DAG.getIntPtrConstant(EltIdx - 8));
4373 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4374 DAG.getIntPtrConstant(i));
4379 // v16i8 shuffles - Prefer shuffles in the following order:
4380 // 1. [ssse3] 1 x pshufb
4381 // 2. [ssse3] 2 x pshufb + 1 x por
4382 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
4384 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4386 const X86TargetLowering &TLI) {
4387 SDValue V1 = SVOp->getOperand(0);
4388 SDValue V2 = SVOp->getOperand(1);
4389 DebugLoc dl = SVOp->getDebugLoc();
4390 SmallVector<int, 16> MaskVals;
4391 SVOp->getMask(MaskVals);
4393 // If we have SSSE3, case 1 is generated when all result bytes come from
4394 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
4395 // present, fall back to case 3.
4396 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4399 for (unsigned i = 0; i < 16; ++i) {
4400 int EltIdx = MaskVals[i];
4409 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4410 if (TLI.getSubtarget()->hasSSSE3()) {
4411 SmallVector<SDValue,16> pshufbMask;
4413 // If all result elements are from one input vector, then only translate
4414 // undef mask values to 0x80 (zero out result) in the pshufb mask.
4416 // Otherwise, we have elements from both input vectors, and must zero out
4417 // elements that come from V2 in the first mask, and V1 in the second mask
4418 // so that we can OR them together.
4419 bool TwoInputs = !(V1Only || V2Only);
4420 for (unsigned i = 0; i != 16; ++i) {
4421 int EltIdx = MaskVals[i];
4422 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4423 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4426 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4428 // If all the elements are from V2, assign it to V1 and return after
4429 // building the first pshufb.
4432 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4433 DAG.getNode(ISD::BUILD_VECTOR, dl,
4434 MVT::v16i8, &pshufbMask[0], 16));
4438 // Calculate the shuffle mask for the second input, shuffle it, and
4439 // OR it with the first shuffled input.
4441 for (unsigned i = 0; i != 16; ++i) {
4442 int EltIdx = MaskVals[i];
4444 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4447 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4449 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4450 DAG.getNode(ISD::BUILD_VECTOR, dl,
4451 MVT::v16i8, &pshufbMask[0], 16));
4452 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4455 // No SSSE3 - Calculate in place words and then fix all out of place words
4456 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
4457 // the 16 different words that comprise the two doublequadword input vectors.
4458 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4459 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4460 SDValue NewV = V2Only ? V2 : V1;
4461 for (int i = 0; i != 8; ++i) {
4462 int Elt0 = MaskVals[i*2];
4463 int Elt1 = MaskVals[i*2+1];
4465 // This word of the result is all undef, skip it.
4466 if (Elt0 < 0 && Elt1 < 0)
4469 // This word of the result is already in the correct place, skip it.
4470 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4472 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4475 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4476 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4479 // If Elt0 and Elt1 are defined, are consecutive, and can be load
4480 // using a single extract together, load it and store it.
4481 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4482 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4483 DAG.getIntPtrConstant(Elt1 / 2));
4484 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4485 DAG.getIntPtrConstant(i));
4489 // If Elt1 is defined, extract it from the appropriate source. If the
4490 // source byte is not also odd, shift the extracted word left 8 bits
4491 // otherwise clear the bottom 8 bits if we need to do an or.
4493 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4494 DAG.getIntPtrConstant(Elt1 / 2));
4495 if ((Elt1 & 1) == 0)
4496 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4497 DAG.getConstant(8, TLI.getShiftAmountTy()));
4499 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4500 DAG.getConstant(0xFF00, MVT::i16));
4502 // If Elt0 is defined, extract it from the appropriate source. If the
4503 // source byte is not also even, shift the extracted word right 8 bits. If
4504 // Elt1 was also defined, OR the extracted values together before
4505 // inserting them in the result.
4507 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4508 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4509 if ((Elt0 & 1) != 0)
4510 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4511 DAG.getConstant(8, TLI.getShiftAmountTy()));
4513 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4514 DAG.getConstant(0x00FF, MVT::i16));
4515 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4518 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4519 DAG.getIntPtrConstant(i));
4521 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4524 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4525 /// ones, or rewriting v4i32 / v2i32 as 2 wide ones if possible. This can be
4526 /// done when every pair / quad of shuffle mask elements point to elements in
4527 /// the right sequence. e.g.
4528 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
4530 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4532 const TargetLowering &TLI, DebugLoc dl) {
4533 EVT VT = SVOp->getValueType(0);
4534 SDValue V1 = SVOp->getOperand(0);
4535 SDValue V2 = SVOp->getOperand(1);
4536 unsigned NumElems = VT.getVectorNumElements();
4537 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4538 EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
4540 switch (VT.getSimpleVT().SimpleTy) {
4541 default: assert(false && "Unexpected!");
4542 case MVT::v4f32: NewVT = MVT::v2f64; break;
4543 case MVT::v4i32: NewVT = MVT::v2i64; break;
4544 case MVT::v8i16: NewVT = MVT::v4i32; break;
4545 case MVT::v16i8: NewVT = MVT::v4i32; break;
4548 if (NewWidth == 2) {
4554 int Scale = NumElems / NewWidth;
4555 SmallVector<int, 8> MaskVec;
4556 for (unsigned i = 0; i < NumElems; i += Scale) {
4558 for (int j = 0; j < Scale; ++j) {
4559 int EltIdx = SVOp->getMaskElt(i+j);
4563 StartIdx = EltIdx - (EltIdx % Scale);
4564 if (EltIdx != StartIdx + j)
4568 MaskVec.push_back(-1);
4570 MaskVec.push_back(StartIdx / Scale);
4573 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4574 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4575 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4578 /// getVZextMovL - Return a zero-extending vector move low node.
4580 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4581 SDValue SrcOp, SelectionDAG &DAG,
4582 const X86Subtarget *Subtarget, DebugLoc dl) {
4583 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4584 LoadSDNode *LD = NULL;
4585 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4586 LD = dyn_cast<LoadSDNode>(SrcOp);
4588 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4590 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4591 if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4592 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4593 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4594 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4596 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4597 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4598 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4599 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4607 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4608 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4609 DAG.getNode(ISD::BIT_CONVERT, dl,
4613 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4616 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4617 SDValue V1 = SVOp->getOperand(0);
4618 SDValue V2 = SVOp->getOperand(1);
4619 DebugLoc dl = SVOp->getDebugLoc();
4620 EVT VT = SVOp->getValueType(0);
4622 SmallVector<std::pair<int, int>, 8> Locs;
4624 SmallVector<int, 8> Mask1(4U, -1);
4625 SmallVector<int, 8> PermMask;
4626 SVOp->getMask(PermMask);
4630 for (unsigned i = 0; i != 4; ++i) {
4631 int Idx = PermMask[i];
4633 Locs[i] = std::make_pair(-1, -1);
4635 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4637 Locs[i] = std::make_pair(0, NumLo);
4641 Locs[i] = std::make_pair(1, NumHi);
4643 Mask1[2+NumHi] = Idx;
4649 if (NumLo <= 2 && NumHi <= 2) {
4650 // If no more than two elements come from either vector. This can be
4651 // implemented with two shuffles. First shuffle gather the elements.
4652 // The second shuffle, which takes the first shuffle as both of its
4653 // vector operands, put the elements into the right order.
4654 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4656 SmallVector<int, 8> Mask2(4U, -1);
4658 for (unsigned i = 0; i != 4; ++i) {
4659 if (Locs[i].first == -1)
4662 unsigned Idx = (i < 2) ? 0 : 4;
4663 Idx += Locs[i].first * 2 + Locs[i].second;
4668 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4669 } else if (NumLo == 3 || NumHi == 3) {
4670 // Otherwise, we must have three elements from one vector, call it X, and
4671 // one element from the other, call it Y. First, use a shufps to build an
4672 // intermediate vector with the one element from Y and the element from X
4673 // that will be in the same half in the final destination (the indexes don't
4674 // matter). Then, use a shufps to build the final vector, taking the half
4675 // containing the element from Y from the intermediate, and the other half
4678 // Normalize it so the 3 elements come from V1.
4679 CommuteVectorShuffleMask(PermMask, VT);
4683 // Find the element from V2.
4685 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4686 int Val = PermMask[HiIndex];
4693 Mask1[0] = PermMask[HiIndex];
4695 Mask1[2] = PermMask[HiIndex^1];
4697 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4700 Mask1[0] = PermMask[0];
4701 Mask1[1] = PermMask[1];
4702 Mask1[2] = HiIndex & 1 ? 6 : 4;
4703 Mask1[3] = HiIndex & 1 ? 4 : 6;
4704 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4706 Mask1[0] = HiIndex & 1 ? 2 : 0;
4707 Mask1[1] = HiIndex & 1 ? 0 : 2;
4708 Mask1[2] = PermMask[2];
4709 Mask1[3] = PermMask[3];
4714 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4718 // Break it into (shuffle shuffle_hi, shuffle_lo).
4720 SmallVector<int,8> LoMask(4U, -1);
4721 SmallVector<int,8> HiMask(4U, -1);
4723 SmallVector<int,8> *MaskPtr = &LoMask;
4724 unsigned MaskIdx = 0;
4727 for (unsigned i = 0; i != 4; ++i) {
4734 int Idx = PermMask[i];
4736 Locs[i] = std::make_pair(-1, -1);
4737 } else if (Idx < 4) {
4738 Locs[i] = std::make_pair(MaskIdx, LoIdx);
4739 (*MaskPtr)[LoIdx] = Idx;
4742 Locs[i] = std::make_pair(MaskIdx, HiIdx);
4743 (*MaskPtr)[HiIdx] = Idx;
4748 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4749 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4750 SmallVector<int, 8> MaskOps;
4751 for (unsigned i = 0; i != 4; ++i) {
4752 if (Locs[i].first == -1) {
4753 MaskOps.push_back(-1);
4755 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4756 MaskOps.push_back(Idx);
4759 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4763 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
4764 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4765 SDValue V1 = Op.getOperand(0);
4766 SDValue V2 = Op.getOperand(1);
4767 EVT VT = Op.getValueType();
4768 DebugLoc dl = Op.getDebugLoc();
4769 unsigned NumElems = VT.getVectorNumElements();
4770 bool isMMX = VT.getSizeInBits() == 64;
4771 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4772 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4773 bool V1IsSplat = false;
4774 bool V2IsSplat = false;
4776 if (isZeroShuffle(SVOp))
4777 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4779 // Promote splats to v4f32.
4780 if (SVOp->isSplat()) {
4781 if (isMMX || NumElems < 4)
4783 return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4786 // If the shuffle can be profitably rewritten as a narrower shuffle, then
4788 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4789 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4790 if (NewOp.getNode())
4791 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4792 LowerVECTOR_SHUFFLE(NewOp, DAG));
4793 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4794 // FIXME: Figure out a cleaner way to do this.
4795 // Try to make use of movq to zero out the top part.
4796 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4797 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4798 if (NewOp.getNode()) {
4799 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4800 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4801 DAG, Subtarget, dl);
4803 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4804 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4805 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4806 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4807 DAG, Subtarget, dl);
4811 if (X86::isPSHUFDMask(SVOp))
4814 // Check if this can be converted into a logical shift.
4815 bool isLeft = false;
4818 bool isShift = getSubtarget()->hasSSE2() &&
4819 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4820 if (isShift && ShVal.hasOneUse()) {
4821 // If the shifted value has multiple uses, it may be cheaper to use
4822 // v_set0 + movlhps or movhlps, etc.
4823 EVT EltVT = VT.getVectorElementType();
4824 ShAmt *= EltVT.getSizeInBits();
4825 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4828 if (X86::isMOVLMask(SVOp)) {
4831 if (ISD::isBuildVectorAllZeros(V1.getNode()))
4832 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4837 // FIXME: fold these into legal mask.
4838 if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4839 X86::isMOVSLDUPMask(SVOp) ||
4840 X86::isMOVHLPSMask(SVOp) ||
4841 X86::isMOVLHPSMask(SVOp) ||
4842 X86::isMOVLPMask(SVOp)))
4845 if (ShouldXformToMOVHLPS(SVOp) ||
4846 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4847 return CommuteVectorShuffle(SVOp, DAG);
4850 // No better options. Use a vshl / vsrl.
4851 EVT EltVT = VT.getVectorElementType();
4852 ShAmt *= EltVT.getSizeInBits();
4853 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4856 bool Commuted = false;
4857 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4858 // 1,1,1,1 -> v8i16 though.
4859 V1IsSplat = isSplatVector(V1.getNode());
4860 V2IsSplat = isSplatVector(V2.getNode());
4862 // Canonicalize the splat or undef, if present, to be on the RHS.
4863 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4864 Op = CommuteVectorShuffle(SVOp, DAG);
4865 SVOp = cast<ShuffleVectorSDNode>(Op);
4866 V1 = SVOp->getOperand(0);
4867 V2 = SVOp->getOperand(1);
4868 std::swap(V1IsSplat, V2IsSplat);
4869 std::swap(V1IsUndef, V2IsUndef);
4873 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4874 // Shuffling low element of v1 into undef, just return v1.
4877 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4878 // the instruction selector will not match, so get a canonical MOVL with
4879 // swapped operands to undo the commute.
4880 return getMOVL(DAG, dl, VT, V2, V1);
4883 if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4884 X86::isUNPCKH_v_undef_Mask(SVOp) ||
4885 X86::isUNPCKLMask(SVOp) ||
4886 X86::isUNPCKHMask(SVOp))
4890 // Normalize mask so all entries that point to V2 points to its first
4891 // element then try to match unpck{h|l} again. If match, return a
4892 // new vector_shuffle with the corrected mask.
4893 SDValue NewMask = NormalizeMask(SVOp, DAG);
4894 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4895 if (NSVOp != SVOp) {
4896 if (X86::isUNPCKLMask(NSVOp, true)) {
4898 } else if (X86::isUNPCKHMask(NSVOp, true)) {
4905 // Commute is back and try unpck* again.
4906 // FIXME: this seems wrong.
4907 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4908 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4909 if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4910 X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4911 X86::isUNPCKLMask(NewSVOp) ||
4912 X86::isUNPCKHMask(NewSVOp))
4916 // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4918 // Normalize the node to match x86 shuffle ops if needed
4919 if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4920 return CommuteVectorShuffle(SVOp, DAG);
4922 // Check for legal shuffle and return?
4923 SmallVector<int, 16> PermMask;
4924 SVOp->getMask(PermMask);
4925 if (isShuffleMaskLegal(PermMask, VT))
4928 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4929 if (VT == MVT::v8i16) {
4930 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4931 if (NewOp.getNode())
4935 if (VT == MVT::v16i8) {
4936 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4937 if (NewOp.getNode())
4941 // Handle all 4 wide cases with a number of shuffles except for MMX.
4942 if (NumElems == 4 && !isMMX)
4943 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4949 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4950 SelectionDAG &DAG) const {
4951 EVT VT = Op.getValueType();
4952 DebugLoc dl = Op.getDebugLoc();
4953 if (VT.getSizeInBits() == 8) {
4954 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4955 Op.getOperand(0), Op.getOperand(1));
4956 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4957 DAG.getValueType(VT));
4958 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4959 } else if (VT.getSizeInBits() == 16) {
4960 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4961 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4963 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4964 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4965 DAG.getNode(ISD::BIT_CONVERT, dl,
4969 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4970 Op.getOperand(0), Op.getOperand(1));
4971 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4972 DAG.getValueType(VT));
4973 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4974 } else if (VT == MVT::f32) {
4975 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4976 // the result back to FR32 register. It's only worth matching if the
4977 // result has a single use which is a store or a bitcast to i32. And in
4978 // the case of a store, it's not worth it if the index is a constant 0,
4979 // because a MOVSSmr can be used instead, which is smaller and faster.
4980 if (!Op.hasOneUse())
4982 SDNode *User = *Op.getNode()->use_begin();
4983 if ((User->getOpcode() != ISD::STORE ||
4984 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4985 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4986 (User->getOpcode() != ISD::BIT_CONVERT ||
4987 User->getValueType(0) != MVT::i32))
4989 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4990 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4993 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4994 } else if (VT == MVT::i32) {
4995 // ExtractPS works with constant index.
4996 if (isa<ConstantSDNode>(Op.getOperand(1)))
5004 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5005 SelectionDAG &DAG) const {
5006 if (!isa<ConstantSDNode>(Op.getOperand(1)))
5009 if (Subtarget->hasSSE41()) {
5010 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
5015 EVT VT = Op.getValueType();
5016 DebugLoc dl = Op.getDebugLoc();
5017 // TODO: handle v16i8.
5018 if (VT.getSizeInBits() == 16) {
5019 SDValue Vec = Op.getOperand(0);
5020 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5022 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5023 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5024 DAG.getNode(ISD::BIT_CONVERT, dl,
5027 // Transform it so it match pextrw which produces a 32-bit result.
5028 EVT EltVT = MVT::i32;
5029 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
5030 Op.getOperand(0), Op.getOperand(1));
5031 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
5032 DAG.getValueType(VT));
5033 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5034 } else if (VT.getSizeInBits() == 32) {
5035 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5039 // SHUFPS the element to the lowest double word, then movss.
5040 int Mask[4] = { Idx, -1, -1, -1 };
5041 EVT VVT = Op.getOperand(0).getValueType();
5042 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5043 DAG.getUNDEF(VVT), Mask);
5044 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5045 DAG.getIntPtrConstant(0));
5046 } else if (VT.getSizeInBits() == 64) {
5047 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
5048 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
5049 // to match extract_elt for f64.
5050 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5054 // UNPCKHPD the element to the lowest double word, then movsd.
5055 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
5056 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
5057 int Mask[2] = { 1, -1 };
5058 EVT VVT = Op.getOperand(0).getValueType();
5059 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5060 DAG.getUNDEF(VVT), Mask);
5061 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5062 DAG.getIntPtrConstant(0));
5069 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
5070 SelectionDAG &DAG) const {
5071 EVT VT = Op.getValueType();
5072 EVT EltVT = VT.getVectorElementType();
5073 DebugLoc dl = Op.getDebugLoc();
5075 SDValue N0 = Op.getOperand(0);
5076 SDValue N1 = Op.getOperand(1);
5077 SDValue N2 = Op.getOperand(2);
5079 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
5080 isa<ConstantSDNode>(N2)) {
5082 if (VT == MVT::v8i16)
5083 Opc = X86ISD::PINSRW;
5084 else if (VT == MVT::v4i16)
5085 Opc = X86ISD::MMX_PINSRW;
5086 else if (VT == MVT::v16i8)
5087 Opc = X86ISD::PINSRB;
5089 Opc = X86ISD::PINSRB;
5091 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
5093 if (N1.getValueType() != MVT::i32)
5094 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5095 if (N2.getValueType() != MVT::i32)
5096 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5097 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
5098 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
5099 // Bits [7:6] of the constant are the source select. This will always be
5100 // zero here. The DAG Combiner may combine an extract_elt index into these
5101 // bits. For example (insert (extract, 3), 2) could be matched by putting
5102 // the '3' into bits [7:6] of X86ISD::INSERTPS.
5103 // Bits [5:4] of the constant are the destination select. This is the
5104 // value of the incoming immediate.
5105 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
5106 // combine either bitwise AND or insert of float 0.0 to set these bits.
5107 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
5108 // Create this as a scalar to vector..
5109 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
5110 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
5111 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
5112 // PINSR* works with constant index.
5119 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
5120 EVT VT = Op.getValueType();
5121 EVT EltVT = VT.getVectorElementType();
5123 if (Subtarget->hasSSE41())
5124 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
5126 if (EltVT == MVT::i8)
5129 DebugLoc dl = Op.getDebugLoc();
5130 SDValue N0 = Op.getOperand(0);
5131 SDValue N1 = Op.getOperand(1);
5132 SDValue N2 = Op.getOperand(2);
5134 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
5135 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
5136 // as its second argument.
5137 if (N1.getValueType() != MVT::i32)
5138 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5139 if (N2.getValueType() != MVT::i32)
5140 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5141 return DAG.getNode(VT == MVT::v8i16 ? X86ISD::PINSRW : X86ISD::MMX_PINSRW,
5142 dl, VT, N0, N1, N2);
5148 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5149 DebugLoc dl = Op.getDebugLoc();
5151 if (Op.getValueType() == MVT::v1i64 &&
5152 Op.getOperand(0).getValueType() == MVT::i64)
5153 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5155 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5156 EVT VT = MVT::v2i32;
5157 switch (Op.getValueType().getSimpleVT().SimpleTy) {
5164 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
5165 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
5168 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5169 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5170 // one of the above mentioned nodes. It has to be wrapped because otherwise
5171 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5172 // be used to form addressing mode. These wrapped nodes will be selected
5175 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
5176 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5178 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5180 unsigned char OpFlag = 0;
5181 unsigned WrapperKind = X86ISD::Wrapper;
5182 CodeModel::Model M = getTargetMachine().getCodeModel();
5184 if (Subtarget->isPICStyleRIPRel() &&
5185 (M == CodeModel::Small || M == CodeModel::Kernel))
5186 WrapperKind = X86ISD::WrapperRIP;
5187 else if (Subtarget->isPICStyleGOT())
5188 OpFlag = X86II::MO_GOTOFF;
5189 else if (Subtarget->isPICStyleStubPIC())
5190 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5192 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5194 CP->getOffset(), OpFlag);
5195 DebugLoc DL = CP->getDebugLoc();
5196 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5197 // With PIC, the address is actually $g + Offset.
5199 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5200 DAG.getNode(X86ISD::GlobalBaseReg,
5201 DebugLoc(), getPointerTy()),
5208 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
5209 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5211 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5213 unsigned char OpFlag = 0;
5214 unsigned WrapperKind = X86ISD::Wrapper;
5215 CodeModel::Model M = getTargetMachine().getCodeModel();
5217 if (Subtarget->isPICStyleRIPRel() &&
5218 (M == CodeModel::Small || M == CodeModel::Kernel))
5219 WrapperKind = X86ISD::WrapperRIP;
5220 else if (Subtarget->isPICStyleGOT())
5221 OpFlag = X86II::MO_GOTOFF;
5222 else if (Subtarget->isPICStyleStubPIC())
5223 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5225 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5227 DebugLoc DL = JT->getDebugLoc();
5228 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5230 // With PIC, the address is actually $g + Offset.
5232 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5233 DAG.getNode(X86ISD::GlobalBaseReg,
5234 DebugLoc(), getPointerTy()),
5242 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
5243 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5245 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5247 unsigned char OpFlag = 0;
5248 unsigned WrapperKind = X86ISD::Wrapper;
5249 CodeModel::Model M = getTargetMachine().getCodeModel();
5251 if (Subtarget->isPICStyleRIPRel() &&
5252 (M == CodeModel::Small || M == CodeModel::Kernel))
5253 WrapperKind = X86ISD::WrapperRIP;
5254 else if (Subtarget->isPICStyleGOT())
5255 OpFlag = X86II::MO_GOTOFF;
5256 else if (Subtarget->isPICStyleStubPIC())
5257 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5259 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5261 DebugLoc DL = Op.getDebugLoc();
5262 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5265 // With PIC, the address is actually $g + Offset.
5266 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
5267 !Subtarget->is64Bit()) {
5268 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5269 DAG.getNode(X86ISD::GlobalBaseReg,
5270 DebugLoc(), getPointerTy()),
5278 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
5279 // Create the TargetBlockAddressAddress node.
5280 unsigned char OpFlags =
5281 Subtarget->ClassifyBlockAddressReference();
5282 CodeModel::Model M = getTargetMachine().getCodeModel();
5283 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5284 DebugLoc dl = Op.getDebugLoc();
5285 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5286 /*isTarget=*/true, OpFlags);
5288 if (Subtarget->isPICStyleRIPRel() &&
5289 (M == CodeModel::Small || M == CodeModel::Kernel))
5290 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5292 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5294 // With PIC, the address is actually $g + Offset.
5295 if (isGlobalRelativeToPICBase(OpFlags)) {
5296 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5297 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5305 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
5307 SelectionDAG &DAG) const {
5308 // Create the TargetGlobalAddress node, folding in the constant
5309 // offset if it is legal.
5310 unsigned char OpFlags =
5311 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5312 CodeModel::Model M = getTargetMachine().getCodeModel();
5314 if (OpFlags == X86II::MO_NO_FLAG &&
5315 X86::isOffsetSuitableForCodeModel(Offset, M)) {
5316 // A direct static reference to a global.
5317 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
5320 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
5323 if (Subtarget->isPICStyleRIPRel() &&
5324 (M == CodeModel::Small || M == CodeModel::Kernel))
5325 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5327 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5329 // With PIC, the address is actually $g + Offset.
5330 if (isGlobalRelativeToPICBase(OpFlags)) {
5331 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5332 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5336 // For globals that require a load from a stub to get the address, emit the
5338 if (isGlobalStubReference(OpFlags))
5339 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
5340 PseudoSourceValue::getGOT(), 0, false, false, 0);
5342 // If there was a non-zero offset that we didn't fold, create an explicit
5345 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
5346 DAG.getConstant(Offset, getPointerTy()));
5352 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
5353 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
5354 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
5355 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
5359 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
5360 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
5361 unsigned char OperandFlags) {
5362 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5363 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5364 DebugLoc dl = GA->getDebugLoc();
5365 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
5366 GA->getValueType(0),
5370 SDValue Ops[] = { Chain, TGA, *InFlag };
5371 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
5373 SDValue Ops[] = { Chain, TGA };
5374 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
5377 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
5378 MFI->setAdjustsStack(true);
5380 SDValue Flag = Chain.getValue(1);
5381 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
5384 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
5386 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5389 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
5390 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
5391 DAG.getNode(X86ISD::GlobalBaseReg,
5392 DebugLoc(), PtrVT), InFlag);
5393 InFlag = Chain.getValue(1);
5395 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
5398 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
5400 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5402 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
5403 X86::RAX, X86II::MO_TLSGD);
5406 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
5407 // "local exec" model.
5408 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5409 const EVT PtrVT, TLSModel::Model model,
5411 DebugLoc dl = GA->getDebugLoc();
5412 // Get the Thread Pointer
5413 SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
5415 DAG.getRegister(is64Bit? X86::FS : X86::GS,
5418 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
5419 NULL, 0, false, false, 0);
5421 unsigned char OperandFlags = 0;
5422 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
5424 unsigned WrapperKind = X86ISD::Wrapper;
5425 if (model == TLSModel::LocalExec) {
5426 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
5427 } else if (is64Bit) {
5428 assert(model == TLSModel::InitialExec);
5429 OperandFlags = X86II::MO_GOTTPOFF;
5430 WrapperKind = X86ISD::WrapperRIP;
5432 assert(model == TLSModel::InitialExec);
5433 OperandFlags = X86II::MO_INDNTPOFF;
5436 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
5438 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
5439 GA->getValueType(0),
5440 GA->getOffset(), OperandFlags);
5441 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
5443 if (model == TLSModel::InitialExec)
5444 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
5445 PseudoSourceValue::getGOT(), 0, false, false, 0);
5447 // The address of the thread local variable is the add of the thread
5448 // pointer with the offset of the variable.
5449 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
5453 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
5455 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5456 const GlobalValue *GV = GA->getGlobal();
5458 if (Subtarget->isTargetELF()) {
5459 // TODO: implement the "local dynamic" model
5460 // TODO: implement the "initial exec"model for pic executables
5462 // If GV is an alias then use the aliasee for determining
5463 // thread-localness.
5464 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
5465 GV = GA->resolveAliasedGlobal(false);
5467 TLSModel::Model model
5468 = getTLSModel(GV, getTargetMachine().getRelocationModel());
5471 case TLSModel::GeneralDynamic:
5472 case TLSModel::LocalDynamic: // not implemented
5473 if (Subtarget->is64Bit())
5474 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
5475 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
5477 case TLSModel::InitialExec:
5478 case TLSModel::LocalExec:
5479 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
5480 Subtarget->is64Bit());
5482 } else if (Subtarget->isTargetDarwin()) {
5483 // Darwin only has one model of TLS. Lower to that.
5484 unsigned char OpFlag = 0;
5485 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
5486 X86ISD::WrapperRIP : X86ISD::Wrapper;
5488 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5490 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
5491 !Subtarget->is64Bit();
5493 OpFlag = X86II::MO_TLVP_PIC_BASE;
5495 OpFlag = X86II::MO_TLVP;
5496 DebugLoc DL = Op.getDebugLoc();
5497 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
5499 GA->getOffset(), OpFlag);
5500 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5502 // With PIC32, the address is actually $g + Offset.
5504 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5505 DAG.getNode(X86ISD::GlobalBaseReg,
5506 DebugLoc(), getPointerTy()),
5509 // Lowering the machine isd will make sure everything is in the right
5511 SDValue Args[] = { Offset };
5512 SDValue Chain = DAG.getNode(X86ISD::TLSCALL, DL, MVT::Other, Args, 1);
5514 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
5515 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5516 MFI->setAdjustsStack(true);
5518 // And our return value (tls address) is in the standard call return value
5520 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
5521 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
5525 "TLS not implemented for this target.");
5527 llvm_unreachable("Unreachable");
5532 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
5533 /// take a 2 x i32 value to shift plus a shift amount.
5534 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
5535 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5536 EVT VT = Op.getValueType();
5537 unsigned VTBits = VT.getSizeInBits();
5538 DebugLoc dl = Op.getDebugLoc();
5539 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
5540 SDValue ShOpLo = Op.getOperand(0);
5541 SDValue ShOpHi = Op.getOperand(1);
5542 SDValue ShAmt = Op.getOperand(2);
5543 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
5544 DAG.getConstant(VTBits - 1, MVT::i8))
5545 : DAG.getConstant(0, VT);
5548 if (Op.getOpcode() == ISD::SHL_PARTS) {
5549 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
5550 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5552 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
5553 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
5556 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
5557 DAG.getConstant(VTBits, MVT::i8));
5558 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
5559 AndNode, DAG.getConstant(0, MVT::i8));
5562 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5563 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
5564 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
5566 if (Op.getOpcode() == ISD::SHL_PARTS) {
5567 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5568 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5570 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5571 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5574 SDValue Ops[2] = { Lo, Hi };
5575 return DAG.getMergeValues(Ops, 2, dl);
5578 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
5579 SelectionDAG &DAG) const {
5580 EVT SrcVT = Op.getOperand(0).getValueType();
5582 if (SrcVT.isVector()) {
5583 if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
5589 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
5590 "Unknown SINT_TO_FP to lower!");
5592 // These are really Legal; return the operand so the caller accepts it as
5594 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
5596 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
5597 Subtarget->is64Bit()) {
5601 DebugLoc dl = Op.getDebugLoc();
5602 unsigned Size = SrcVT.getSizeInBits()/8;
5603 MachineFunction &MF = DAG.getMachineFunction();
5604 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
5605 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5606 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5608 PseudoSourceValue::getFixedStack(SSFI), 0,
5610 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
5613 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
5615 SelectionDAG &DAG) const {
5617 DebugLoc dl = Op.getDebugLoc();
5619 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
5621 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
5623 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
5624 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
5625 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
5626 Tys, Ops, array_lengthof(Ops));
5629 Chain = Result.getValue(1);
5630 SDValue InFlag = Result.getValue(2);
5632 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5633 // shouldn't be necessary except that RFP cannot be live across
5634 // multiple blocks. When stackifier is fixed, they can be uncoupled.
5635 MachineFunction &MF = DAG.getMachineFunction();
5636 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5637 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5638 Tys = DAG.getVTList(MVT::Other);
5640 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
5642 Chain = DAG.getNode(X86ISD::FST, dl, Tys, Ops, array_lengthof(Ops));
5643 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5644 PseudoSourceValue::getFixedStack(SSFI), 0,
5651 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5652 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
5653 SelectionDAG &DAG) const {
5654 // This algorithm is not obvious. Here it is in C code, more or less:
5656 double uint64_to_double( uint32_t hi, uint32_t lo ) {
5657 static const __m128i exp = { 0x4330000045300000ULL, 0 };
5658 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5660 // Copy ints to xmm registers.
5661 __m128i xh = _mm_cvtsi32_si128( hi );
5662 __m128i xl = _mm_cvtsi32_si128( lo );
5664 // Combine into low half of a single xmm register.
5665 __m128i x = _mm_unpacklo_epi32( xh, xl );
5669 // Merge in appropriate exponents to give the integer bits the right
5671 x = _mm_unpacklo_epi32( x, exp );
5673 // Subtract away the biases to deal with the IEEE-754 double precision
5675 d = _mm_sub_pd( (__m128d) x, bias );
5677 // All conversions up to here are exact. The correctly rounded result is
5678 // calculated using the current rounding mode using the following
5680 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5681 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
5682 // store doesn't really need to be here (except
5683 // maybe to zero the other double)
5688 DebugLoc dl = Op.getDebugLoc();
5689 LLVMContext *Context = DAG.getContext();
5691 // Build some magic constants.
5692 std::vector<Constant*> CV0;
5693 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
5694 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
5695 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5696 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5697 Constant *C0 = ConstantVector::get(CV0);
5698 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5700 std::vector<Constant*> CV1;
5702 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
5704 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
5705 Constant *C1 = ConstantVector::get(CV1);
5706 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5708 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5709 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5711 DAG.getIntPtrConstant(1)));
5712 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5713 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5715 DAG.getIntPtrConstant(0)));
5716 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
5717 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5718 PseudoSourceValue::getConstantPool(), 0,
5720 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
5721 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5722 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5723 PseudoSourceValue::getConstantPool(), 0,
5725 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5727 // Add the halves; easiest way is to swap them into another reg first.
5728 int ShufMask[2] = { 1, -1 };
5729 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
5730 DAG.getUNDEF(MVT::v2f64), ShufMask);
5731 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5732 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5733 DAG.getIntPtrConstant(0));
5736 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5737 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
5738 SelectionDAG &DAG) const {
5739 DebugLoc dl = Op.getDebugLoc();
5740 // FP constant to bias correct the final result.
5741 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5744 // Load the 32-bit value into an XMM register.
5745 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5746 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5748 DAG.getIntPtrConstant(0)));
5750 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5751 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5752 DAG.getIntPtrConstant(0));
5754 // Or the load with the bias.
5755 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5756 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5757 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5759 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5760 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5761 MVT::v2f64, Bias)));
5762 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5763 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5764 DAG.getIntPtrConstant(0));
5766 // Subtract the bias.
5767 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5769 // Handle final rounding.
5770 EVT DestVT = Op.getValueType();
5772 if (DestVT.bitsLT(MVT::f64)) {
5773 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5774 DAG.getIntPtrConstant(0));
5775 } else if (DestVT.bitsGT(MVT::f64)) {
5776 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5779 // Handle final rounding.
5783 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
5784 SelectionDAG &DAG) const {
5785 SDValue N0 = Op.getOperand(0);
5786 DebugLoc dl = Op.getDebugLoc();
5788 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
5789 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5790 // the optimization here.
5791 if (DAG.SignBitIsZero(N0))
5792 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5794 EVT SrcVT = N0.getValueType();
5795 EVT DstVT = Op.getValueType();
5796 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
5797 return LowerUINT_TO_FP_i64(Op, DAG);
5798 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
5799 return LowerUINT_TO_FP_i32(Op, DAG);
5801 // Make a 64-bit buffer, and use it to build an FILD.
5802 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5803 if (SrcVT == MVT::i32) {
5804 SDValue WordOff = DAG.getConstant(4, getPointerTy());
5805 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5806 getPointerTy(), StackSlot, WordOff);
5807 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5808 StackSlot, NULL, 0, false, false, 0);
5809 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5810 OffsetSlot, NULL, 0, false, false, 0);
5811 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5815 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
5816 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5817 StackSlot, NULL, 0, false, false, 0);
5818 // For i64 source, we need to add the appropriate power of 2 if the input
5819 // was negative. This is the same as the optimization in
5820 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
5821 // we must be careful to do the computation in x87 extended precision, not
5822 // in SSE. (The generic code can't know it's OK to do this, or how to.)
5823 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
5824 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
5825 SDValue Fild = DAG.getNode(X86ISD::FILD, dl, Tys, Ops, 3);
5827 APInt FF(32, 0x5F800000ULL);
5829 // Check whether the sign bit is set.
5830 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
5831 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
5834 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
5835 SDValue FudgePtr = DAG.getConstantPool(
5836 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
5839 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
5840 SDValue Zero = DAG.getIntPtrConstant(0);
5841 SDValue Four = DAG.getIntPtrConstant(4);
5842 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
5844 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
5846 // Load the value out, extending it from f32 to f80.
5847 // FIXME: Avoid the extend by constructing the right constant pool?
5848 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, MVT::f80, dl, DAG.getEntryNode(),
5849 FudgePtr, PseudoSourceValue::getConstantPool(),
5850 0, MVT::f32, false, false, 4);
5851 // Extend everything to 80 bits to force it to be done on x87.
5852 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
5853 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
5856 std::pair<SDValue,SDValue> X86TargetLowering::
5857 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
5858 DebugLoc dl = Op.getDebugLoc();
5860 EVT DstTy = Op.getValueType();
5863 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5867 assert(DstTy.getSimpleVT() <= MVT::i64 &&
5868 DstTy.getSimpleVT() >= MVT::i16 &&
5869 "Unknown FP_TO_SINT to lower!");
5871 // These are really Legal.
5872 if (DstTy == MVT::i32 &&
5873 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5874 return std::make_pair(SDValue(), SDValue());
5875 if (Subtarget->is64Bit() &&
5876 DstTy == MVT::i64 &&
5877 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5878 return std::make_pair(SDValue(), SDValue());
5880 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5882 MachineFunction &MF = DAG.getMachineFunction();
5883 unsigned MemSize = DstTy.getSizeInBits()/8;
5884 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5885 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5888 switch (DstTy.getSimpleVT().SimpleTy) {
5889 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5890 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5891 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5892 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5895 SDValue Chain = DAG.getEntryNode();
5896 SDValue Value = Op.getOperand(0);
5897 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5898 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5899 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5900 PseudoSourceValue::getFixedStack(SSFI), 0,
5902 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5904 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5906 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5907 Chain = Value.getValue(1);
5908 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5909 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5912 // Build the FP_TO_INT*_IN_MEM
5913 SDValue Ops[] = { Chain, Value, StackSlot };
5914 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5916 return std::make_pair(FIST, StackSlot);
5919 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
5920 SelectionDAG &DAG) const {
5921 if (Op.getValueType().isVector()) {
5922 if (Op.getValueType() == MVT::v2i32 &&
5923 Op.getOperand(0).getValueType() == MVT::v2f64) {
5929 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5930 SDValue FIST = Vals.first, StackSlot = Vals.second;
5931 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5932 if (FIST.getNode() == 0) return Op;
5935 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5936 FIST, StackSlot, NULL, 0, false, false, 0);
5939 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
5940 SelectionDAG &DAG) const {
5941 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5942 SDValue FIST = Vals.first, StackSlot = Vals.second;
5943 assert(FIST.getNode() && "Unexpected failure");
5946 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5947 FIST, StackSlot, NULL, 0, false, false, 0);
5950 SDValue X86TargetLowering::LowerFABS(SDValue Op,
5951 SelectionDAG &DAG) const {
5952 LLVMContext *Context = DAG.getContext();
5953 DebugLoc dl = Op.getDebugLoc();
5954 EVT VT = Op.getValueType();
5957 EltVT = VT.getVectorElementType();
5958 std::vector<Constant*> CV;
5959 if (EltVT == MVT::f64) {
5960 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5964 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5970 Constant *C = ConstantVector::get(CV);
5971 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5972 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5973 PseudoSourceValue::getConstantPool(), 0,
5975 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5978 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
5979 LLVMContext *Context = DAG.getContext();
5980 DebugLoc dl = Op.getDebugLoc();
5981 EVT VT = Op.getValueType();
5984 EltVT = VT.getVectorElementType();
5985 std::vector<Constant*> CV;
5986 if (EltVT == MVT::f64) {
5987 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5991 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5997 Constant *C = ConstantVector::get(CV);
5998 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5999 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6000 PseudoSourceValue::getConstantPool(), 0,
6002 if (VT.isVector()) {
6003 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
6004 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
6005 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
6007 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
6009 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
6013 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
6014 LLVMContext *Context = DAG.getContext();
6015 SDValue Op0 = Op.getOperand(0);
6016 SDValue Op1 = Op.getOperand(1);
6017 DebugLoc dl = Op.getDebugLoc();
6018 EVT VT = Op.getValueType();
6019 EVT SrcVT = Op1.getValueType();
6021 // If second operand is smaller, extend it first.
6022 if (SrcVT.bitsLT(VT)) {
6023 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
6026 // And if it is bigger, shrink it first.
6027 if (SrcVT.bitsGT(VT)) {
6028 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
6032 // At this point the operands and the result should have the same
6033 // type, and that won't be f80 since that is not custom lowered.
6035 // First get the sign bit of second operand.
6036 std::vector<Constant*> CV;
6037 if (SrcVT == MVT::f64) {
6038 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
6039 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6041 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
6042 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6043 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6044 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6046 Constant *C = ConstantVector::get(CV);
6047 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6048 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
6049 PseudoSourceValue::getConstantPool(), 0,
6051 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
6053 // Shift sign bit right or left if the two operands have different types.
6054 if (SrcVT.bitsGT(VT)) {
6055 // Op0 is MVT::f32, Op1 is MVT::f64.
6056 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
6057 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
6058 DAG.getConstant(32, MVT::i32));
6059 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
6060 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
6061 DAG.getIntPtrConstant(0));
6064 // Clear first operand sign bit.
6066 if (VT == MVT::f64) {
6067 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
6068 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6070 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
6071 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6072 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6073 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6075 C = ConstantVector::get(CV);
6076 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6077 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6078 PseudoSourceValue::getConstantPool(), 0,
6080 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
6082 // Or the value with the sign bit.
6083 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
6086 /// Emit nodes that will be selected as "test Op0,Op0", or something
6088 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
6089 SelectionDAG &DAG) const {
6090 DebugLoc dl = Op.getDebugLoc();
6092 // CF and OF aren't always set the way we want. Determine which
6093 // of these we need.
6094 bool NeedCF = false;
6095 bool NeedOF = false;
6098 case X86::COND_A: case X86::COND_AE:
6099 case X86::COND_B: case X86::COND_BE:
6102 case X86::COND_G: case X86::COND_GE:
6103 case X86::COND_L: case X86::COND_LE:
6104 case X86::COND_O: case X86::COND_NO:
6109 // See if we can use the EFLAGS value from the operand instead of
6110 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
6111 // we prove that the arithmetic won't overflow, we can't use OF or CF.
6112 if (Op.getResNo() != 0 || NeedOF || NeedCF)
6113 // Emit a CMP with 0, which is the TEST pattern.
6114 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6115 DAG.getConstant(0, Op.getValueType()));
6117 unsigned Opcode = 0;
6118 unsigned NumOperands = 0;
6119 switch (Op.getNode()->getOpcode()) {
6121 // Due to an isel shortcoming, be conservative if this add is likely to be
6122 // selected as part of a load-modify-store instruction. When the root node
6123 // in a match is a store, isel doesn't know how to remap non-chain non-flag
6124 // uses of other nodes in the match, such as the ADD in this case. This
6125 // leads to the ADD being left around and reselected, with the result being
6126 // two adds in the output. Alas, even if none our users are stores, that
6127 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
6128 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
6129 // climbing the DAG back to the root, and it doesn't seem to be worth the
6131 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6132 UE = Op.getNode()->use_end(); UI != UE; ++UI)
6133 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
6136 if (ConstantSDNode *C =
6137 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
6138 // An add of one will be selected as an INC.
6139 if (C->getAPIntValue() == 1) {
6140 Opcode = X86ISD::INC;
6145 // An add of negative one (subtract of one) will be selected as a DEC.
6146 if (C->getAPIntValue().isAllOnesValue()) {
6147 Opcode = X86ISD::DEC;
6153 // Otherwise use a regular EFLAGS-setting add.
6154 Opcode = X86ISD::ADD;
6158 // If the primary and result isn't used, don't bother using X86ISD::AND,
6159 // because a TEST instruction will be better.
6160 bool NonFlagUse = false;
6161 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6162 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
6164 unsigned UOpNo = UI.getOperandNo();
6165 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
6166 // Look pass truncate.
6167 UOpNo = User->use_begin().getOperandNo();
6168 User = *User->use_begin();
6171 if (User->getOpcode() != ISD::BRCOND &&
6172 User->getOpcode() != ISD::SETCC &&
6173 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
6186 // Due to the ISEL shortcoming noted above, be conservative if this op is
6187 // likely to be selected as part of a load-modify-store instruction.
6188 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6189 UE = Op.getNode()->use_end(); UI != UE; ++UI)
6190 if (UI->getOpcode() == ISD::STORE)
6193 // Otherwise use a regular EFLAGS-setting instruction.
6194 switch (Op.getNode()->getOpcode()) {
6195 default: llvm_unreachable("unexpected operator!");
6196 case ISD::SUB: Opcode = X86ISD::SUB; break;
6197 case ISD::OR: Opcode = X86ISD::OR; break;
6198 case ISD::XOR: Opcode = X86ISD::XOR; break;
6199 case ISD::AND: Opcode = X86ISD::AND; break;
6211 return SDValue(Op.getNode(), 1);
6218 // Emit a CMP with 0, which is the TEST pattern.
6219 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6220 DAG.getConstant(0, Op.getValueType()));
6222 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
6223 SmallVector<SDValue, 4> Ops;
6224 for (unsigned i = 0; i != NumOperands; ++i)
6225 Ops.push_back(Op.getOperand(i));
6227 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
6228 DAG.ReplaceAllUsesWith(Op, New);
6229 return SDValue(New.getNode(), 1);
6232 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
6234 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
6235 SelectionDAG &DAG) const {
6236 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
6237 if (C->getAPIntValue() == 0)
6238 return EmitTest(Op0, X86CC, DAG);
6240 DebugLoc dl = Op0.getDebugLoc();
6241 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
6244 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
6245 /// if it's possible.
6246 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
6247 DebugLoc dl, SelectionDAG &DAG) const {
6248 SDValue Op0 = And.getOperand(0);
6249 SDValue Op1 = And.getOperand(1);
6250 if (Op0.getOpcode() == ISD::TRUNCATE)
6251 Op0 = Op0.getOperand(0);
6252 if (Op1.getOpcode() == ISD::TRUNCATE)
6253 Op1 = Op1.getOperand(0);
6256 if (Op1.getOpcode() == ISD::SHL)
6257 std::swap(Op0, Op1);
6258 if (Op0.getOpcode() == ISD::SHL) {
6259 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
6260 if (And00C->getZExtValue() == 1) {
6261 // If we looked past a truncate, check that it's only truncating away
6263 unsigned BitWidth = Op0.getValueSizeInBits();
6264 unsigned AndBitWidth = And.getValueSizeInBits();
6265 if (BitWidth > AndBitWidth) {
6266 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
6267 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
6268 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
6272 RHS = Op0.getOperand(1);
6274 } else if (Op1.getOpcode() == ISD::Constant) {
6275 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
6276 SDValue AndLHS = Op0;
6277 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
6278 LHS = AndLHS.getOperand(0);
6279 RHS = AndLHS.getOperand(1);
6283 if (LHS.getNode()) {
6284 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
6285 // instruction. Since the shift amount is in-range-or-undefined, we know
6286 // that doing a bittest on the i32 value is ok. We extend to i32 because
6287 // the encoding for the i16 version is larger than the i32 version.
6288 // Also promote i16 to i32 for performance / code size reason.
6289 if (LHS.getValueType() == MVT::i8 ||
6290 LHS.getValueType() == MVT::i16)
6291 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
6293 // If the operand types disagree, extend the shift amount to match. Since
6294 // BT ignores high bits (like shifts) we can use anyextend.
6295 if (LHS.getValueType() != RHS.getValueType())
6296 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
6298 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
6299 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
6300 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6301 DAG.getConstant(Cond, MVT::i8), BT);
6307 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
6308 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
6309 SDValue Op0 = Op.getOperand(0);
6310 SDValue Op1 = Op.getOperand(1);
6311 DebugLoc dl = Op.getDebugLoc();
6312 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6314 // Optimize to BT if possible.
6315 // Lower (X & (1 << N)) == 0 to BT(X, N).
6316 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
6317 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
6318 if (Op0.getOpcode() == ISD::AND &&
6320 Op1.getOpcode() == ISD::Constant &&
6321 cast<ConstantSDNode>(Op1)->isNullValue() &&
6322 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6323 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
6324 if (NewSetCC.getNode())
6328 // Look for "(setcc) == / != 1" to avoid unncessary setcc.
6329 if (Op0.getOpcode() == X86ISD::SETCC &&
6330 Op1.getOpcode() == ISD::Constant &&
6331 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
6332 cast<ConstantSDNode>(Op1)->isNullValue()) &&
6333 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6334 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
6335 bool Invert = (CC == ISD::SETNE) ^
6336 cast<ConstantSDNode>(Op1)->isNullValue();
6338 CCode = X86::GetOppositeBranchCondition(CCode);
6339 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6340 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
6343 bool isFP = Op1.getValueType().isFloatingPoint();
6344 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
6345 if (X86CC == X86::COND_INVALID)
6348 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
6350 // Use sbb x, x to materialize carry bit into a GPR.
6351 if (X86CC == X86::COND_B)
6352 return DAG.getNode(ISD::AND, dl, MVT::i8,
6353 DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
6354 DAG.getConstant(X86CC, MVT::i8), Cond),
6355 DAG.getConstant(1, MVT::i8));
6357 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6358 DAG.getConstant(X86CC, MVT::i8), Cond);
6361 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
6363 SDValue Op0 = Op.getOperand(0);
6364 SDValue Op1 = Op.getOperand(1);
6365 SDValue CC = Op.getOperand(2);
6366 EVT VT = Op.getValueType();
6367 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6368 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
6369 DebugLoc dl = Op.getDebugLoc();
6373 EVT VT0 = Op0.getValueType();
6374 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
6375 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
6378 switch (SetCCOpcode) {
6381 case ISD::SETEQ: SSECC = 0; break;
6383 case ISD::SETGT: Swap = true; // Fallthrough
6385 case ISD::SETOLT: SSECC = 1; break;
6387 case ISD::SETGE: Swap = true; // Fallthrough
6389 case ISD::SETOLE: SSECC = 2; break;
6390 case ISD::SETUO: SSECC = 3; break;
6392 case ISD::SETNE: SSECC = 4; break;
6393 case ISD::SETULE: Swap = true;
6394 case ISD::SETUGE: SSECC = 5; break;
6395 case ISD::SETULT: Swap = true;
6396 case ISD::SETUGT: SSECC = 6; break;
6397 case ISD::SETO: SSECC = 7; break;
6400 std::swap(Op0, Op1);
6402 // In the two special cases we can't handle, emit two comparisons.
6404 if (SetCCOpcode == ISD::SETUEQ) {
6406 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
6407 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
6408 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
6410 else if (SetCCOpcode == ISD::SETONE) {
6412 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
6413 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
6414 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
6416 llvm_unreachable("Illegal FP comparison");
6418 // Handle all other FP comparisons here.
6419 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
6422 // We are handling one of the integer comparisons here. Since SSE only has
6423 // GT and EQ comparisons for integer, swapping operands and multiple
6424 // operations may be required for some comparisons.
6425 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
6426 bool Swap = false, Invert = false, FlipSigns = false;
6428 switch (VT.getSimpleVT().SimpleTy) {
6431 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
6433 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
6435 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
6436 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
6439 switch (SetCCOpcode) {
6441 case ISD::SETNE: Invert = true;
6442 case ISD::SETEQ: Opc = EQOpc; break;
6443 case ISD::SETLT: Swap = true;
6444 case ISD::SETGT: Opc = GTOpc; break;
6445 case ISD::SETGE: Swap = true;
6446 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
6447 case ISD::SETULT: Swap = true;
6448 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
6449 case ISD::SETUGE: Swap = true;
6450 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
6453 std::swap(Op0, Op1);
6455 // Since SSE has no unsigned integer comparisons, we need to flip the sign
6456 // bits of the inputs before performing those operations.
6458 EVT EltVT = VT.getVectorElementType();
6459 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
6461 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
6462 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
6464 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
6465 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
6468 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
6470 // If the logical-not of the result is required, perform that now.
6472 Result = DAG.getNOT(dl, Result, VT);
6477 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
6478 static bool isX86LogicalCmp(SDValue Op) {
6479 unsigned Opc = Op.getNode()->getOpcode();
6480 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
6482 if (Op.getResNo() == 1 &&
6483 (Opc == X86ISD::ADD ||
6484 Opc == X86ISD::SUB ||
6485 Opc == X86ISD::SMUL ||
6486 Opc == X86ISD::UMUL ||
6487 Opc == X86ISD::INC ||
6488 Opc == X86ISD::DEC ||
6489 Opc == X86ISD::OR ||
6490 Opc == X86ISD::XOR ||
6491 Opc == X86ISD::AND))
6497 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
6498 bool addTest = true;
6499 SDValue Cond = Op.getOperand(0);
6500 DebugLoc dl = Op.getDebugLoc();
6503 if (Cond.getOpcode() == ISD::SETCC) {
6504 SDValue NewCond = LowerSETCC(Cond, DAG);
6505 if (NewCond.getNode())
6509 // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
6510 SDValue Op1 = Op.getOperand(1);
6511 SDValue Op2 = Op.getOperand(2);
6512 if (Cond.getOpcode() == X86ISD::SETCC &&
6513 cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
6514 SDValue Cmp = Cond.getOperand(1);
6515 if (Cmp.getOpcode() == X86ISD::CMP) {
6516 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
6517 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
6518 ConstantSDNode *RHSC =
6519 dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
6520 if (N1C && N1C->isAllOnesValue() &&
6521 N2C && N2C->isNullValue() &&
6522 RHSC && RHSC->isNullValue()) {
6523 SDValue CmpOp0 = Cmp.getOperand(0);
6524 Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6525 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
6526 return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
6527 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
6532 // Look pass (and (setcc_carry (cmp ...)), 1).
6533 if (Cond.getOpcode() == ISD::AND &&
6534 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6535 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6536 if (C && C->getAPIntValue() == 1)
6537 Cond = Cond.getOperand(0);
6540 // If condition flag is set by a X86ISD::CMP, then use it as the condition
6541 // setting operand in place of the X86ISD::SETCC.
6542 if (Cond.getOpcode() == X86ISD::SETCC ||
6543 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6544 CC = Cond.getOperand(0);
6546 SDValue Cmp = Cond.getOperand(1);
6547 unsigned Opc = Cmp.getOpcode();
6548 EVT VT = Op.getValueType();
6550 bool IllegalFPCMov = false;
6551 if (VT.isFloatingPoint() && !VT.isVector() &&
6552 !isScalarFPTypeInSSEReg(VT)) // FPStack?
6553 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
6555 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
6556 Opc == X86ISD::BT) { // FIXME
6563 // Look pass the truncate.
6564 if (Cond.getOpcode() == ISD::TRUNCATE)
6565 Cond = Cond.getOperand(0);
6567 // We know the result of AND is compared against zero. Try to match
6569 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
6570 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6571 if (NewSetCC.getNode()) {
6572 CC = NewSetCC.getOperand(0);
6573 Cond = NewSetCC.getOperand(1);
6580 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6581 Cond = EmitTest(Cond, X86::COND_NE, DAG);
6584 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
6585 // condition is true.
6586 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
6587 SDValue Ops[] = { Op2, Op1, CC, Cond };
6588 return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
6591 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
6592 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
6593 // from the AND / OR.
6594 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
6595 Opc = Op.getOpcode();
6596 if (Opc != ISD::OR && Opc != ISD::AND)
6598 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6599 Op.getOperand(0).hasOneUse() &&
6600 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
6601 Op.getOperand(1).hasOneUse());
6604 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
6605 // 1 and that the SETCC node has a single use.
6606 static bool isXor1OfSetCC(SDValue Op) {
6607 if (Op.getOpcode() != ISD::XOR)
6609 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6610 if (N1C && N1C->getAPIntValue() == 1) {
6611 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6612 Op.getOperand(0).hasOneUse();
6617 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
6618 bool addTest = true;
6619 SDValue Chain = Op.getOperand(0);
6620 SDValue Cond = Op.getOperand(1);
6621 SDValue Dest = Op.getOperand(2);
6622 DebugLoc dl = Op.getDebugLoc();
6625 if (Cond.getOpcode() == ISD::SETCC) {
6626 SDValue NewCond = LowerSETCC(Cond, DAG);
6627 if (NewCond.getNode())
6631 // FIXME: LowerXALUO doesn't handle these!!
6632 else if (Cond.getOpcode() == X86ISD::ADD ||
6633 Cond.getOpcode() == X86ISD::SUB ||
6634 Cond.getOpcode() == X86ISD::SMUL ||
6635 Cond.getOpcode() == X86ISD::UMUL)
6636 Cond = LowerXALUO(Cond, DAG);
6639 // Look pass (and (setcc_carry (cmp ...)), 1).
6640 if (Cond.getOpcode() == ISD::AND &&
6641 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6642 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6643 if (C && C->getAPIntValue() == 1)
6644 Cond = Cond.getOperand(0);
6647 // If condition flag is set by a X86ISD::CMP, then use it as the condition
6648 // setting operand in place of the X86ISD::SETCC.
6649 if (Cond.getOpcode() == X86ISD::SETCC ||
6650 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6651 CC = Cond.getOperand(0);
6653 SDValue Cmp = Cond.getOperand(1);
6654 unsigned Opc = Cmp.getOpcode();
6655 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
6656 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
6660 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
6664 // These can only come from an arithmetic instruction with overflow,
6665 // e.g. SADDO, UADDO.
6666 Cond = Cond.getNode()->getOperand(1);
6673 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
6674 SDValue Cmp = Cond.getOperand(0).getOperand(1);
6675 if (CondOpc == ISD::OR) {
6676 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
6677 // two branches instead of an explicit OR instruction with a
6679 if (Cmp == Cond.getOperand(1).getOperand(1) &&
6680 isX86LogicalCmp(Cmp)) {
6681 CC = Cond.getOperand(0).getOperand(0);
6682 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6683 Chain, Dest, CC, Cmp);
6684 CC = Cond.getOperand(1).getOperand(0);
6688 } else { // ISD::AND
6689 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
6690 // two branches instead of an explicit AND instruction with a
6691 // separate test. However, we only do this if this block doesn't
6692 // have a fall-through edge, because this requires an explicit
6693 // jmp when the condition is false.
6694 if (Cmp == Cond.getOperand(1).getOperand(1) &&
6695 isX86LogicalCmp(Cmp) &&
6696 Op.getNode()->hasOneUse()) {
6697 X86::CondCode CCode =
6698 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6699 CCode = X86::GetOppositeBranchCondition(CCode);
6700 CC = DAG.getConstant(CCode, MVT::i8);
6701 SDNode *User = *Op.getNode()->use_begin();
6702 // Look for an unconditional branch following this conditional branch.
6703 // We need this because we need to reverse the successors in order
6704 // to implement FCMP_OEQ.
6705 if (User->getOpcode() == ISD::BR) {
6706 SDValue FalseBB = User->getOperand(1);
6708 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
6709 assert(NewBR == User);
6713 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6714 Chain, Dest, CC, Cmp);
6715 X86::CondCode CCode =
6716 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
6717 CCode = X86::GetOppositeBranchCondition(CCode);
6718 CC = DAG.getConstant(CCode, MVT::i8);
6724 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
6725 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
6726 // It should be transformed during dag combiner except when the condition
6727 // is set by a arithmetics with overflow node.
6728 X86::CondCode CCode =
6729 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6730 CCode = X86::GetOppositeBranchCondition(CCode);
6731 CC = DAG.getConstant(CCode, MVT::i8);
6732 Cond = Cond.getOperand(0).getOperand(1);
6738 // Look pass the truncate.
6739 if (Cond.getOpcode() == ISD::TRUNCATE)
6740 Cond = Cond.getOperand(0);
6742 // We know the result of AND is compared against zero. Try to match
6744 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
6745 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6746 if (NewSetCC.getNode()) {
6747 CC = NewSetCC.getOperand(0);
6748 Cond = NewSetCC.getOperand(1);
6755 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6756 Cond = EmitTest(Cond, X86::COND_NE, DAG);
6758 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6759 Chain, Dest, CC, Cond);
6763 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
6764 // Calls to _alloca is needed to probe the stack when allocating more than 4k
6765 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
6766 // that the guard pages used by the OS virtual memory manager are allocated in
6767 // correct sequence.
6769 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6770 SelectionDAG &DAG) const {
6771 assert(Subtarget->isTargetCygMing() &&
6772 "This should be used only on Cygwin/Mingw targets");
6773 DebugLoc dl = Op.getDebugLoc();
6776 SDValue Chain = Op.getOperand(0);
6777 SDValue Size = Op.getOperand(1);
6778 // FIXME: Ensure alignment here
6782 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
6784 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
6785 Flag = Chain.getValue(1);
6787 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6789 Chain = DAG.getNode(X86ISD::MINGW_ALLOCA, dl, NodeTys, Chain, Flag);
6790 Flag = Chain.getValue(1);
6792 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
6794 SDValue Ops1[2] = { Chain.getValue(0), Chain };
6795 return DAG.getMergeValues(Ops1, 2, dl);
6798 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
6799 MachineFunction &MF = DAG.getMachineFunction();
6800 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
6802 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6803 DebugLoc dl = Op.getDebugLoc();
6805 if (!Subtarget->is64Bit()) {
6806 // vastart just stores the address of the VarArgsFrameIndex slot into the
6807 // memory location argument.
6808 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
6810 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0,
6815 // gp_offset (0 - 6 * 8)
6816 // fp_offset (48 - 48 + 8 * 16)
6817 // overflow_arg_area (point to parameters coming in memory).
6819 SmallVector<SDValue, 8> MemOps;
6820 SDValue FIN = Op.getOperand(1);
6822 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6823 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
6825 FIN, SV, 0, false, false, 0);
6826 MemOps.push_back(Store);
6829 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6830 FIN, DAG.getIntPtrConstant(4));
6831 Store = DAG.getStore(Op.getOperand(0), dl,
6832 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
6834 FIN, SV, 4, false, false, 0);
6835 MemOps.push_back(Store);
6837 // Store ptr to overflow_arg_area
6838 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6839 FIN, DAG.getIntPtrConstant(4));
6840 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
6842 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 8,
6844 MemOps.push_back(Store);
6846 // Store ptr to reg_save_area.
6847 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6848 FIN, DAG.getIntPtrConstant(8));
6849 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
6851 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 16,
6853 MemOps.push_back(Store);
6854 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6855 &MemOps[0], MemOps.size());
6858 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
6859 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6860 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6862 report_fatal_error("VAArgInst is not yet implemented for x86-64!");
6866 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
6867 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6868 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6869 SDValue Chain = Op.getOperand(0);
6870 SDValue DstPtr = Op.getOperand(1);
6871 SDValue SrcPtr = Op.getOperand(2);
6872 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6873 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6874 DebugLoc dl = Op.getDebugLoc();
6876 return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6877 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
6878 false, DstSV, 0, SrcSV, 0);
6882 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
6883 DebugLoc dl = Op.getDebugLoc();
6884 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6886 default: return SDValue(); // Don't custom lower most intrinsics.
6887 // Comparison intrinsics.
6888 case Intrinsic::x86_sse_comieq_ss:
6889 case Intrinsic::x86_sse_comilt_ss:
6890 case Intrinsic::x86_sse_comile_ss:
6891 case Intrinsic::x86_sse_comigt_ss:
6892 case Intrinsic::x86_sse_comige_ss:
6893 case Intrinsic::x86_sse_comineq_ss:
6894 case Intrinsic::x86_sse_ucomieq_ss:
6895 case Intrinsic::x86_sse_ucomilt_ss:
6896 case Intrinsic::x86_sse_ucomile_ss:
6897 case Intrinsic::x86_sse_ucomigt_ss:
6898 case Intrinsic::x86_sse_ucomige_ss:
6899 case Intrinsic::x86_sse_ucomineq_ss:
6900 case Intrinsic::x86_sse2_comieq_sd:
6901 case Intrinsic::x86_sse2_comilt_sd:
6902 case Intrinsic::x86_sse2_comile_sd:
6903 case Intrinsic::x86_sse2_comigt_sd:
6904 case Intrinsic::x86_sse2_comige_sd:
6905 case Intrinsic::x86_sse2_comineq_sd:
6906 case Intrinsic::x86_sse2_ucomieq_sd:
6907 case Intrinsic::x86_sse2_ucomilt_sd:
6908 case Intrinsic::x86_sse2_ucomile_sd:
6909 case Intrinsic::x86_sse2_ucomigt_sd:
6910 case Intrinsic::x86_sse2_ucomige_sd:
6911 case Intrinsic::x86_sse2_ucomineq_sd: {
6913 ISD::CondCode CC = ISD::SETCC_INVALID;
6916 case Intrinsic::x86_sse_comieq_ss:
6917 case Intrinsic::x86_sse2_comieq_sd:
6921 case Intrinsic::x86_sse_comilt_ss:
6922 case Intrinsic::x86_sse2_comilt_sd:
6926 case Intrinsic::x86_sse_comile_ss:
6927 case Intrinsic::x86_sse2_comile_sd:
6931 case Intrinsic::x86_sse_comigt_ss:
6932 case Intrinsic::x86_sse2_comigt_sd:
6936 case Intrinsic::x86_sse_comige_ss:
6937 case Intrinsic::x86_sse2_comige_sd:
6941 case Intrinsic::x86_sse_comineq_ss:
6942 case Intrinsic::x86_sse2_comineq_sd:
6946 case Intrinsic::x86_sse_ucomieq_ss:
6947 case Intrinsic::x86_sse2_ucomieq_sd:
6948 Opc = X86ISD::UCOMI;
6951 case Intrinsic::x86_sse_ucomilt_ss:
6952 case Intrinsic::x86_sse2_ucomilt_sd:
6953 Opc = X86ISD::UCOMI;
6956 case Intrinsic::x86_sse_ucomile_ss:
6957 case Intrinsic::x86_sse2_ucomile_sd:
6958 Opc = X86ISD::UCOMI;
6961 case Intrinsic::x86_sse_ucomigt_ss:
6962 case Intrinsic::x86_sse2_ucomigt_sd:
6963 Opc = X86ISD::UCOMI;
6966 case Intrinsic::x86_sse_ucomige_ss:
6967 case Intrinsic::x86_sse2_ucomige_sd:
6968 Opc = X86ISD::UCOMI;
6971 case Intrinsic::x86_sse_ucomineq_ss:
6972 case Intrinsic::x86_sse2_ucomineq_sd:
6973 Opc = X86ISD::UCOMI;
6978 SDValue LHS = Op.getOperand(1);
6979 SDValue RHS = Op.getOperand(2);
6980 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6981 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
6982 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6983 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6984 DAG.getConstant(X86CC, MVT::i8), Cond);
6985 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6987 // ptest intrinsics. The intrinsic these come from are designed to return
6988 // an integer value, not just an instruction so lower it to the ptest
6989 // pattern and a setcc for the result.
6990 case Intrinsic::x86_sse41_ptestz:
6991 case Intrinsic::x86_sse41_ptestc:
6992 case Intrinsic::x86_sse41_ptestnzc:{
6995 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
6996 case Intrinsic::x86_sse41_ptestz:
6998 X86CC = X86::COND_E;
7000 case Intrinsic::x86_sse41_ptestc:
7002 X86CC = X86::COND_B;
7004 case Intrinsic::x86_sse41_ptestnzc:
7006 X86CC = X86::COND_A;
7010 SDValue LHS = Op.getOperand(1);
7011 SDValue RHS = Op.getOperand(2);
7012 SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
7013 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
7014 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
7015 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7018 // Fix vector shift instructions where the last operand is a non-immediate
7020 case Intrinsic::x86_sse2_pslli_w:
7021 case Intrinsic::x86_sse2_pslli_d:
7022 case Intrinsic::x86_sse2_pslli_q:
7023 case Intrinsic::x86_sse2_psrli_w:
7024 case Intrinsic::x86_sse2_psrli_d:
7025 case Intrinsic::x86_sse2_psrli_q:
7026 case Intrinsic::x86_sse2_psrai_w:
7027 case Intrinsic::x86_sse2_psrai_d:
7028 case Intrinsic::x86_mmx_pslli_w:
7029 case Intrinsic::x86_mmx_pslli_d:
7030 case Intrinsic::x86_mmx_pslli_q:
7031 case Intrinsic::x86_mmx_psrli_w:
7032 case Intrinsic::x86_mmx_psrli_d:
7033 case Intrinsic::x86_mmx_psrli_q:
7034 case Intrinsic::x86_mmx_psrai_w:
7035 case Intrinsic::x86_mmx_psrai_d: {
7036 SDValue ShAmt = Op.getOperand(2);
7037 if (isa<ConstantSDNode>(ShAmt))
7040 unsigned NewIntNo = 0;
7041 EVT ShAmtVT = MVT::v4i32;
7043 case Intrinsic::x86_sse2_pslli_w:
7044 NewIntNo = Intrinsic::x86_sse2_psll_w;
7046 case Intrinsic::x86_sse2_pslli_d:
7047 NewIntNo = Intrinsic::x86_sse2_psll_d;
7049 case Intrinsic::x86_sse2_pslli_q:
7050 NewIntNo = Intrinsic::x86_sse2_psll_q;
7052 case Intrinsic::x86_sse2_psrli_w:
7053 NewIntNo = Intrinsic::x86_sse2_psrl_w;
7055 case Intrinsic::x86_sse2_psrli_d:
7056 NewIntNo = Intrinsic::x86_sse2_psrl_d;
7058 case Intrinsic::x86_sse2_psrli_q:
7059 NewIntNo = Intrinsic::x86_sse2_psrl_q;
7061 case Intrinsic::x86_sse2_psrai_w:
7062 NewIntNo = Intrinsic::x86_sse2_psra_w;
7064 case Intrinsic::x86_sse2_psrai_d:
7065 NewIntNo = Intrinsic::x86_sse2_psra_d;
7068 ShAmtVT = MVT::v2i32;
7070 case Intrinsic::x86_mmx_pslli_w:
7071 NewIntNo = Intrinsic::x86_mmx_psll_w;
7073 case Intrinsic::x86_mmx_pslli_d:
7074 NewIntNo = Intrinsic::x86_mmx_psll_d;
7076 case Intrinsic::x86_mmx_pslli_q:
7077 NewIntNo = Intrinsic::x86_mmx_psll_q;
7079 case Intrinsic::x86_mmx_psrli_w:
7080 NewIntNo = Intrinsic::x86_mmx_psrl_w;
7082 case Intrinsic::x86_mmx_psrli_d:
7083 NewIntNo = Intrinsic::x86_mmx_psrl_d;
7085 case Intrinsic::x86_mmx_psrli_q:
7086 NewIntNo = Intrinsic::x86_mmx_psrl_q;
7088 case Intrinsic::x86_mmx_psrai_w:
7089 NewIntNo = Intrinsic::x86_mmx_psra_w;
7091 case Intrinsic::x86_mmx_psrai_d:
7092 NewIntNo = Intrinsic::x86_mmx_psra_d;
7094 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7100 // The vector shift intrinsics with scalars uses 32b shift amounts but
7101 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
7105 ShOps[1] = DAG.getConstant(0, MVT::i32);
7106 if (ShAmtVT == MVT::v4i32) {
7107 ShOps[2] = DAG.getUNDEF(MVT::i32);
7108 ShOps[3] = DAG.getUNDEF(MVT::i32);
7109 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
7111 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
7114 EVT VT = Op.getValueType();
7115 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
7116 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7117 DAG.getConstant(NewIntNo, MVT::i32),
7118 Op.getOperand(1), ShAmt);
7123 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
7124 SelectionDAG &DAG) const {
7125 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7126 MFI->setReturnAddressIsTaken(true);
7128 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7129 DebugLoc dl = Op.getDebugLoc();
7132 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7134 DAG.getConstant(TD->getPointerSize(),
7135 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
7136 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7137 DAG.getNode(ISD::ADD, dl, getPointerTy(),
7139 NULL, 0, false, false, 0);
7142 // Just load the return address.
7143 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
7144 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7145 RetAddrFI, NULL, 0, false, false, 0);
7148 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
7149 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7150 MFI->setFrameAddressIsTaken(true);
7152 EVT VT = Op.getValueType();
7153 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
7154 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7155 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
7156 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
7158 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0,
7163 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
7164 SelectionDAG &DAG) const {
7165 return DAG.getIntPtrConstant(2*TD->getPointerSize());
7168 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
7169 MachineFunction &MF = DAG.getMachineFunction();
7170 SDValue Chain = Op.getOperand(0);
7171 SDValue Offset = Op.getOperand(1);
7172 SDValue Handler = Op.getOperand(2);
7173 DebugLoc dl = Op.getDebugLoc();
7175 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
7177 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
7179 SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
7180 DAG.getIntPtrConstant(-TD->getPointerSize()));
7181 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
7182 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0, false, false, 0);
7183 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
7184 MF.getRegInfo().addLiveOut(StoreAddrReg);
7186 return DAG.getNode(X86ISD::EH_RETURN, dl,
7188 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
7191 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
7192 SelectionDAG &DAG) const {
7193 SDValue Root = Op.getOperand(0);
7194 SDValue Trmp = Op.getOperand(1); // trampoline
7195 SDValue FPtr = Op.getOperand(2); // nested function
7196 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
7197 DebugLoc dl = Op.getDebugLoc();
7199 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7201 if (Subtarget->is64Bit()) {
7202 SDValue OutChains[6];
7204 // Large code-model.
7205 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
7206 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
7208 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
7209 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
7211 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
7213 // Load the pointer to the nested function into R11.
7214 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
7215 SDValue Addr = Trmp;
7216 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7217 Addr, TrmpAddr, 0, false, false, 0);
7219 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7220 DAG.getConstant(2, MVT::i64));
7221 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2,
7224 // Load the 'nest' parameter value into R10.
7225 // R10 is specified in X86CallingConv.td
7226 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
7227 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7228 DAG.getConstant(10, MVT::i64));
7229 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7230 Addr, TrmpAddr, 10, false, false, 0);
7232 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7233 DAG.getConstant(12, MVT::i64));
7234 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12,
7237 // Jump to the nested function.
7238 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
7239 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7240 DAG.getConstant(20, MVT::i64));
7241 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7242 Addr, TrmpAddr, 20, false, false, 0);
7244 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
7245 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7246 DAG.getConstant(22, MVT::i64));
7247 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
7248 TrmpAddr, 22, false, false, 0);
7251 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
7252 return DAG.getMergeValues(Ops, 2, dl);
7254 const Function *Func =
7255 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
7256 CallingConv::ID CC = Func->getCallingConv();
7261 llvm_unreachable("Unsupported calling convention");
7262 case CallingConv::C:
7263 case CallingConv::X86_StdCall: {
7264 // Pass 'nest' parameter in ECX.
7265 // Must be kept in sync with X86CallingConv.td
7268 // Check that ECX wasn't needed by an 'inreg' parameter.
7269 const FunctionType *FTy = Func->getFunctionType();
7270 const AttrListPtr &Attrs = Func->getAttributes();
7272 if (!Attrs.isEmpty() && !Func->isVarArg()) {
7273 unsigned InRegCount = 0;
7276 for (FunctionType::param_iterator I = FTy->param_begin(),
7277 E = FTy->param_end(); I != E; ++I, ++Idx)
7278 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
7279 // FIXME: should only count parameters that are lowered to integers.
7280 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
7282 if (InRegCount > 2) {
7283 report_fatal_error("Nest register in use - reduce number of inreg"
7289 case CallingConv::X86_FastCall:
7290 case CallingConv::X86_ThisCall:
7291 case CallingConv::Fast:
7292 // Pass 'nest' parameter in EAX.
7293 // Must be kept in sync with X86CallingConv.td
7298 SDValue OutChains[4];
7301 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7302 DAG.getConstant(10, MVT::i32));
7303 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
7305 // This is storing the opcode for MOV32ri.
7306 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
7307 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
7308 OutChains[0] = DAG.getStore(Root, dl,
7309 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
7310 Trmp, TrmpAddr, 0, false, false, 0);
7312 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7313 DAG.getConstant(1, MVT::i32));
7314 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1,
7317 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
7318 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7319 DAG.getConstant(5, MVT::i32));
7320 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
7321 TrmpAddr, 5, false, false, 1);
7323 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7324 DAG.getConstant(6, MVT::i32));
7325 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6,
7329 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
7330 return DAG.getMergeValues(Ops, 2, dl);
7334 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
7335 SelectionDAG &DAG) const {
7337 The rounding mode is in bits 11:10 of FPSR, and has the following
7344 FLT_ROUNDS, on the other hand, expects the following:
7351 To perform the conversion, we do:
7352 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
7355 MachineFunction &MF = DAG.getMachineFunction();
7356 const TargetMachine &TM = MF.getTarget();
7357 const TargetFrameInfo &TFI = *TM.getFrameInfo();
7358 unsigned StackAlignment = TFI.getStackAlignment();
7359 EVT VT = Op.getValueType();
7360 DebugLoc dl = Op.getDebugLoc();
7362 // Save FP Control Word to stack slot
7363 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
7364 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7366 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
7367 DAG.getEntryNode(), StackSlot);
7369 // Load FP Control Word from stack slot
7370 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0,
7373 // Transform as necessary
7375 DAG.getNode(ISD::SRL, dl, MVT::i16,
7376 DAG.getNode(ISD::AND, dl, MVT::i16,
7377 CWD, DAG.getConstant(0x800, MVT::i16)),
7378 DAG.getConstant(11, MVT::i8));
7380 DAG.getNode(ISD::SRL, dl, MVT::i16,
7381 DAG.getNode(ISD::AND, dl, MVT::i16,
7382 CWD, DAG.getConstant(0x400, MVT::i16)),
7383 DAG.getConstant(9, MVT::i8));
7386 DAG.getNode(ISD::AND, dl, MVT::i16,
7387 DAG.getNode(ISD::ADD, dl, MVT::i16,
7388 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
7389 DAG.getConstant(1, MVT::i16)),
7390 DAG.getConstant(3, MVT::i16));
7393 return DAG.getNode((VT.getSizeInBits() < 16 ?
7394 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7397 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
7398 EVT VT = Op.getValueType();
7400 unsigned NumBits = VT.getSizeInBits();
7401 DebugLoc dl = Op.getDebugLoc();
7403 Op = Op.getOperand(0);
7404 if (VT == MVT::i8) {
7405 // Zero extend to i32 since there is not an i8 bsr.
7407 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7410 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
7411 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7412 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
7414 // If src is zero (i.e. bsr sets ZF), returns NumBits.
7417 DAG.getConstant(NumBits+NumBits-1, OpVT),
7418 DAG.getConstant(X86::COND_E, MVT::i8),
7421 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7423 // Finally xor with NumBits-1.
7424 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
7427 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7431 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
7432 EVT VT = Op.getValueType();
7434 unsigned NumBits = VT.getSizeInBits();
7435 DebugLoc dl = Op.getDebugLoc();
7437 Op = Op.getOperand(0);
7438 if (VT == MVT::i8) {
7440 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7443 // Issue a bsf (scan bits forward) which also sets EFLAGS.
7444 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7445 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
7447 // If src is zero (i.e. bsf sets ZF), returns NumBits.
7450 DAG.getConstant(NumBits, OpVT),
7451 DAG.getConstant(X86::COND_E, MVT::i8),
7454 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7457 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7461 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
7462 EVT VT = Op.getValueType();
7463 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
7464 DebugLoc dl = Op.getDebugLoc();
7466 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
7467 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
7468 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
7469 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
7470 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
7472 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
7473 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
7474 // return AloBlo + AloBhi + AhiBlo;
7476 SDValue A = Op.getOperand(0);
7477 SDValue B = Op.getOperand(1);
7479 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7480 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7481 A, DAG.getConstant(32, MVT::i32));
7482 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7483 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7484 B, DAG.getConstant(32, MVT::i32));
7485 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7486 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7488 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7489 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7491 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7492 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7494 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7495 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7496 AloBhi, DAG.getConstant(32, MVT::i32));
7497 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7498 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7499 AhiBlo, DAG.getConstant(32, MVT::i32));
7500 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
7501 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
7505 SDValue X86TargetLowering::LowerSHL(SDValue Op, SelectionDAG &DAG) const {
7506 EVT VT = Op.getValueType();
7507 DebugLoc dl = Op.getDebugLoc();
7508 SDValue R = Op.getOperand(0);
7510 LLVMContext *Context = DAG.getContext();
7512 assert(Subtarget->hasSSE41() && "Cannot lower SHL without SSE4.1 or later");
7514 if (VT == MVT::v4i32) {
7515 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7516 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
7517 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
7519 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
7521 std::vector<Constant*> CV(4, CI);
7522 Constant *C = ConstantVector::get(CV);
7523 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7524 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7525 PseudoSourceValue::getConstantPool(), 0,
7528 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
7529 Op = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, Op);
7530 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
7531 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
7533 if (VT == MVT::v16i8) {
7535 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7536 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
7537 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
7539 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
7540 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
7542 std::vector<Constant*> CVM1(16, CM1);
7543 std::vector<Constant*> CVM2(16, CM2);
7544 Constant *C = ConstantVector::get(CVM1);
7545 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7546 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7547 PseudoSourceValue::getConstantPool(), 0,
7550 // r = pblendv(r, psllw(r & (char16)15, 4), a);
7551 M = DAG.getNode(ISD::AND, dl, VT, R, M);
7552 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7553 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
7554 DAG.getConstant(4, MVT::i32));
7555 R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7556 DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
7559 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
7561 C = ConstantVector::get(CVM2);
7562 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
7563 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
7564 PseudoSourceValue::getConstantPool(), 0, false, false, 16);
7566 // r = pblendv(r, psllw(r & (char16)63, 2), a);
7567 M = DAG.getNode(ISD::AND, dl, VT, R, M);
7568 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7569 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
7570 DAG.getConstant(2, MVT::i32));
7571 R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7572 DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
7575 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
7577 // return pblendv(r, r+r, a);
7578 R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7579 DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
7580 R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
7586 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
7587 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
7588 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
7589 // looks for this combo and may remove the "setcc" instruction if the "setcc"
7590 // has only one use.
7591 SDNode *N = Op.getNode();
7592 SDValue LHS = N->getOperand(0);
7593 SDValue RHS = N->getOperand(1);
7594 unsigned BaseOp = 0;
7596 DebugLoc dl = Op.getDebugLoc();
7598 switch (Op.getOpcode()) {
7599 default: llvm_unreachable("Unknown ovf instruction!");
7601 // A subtract of one will be selected as a INC. Note that INC doesn't
7602 // set CF, so we can't do this for UADDO.
7603 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7604 if (C->getAPIntValue() == 1) {
7605 BaseOp = X86ISD::INC;
7609 BaseOp = X86ISD::ADD;
7613 BaseOp = X86ISD::ADD;
7617 // A subtract of one will be selected as a DEC. Note that DEC doesn't
7618 // set CF, so we can't do this for USUBO.
7619 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7620 if (C->getAPIntValue() == 1) {
7621 BaseOp = X86ISD::DEC;
7625 BaseOp = X86ISD::SUB;
7629 BaseOp = X86ISD::SUB;
7633 BaseOp = X86ISD::SMUL;
7637 BaseOp = X86ISD::UMUL;
7642 // Also sets EFLAGS.
7643 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
7644 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
7647 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
7648 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
7650 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
7654 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
7655 DebugLoc dl = Op.getDebugLoc();
7657 if (!Subtarget->hasSSE2())
7658 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0),
7659 DAG.getConstant(0, MVT::i32));
7661 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
7663 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
7665 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7666 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
7667 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
7668 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
7670 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
7671 if (!Op1 && !Op2 && !Op3 && Op4)
7672 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
7674 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
7675 if (Op1 && !Op2 && !Op3 && !Op4)
7676 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
7678 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
7680 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
7684 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
7685 EVT T = Op.getValueType();
7686 DebugLoc dl = Op.getDebugLoc();
7689 switch(T.getSimpleVT().SimpleTy) {
7691 assert(false && "Invalid value type!");
7692 case MVT::i8: Reg = X86::AL; size = 1; break;
7693 case MVT::i16: Reg = X86::AX; size = 2; break;
7694 case MVT::i32: Reg = X86::EAX; size = 4; break;
7696 assert(Subtarget->is64Bit() && "Node not type legal!");
7697 Reg = X86::RAX; size = 8;
7700 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
7701 Op.getOperand(2), SDValue());
7702 SDValue Ops[] = { cpIn.getValue(0),
7705 DAG.getTargetConstant(size, MVT::i8),
7707 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7708 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
7710 DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
7714 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
7715 SelectionDAG &DAG) const {
7716 assert(Subtarget->is64Bit() && "Result not type legalized?");
7717 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7718 SDValue TheChain = Op.getOperand(0);
7719 DebugLoc dl = Op.getDebugLoc();
7720 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7721 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
7722 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
7724 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
7725 DAG.getConstant(32, MVT::i8));
7727 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
7730 return DAG.getMergeValues(Ops, 2, dl);
7733 SDValue X86TargetLowering::LowerBIT_CONVERT(SDValue Op,
7734 SelectionDAG &DAG) const {
7735 EVT SrcVT = Op.getOperand(0).getValueType();
7736 EVT DstVT = Op.getValueType();
7737 assert((Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
7738 Subtarget->hasMMX() && !DisableMMX) &&
7739 "Unexpected custom BIT_CONVERT");
7740 assert((DstVT == MVT::i64 ||
7741 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
7742 "Unexpected custom BIT_CONVERT");
7743 // i64 <=> MMX conversions are Legal.
7744 if (SrcVT==MVT::i64 && DstVT.isVector())
7746 if (DstVT==MVT::i64 && SrcVT.isVector())
7748 // MMX <=> MMX conversions are Legal.
7749 if (SrcVT.isVector() && DstVT.isVector())
7751 // All other conversions need to be expanded.
7754 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
7755 SDNode *Node = Op.getNode();
7756 DebugLoc dl = Node->getDebugLoc();
7757 EVT T = Node->getValueType(0);
7758 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
7759 DAG.getConstant(0, T), Node->getOperand(2));
7760 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
7761 cast<AtomicSDNode>(Node)->getMemoryVT(),
7762 Node->getOperand(0),
7763 Node->getOperand(1), negOp,
7764 cast<AtomicSDNode>(Node)->getSrcValue(),
7765 cast<AtomicSDNode>(Node)->getAlignment());
7768 /// LowerOperation - Provide custom lowering hooks for some operations.
7770 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7771 switch (Op.getOpcode()) {
7772 default: llvm_unreachable("Should not custom lower this!");
7773 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
7774 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
7775 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
7776 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
7777 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
7778 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7779 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7780 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7781 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
7782 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
7783 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
7784 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7785 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
7786 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
7787 case ISD::SHL_PARTS:
7788 case ISD::SRA_PARTS:
7789 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
7790 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
7791 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
7792 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
7793 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
7794 case ISD::FABS: return LowerFABS(Op, DAG);
7795 case ISD::FNEG: return LowerFNEG(Op, DAG);
7796 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
7797 case ISD::SETCC: return LowerSETCC(Op, DAG);
7798 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
7799 case ISD::SELECT: return LowerSELECT(Op, DAG);
7800 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
7801 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
7802 case ISD::VASTART: return LowerVASTART(Op, DAG);
7803 case ISD::VAARG: return LowerVAARG(Op, DAG);
7804 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
7805 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7806 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
7807 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
7808 case ISD::FRAME_TO_ARGS_OFFSET:
7809 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
7810 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
7811 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
7812 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
7813 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
7814 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
7815 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
7816 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
7817 case ISD::SHL: return LowerSHL(Op, DAG);
7823 case ISD::UMULO: return LowerXALUO(Op, DAG);
7824 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
7825 case ISD::BIT_CONVERT: return LowerBIT_CONVERT(Op, DAG);
7829 void X86TargetLowering::
7830 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
7831 SelectionDAG &DAG, unsigned NewOp) const {
7832 EVT T = Node->getValueType(0);
7833 DebugLoc dl = Node->getDebugLoc();
7834 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
7836 SDValue Chain = Node->getOperand(0);
7837 SDValue In1 = Node->getOperand(1);
7838 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7839 Node->getOperand(2), DAG.getIntPtrConstant(0));
7840 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7841 Node->getOperand(2), DAG.getIntPtrConstant(1));
7842 SDValue Ops[] = { Chain, In1, In2L, In2H };
7843 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7845 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
7846 cast<MemSDNode>(Node)->getMemOperand());
7847 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7848 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7849 Results.push_back(Result.getValue(2));
7852 /// ReplaceNodeResults - Replace a node with an illegal result type
7853 /// with a new node built out of custom code.
7854 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7855 SmallVectorImpl<SDValue>&Results,
7856 SelectionDAG &DAG) const {
7857 DebugLoc dl = N->getDebugLoc();
7858 switch (N->getOpcode()) {
7860 assert(false && "Do not know how to custom type legalize this operation!");
7862 case ISD::FP_TO_SINT: {
7863 std::pair<SDValue,SDValue> Vals =
7864 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
7865 SDValue FIST = Vals.first, StackSlot = Vals.second;
7866 if (FIST.getNode() != 0) {
7867 EVT VT = N->getValueType(0);
7868 // Return a load from the stack slot.
7869 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0,
7874 case ISD::READCYCLECOUNTER: {
7875 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7876 SDValue TheChain = N->getOperand(0);
7877 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7878 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7880 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7882 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7883 SDValue Ops[] = { eax, edx };
7884 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7885 Results.push_back(edx.getValue(1));
7888 case ISD::ATOMIC_CMP_SWAP: {
7889 EVT T = N->getValueType(0);
7890 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7891 SDValue cpInL, cpInH;
7892 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7893 DAG.getConstant(0, MVT::i32));
7894 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7895 DAG.getConstant(1, MVT::i32));
7896 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7897 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7899 SDValue swapInL, swapInH;
7900 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7901 DAG.getConstant(0, MVT::i32));
7902 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7903 DAG.getConstant(1, MVT::i32));
7904 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7906 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7907 swapInL.getValue(1));
7908 SDValue Ops[] = { swapInH.getValue(0),
7910 swapInH.getValue(1) };
7911 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7912 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7913 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7914 MVT::i32, Result.getValue(1));
7915 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7916 MVT::i32, cpOutL.getValue(2));
7917 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7918 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7919 Results.push_back(cpOutH.getValue(1));
7922 case ISD::ATOMIC_LOAD_ADD:
7923 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7925 case ISD::ATOMIC_LOAD_AND:
7926 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7928 case ISD::ATOMIC_LOAD_NAND:
7929 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7931 case ISD::ATOMIC_LOAD_OR:
7932 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7934 case ISD::ATOMIC_LOAD_SUB:
7935 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7937 case ISD::ATOMIC_LOAD_XOR:
7938 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7940 case ISD::ATOMIC_SWAP:
7941 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7946 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7948 default: return NULL;
7949 case X86ISD::BSF: return "X86ISD::BSF";
7950 case X86ISD::BSR: return "X86ISD::BSR";
7951 case X86ISD::SHLD: return "X86ISD::SHLD";
7952 case X86ISD::SHRD: return "X86ISD::SHRD";
7953 case X86ISD::FAND: return "X86ISD::FAND";
7954 case X86ISD::FOR: return "X86ISD::FOR";
7955 case X86ISD::FXOR: return "X86ISD::FXOR";
7956 case X86ISD::FSRL: return "X86ISD::FSRL";
7957 case X86ISD::FILD: return "X86ISD::FILD";
7958 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
7959 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7960 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7961 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7962 case X86ISD::FLD: return "X86ISD::FLD";
7963 case X86ISD::FST: return "X86ISD::FST";
7964 case X86ISD::CALL: return "X86ISD::CALL";
7965 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
7966 case X86ISD::BT: return "X86ISD::BT";
7967 case X86ISD::CMP: return "X86ISD::CMP";
7968 case X86ISD::COMI: return "X86ISD::COMI";
7969 case X86ISD::UCOMI: return "X86ISD::UCOMI";
7970 case X86ISD::SETCC: return "X86ISD::SETCC";
7971 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
7972 case X86ISD::CMOV: return "X86ISD::CMOV";
7973 case X86ISD::BRCOND: return "X86ISD::BRCOND";
7974 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
7975 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
7976 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
7977 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
7978 case X86ISD::Wrapper: return "X86ISD::Wrapper";
7979 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
7980 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
7981 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
7982 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
7983 case X86ISD::PINSRB: return "X86ISD::PINSRB";
7984 case X86ISD::PINSRW: return "X86ISD::PINSRW";
7985 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
7986 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
7987 case X86ISD::FMAX: return "X86ISD::FMAX";
7988 case X86ISD::FMIN: return "X86ISD::FMIN";
7989 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
7990 case X86ISD::FRCP: return "X86ISD::FRCP";
7991 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
7992 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
7993 case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7994 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
7995 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
7996 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
7997 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
7998 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
7999 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
8000 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
8001 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
8002 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
8003 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
8004 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
8005 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
8006 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
8007 case X86ISD::VSHL: return "X86ISD::VSHL";
8008 case X86ISD::VSRL: return "X86ISD::VSRL";
8009 case X86ISD::CMPPD: return "X86ISD::CMPPD";
8010 case X86ISD::CMPPS: return "X86ISD::CMPPS";
8011 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
8012 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
8013 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
8014 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
8015 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
8016 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
8017 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
8018 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
8019 case X86ISD::ADD: return "X86ISD::ADD";
8020 case X86ISD::SUB: return "X86ISD::SUB";
8021 case X86ISD::SMUL: return "X86ISD::SMUL";
8022 case X86ISD::UMUL: return "X86ISD::UMUL";
8023 case X86ISD::INC: return "X86ISD::INC";
8024 case X86ISD::DEC: return "X86ISD::DEC";
8025 case X86ISD::OR: return "X86ISD::OR";
8026 case X86ISD::XOR: return "X86ISD::XOR";
8027 case X86ISD::AND: return "X86ISD::AND";
8028 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
8029 case X86ISD::PTEST: return "X86ISD::PTEST";
8030 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
8031 case X86ISD::MINGW_ALLOCA: return "X86ISD::MINGW_ALLOCA";
8035 // isLegalAddressingMode - Return true if the addressing mode represented
8036 // by AM is legal for this target, for a load/store of the specified type.
8037 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
8038 const Type *Ty) const {
8039 // X86 supports extremely general addressing modes.
8040 CodeModel::Model M = getTargetMachine().getCodeModel();
8042 // X86 allows a sign-extended 32-bit immediate field as a displacement.
8043 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
8048 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
8050 // If a reference to this global requires an extra load, we can't fold it.
8051 if (isGlobalStubReference(GVFlags))
8054 // If BaseGV requires a register for the PIC base, we cannot also have a
8055 // BaseReg specified.
8056 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
8059 // If lower 4G is not available, then we must use rip-relative addressing.
8060 if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
8070 // These scales always work.
8075 // These scales are formed with basereg+scalereg. Only accept if there is
8080 default: // Other stuff never works.
8088 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
8089 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8091 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8092 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8093 if (NumBits1 <= NumBits2)
8098 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
8099 if (!VT1.isInteger() || !VT2.isInteger())
8101 unsigned NumBits1 = VT1.getSizeInBits();
8102 unsigned NumBits2 = VT2.getSizeInBits();
8103 if (NumBits1 <= NumBits2)
8108 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
8109 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
8110 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
8113 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
8114 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
8115 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
8118 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
8119 // i16 instructions are longer (0x66 prefix) and potentially slower.
8120 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
8123 /// isShuffleMaskLegal - Targets can use this to indicate that they only
8124 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
8125 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
8126 /// are assumed to be legal.
8128 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
8130 // Very little shuffling can be done for 64-bit vectors right now.
8131 if (VT.getSizeInBits() == 64)
8132 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
8134 // FIXME: pshufb, blends, shifts.
8135 return (VT.getVectorNumElements() == 2 ||
8136 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
8137 isMOVLMask(M, VT) ||
8138 isSHUFPMask(M, VT) ||
8139 isPSHUFDMask(M, VT) ||
8140 isPSHUFHWMask(M, VT) ||
8141 isPSHUFLWMask(M, VT) ||
8142 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
8143 isUNPCKLMask(M, VT) ||
8144 isUNPCKHMask(M, VT) ||
8145 isUNPCKL_v_undef_Mask(M, VT) ||
8146 isUNPCKH_v_undef_Mask(M, VT));
8150 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
8152 unsigned NumElts = VT.getVectorNumElements();
8153 // FIXME: This collection of masks seems suspect.
8156 if (NumElts == 4 && VT.getSizeInBits() == 128) {
8157 return (isMOVLMask(Mask, VT) ||
8158 isCommutedMOVLMask(Mask, VT, true) ||
8159 isSHUFPMask(Mask, VT) ||
8160 isCommutedSHUFPMask(Mask, VT));
8165 //===----------------------------------------------------------------------===//
8166 // X86 Scheduler Hooks
8167 //===----------------------------------------------------------------------===//
8169 // private utility function
8171 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
8172 MachineBasicBlock *MBB,
8179 TargetRegisterClass *RC,
8180 bool invSrc) const {
8181 // For the atomic bitwise operator, we generate
8184 // ld t1 = [bitinstr.addr]
8185 // op t2 = t1, [bitinstr.val]
8187 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
8189 // fallthrough -->nextMBB
8190 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8191 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8192 MachineFunction::iterator MBBIter = MBB;
8195 /// First build the CFG
8196 MachineFunction *F = MBB->getParent();
8197 MachineBasicBlock *thisMBB = MBB;
8198 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8199 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8200 F->insert(MBBIter, newMBB);
8201 F->insert(MBBIter, nextMBB);
8203 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
8204 nextMBB->splice(nextMBB->begin(), thisMBB,
8205 llvm::next(MachineBasicBlock::iterator(bInstr)),
8207 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
8209 // Update thisMBB to fall through to newMBB
8210 thisMBB->addSuccessor(newMBB);
8212 // newMBB jumps to itself and fall through to nextMBB
8213 newMBB->addSuccessor(nextMBB);
8214 newMBB->addSuccessor(newMBB);
8216 // Insert instructions into newMBB based on incoming instruction
8217 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
8218 "unexpected number of operands");
8219 DebugLoc dl = bInstr->getDebugLoc();
8220 MachineOperand& destOper = bInstr->getOperand(0);
8221 MachineOperand* argOpers[2 + X86::AddrNumOperands];
8222 int numArgs = bInstr->getNumOperands() - 1;
8223 for (int i=0; i < numArgs; ++i)
8224 argOpers[i] = &bInstr->getOperand(i+1);
8226 // x86 address has 4 operands: base, index, scale, and displacement
8227 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
8228 int valArgIndx = lastAddrIndx + 1;
8230 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
8231 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
8232 for (int i=0; i <= lastAddrIndx; ++i)
8233 (*MIB).addOperand(*argOpers[i]);
8235 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
8237 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
8242 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8243 assert((argOpers[valArgIndx]->isReg() ||
8244 argOpers[valArgIndx]->isImm()) &&
8246 if (argOpers[valArgIndx]->isReg())
8247 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
8249 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
8251 (*MIB).addOperand(*argOpers[valArgIndx]);
8253 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
8256 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
8257 for (int i=0; i <= lastAddrIndx; ++i)
8258 (*MIB).addOperand(*argOpers[i]);
8260 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8261 (*MIB).setMemRefs(bInstr->memoperands_begin(),
8262 bInstr->memoperands_end());
8264 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
8268 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8270 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
8274 // private utility function: 64 bit atomics on 32 bit host.
8276 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
8277 MachineBasicBlock *MBB,
8282 bool invSrc) const {
8283 // For the atomic bitwise operator, we generate
8284 // thisMBB (instructions are in pairs, except cmpxchg8b)
8285 // ld t1,t2 = [bitinstr.addr]
8287 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
8288 // op t5, t6 <- out1, out2, [bitinstr.val]
8289 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
8290 // mov ECX, EBX <- t5, t6
8291 // mov EAX, EDX <- t1, t2
8292 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
8293 // mov t3, t4 <- EAX, EDX
8295 // result in out1, out2
8296 // fallthrough -->nextMBB
8298 const TargetRegisterClass *RC = X86::GR32RegisterClass;
8299 const unsigned LoadOpc = X86::MOV32rm;
8300 const unsigned NotOpc = X86::NOT32r;
8301 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8302 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8303 MachineFunction::iterator MBBIter = MBB;
8306 /// First build the CFG
8307 MachineFunction *F = MBB->getParent();
8308 MachineBasicBlock *thisMBB = MBB;
8309 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8310 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8311 F->insert(MBBIter, newMBB);
8312 F->insert(MBBIter, nextMBB);
8314 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
8315 nextMBB->splice(nextMBB->begin(), thisMBB,
8316 llvm::next(MachineBasicBlock::iterator(bInstr)),
8318 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
8320 // Update thisMBB to fall through to newMBB
8321 thisMBB->addSuccessor(newMBB);
8323 // newMBB jumps to itself and fall through to nextMBB
8324 newMBB->addSuccessor(nextMBB);
8325 newMBB->addSuccessor(newMBB);
8327 DebugLoc dl = bInstr->getDebugLoc();
8328 // Insert instructions into newMBB based on incoming instruction
8329 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
8330 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
8331 "unexpected number of operands");
8332 MachineOperand& dest1Oper = bInstr->getOperand(0);
8333 MachineOperand& dest2Oper = bInstr->getOperand(1);
8334 MachineOperand* argOpers[2 + X86::AddrNumOperands];
8335 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
8336 argOpers[i] = &bInstr->getOperand(i+2);
8338 // We use some of the operands multiple times, so conservatively just
8339 // clear any kill flags that might be present.
8340 if (argOpers[i]->isReg() && argOpers[i]->isUse())
8341 argOpers[i]->setIsKill(false);
8344 // x86 address has 5 operands: base, index, scale, displacement, and segment.
8345 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
8347 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
8348 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
8349 for (int i=0; i <= lastAddrIndx; ++i)
8350 (*MIB).addOperand(*argOpers[i]);
8351 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8352 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
8353 // add 4 to displacement.
8354 for (int i=0; i <= lastAddrIndx-2; ++i)
8355 (*MIB).addOperand(*argOpers[i]);
8356 MachineOperand newOp3 = *(argOpers[3]);
8358 newOp3.setImm(newOp3.getImm()+4);
8360 newOp3.setOffset(newOp3.getOffset()+4);
8361 (*MIB).addOperand(newOp3);
8362 (*MIB).addOperand(*argOpers[lastAddrIndx]);
8364 // t3/4 are defined later, at the bottom of the loop
8365 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
8366 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
8367 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
8368 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
8369 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
8370 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
8372 // The subsequent operations should be using the destination registers of
8373 //the PHI instructions.
8375 t1 = F->getRegInfo().createVirtualRegister(RC);
8376 t2 = F->getRegInfo().createVirtualRegister(RC);
8377 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
8378 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
8380 t1 = dest1Oper.getReg();
8381 t2 = dest2Oper.getReg();
8384 int valArgIndx = lastAddrIndx + 1;
8385 assert((argOpers[valArgIndx]->isReg() ||
8386 argOpers[valArgIndx]->isImm()) &&
8388 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
8389 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
8390 if (argOpers[valArgIndx]->isReg())
8391 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
8393 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
8394 if (regOpcL != X86::MOV32rr)
8396 (*MIB).addOperand(*argOpers[valArgIndx]);
8397 assert(argOpers[valArgIndx + 1]->isReg() ==
8398 argOpers[valArgIndx]->isReg());
8399 assert(argOpers[valArgIndx + 1]->isImm() ==
8400 argOpers[valArgIndx]->isImm());
8401 if (argOpers[valArgIndx + 1]->isReg())
8402 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
8404 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
8405 if (regOpcH != X86::MOV32rr)
8407 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
8409 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
8411 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
8414 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
8416 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
8419 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
8420 for (int i=0; i <= lastAddrIndx; ++i)
8421 (*MIB).addOperand(*argOpers[i]);
8423 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8424 (*MIB).setMemRefs(bInstr->memoperands_begin(),
8425 bInstr->memoperands_end());
8427 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
8428 MIB.addReg(X86::EAX);
8429 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
8430 MIB.addReg(X86::EDX);
8433 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8435 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
8439 // private utility function
8441 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
8442 MachineBasicBlock *MBB,
8443 unsigned cmovOpc) const {
8444 // For the atomic min/max operator, we generate
8447 // ld t1 = [min/max.addr]
8448 // mov t2 = [min/max.val]
8450 // cmov[cond] t2 = t1
8452 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
8454 // fallthrough -->nextMBB
8456 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8457 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8458 MachineFunction::iterator MBBIter = MBB;
8461 /// First build the CFG
8462 MachineFunction *F = MBB->getParent();
8463 MachineBasicBlock *thisMBB = MBB;
8464 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8465 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8466 F->insert(MBBIter, newMBB);
8467 F->insert(MBBIter, nextMBB);
8469 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
8470 nextMBB->splice(nextMBB->begin(), thisMBB,
8471 llvm::next(MachineBasicBlock::iterator(mInstr)),
8473 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
8475 // Update thisMBB to fall through to newMBB
8476 thisMBB->addSuccessor(newMBB);
8478 // newMBB jumps to newMBB and fall through to nextMBB
8479 newMBB->addSuccessor(nextMBB);
8480 newMBB->addSuccessor(newMBB);
8482 DebugLoc dl = mInstr->getDebugLoc();
8483 // Insert instructions into newMBB based on incoming instruction
8484 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
8485 "unexpected number of operands");
8486 MachineOperand& destOper = mInstr->getOperand(0);
8487 MachineOperand* argOpers[2 + X86::AddrNumOperands];
8488 int numArgs = mInstr->getNumOperands() - 1;
8489 for (int i=0; i < numArgs; ++i)
8490 argOpers[i] = &mInstr->getOperand(i+1);
8492 // x86 address has 4 operands: base, index, scale, and displacement
8493 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
8494 int valArgIndx = lastAddrIndx + 1;
8496 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8497 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
8498 for (int i=0; i <= lastAddrIndx; ++i)
8499 (*MIB).addOperand(*argOpers[i]);
8501 // We only support register and immediate values
8502 assert((argOpers[valArgIndx]->isReg() ||
8503 argOpers[valArgIndx]->isImm()) &&
8506 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8507 if (argOpers[valArgIndx]->isReg())
8508 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
8510 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8511 (*MIB).addOperand(*argOpers[valArgIndx]);
8513 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
8516 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
8521 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8522 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
8526 // Cmp and exchange if none has modified the memory location
8527 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
8528 for (int i=0; i <= lastAddrIndx; ++i)
8529 (*MIB).addOperand(*argOpers[i]);
8531 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8532 (*MIB).setMemRefs(mInstr->memoperands_begin(),
8533 mInstr->memoperands_end());
8535 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
8536 MIB.addReg(X86::EAX);
8539 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8541 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
8545 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
8546 // all of this code can be replaced with that in the .td file.
8548 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
8549 unsigned numArgs, bool memArg) const {
8551 DebugLoc dl = MI->getDebugLoc();
8552 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8556 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
8558 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
8560 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
8562 for (unsigned i = 0; i < numArgs; ++i) {
8563 MachineOperand &Op = MI->getOperand(i+1);
8565 if (!(Op.isReg() && Op.isImplicit()))
8569 BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
8572 MI->eraseFromParent();
8578 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
8580 MachineBasicBlock *MBB) const {
8581 // Emit code to save XMM registers to the stack. The ABI says that the
8582 // number of registers to save is given in %al, so it's theoretically
8583 // possible to do an indirect jump trick to avoid saving all of them,
8584 // however this code takes a simpler approach and just executes all
8585 // of the stores if %al is non-zero. It's less code, and it's probably
8586 // easier on the hardware branch predictor, and stores aren't all that
8587 // expensive anyway.
8589 // Create the new basic blocks. One block contains all the XMM stores,
8590 // and one block is the final destination regardless of whether any
8591 // stores were performed.
8592 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8593 MachineFunction *F = MBB->getParent();
8594 MachineFunction::iterator MBBIter = MBB;
8596 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
8597 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
8598 F->insert(MBBIter, XMMSaveMBB);
8599 F->insert(MBBIter, EndMBB);
8601 // Transfer the remainder of MBB and its successor edges to EndMBB.
8602 EndMBB->splice(EndMBB->begin(), MBB,
8603 llvm::next(MachineBasicBlock::iterator(MI)),
8605 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
8607 // The original block will now fall through to the XMM save block.
8608 MBB->addSuccessor(XMMSaveMBB);
8609 // The XMMSaveMBB will fall through to the end block.
8610 XMMSaveMBB->addSuccessor(EndMBB);
8612 // Now add the instructions.
8613 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8614 DebugLoc DL = MI->getDebugLoc();
8616 unsigned CountReg = MI->getOperand(0).getReg();
8617 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
8618 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
8620 if (!Subtarget->isTargetWin64()) {
8621 // If %al is 0, branch around the XMM save block.
8622 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
8623 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
8624 MBB->addSuccessor(EndMBB);
8627 // In the XMM save block, save all the XMM argument registers.
8628 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
8629 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
8630 MachineMemOperand *MMO =
8631 F->getMachineMemOperand(
8632 PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
8633 MachineMemOperand::MOStore, Offset,
8634 /*Size=*/16, /*Align=*/16);
8635 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
8636 .addFrameIndex(RegSaveFrameIndex)
8637 .addImm(/*Scale=*/1)
8638 .addReg(/*IndexReg=*/0)
8639 .addImm(/*Disp=*/Offset)
8640 .addReg(/*Segment=*/0)
8641 .addReg(MI->getOperand(i).getReg())
8642 .addMemOperand(MMO);
8645 MI->eraseFromParent(); // The pseudo instruction is gone now.
8651 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
8652 MachineBasicBlock *BB) const {
8653 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8654 DebugLoc DL = MI->getDebugLoc();
8656 // To "insert" a SELECT_CC instruction, we actually have to insert the
8657 // diamond control-flow pattern. The incoming instruction knows the
8658 // destination vreg to set, the condition code register to branch on, the
8659 // true/false values to select between, and a branch opcode to use.
8660 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8661 MachineFunction::iterator It = BB;
8667 // cmpTY ccX, r1, r2
8669 // fallthrough --> copy0MBB
8670 MachineBasicBlock *thisMBB = BB;
8671 MachineFunction *F = BB->getParent();
8672 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8673 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8674 F->insert(It, copy0MBB);
8675 F->insert(It, sinkMBB);
8677 // If the EFLAGS register isn't dead in the terminator, then claim that it's
8678 // live into the sink and copy blocks.
8679 const MachineFunction *MF = BB->getParent();
8680 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
8681 BitVector ReservedRegs = TRI->getReservedRegs(*MF);
8683 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
8684 const MachineOperand &MO = MI->getOperand(I);
8685 if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
8686 unsigned Reg = MO.getReg();
8687 if (Reg != X86::EFLAGS) continue;
8688 copy0MBB->addLiveIn(Reg);
8689 sinkMBB->addLiveIn(Reg);
8692 // Transfer the remainder of BB and its successor edges to sinkMBB.
8693 sinkMBB->splice(sinkMBB->begin(), BB,
8694 llvm::next(MachineBasicBlock::iterator(MI)),
8696 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8698 // Add the true and fallthrough blocks as its successors.
8699 BB->addSuccessor(copy0MBB);
8700 BB->addSuccessor(sinkMBB);
8702 // Create the conditional branch instruction.
8704 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
8705 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
8708 // %FalseValue = ...
8709 // # fallthrough to sinkMBB
8710 copy0MBB->addSuccessor(sinkMBB);
8713 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8715 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
8716 TII->get(X86::PHI), MI->getOperand(0).getReg())
8717 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8718 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8720 MI->eraseFromParent(); // The pseudo instruction is gone now.
8725 X86TargetLowering::EmitLoweredMingwAlloca(MachineInstr *MI,
8726 MachineBasicBlock *BB) const {
8727 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8728 DebugLoc DL = MI->getDebugLoc();
8730 // The lowering is pretty easy: we're just emitting the call to _alloca. The
8731 // non-trivial part is impdef of ESP.
8732 // FIXME: The code should be tweaked as soon as we'll try to do codegen for
8735 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
8736 .addExternalSymbol("_alloca")
8737 .addReg(X86::EAX, RegState::Implicit)
8738 .addReg(X86::ESP, RegState::Implicit)
8739 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
8740 .addReg(X86::ESP, RegState::Define | RegState::Implicit);
8742 MI->eraseFromParent(); // The pseudo instruction is gone now.
8747 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
8748 MachineBasicBlock *BB) const {
8749 // This is pretty easy. We're taking the value that we received from
8750 // our load from the relocation, sticking it in either RDI (x86-64)
8751 // or EAX and doing an indirect call. The return value will then
8752 // be in the normal return register.
8753 const X86InstrInfo *TII
8754 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
8755 DebugLoc DL = MI->getDebugLoc();
8756 MachineFunction *F = BB->getParent();
8758 assert(MI->getOperand(3).isGlobal() && "This should be a global");
8760 if (Subtarget->is64Bit()) {
8761 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
8762 TII->get(X86::MOV64rm), X86::RDI)
8764 .addImm(0).addReg(0)
8765 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
8766 MI->getOperand(3).getTargetFlags())
8768 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
8769 addDirectMem(MIB, X86::RDI);
8770 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
8771 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
8772 TII->get(X86::MOV32rm), X86::EAX)
8774 .addImm(0).addReg(0)
8775 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
8776 MI->getOperand(3).getTargetFlags())
8778 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
8779 addDirectMem(MIB, X86::EAX);
8781 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
8782 TII->get(X86::MOV32rm), X86::EAX)
8783 .addReg(TII->getGlobalBaseReg(F))
8784 .addImm(0).addReg(0)
8785 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
8786 MI->getOperand(3).getTargetFlags())
8788 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
8789 addDirectMem(MIB, X86::EAX);
8792 MI->eraseFromParent(); // The pseudo instruction is gone now.
8797 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8798 MachineBasicBlock *BB) const {
8799 switch (MI->getOpcode()) {
8800 default: assert(false && "Unexpected instr type to insert");
8801 case X86::MINGW_ALLOCA:
8802 return EmitLoweredMingwAlloca(MI, BB);
8803 case X86::TLSCall_32:
8804 case X86::TLSCall_64:
8805 return EmitLoweredTLSCall(MI, BB);
8807 case X86::CMOV_V1I64:
8808 case X86::CMOV_FR32:
8809 case X86::CMOV_FR64:
8810 case X86::CMOV_V4F32:
8811 case X86::CMOV_V2F64:
8812 case X86::CMOV_V2I64:
8813 case X86::CMOV_GR16:
8814 case X86::CMOV_GR32:
8815 case X86::CMOV_RFP32:
8816 case X86::CMOV_RFP64:
8817 case X86::CMOV_RFP80:
8818 return EmitLoweredSelect(MI, BB);
8820 case X86::FP32_TO_INT16_IN_MEM:
8821 case X86::FP32_TO_INT32_IN_MEM:
8822 case X86::FP32_TO_INT64_IN_MEM:
8823 case X86::FP64_TO_INT16_IN_MEM:
8824 case X86::FP64_TO_INT32_IN_MEM:
8825 case X86::FP64_TO_INT64_IN_MEM:
8826 case X86::FP80_TO_INT16_IN_MEM:
8827 case X86::FP80_TO_INT32_IN_MEM:
8828 case X86::FP80_TO_INT64_IN_MEM: {
8829 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8830 DebugLoc DL = MI->getDebugLoc();
8832 // Change the floating point control register to use "round towards zero"
8833 // mode when truncating to an integer value.
8834 MachineFunction *F = BB->getParent();
8835 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
8836 addFrameReference(BuildMI(*BB, MI, DL,
8837 TII->get(X86::FNSTCW16m)), CWFrameIdx);
8839 // Load the old value of the high byte of the control word...
8841 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
8842 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
8845 // Set the high part to be round to zero...
8846 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
8849 // Reload the modified control word now...
8850 addFrameReference(BuildMI(*BB, MI, DL,
8851 TII->get(X86::FLDCW16m)), CWFrameIdx);
8853 // Restore the memory image of control word to original value
8854 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
8857 // Get the X86 opcode to use.
8859 switch (MI->getOpcode()) {
8860 default: llvm_unreachable("illegal opcode!");
8861 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
8862 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
8863 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
8864 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
8865 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
8866 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
8867 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
8868 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
8869 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
8873 MachineOperand &Op = MI->getOperand(0);
8875 AM.BaseType = X86AddressMode::RegBase;
8876 AM.Base.Reg = Op.getReg();
8878 AM.BaseType = X86AddressMode::FrameIndexBase;
8879 AM.Base.FrameIndex = Op.getIndex();
8881 Op = MI->getOperand(1);
8883 AM.Scale = Op.getImm();
8884 Op = MI->getOperand(2);
8886 AM.IndexReg = Op.getImm();
8887 Op = MI->getOperand(3);
8888 if (Op.isGlobal()) {
8889 AM.GV = Op.getGlobal();
8891 AM.Disp = Op.getImm();
8893 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
8894 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
8896 // Reload the original control word now.
8897 addFrameReference(BuildMI(*BB, MI, DL,
8898 TII->get(X86::FLDCW16m)), CWFrameIdx);
8900 MI->eraseFromParent(); // The pseudo instruction is gone now.
8903 // String/text processing lowering.
8904 case X86::PCMPISTRM128REG:
8905 return EmitPCMP(MI, BB, 3, false /* in-mem */);
8906 case X86::PCMPISTRM128MEM:
8907 return EmitPCMP(MI, BB, 3, true /* in-mem */);
8908 case X86::PCMPESTRM128REG:
8909 return EmitPCMP(MI, BB, 5, false /* in mem */);
8910 case X86::PCMPESTRM128MEM:
8911 return EmitPCMP(MI, BB, 5, true /* in mem */);
8914 case X86::ATOMAND32:
8915 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8916 X86::AND32ri, X86::MOV32rm,
8918 X86::NOT32r, X86::EAX,
8919 X86::GR32RegisterClass);
8921 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
8922 X86::OR32ri, X86::MOV32rm,
8924 X86::NOT32r, X86::EAX,
8925 X86::GR32RegisterClass);
8926 case X86::ATOMXOR32:
8927 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
8928 X86::XOR32ri, X86::MOV32rm,
8930 X86::NOT32r, X86::EAX,
8931 X86::GR32RegisterClass);
8932 case X86::ATOMNAND32:
8933 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8934 X86::AND32ri, X86::MOV32rm,
8936 X86::NOT32r, X86::EAX,
8937 X86::GR32RegisterClass, true);
8938 case X86::ATOMMIN32:
8939 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
8940 case X86::ATOMMAX32:
8941 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
8942 case X86::ATOMUMIN32:
8943 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
8944 case X86::ATOMUMAX32:
8945 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
8947 case X86::ATOMAND16:
8948 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8949 X86::AND16ri, X86::MOV16rm,
8951 X86::NOT16r, X86::AX,
8952 X86::GR16RegisterClass);
8954 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
8955 X86::OR16ri, X86::MOV16rm,
8957 X86::NOT16r, X86::AX,
8958 X86::GR16RegisterClass);
8959 case X86::ATOMXOR16:
8960 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
8961 X86::XOR16ri, X86::MOV16rm,
8963 X86::NOT16r, X86::AX,
8964 X86::GR16RegisterClass);
8965 case X86::ATOMNAND16:
8966 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8967 X86::AND16ri, X86::MOV16rm,
8969 X86::NOT16r, X86::AX,
8970 X86::GR16RegisterClass, true);
8971 case X86::ATOMMIN16:
8972 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
8973 case X86::ATOMMAX16:
8974 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
8975 case X86::ATOMUMIN16:
8976 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
8977 case X86::ATOMUMAX16:
8978 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
8981 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8982 X86::AND8ri, X86::MOV8rm,
8984 X86::NOT8r, X86::AL,
8985 X86::GR8RegisterClass);
8987 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
8988 X86::OR8ri, X86::MOV8rm,
8990 X86::NOT8r, X86::AL,
8991 X86::GR8RegisterClass);
8993 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
8994 X86::XOR8ri, X86::MOV8rm,
8996 X86::NOT8r, X86::AL,
8997 X86::GR8RegisterClass);
8998 case X86::ATOMNAND8:
8999 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
9000 X86::AND8ri, X86::MOV8rm,
9002 X86::NOT8r, X86::AL,
9003 X86::GR8RegisterClass, true);
9004 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
9005 // This group is for 64-bit host.
9006 case X86::ATOMAND64:
9007 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
9008 X86::AND64ri32, X86::MOV64rm,
9010 X86::NOT64r, X86::RAX,
9011 X86::GR64RegisterClass);
9013 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
9014 X86::OR64ri32, X86::MOV64rm,
9016 X86::NOT64r, X86::RAX,
9017 X86::GR64RegisterClass);
9018 case X86::ATOMXOR64:
9019 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
9020 X86::XOR64ri32, X86::MOV64rm,
9022 X86::NOT64r, X86::RAX,
9023 X86::GR64RegisterClass);
9024 case X86::ATOMNAND64:
9025 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
9026 X86::AND64ri32, X86::MOV64rm,
9028 X86::NOT64r, X86::RAX,
9029 X86::GR64RegisterClass, true);
9030 case X86::ATOMMIN64:
9031 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
9032 case X86::ATOMMAX64:
9033 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
9034 case X86::ATOMUMIN64:
9035 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
9036 case X86::ATOMUMAX64:
9037 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
9039 // This group does 64-bit operations on a 32-bit host.
9040 case X86::ATOMAND6432:
9041 return EmitAtomicBit6432WithCustomInserter(MI, BB,
9042 X86::AND32rr, X86::AND32rr,
9043 X86::AND32ri, X86::AND32ri,
9045 case X86::ATOMOR6432:
9046 return EmitAtomicBit6432WithCustomInserter(MI, BB,
9047 X86::OR32rr, X86::OR32rr,
9048 X86::OR32ri, X86::OR32ri,
9050 case X86::ATOMXOR6432:
9051 return EmitAtomicBit6432WithCustomInserter(MI, BB,
9052 X86::XOR32rr, X86::XOR32rr,
9053 X86::XOR32ri, X86::XOR32ri,
9055 case X86::ATOMNAND6432:
9056 return EmitAtomicBit6432WithCustomInserter(MI, BB,
9057 X86::AND32rr, X86::AND32rr,
9058 X86::AND32ri, X86::AND32ri,
9060 case X86::ATOMADD6432:
9061 return EmitAtomicBit6432WithCustomInserter(MI, BB,
9062 X86::ADD32rr, X86::ADC32rr,
9063 X86::ADD32ri, X86::ADC32ri,
9065 case X86::ATOMSUB6432:
9066 return EmitAtomicBit6432WithCustomInserter(MI, BB,
9067 X86::SUB32rr, X86::SBB32rr,
9068 X86::SUB32ri, X86::SBB32ri,
9070 case X86::ATOMSWAP6432:
9071 return EmitAtomicBit6432WithCustomInserter(MI, BB,
9072 X86::MOV32rr, X86::MOV32rr,
9073 X86::MOV32ri, X86::MOV32ri,
9075 case X86::VASTART_SAVE_XMM_REGS:
9076 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
9080 //===----------------------------------------------------------------------===//
9081 // X86 Optimization Hooks
9082 //===----------------------------------------------------------------------===//
9084 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9088 const SelectionDAG &DAG,
9089 unsigned Depth) const {
9090 unsigned Opc = Op.getOpcode();
9091 assert((Opc >= ISD::BUILTIN_OP_END ||
9092 Opc == ISD::INTRINSIC_WO_CHAIN ||
9093 Opc == ISD::INTRINSIC_W_CHAIN ||
9094 Opc == ISD::INTRINSIC_VOID) &&
9095 "Should use MaskedValueIsZero if you don't know whether Op"
9096 " is a target node!");
9098 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
9110 // These nodes' second result is a boolean.
9111 if (Op.getResNo() == 0)
9115 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
9116 Mask.getBitWidth() - 1);
9121 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
9122 /// node is a GlobalAddress + offset.
9123 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
9124 const GlobalValue* &GA,
9125 int64_t &Offset) const {
9126 if (N->getOpcode() == X86ISD::Wrapper) {
9127 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
9128 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
9129 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
9133 return TargetLowering::isGAPlusOffset(N, GA, Offset);
9136 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
9137 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
9138 /// if the load addresses are consecutive, non-overlapping, and in the right
9140 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
9141 const TargetLowering &TLI) {
9142 DebugLoc dl = N->getDebugLoc();
9143 EVT VT = N->getValueType(0);
9144 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9146 if (VT.getSizeInBits() != 128)
9149 SmallVector<SDValue, 16> Elts;
9150 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
9151 Elts.push_back(DAG.getShuffleScalarElt(SVN, i));
9153 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
9156 /// PerformShuffleCombine - Detect vector gather/scatter index generation
9157 /// and convert it from being a bunch of shuffles and extracts to a simple
9158 /// store and scalar loads to extract the elements.
9159 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
9160 const TargetLowering &TLI) {
9161 SDValue InputVector = N->getOperand(0);
9163 // Only operate on vectors of 4 elements, where the alternative shuffling
9164 // gets to be more expensive.
9165 if (InputVector.getValueType() != MVT::v4i32)
9168 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
9169 // single use which is a sign-extend or zero-extend, and all elements are
9171 SmallVector<SDNode *, 4> Uses;
9172 unsigned ExtractedElements = 0;
9173 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
9174 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
9175 if (UI.getUse().getResNo() != InputVector.getResNo())
9178 SDNode *Extract = *UI;
9179 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9182 if (Extract->getValueType(0) != MVT::i32)
9184 if (!Extract->hasOneUse())
9186 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
9187 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
9189 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
9192 // Record which element was extracted.
9193 ExtractedElements |=
9194 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
9196 Uses.push_back(Extract);
9199 // If not all the elements were used, this may not be worthwhile.
9200 if (ExtractedElements != 15)
9203 // Ok, we've now decided to do the transformation.
9204 DebugLoc dl = InputVector.getDebugLoc();
9206 // Store the value to a temporary stack slot.
9207 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
9208 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr, NULL,
9209 0, false, false, 0);
9211 // Replace each use (extract) with a load of the appropriate element.
9212 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
9213 UE = Uses.end(); UI != UE; ++UI) {
9214 SDNode *Extract = *UI;
9216 // Compute the element's address.
9217 SDValue Idx = Extract->getOperand(1);
9219 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
9220 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
9221 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
9223 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(),
9224 OffsetVal, StackPtr);
9227 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
9228 ScalarAddr, NULL, 0, false, false, 0);
9230 // Replace the exact with the load.
9231 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
9234 // The replacement was made in place; don't return anything.
9238 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
9239 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
9240 const X86Subtarget *Subtarget) {
9241 DebugLoc DL = N->getDebugLoc();
9242 SDValue Cond = N->getOperand(0);
9243 // Get the LHS/RHS of the select.
9244 SDValue LHS = N->getOperand(1);
9245 SDValue RHS = N->getOperand(2);
9247 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
9248 // instructions match the semantics of the common C idiom x<y?x:y but not
9249 // x<=y?x:y, because of how they handle negative zero (which can be
9250 // ignored in unsafe-math mode).
9251 if (Subtarget->hasSSE2() &&
9252 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
9253 Cond.getOpcode() == ISD::SETCC) {
9254 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
9256 unsigned Opcode = 0;
9257 // Check for x CC y ? x : y.
9258 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
9259 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
9263 // Converting this to a min would handle NaNs incorrectly, and swapping
9264 // the operands would cause it to handle comparisons between positive
9265 // and negative zero incorrectly.
9266 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
9267 if (!UnsafeFPMath &&
9268 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9270 std::swap(LHS, RHS);
9272 Opcode = X86ISD::FMIN;
9275 // Converting this to a min would handle comparisons between positive
9276 // and negative zero incorrectly.
9277 if (!UnsafeFPMath &&
9278 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
9280 Opcode = X86ISD::FMIN;
9283 // Converting this to a min would handle both negative zeros and NaNs
9284 // incorrectly, but we can swap the operands to fix both.
9285 std::swap(LHS, RHS);
9289 Opcode = X86ISD::FMIN;
9293 // Converting this to a max would handle comparisons between positive
9294 // and negative zero incorrectly.
9295 if (!UnsafeFPMath &&
9296 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
9298 Opcode = X86ISD::FMAX;
9301 // Converting this to a max would handle NaNs incorrectly, and swapping
9302 // the operands would cause it to handle comparisons between positive
9303 // and negative zero incorrectly.
9304 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
9305 if (!UnsafeFPMath &&
9306 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9308 std::swap(LHS, RHS);
9310 Opcode = X86ISD::FMAX;
9313 // Converting this to a max would handle both negative zeros and NaNs
9314 // incorrectly, but we can swap the operands to fix both.
9315 std::swap(LHS, RHS);
9319 Opcode = X86ISD::FMAX;
9322 // Check for x CC y ? y : x -- a min/max with reversed arms.
9323 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
9324 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
9328 // Converting this to a min would handle comparisons between positive
9329 // and negative zero incorrectly, and swapping the operands would
9330 // cause it to handle NaNs incorrectly.
9331 if (!UnsafeFPMath &&
9332 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
9333 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
9335 std::swap(LHS, RHS);
9337 Opcode = X86ISD::FMIN;
9340 // Converting this to a min would handle NaNs incorrectly.
9341 if (!UnsafeFPMath &&
9342 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9344 Opcode = X86ISD::FMIN;
9347 // Converting this to a min would handle both negative zeros and NaNs
9348 // incorrectly, but we can swap the operands to fix both.
9349 std::swap(LHS, RHS);
9353 Opcode = X86ISD::FMIN;
9357 // Converting this to a max would handle NaNs incorrectly.
9358 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
9360 Opcode = X86ISD::FMAX;
9363 // Converting this to a max would handle comparisons between positive
9364 // and negative zero incorrectly, and swapping the operands would
9365 // cause it to handle NaNs incorrectly.
9366 if (!UnsafeFPMath &&
9367 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
9368 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
9370 std::swap(LHS, RHS);
9372 Opcode = X86ISD::FMAX;
9375 // Converting this to a max would handle both negative zeros and NaNs
9376 // incorrectly, but we can swap the operands to fix both.
9377 std::swap(LHS, RHS);
9381 Opcode = X86ISD::FMAX;
9387 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
9390 // If this is a select between two integer constants, try to do some
9392 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
9393 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
9394 // Don't do this for crazy integer types.
9395 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
9396 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
9397 // so that TrueC (the true value) is larger than FalseC.
9398 bool NeedsCondInvert = false;
9400 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
9401 // Efficiently invertible.
9402 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
9403 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
9404 isa<ConstantSDNode>(Cond.getOperand(1))))) {
9405 NeedsCondInvert = true;
9406 std::swap(TrueC, FalseC);
9409 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
9410 if (FalseC->getAPIntValue() == 0 &&
9411 TrueC->getAPIntValue().isPowerOf2()) {
9412 if (NeedsCondInvert) // Invert the condition if needed.
9413 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9414 DAG.getConstant(1, Cond.getValueType()));
9416 // Zero extend the condition if needed.
9417 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
9419 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9420 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
9421 DAG.getConstant(ShAmt, MVT::i8));
9424 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
9425 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9426 if (NeedsCondInvert) // Invert the condition if needed.
9427 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9428 DAG.getConstant(1, Cond.getValueType()));
9430 // Zero extend the condition if needed.
9431 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9432 FalseC->getValueType(0), Cond);
9433 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9434 SDValue(FalseC, 0));
9437 // Optimize cases that will turn into an LEA instruction. This requires
9438 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9439 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9440 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9441 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9443 bool isFastMultiplier = false;
9445 switch ((unsigned char)Diff) {
9447 case 1: // result = add base, cond
9448 case 2: // result = lea base( , cond*2)
9449 case 3: // result = lea base(cond, cond*2)
9450 case 4: // result = lea base( , cond*4)
9451 case 5: // result = lea base(cond, cond*4)
9452 case 8: // result = lea base( , cond*8)
9453 case 9: // result = lea base(cond, cond*8)
9454 isFastMultiplier = true;
9459 if (isFastMultiplier) {
9460 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9461 if (NeedsCondInvert) // Invert the condition if needed.
9462 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9463 DAG.getConstant(1, Cond.getValueType()));
9465 // Zero extend the condition if needed.
9466 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9468 // Scale the condition by the difference.
9470 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9471 DAG.getConstant(Diff, Cond.getValueType()));
9473 // Add the base if non-zero.
9474 if (FalseC->getAPIntValue() != 0)
9475 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9476 SDValue(FalseC, 0));
9486 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
9487 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
9488 TargetLowering::DAGCombinerInfo &DCI) {
9489 DebugLoc DL = N->getDebugLoc();
9491 // If the flag operand isn't dead, don't touch this CMOV.
9492 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
9495 // If this is a select between two integer constants, try to do some
9496 // optimizations. Note that the operands are ordered the opposite of SELECT
9498 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
9499 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9500 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
9501 // larger than FalseC (the false value).
9502 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
9504 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
9505 CC = X86::GetOppositeBranchCondition(CC);
9506 std::swap(TrueC, FalseC);
9509 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
9510 // This is efficient for any integer data type (including i8/i16) and
9512 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
9513 SDValue Cond = N->getOperand(3);
9514 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9515 DAG.getConstant(CC, MVT::i8), Cond);
9517 // Zero extend the condition if needed.
9518 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
9520 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9521 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
9522 DAG.getConstant(ShAmt, MVT::i8));
9523 if (N->getNumValues() == 2) // Dead flag value?
9524 return DCI.CombineTo(N, Cond, SDValue());
9528 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
9529 // for any integer data type, including i8/i16.
9530 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9531 SDValue Cond = N->getOperand(3);
9532 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9533 DAG.getConstant(CC, MVT::i8), Cond);
9535 // Zero extend the condition if needed.
9536 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9537 FalseC->getValueType(0), Cond);
9538 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9539 SDValue(FalseC, 0));
9541 if (N->getNumValues() == 2) // Dead flag value?
9542 return DCI.CombineTo(N, Cond, SDValue());
9546 // Optimize cases that will turn into an LEA instruction. This requires
9547 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9548 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9549 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9550 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9552 bool isFastMultiplier = false;
9554 switch ((unsigned char)Diff) {
9556 case 1: // result = add base, cond
9557 case 2: // result = lea base( , cond*2)
9558 case 3: // result = lea base(cond, cond*2)
9559 case 4: // result = lea base( , cond*4)
9560 case 5: // result = lea base(cond, cond*4)
9561 case 8: // result = lea base( , cond*8)
9562 case 9: // result = lea base(cond, cond*8)
9563 isFastMultiplier = true;
9568 if (isFastMultiplier) {
9569 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9570 SDValue Cond = N->getOperand(3);
9571 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9572 DAG.getConstant(CC, MVT::i8), Cond);
9573 // Zero extend the condition if needed.
9574 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9576 // Scale the condition by the difference.
9578 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9579 DAG.getConstant(Diff, Cond.getValueType()));
9581 // Add the base if non-zero.
9582 if (FalseC->getAPIntValue() != 0)
9583 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9584 SDValue(FalseC, 0));
9585 if (N->getNumValues() == 2) // Dead flag value?
9586 return DCI.CombineTo(N, Cond, SDValue());
9596 /// PerformMulCombine - Optimize a single multiply with constant into two
9597 /// in order to implement it with two cheaper instructions, e.g.
9598 /// LEA + SHL, LEA + LEA.
9599 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
9600 TargetLowering::DAGCombinerInfo &DCI) {
9601 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9604 EVT VT = N->getValueType(0);
9608 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9611 uint64_t MulAmt = C->getZExtValue();
9612 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
9615 uint64_t MulAmt1 = 0;
9616 uint64_t MulAmt2 = 0;
9617 if ((MulAmt % 9) == 0) {
9619 MulAmt2 = MulAmt / 9;
9620 } else if ((MulAmt % 5) == 0) {
9622 MulAmt2 = MulAmt / 5;
9623 } else if ((MulAmt % 3) == 0) {
9625 MulAmt2 = MulAmt / 3;
9628 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
9629 DebugLoc DL = N->getDebugLoc();
9631 if (isPowerOf2_64(MulAmt2) &&
9632 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
9633 // If second multiplifer is pow2, issue it first. We want the multiply by
9634 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
9636 std::swap(MulAmt1, MulAmt2);
9639 if (isPowerOf2_64(MulAmt1))
9640 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
9641 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
9643 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
9644 DAG.getConstant(MulAmt1, VT));
9646 if (isPowerOf2_64(MulAmt2))
9647 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
9648 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
9650 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
9651 DAG.getConstant(MulAmt2, VT));
9653 // Do not add new nodes to DAG combiner worklist.
9654 DCI.CombineTo(N, NewMul, false);
9659 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
9660 SDValue N0 = N->getOperand(0);
9661 SDValue N1 = N->getOperand(1);
9662 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9663 EVT VT = N0.getValueType();
9665 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
9666 // since the result of setcc_c is all zero's or all ones.
9667 if (N1C && N0.getOpcode() == ISD::AND &&
9668 N0.getOperand(1).getOpcode() == ISD::Constant) {
9669 SDValue N00 = N0.getOperand(0);
9670 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
9671 ((N00.getOpcode() == ISD::ANY_EXTEND ||
9672 N00.getOpcode() == ISD::ZERO_EXTEND) &&
9673 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
9674 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
9675 APInt ShAmt = N1C->getAPIntValue();
9676 Mask = Mask.shl(ShAmt);
9678 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
9679 N00, DAG.getConstant(Mask, VT));
9686 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
9688 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
9689 const X86Subtarget *Subtarget) {
9690 EVT VT = N->getValueType(0);
9691 if (!VT.isVector() && VT.isInteger() &&
9692 N->getOpcode() == ISD::SHL)
9693 return PerformSHLCombine(N, DAG);
9695 // On X86 with SSE2 support, we can transform this to a vector shift if
9696 // all elements are shifted by the same amount. We can't do this in legalize
9697 // because the a constant vector is typically transformed to a constant pool
9698 // so we have no knowledge of the shift amount.
9699 if (!Subtarget->hasSSE2())
9702 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
9705 SDValue ShAmtOp = N->getOperand(1);
9706 EVT EltVT = VT.getVectorElementType();
9707 DebugLoc DL = N->getDebugLoc();
9708 SDValue BaseShAmt = SDValue();
9709 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
9710 unsigned NumElts = VT.getVectorNumElements();
9712 for (; i != NumElts; ++i) {
9713 SDValue Arg = ShAmtOp.getOperand(i);
9714 if (Arg.getOpcode() == ISD::UNDEF) continue;
9718 for (; i != NumElts; ++i) {
9719 SDValue Arg = ShAmtOp.getOperand(i);
9720 if (Arg.getOpcode() == ISD::UNDEF) continue;
9721 if (Arg != BaseShAmt) {
9725 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
9726 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
9727 SDValue InVec = ShAmtOp.getOperand(0);
9728 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
9729 unsigned NumElts = InVec.getValueType().getVectorNumElements();
9731 for (; i != NumElts; ++i) {
9732 SDValue Arg = InVec.getOperand(i);
9733 if (Arg.getOpcode() == ISD::UNDEF) continue;
9737 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
9738 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
9739 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
9740 if (C->getZExtValue() == SplatIdx)
9741 BaseShAmt = InVec.getOperand(1);
9744 if (BaseShAmt.getNode() == 0)
9745 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
9746 DAG.getIntPtrConstant(0));
9750 // The shift amount is an i32.
9751 if (EltVT.bitsGT(MVT::i32))
9752 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
9753 else if (EltVT.bitsLT(MVT::i32))
9754 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
9756 // The shift amount is identical so we can do a vector shift.
9757 SDValue ValOp = N->getOperand(0);
9758 switch (N->getOpcode()) {
9760 llvm_unreachable("Unknown shift opcode!");
9763 if (VT == MVT::v2i64)
9764 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9765 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9767 if (VT == MVT::v4i32)
9768 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9769 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9771 if (VT == MVT::v8i16)
9772 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9773 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9777 if (VT == MVT::v4i32)
9778 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9779 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9781 if (VT == MVT::v8i16)
9782 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9783 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9787 if (VT == MVT::v2i64)
9788 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9789 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9791 if (VT == MVT::v4i32)
9792 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9793 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9795 if (VT == MVT::v8i16)
9796 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9797 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9804 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
9805 TargetLowering::DAGCombinerInfo &DCI,
9806 const X86Subtarget *Subtarget) {
9807 if (DCI.isBeforeLegalizeOps())
9810 EVT VT = N->getValueType(0);
9811 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
9814 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
9815 SDValue N0 = N->getOperand(0);
9816 SDValue N1 = N->getOperand(1);
9817 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
9819 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
9821 if (!N0.hasOneUse() || !N1.hasOneUse())
9824 SDValue ShAmt0 = N0.getOperand(1);
9825 if (ShAmt0.getValueType() != MVT::i8)
9827 SDValue ShAmt1 = N1.getOperand(1);
9828 if (ShAmt1.getValueType() != MVT::i8)
9830 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
9831 ShAmt0 = ShAmt0.getOperand(0);
9832 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
9833 ShAmt1 = ShAmt1.getOperand(0);
9835 DebugLoc DL = N->getDebugLoc();
9836 unsigned Opc = X86ISD::SHLD;
9837 SDValue Op0 = N0.getOperand(0);
9838 SDValue Op1 = N1.getOperand(0);
9839 if (ShAmt0.getOpcode() == ISD::SUB) {
9841 std::swap(Op0, Op1);
9842 std::swap(ShAmt0, ShAmt1);
9845 unsigned Bits = VT.getSizeInBits();
9846 if (ShAmt1.getOpcode() == ISD::SUB) {
9847 SDValue Sum = ShAmt1.getOperand(0);
9848 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
9849 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
9850 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
9851 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
9852 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
9853 return DAG.getNode(Opc, DL, VT,
9855 DAG.getNode(ISD::TRUNCATE, DL,
9858 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
9859 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
9861 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
9862 return DAG.getNode(Opc, DL, VT,
9863 N0.getOperand(0), N1.getOperand(0),
9864 DAG.getNode(ISD::TRUNCATE, DL,
9871 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
9872 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
9873 const X86Subtarget *Subtarget) {
9874 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
9875 // the FP state in cases where an emms may be missing.
9876 // A preferable solution to the general problem is to figure out the right
9877 // places to insert EMMS. This qualifies as a quick hack.
9879 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
9880 StoreSDNode *St = cast<StoreSDNode>(N);
9881 EVT VT = St->getValue().getValueType();
9882 if (VT.getSizeInBits() != 64)
9885 const Function *F = DAG.getMachineFunction().getFunction();
9886 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
9887 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
9888 && Subtarget->hasSSE2();
9889 if ((VT.isVector() ||
9890 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
9891 isa<LoadSDNode>(St->getValue()) &&
9892 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
9893 St->getChain().hasOneUse() && !St->isVolatile()) {
9894 SDNode* LdVal = St->getValue().getNode();
9896 int TokenFactorIndex = -1;
9897 SmallVector<SDValue, 8> Ops;
9898 SDNode* ChainVal = St->getChain().getNode();
9899 // Must be a store of a load. We currently handle two cases: the load
9900 // is a direct child, and it's under an intervening TokenFactor. It is
9901 // possible to dig deeper under nested TokenFactors.
9902 if (ChainVal == LdVal)
9903 Ld = cast<LoadSDNode>(St->getChain());
9904 else if (St->getValue().hasOneUse() &&
9905 ChainVal->getOpcode() == ISD::TokenFactor) {
9906 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
9907 if (ChainVal->getOperand(i).getNode() == LdVal) {
9908 TokenFactorIndex = i;
9909 Ld = cast<LoadSDNode>(St->getValue());
9911 Ops.push_back(ChainVal->getOperand(i));
9915 if (!Ld || !ISD::isNormalLoad(Ld))
9918 // If this is not the MMX case, i.e. we are just turning i64 load/store
9919 // into f64 load/store, avoid the transformation if there are multiple
9920 // uses of the loaded value.
9921 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
9924 DebugLoc LdDL = Ld->getDebugLoc();
9925 DebugLoc StDL = N->getDebugLoc();
9926 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
9927 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
9929 if (Subtarget->is64Bit() || F64IsLegal) {
9930 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
9931 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
9932 Ld->getBasePtr(), Ld->getSrcValue(),
9933 Ld->getSrcValueOffset(), Ld->isVolatile(),
9934 Ld->isNonTemporal(), Ld->getAlignment());
9935 SDValue NewChain = NewLd.getValue(1);
9936 if (TokenFactorIndex != -1) {
9937 Ops.push_back(NewChain);
9938 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9941 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
9942 St->getSrcValue(), St->getSrcValueOffset(),
9943 St->isVolatile(), St->isNonTemporal(),
9944 St->getAlignment());
9947 // Otherwise, lower to two pairs of 32-bit loads / stores.
9948 SDValue LoAddr = Ld->getBasePtr();
9949 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
9950 DAG.getConstant(4, MVT::i32));
9952 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
9953 Ld->getSrcValue(), Ld->getSrcValueOffset(),
9954 Ld->isVolatile(), Ld->isNonTemporal(),
9955 Ld->getAlignment());
9956 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
9957 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
9958 Ld->isVolatile(), Ld->isNonTemporal(),
9959 MinAlign(Ld->getAlignment(), 4));
9961 SDValue NewChain = LoLd.getValue(1);
9962 if (TokenFactorIndex != -1) {
9963 Ops.push_back(LoLd);
9964 Ops.push_back(HiLd);
9965 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9969 LoAddr = St->getBasePtr();
9970 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
9971 DAG.getConstant(4, MVT::i32));
9973 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
9974 St->getSrcValue(), St->getSrcValueOffset(),
9975 St->isVolatile(), St->isNonTemporal(),
9976 St->getAlignment());
9977 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
9979 St->getSrcValueOffset() + 4,
9981 St->isNonTemporal(),
9982 MinAlign(St->getAlignment(), 4));
9983 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
9988 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
9989 /// X86ISD::FXOR nodes.
9990 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
9991 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
9992 // F[X]OR(0.0, x) -> x
9993 // F[X]OR(x, 0.0) -> x
9994 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9995 if (C->getValueAPF().isPosZero())
9996 return N->getOperand(1);
9997 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9998 if (C->getValueAPF().isPosZero())
9999 return N->getOperand(0);
10003 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
10004 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
10005 // FAND(0.0, x) -> 0.0
10006 // FAND(x, 0.0) -> 0.0
10007 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
10008 if (C->getValueAPF().isPosZero())
10009 return N->getOperand(0);
10010 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
10011 if (C->getValueAPF().isPosZero())
10012 return N->getOperand(1);
10016 static SDValue PerformBTCombine(SDNode *N,
10018 TargetLowering::DAGCombinerInfo &DCI) {
10019 // BT ignores high bits in the bit index operand.
10020 SDValue Op1 = N->getOperand(1);
10021 if (Op1.hasOneUse()) {
10022 unsigned BitWidth = Op1.getValueSizeInBits();
10023 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
10024 APInt KnownZero, KnownOne;
10025 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
10026 !DCI.isBeforeLegalizeOps());
10027 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10028 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
10029 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
10030 DCI.CommitTargetLoweringOpt(TLO);
10035 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
10036 SDValue Op = N->getOperand(0);
10037 if (Op.getOpcode() == ISD::BIT_CONVERT)
10038 Op = Op.getOperand(0);
10039 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
10040 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
10041 VT.getVectorElementType().getSizeInBits() ==
10042 OpVT.getVectorElementType().getSizeInBits()) {
10043 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
10048 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
10049 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
10050 // (and (i32 x86isd::setcc_carry), 1)
10051 // This eliminates the zext. This transformation is necessary because
10052 // ISD::SETCC is always legalized to i8.
10053 DebugLoc dl = N->getDebugLoc();
10054 SDValue N0 = N->getOperand(0);
10055 EVT VT = N->getValueType(0);
10056 if (N0.getOpcode() == ISD::AND &&
10058 N0.getOperand(0).hasOneUse()) {
10059 SDValue N00 = N0.getOperand(0);
10060 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
10062 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
10063 if (!C || C->getZExtValue() != 1)
10065 return DAG.getNode(ISD::AND, dl, VT,
10066 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
10067 N00.getOperand(0), N00.getOperand(1)),
10068 DAG.getConstant(1, VT));
10074 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
10075 DAGCombinerInfo &DCI) const {
10076 SelectionDAG &DAG = DCI.DAG;
10077 switch (N->getOpcode()) {
10079 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
10080 case ISD::EXTRACT_VECTOR_ELT:
10081 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
10082 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
10083 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
10084 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
10087 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
10088 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
10089 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
10091 case X86ISD::FOR: return PerformFORCombine(N, DAG);
10092 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
10093 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
10094 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
10095 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
10101 /// isTypeDesirableForOp - Return true if the target has native support for
10102 /// the specified value type and it is 'desirable' to use the type for the
10103 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
10104 /// instruction encodings are longer and some i16 instructions are slow.
10105 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
10106 if (!isTypeLegal(VT))
10108 if (VT != MVT::i16)
10115 case ISD::SIGN_EXTEND:
10116 case ISD::ZERO_EXTEND:
10117 case ISD::ANY_EXTEND:
10130 static bool MayFoldLoad(SDValue Op) {
10131 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
10134 static bool MayFoldIntoStore(SDValue Op) {
10135 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
10138 /// IsDesirableToPromoteOp - This method query the target whether it is
10139 /// beneficial for dag combiner to promote the specified node. If true, it
10140 /// should return the desired promotion type by reference.
10141 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
10142 EVT VT = Op.getValueType();
10143 if (VT != MVT::i16)
10146 bool Promote = false;
10147 bool Commute = false;
10148 switch (Op.getOpcode()) {
10151 LoadSDNode *LD = cast<LoadSDNode>(Op);
10152 // If the non-extending load has a single use and it's not live out, then it
10153 // might be folded.
10154 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
10155 Op.hasOneUse()*/) {
10156 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10157 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
10158 // The only case where we'd want to promote LOAD (rather then it being
10159 // promoted as an operand is when it's only use is liveout.
10160 if (UI->getOpcode() != ISD::CopyToReg)
10167 case ISD::SIGN_EXTEND:
10168 case ISD::ZERO_EXTEND:
10169 case ISD::ANY_EXTEND:
10174 SDValue N0 = Op.getOperand(0);
10175 // Look out for (store (shl (load), x)).
10176 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
10189 SDValue N0 = Op.getOperand(0);
10190 SDValue N1 = Op.getOperand(1);
10191 if (!Commute && MayFoldLoad(N1))
10193 // Avoid disabling potential load folding opportunities.
10194 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
10196 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
10206 //===----------------------------------------------------------------------===//
10207 // X86 Inline Assembly Support
10208 //===----------------------------------------------------------------------===//
10210 static bool LowerToBSwap(CallInst *CI) {
10211 // FIXME: this should verify that we are targetting a 486 or better. If not,
10212 // we will turn this bswap into something that will be lowered to logical ops
10213 // instead of emitting the bswap asm. For now, we don't support 486 or lower
10214 // so don't worry about this.
10216 // Verify this is a simple bswap.
10217 if (CI->getNumArgOperands() != 1 ||
10218 CI->getType() != CI->getArgOperand(0)->getType() ||
10219 !CI->getType()->isIntegerTy())
10222 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10223 if (!Ty || Ty->getBitWidth() % 16 != 0)
10226 // Okay, we can do this xform, do so now.
10227 const Type *Tys[] = { Ty };
10228 Module *M = CI->getParent()->getParent()->getParent();
10229 Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
10231 Value *Op = CI->getArgOperand(0);
10232 Op = CallInst::Create(Int, Op, CI->getName(), CI);
10234 CI->replaceAllUsesWith(Op);
10235 CI->eraseFromParent();
10239 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
10240 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10241 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
10243 std::string AsmStr = IA->getAsmString();
10245 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
10246 SmallVector<StringRef, 4> AsmPieces;
10247 SplitString(AsmStr, AsmPieces, "\n"); // ; as separator?
10249 switch (AsmPieces.size()) {
10250 default: return false;
10252 AsmStr = AsmPieces[0];
10254 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
10257 if (AsmPieces.size() == 2 &&
10258 (AsmPieces[0] == "bswap" ||
10259 AsmPieces[0] == "bswapq" ||
10260 AsmPieces[0] == "bswapl") &&
10261 (AsmPieces[1] == "$0" ||
10262 AsmPieces[1] == "${0:q}")) {
10263 // No need to check constraints, nothing other than the equivalent of
10264 // "=r,0" would be valid here.
10265 return LowerToBSwap(CI);
10267 // rorw $$8, ${0:w} --> llvm.bswap.i16
10268 if (CI->getType()->isIntegerTy(16) &&
10269 AsmPieces.size() == 3 &&
10270 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
10271 AsmPieces[1] == "$$8," &&
10272 AsmPieces[2] == "${0:w}" &&
10273 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
10275 const std::string &Constraints = IA->getConstraintString();
10276 SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
10277 std::sort(AsmPieces.begin(), AsmPieces.end());
10278 if (AsmPieces.size() == 4 &&
10279 AsmPieces[0] == "~{cc}" &&
10280 AsmPieces[1] == "~{dirflag}" &&
10281 AsmPieces[2] == "~{flags}" &&
10282 AsmPieces[3] == "~{fpsr}") {
10283 return LowerToBSwap(CI);
10288 if (CI->getType()->isIntegerTy(64) &&
10289 Constraints.size() >= 2 &&
10290 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
10291 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
10292 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
10293 SmallVector<StringRef, 4> Words;
10294 SplitString(AsmPieces[0], Words, " \t");
10295 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
10297 SplitString(AsmPieces[1], Words, " \t");
10298 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
10300 SplitString(AsmPieces[2], Words, " \t,");
10301 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
10302 Words[2] == "%edx") {
10303 return LowerToBSwap(CI);
10315 /// getConstraintType - Given a constraint letter, return the type of
10316 /// constraint it is for this target.
10317 X86TargetLowering::ConstraintType
10318 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
10319 if (Constraint.size() == 1) {
10320 switch (Constraint[0]) {
10332 return C_RegisterClass;
10340 return TargetLowering::getConstraintType(Constraint);
10343 /// LowerXConstraint - try to replace an X constraint, which matches anything,
10344 /// with another that has more specific requirements based on the type of the
10345 /// corresponding operand.
10346 const char *X86TargetLowering::
10347 LowerXConstraint(EVT ConstraintVT) const {
10348 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
10349 // 'f' like normal targets.
10350 if (ConstraintVT.isFloatingPoint()) {
10351 if (Subtarget->hasSSE2())
10353 if (Subtarget->hasSSE1())
10357 return TargetLowering::LowerXConstraint(ConstraintVT);
10360 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10361 /// vector. If it is invalid, don't add anything to Ops.
10362 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10364 std::vector<SDValue>&Ops,
10365 SelectionDAG &DAG) const {
10366 SDValue Result(0, 0);
10368 switch (Constraint) {
10371 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10372 if (C->getZExtValue() <= 31) {
10373 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10379 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10380 if (C->getZExtValue() <= 63) {
10381 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10387 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10388 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
10389 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10395 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10396 if (C->getZExtValue() <= 255) {
10397 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10403 // 32-bit signed value
10404 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10405 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10406 C->getSExtValue())) {
10407 // Widen to 64 bits here to get it sign extended.
10408 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
10411 // FIXME gcc accepts some relocatable values here too, but only in certain
10412 // memory models; it's complicated.
10417 // 32-bit unsigned value
10418 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10419 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10420 C->getZExtValue())) {
10421 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10425 // FIXME gcc accepts some relocatable values here too, but only in certain
10426 // memory models; it's complicated.
10430 // Literal immediates are always ok.
10431 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
10432 // Widen to 64 bits here to get it sign extended.
10433 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
10437 // In any sort of PIC mode addresses need to be computed at runtime by
10438 // adding in a register or some sort of table lookup. These can't
10439 // be used as immediates.
10440 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
10443 // If we are in non-pic codegen mode, we allow the address of a global (with
10444 // an optional displacement) to be used with 'i'.
10445 GlobalAddressSDNode *GA = 0;
10446 int64_t Offset = 0;
10448 // Match either (GA), (GA+C), (GA+C1+C2), etc.
10450 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
10451 Offset += GA->getOffset();
10453 } else if (Op.getOpcode() == ISD::ADD) {
10454 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10455 Offset += C->getZExtValue();
10456 Op = Op.getOperand(0);
10459 } else if (Op.getOpcode() == ISD::SUB) {
10460 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10461 Offset += -C->getZExtValue();
10462 Op = Op.getOperand(0);
10467 // Otherwise, this isn't something we can handle, reject it.
10471 const GlobalValue *GV = GA->getGlobal();
10472 // If we require an extra load to get this address, as in PIC mode, we
10473 // can't accept it.
10474 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
10475 getTargetMachine())))
10478 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
10479 GA->getValueType(0), Offset);
10484 if (Result.getNode()) {
10485 Ops.push_back(Result);
10488 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10491 std::vector<unsigned> X86TargetLowering::
10492 getRegClassForInlineAsmConstraint(const std::string &Constraint,
10494 if (Constraint.size() == 1) {
10495 // FIXME: not handling fp-stack yet!
10496 switch (Constraint[0]) { // GCC X86 Constraint Letters
10497 default: break; // Unknown constraint letter
10498 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
10499 if (Subtarget->is64Bit()) {
10500 if (VT == MVT::i32)
10501 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
10502 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
10503 X86::R10D,X86::R11D,X86::R12D,
10504 X86::R13D,X86::R14D,X86::R15D,
10505 X86::EBP, X86::ESP, 0);
10506 else if (VT == MVT::i16)
10507 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
10508 X86::SI, X86::DI, X86::R8W,X86::R9W,
10509 X86::R10W,X86::R11W,X86::R12W,
10510 X86::R13W,X86::R14W,X86::R15W,
10511 X86::BP, X86::SP, 0);
10512 else if (VT == MVT::i8)
10513 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
10514 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
10515 X86::R10B,X86::R11B,X86::R12B,
10516 X86::R13B,X86::R14B,X86::R15B,
10517 X86::BPL, X86::SPL, 0);
10519 else if (VT == MVT::i64)
10520 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
10521 X86::RSI, X86::RDI, X86::R8, X86::R9,
10522 X86::R10, X86::R11, X86::R12,
10523 X86::R13, X86::R14, X86::R15,
10524 X86::RBP, X86::RSP, 0);
10528 // 32-bit fallthrough
10529 case 'Q': // Q_REGS
10530 if (VT == MVT::i32)
10531 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
10532 else if (VT == MVT::i16)
10533 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
10534 else if (VT == MVT::i8)
10535 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
10536 else if (VT == MVT::i64)
10537 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
10542 return std::vector<unsigned>();
10545 std::pair<unsigned, const TargetRegisterClass*>
10546 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10548 // First, see if this is a constraint that directly corresponds to an LLVM
10550 if (Constraint.size() == 1) {
10551 // GCC Constraint Letters
10552 switch (Constraint[0]) {
10554 case 'r': // GENERAL_REGS
10555 case 'l': // INDEX_REGS
10557 return std::make_pair(0U, X86::GR8RegisterClass);
10558 if (VT == MVT::i16)
10559 return std::make_pair(0U, X86::GR16RegisterClass);
10560 if (VT == MVT::i32 || !Subtarget->is64Bit())
10561 return std::make_pair(0U, X86::GR32RegisterClass);
10562 return std::make_pair(0U, X86::GR64RegisterClass);
10563 case 'R': // LEGACY_REGS
10565 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
10566 if (VT == MVT::i16)
10567 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
10568 if (VT == MVT::i32 || !Subtarget->is64Bit())
10569 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
10570 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
10571 case 'f': // FP Stack registers.
10572 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
10573 // value to the correct fpstack register class.
10574 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
10575 return std::make_pair(0U, X86::RFP32RegisterClass);
10576 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
10577 return std::make_pair(0U, X86::RFP64RegisterClass);
10578 return std::make_pair(0U, X86::RFP80RegisterClass);
10579 case 'y': // MMX_REGS if MMX allowed.
10580 if (!Subtarget->hasMMX()) break;
10581 return std::make_pair(0U, X86::VR64RegisterClass);
10582 case 'Y': // SSE_REGS if SSE2 allowed
10583 if (!Subtarget->hasSSE2()) break;
10585 case 'x': // SSE_REGS if SSE1 allowed
10586 if (!Subtarget->hasSSE1()) break;
10588 switch (VT.getSimpleVT().SimpleTy) {
10590 // Scalar SSE types.
10593 return std::make_pair(0U, X86::FR32RegisterClass);
10596 return std::make_pair(0U, X86::FR64RegisterClass);
10604 return std::make_pair(0U, X86::VR128RegisterClass);
10610 // Use the default implementation in TargetLowering to convert the register
10611 // constraint into a member of a register class.
10612 std::pair<unsigned, const TargetRegisterClass*> Res;
10613 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10615 // Not found as a standard register?
10616 if (Res.second == 0) {
10617 // Map st(0) -> st(7) -> ST0
10618 if (Constraint.size() == 7 && Constraint[0] == '{' &&
10619 tolower(Constraint[1]) == 's' &&
10620 tolower(Constraint[2]) == 't' &&
10621 Constraint[3] == '(' &&
10622 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
10623 Constraint[5] == ')' &&
10624 Constraint[6] == '}') {
10626 Res.first = X86::ST0+Constraint[4]-'0';
10627 Res.second = X86::RFP80RegisterClass;
10631 // GCC allows "st(0)" to be called just plain "st".
10632 if (StringRef("{st}").equals_lower(Constraint)) {
10633 Res.first = X86::ST0;
10634 Res.second = X86::RFP80RegisterClass;
10639 if (StringRef("{flags}").equals_lower(Constraint)) {
10640 Res.first = X86::EFLAGS;
10641 Res.second = X86::CCRRegisterClass;
10645 // 'A' means EAX + EDX.
10646 if (Constraint == "A") {
10647 Res.first = X86::EAX;
10648 Res.second = X86::GR32_ADRegisterClass;
10654 // Otherwise, check to see if this is a register class of the wrong value
10655 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
10656 // turn into {ax},{dx}.
10657 if (Res.second->hasType(VT))
10658 return Res; // Correct type already, nothing to do.
10660 // All of the single-register GCC register classes map their values onto
10661 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
10662 // really want an 8-bit or 32-bit register, map to the appropriate register
10663 // class and return the appropriate register.
10664 if (Res.second == X86::GR16RegisterClass) {
10665 if (VT == MVT::i8) {
10666 unsigned DestReg = 0;
10667 switch (Res.first) {
10669 case X86::AX: DestReg = X86::AL; break;
10670 case X86::DX: DestReg = X86::DL; break;
10671 case X86::CX: DestReg = X86::CL; break;
10672 case X86::BX: DestReg = X86::BL; break;
10675 Res.first = DestReg;
10676 Res.second = X86::GR8RegisterClass;
10678 } else if (VT == MVT::i32) {
10679 unsigned DestReg = 0;
10680 switch (Res.first) {
10682 case X86::AX: DestReg = X86::EAX; break;
10683 case X86::DX: DestReg = X86::EDX; break;
10684 case X86::CX: DestReg = X86::ECX; break;
10685 case X86::BX: DestReg = X86::EBX; break;
10686 case X86::SI: DestReg = X86::ESI; break;
10687 case X86::DI: DestReg = X86::EDI; break;
10688 case X86::BP: DestReg = X86::EBP; break;
10689 case X86::SP: DestReg = X86::ESP; break;
10692 Res.first = DestReg;
10693 Res.second = X86::GR32RegisterClass;
10695 } else if (VT == MVT::i64) {
10696 unsigned DestReg = 0;
10697 switch (Res.first) {
10699 case X86::AX: DestReg = X86::RAX; break;
10700 case X86::DX: DestReg = X86::RDX; break;
10701 case X86::CX: DestReg = X86::RCX; break;
10702 case X86::BX: DestReg = X86::RBX; break;
10703 case X86::SI: DestReg = X86::RSI; break;
10704 case X86::DI: DestReg = X86::RDI; break;
10705 case X86::BP: DestReg = X86::RBP; break;
10706 case X86::SP: DestReg = X86::RSP; break;
10709 Res.first = DestReg;
10710 Res.second = X86::GR64RegisterClass;
10713 } else if (Res.second == X86::FR32RegisterClass ||
10714 Res.second == X86::FR64RegisterClass ||
10715 Res.second == X86::VR128RegisterClass) {
10716 // Handle references to XMM physical registers that got mapped into the
10717 // wrong class. This can happen with constraints like {xmm0} where the
10718 // target independent register mapper will just pick the first match it can
10719 // find, ignoring the required type.
10720 if (VT == MVT::f32)
10721 Res.second = X86::FR32RegisterClass;
10722 else if (VT == MVT::f64)
10723 Res.second = X86::FR64RegisterClass;
10724 else if (X86::VR128RegisterClass->hasType(VT))
10725 Res.second = X86::VR128RegisterClass;