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 //===----------------------------------------------------------------------===//
16 #include "X86InstrBuilder.h"
17 #include "X86ISelLowering.h"
18 #include "X86TargetMachine.h"
19 #include "X86TargetObjectFile.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/GlobalAlias.h"
24 #include "llvm/GlobalVariable.h"
25 #include "llvm/Function.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Intrinsics.h"
28 #include "llvm/LLVMContext.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/PseudoSourceValue.h"
36 #include "llvm/MC/MCContext.h"
37 #include "llvm/MC/MCExpr.h"
38 #include "llvm/MC/MCSymbol.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/ADT/BitVector.h"
41 #include "llvm/ADT/SmallSet.h"
42 #include "llvm/ADT/StringExtras.h"
43 #include "llvm/ADT/VectorExtras.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/MathExtras.h"
48 #include "llvm/Support/raw_ostream.h"
52 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
54 // Disable16Bit - 16-bit operations typically have a larger encoding than
55 // corresponding 32-bit instructions, and 16-bit code is slow on some
56 // processors. This is an experimental flag to disable 16-bit operations
57 // (which forces them to be Legalized to 32-bit operations).
59 Disable16Bit("disable-16bit", cl::Hidden,
60 cl::desc("Disable use of 16-bit instructions"));
62 // Forward declarations.
63 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
66 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
67 switch (TM.getSubtarget<X86Subtarget>().TargetType) {
68 default: llvm_unreachable("unknown subtarget type");
69 case X86Subtarget::isDarwin:
70 if (TM.getSubtarget<X86Subtarget>().is64Bit())
71 return new X8664_MachoTargetObjectFile();
72 return new X8632_MachoTargetObjectFile();
73 case X86Subtarget::isELF:
74 return new TargetLoweringObjectFileELF();
75 case X86Subtarget::isMingw:
76 case X86Subtarget::isCygwin:
77 case X86Subtarget::isWindows:
78 return new TargetLoweringObjectFileCOFF();
83 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
84 : TargetLowering(TM, createTLOF(TM)) {
85 Subtarget = &TM.getSubtarget<X86Subtarget>();
86 X86ScalarSSEf64 = Subtarget->hasSSE2();
87 X86ScalarSSEf32 = Subtarget->hasSSE1();
88 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
90 RegInfo = TM.getRegisterInfo();
93 // Set up the TargetLowering object.
95 // X86 is weird, it always uses i8 for shift amounts and setcc results.
96 setShiftAmountType(MVT::i8);
97 setBooleanContents(ZeroOrOneBooleanContent);
98 setSchedulingPreference(SchedulingForRegPressure);
99 setStackPointerRegisterToSaveRestore(X86StackPtr);
101 if (Subtarget->isTargetDarwin()) {
102 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
103 setUseUnderscoreSetJmp(false);
104 setUseUnderscoreLongJmp(false);
105 } else if (Subtarget->isTargetMingw()) {
106 // MS runtime is weird: it exports _setjmp, but longjmp!
107 setUseUnderscoreSetJmp(true);
108 setUseUnderscoreLongJmp(false);
110 setUseUnderscoreSetJmp(true);
111 setUseUnderscoreLongJmp(true);
114 // Set up the register classes.
115 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
117 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
118 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
119 if (Subtarget->is64Bit())
120 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
122 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
124 // We don't accept any truncstore of integer registers.
125 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
127 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
128 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
130 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
131 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
132 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
134 // SETOEQ and SETUNE require checking two conditions.
135 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
136 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
137 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
138 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
139 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
140 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
142 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
144 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
145 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
146 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
148 if (Subtarget->is64Bit()) {
149 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
150 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
151 } else if (!UseSoftFloat) {
152 if (X86ScalarSSEf64) {
153 // We have an impenetrably clever algorithm for ui64->double only.
154 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
156 // We have an algorithm for SSE2, and we turn this into a 64-bit
157 // FILD for other targets.
158 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
161 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
163 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
164 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
167 // SSE has no i16 to fp conversion, only i32
168 if (X86ScalarSSEf32) {
169 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
170 // f32 and f64 cases are Legal, f80 case is not
171 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
173 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
174 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
177 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
178 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
181 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
182 // are Legal, f80 is custom lowered.
183 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
184 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
186 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
188 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
189 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
191 if (X86ScalarSSEf32) {
192 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
193 // f32 and f64 cases are Legal, f80 case is not
194 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
196 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
197 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
200 // Handle FP_TO_UINT by promoting the destination to a larger signed
202 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
203 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
204 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
206 if (Subtarget->is64Bit()) {
207 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
208 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
209 } else if (!UseSoftFloat) {
210 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
211 // Expand FP_TO_UINT into a select.
212 // FIXME: We would like to use a Custom expander here eventually to do
213 // the optimal thing for SSE vs. the default expansion in the legalizer.
214 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
216 // With SSE3 we can use fisttpll to convert to a signed i64; without
217 // SSE, we're stuck with a fistpll.
218 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
221 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
222 if (!X86ScalarSSEf64) {
223 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
224 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
227 // Scalar integer divide and remainder are lowered to use operations that
228 // produce two results, to match the available instructions. This exposes
229 // the two-result form to trivial CSE, which is able to combine x/y and x%y
230 // into a single instruction.
232 // Scalar integer multiply-high is also lowered to use two-result
233 // operations, to match the available instructions. However, plain multiply
234 // (low) operations are left as Legal, as there are single-result
235 // instructions for this in x86. Using the two-result multiply instructions
236 // when both high and low results are needed must be arranged by dagcombine.
237 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
238 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
239 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
240 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
241 setOperationAction(ISD::SREM , MVT::i8 , Expand);
242 setOperationAction(ISD::UREM , MVT::i8 , Expand);
243 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
244 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
245 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
246 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
247 setOperationAction(ISD::SREM , MVT::i16 , Expand);
248 setOperationAction(ISD::UREM , MVT::i16 , Expand);
249 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
250 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
251 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
252 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
253 setOperationAction(ISD::SREM , MVT::i32 , Expand);
254 setOperationAction(ISD::UREM , MVT::i32 , Expand);
255 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
256 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
257 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
258 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
259 setOperationAction(ISD::SREM , MVT::i64 , Expand);
260 setOperationAction(ISD::UREM , MVT::i64 , Expand);
262 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
263 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
264 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
265 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
266 if (Subtarget->is64Bit())
267 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
268 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
269 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
270 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
271 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
272 setOperationAction(ISD::FREM , MVT::f32 , Expand);
273 setOperationAction(ISD::FREM , MVT::f64 , Expand);
274 setOperationAction(ISD::FREM , MVT::f80 , Expand);
275 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
277 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
278 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
279 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
280 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
282 setOperationAction(ISD::CTTZ , MVT::i16 , Expand);
283 setOperationAction(ISD::CTLZ , MVT::i16 , Expand);
285 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
286 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
288 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
289 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
290 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
291 if (Subtarget->is64Bit()) {
292 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
293 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
294 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
297 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
298 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
300 // These should be promoted to a larger select which is supported.
301 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
302 // X86 wants to expand cmov itself.
303 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
305 setOperationAction(ISD::SELECT , MVT::i16 , Expand);
307 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
308 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
309 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
310 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
311 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
312 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
314 setOperationAction(ISD::SETCC , MVT::i16 , Expand);
316 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
317 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
318 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
319 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
320 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
321 if (Subtarget->is64Bit()) {
322 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
323 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
325 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
328 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
329 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
330 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
331 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
332 if (Subtarget->is64Bit())
333 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
334 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
335 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
336 if (Subtarget->is64Bit()) {
337 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
338 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
339 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
340 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
341 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
343 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
344 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
345 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
346 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
347 if (Subtarget->is64Bit()) {
348 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
349 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
350 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
353 if (Subtarget->hasSSE1())
354 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
356 if (!Subtarget->hasSSE2())
357 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
359 // Expand certain atomics
360 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
361 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
362 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
363 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
365 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
366 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
367 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
368 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
370 if (!Subtarget->is64Bit()) {
371 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
372 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
373 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
374 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
375 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
376 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
377 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
380 // FIXME - use subtarget debug flags
381 if (!Subtarget->isTargetDarwin() &&
382 !Subtarget->isTargetELF() &&
383 !Subtarget->isTargetCygMing()) {
384 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
387 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
388 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
389 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
390 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
391 if (Subtarget->is64Bit()) {
392 setExceptionPointerRegister(X86::RAX);
393 setExceptionSelectorRegister(X86::RDX);
395 setExceptionPointerRegister(X86::EAX);
396 setExceptionSelectorRegister(X86::EDX);
398 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
399 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
401 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
403 setOperationAction(ISD::TRAP, MVT::Other, Legal);
405 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
406 setOperationAction(ISD::VASTART , MVT::Other, Custom);
407 setOperationAction(ISD::VAEND , MVT::Other, Expand);
408 if (Subtarget->is64Bit()) {
409 setOperationAction(ISD::VAARG , MVT::Other, Custom);
410 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
412 setOperationAction(ISD::VAARG , MVT::Other, Expand);
413 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
416 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
417 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
418 if (Subtarget->is64Bit())
419 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
420 if (Subtarget->isTargetCygMing())
421 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
423 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
425 if (!UseSoftFloat && X86ScalarSSEf64) {
426 // f32 and f64 use SSE.
427 // Set up the FP register classes.
428 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
429 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
431 // Use ANDPD to simulate FABS.
432 setOperationAction(ISD::FABS , MVT::f64, Custom);
433 setOperationAction(ISD::FABS , MVT::f32, Custom);
435 // Use XORP to simulate FNEG.
436 setOperationAction(ISD::FNEG , MVT::f64, Custom);
437 setOperationAction(ISD::FNEG , MVT::f32, Custom);
439 // Use ANDPD and ORPD to simulate FCOPYSIGN.
440 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
441 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
443 // We don't support sin/cos/fmod
444 setOperationAction(ISD::FSIN , MVT::f64, Expand);
445 setOperationAction(ISD::FCOS , MVT::f64, Expand);
446 setOperationAction(ISD::FSIN , MVT::f32, Expand);
447 setOperationAction(ISD::FCOS , MVT::f32, Expand);
449 // Expand FP immediates into loads from the stack, except for the special
451 addLegalFPImmediate(APFloat(+0.0)); // xorpd
452 addLegalFPImmediate(APFloat(+0.0f)); // xorps
453 } else if (!UseSoftFloat && X86ScalarSSEf32) {
454 // Use SSE for f32, x87 for f64.
455 // Set up the FP register classes.
456 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
457 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
459 // Use ANDPS to simulate FABS.
460 setOperationAction(ISD::FABS , MVT::f32, Custom);
462 // Use XORP to simulate FNEG.
463 setOperationAction(ISD::FNEG , MVT::f32, Custom);
465 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
467 // Use ANDPS and ORPS to simulate FCOPYSIGN.
468 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
469 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
471 // We don't support sin/cos/fmod
472 setOperationAction(ISD::FSIN , MVT::f32, Expand);
473 setOperationAction(ISD::FCOS , MVT::f32, Expand);
475 // Special cases we handle for FP constants.
476 addLegalFPImmediate(APFloat(+0.0f)); // xorps
477 addLegalFPImmediate(APFloat(+0.0)); // FLD0
478 addLegalFPImmediate(APFloat(+1.0)); // FLD1
479 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
480 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
483 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
484 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
486 } else if (!UseSoftFloat) {
487 // f32 and f64 in x87.
488 // Set up the FP register classes.
489 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
490 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
492 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
493 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
494 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
495 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
498 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
499 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
501 addLegalFPImmediate(APFloat(+0.0)); // FLD0
502 addLegalFPImmediate(APFloat(+1.0)); // FLD1
503 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
504 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
505 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
506 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
507 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
508 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
511 // Long double always uses X87.
513 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
514 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
515 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
518 APFloat TmpFlt(+0.0);
519 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
521 addLegalFPImmediate(TmpFlt); // FLD0
523 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
524 APFloat TmpFlt2(+1.0);
525 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
527 addLegalFPImmediate(TmpFlt2); // FLD1
528 TmpFlt2.changeSign();
529 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
533 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
534 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
538 // Always use a library call for pow.
539 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
540 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
541 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
543 setOperationAction(ISD::FLOG, MVT::f80, Expand);
544 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
545 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
546 setOperationAction(ISD::FEXP, MVT::f80, Expand);
547 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
549 // First set operation action for all vector types to either promote
550 // (for widening) or expand (for scalarization). Then we will selectively
551 // turn on ones that can be effectively codegen'd.
552 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
553 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
554 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
555 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
556 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
557 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
558 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
559 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
560 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
561 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
562 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
563 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
564 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
565 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
566 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
567 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
568 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
569 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
570 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
571 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
572 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
573 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
574 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
575 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
576 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
577 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
578 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
579 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
580 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
581 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
582 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
583 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
584 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
585 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
586 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
587 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
588 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
589 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
590 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
591 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
592 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
593 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
594 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
595 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
596 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
597 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
598 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
599 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
600 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
601 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
602 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
603 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
604 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
605 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
606 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
607 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
608 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
609 setTruncStoreAction((MVT::SimpleValueType)VT,
610 (MVT::SimpleValueType)InnerVT, Expand);
611 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
612 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
613 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
616 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
617 // with -msoft-float, disable use of MMX as well.
618 if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
619 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
620 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
621 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
622 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
623 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
625 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
626 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
627 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
628 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
630 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
631 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
632 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
633 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
635 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
636 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
638 setOperationAction(ISD::AND, MVT::v8i8, Promote);
639 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
640 setOperationAction(ISD::AND, MVT::v4i16, Promote);
641 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
642 setOperationAction(ISD::AND, MVT::v2i32, Promote);
643 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
644 setOperationAction(ISD::AND, MVT::v1i64, Legal);
646 setOperationAction(ISD::OR, MVT::v8i8, Promote);
647 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
648 setOperationAction(ISD::OR, MVT::v4i16, Promote);
649 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
650 setOperationAction(ISD::OR, MVT::v2i32, Promote);
651 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
652 setOperationAction(ISD::OR, MVT::v1i64, Legal);
654 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
655 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
656 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
657 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
658 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
659 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
660 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
662 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
663 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
664 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
665 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
666 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
667 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
668 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
669 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
670 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
672 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
673 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
674 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
675 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
676 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
678 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
679 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
680 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
681 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
683 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
684 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
685 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
686 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
688 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
690 setOperationAction(ISD::SELECT, MVT::v8i8, Promote);
691 setOperationAction(ISD::SELECT, MVT::v4i16, Promote);
692 setOperationAction(ISD::SELECT, MVT::v2i32, Promote);
693 setOperationAction(ISD::SELECT, MVT::v1i64, Custom);
694 setOperationAction(ISD::VSETCC, MVT::v8i8, Custom);
695 setOperationAction(ISD::VSETCC, MVT::v4i16, Custom);
696 setOperationAction(ISD::VSETCC, MVT::v2i32, 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 // FIXME: Do we need to handle scalar-to-vector here?
828 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
830 // i8 and i16 vectors are custom , because the source register and source
831 // source memory operand types are not the same width. f32 vectors are
832 // custom since the immediate controlling the insert encodes additional
834 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
835 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
836 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
837 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
839 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
840 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
841 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
842 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
844 if (Subtarget->is64Bit()) {
845 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
846 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
850 if (Subtarget->hasSSE42()) {
851 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
854 if (!UseSoftFloat && Subtarget->hasAVX()) {
855 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
856 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
857 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
858 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
860 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
861 setOperationAction(ISD::LOAD, MVT::v8i32, Legal);
862 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
863 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
864 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
865 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
866 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
867 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
868 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
869 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
870 //setOperationAction(ISD::BUILD_VECTOR, MVT::v8f32, Custom);
871 //setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Custom);
872 //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
873 //setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
874 //setOperationAction(ISD::VSETCC, MVT::v8f32, Custom);
876 // Operations to consider commented out -v16i16 v32i8
877 //setOperationAction(ISD::ADD, MVT::v16i16, Legal);
878 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
879 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
880 //setOperationAction(ISD::SUB, MVT::v32i8, Legal);
881 //setOperationAction(ISD::SUB, MVT::v16i16, Legal);
882 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
883 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
884 //setOperationAction(ISD::MUL, MVT::v16i16, Legal);
885 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
886 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
887 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
888 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
889 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
890 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
892 setOperationAction(ISD::VSETCC, MVT::v4f64, Custom);
893 // setOperationAction(ISD::VSETCC, MVT::v32i8, Custom);
894 // setOperationAction(ISD::VSETCC, MVT::v16i16, Custom);
895 setOperationAction(ISD::VSETCC, MVT::v8i32, Custom);
897 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v32i8, Custom);
898 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i16, Custom);
899 // setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i16, Custom);
900 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i32, Custom);
901 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8f32, Custom);
903 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
904 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i64, Custom);
905 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f64, Custom);
906 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i64, Custom);
907 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f64, Custom);
908 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
911 // Not sure we want to do this since there are no 256-bit integer
914 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
915 // This includes 256-bit vectors
916 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
917 EVT VT = (MVT::SimpleValueType)i;
919 // Do not attempt to custom lower non-power-of-2 vectors
920 if (!isPowerOf2_32(VT.getVectorNumElements()))
923 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
924 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
925 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
928 if (Subtarget->is64Bit()) {
929 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i64, Custom);
930 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
935 // Not sure we want to do this since there are no 256-bit integer
938 // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
939 // Including 256-bit vectors
940 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
941 EVT VT = (MVT::SimpleValueType)i;
943 if (!VT.is256BitVector()) {
946 setOperationAction(ISD::AND, VT, Promote);
947 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
948 setOperationAction(ISD::OR, VT, Promote);
949 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
950 setOperationAction(ISD::XOR, VT, Promote);
951 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
952 setOperationAction(ISD::LOAD, VT, Promote);
953 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
954 setOperationAction(ISD::SELECT, VT, Promote);
955 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
958 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
962 // We want to custom lower some of our intrinsics.
963 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
965 // Add/Sub/Mul with overflow operations are custom lowered.
966 setOperationAction(ISD::SADDO, MVT::i32, Custom);
967 setOperationAction(ISD::SADDO, MVT::i64, Custom);
968 setOperationAction(ISD::UADDO, MVT::i32, Custom);
969 setOperationAction(ISD::UADDO, MVT::i64, Custom);
970 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
971 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
972 setOperationAction(ISD::USUBO, MVT::i32, Custom);
973 setOperationAction(ISD::USUBO, MVT::i64, Custom);
974 setOperationAction(ISD::SMULO, MVT::i32, Custom);
975 setOperationAction(ISD::SMULO, MVT::i64, Custom);
977 if (!Subtarget->is64Bit()) {
978 // These libcalls are not available in 32-bit.
979 setLibcallName(RTLIB::SHL_I128, 0);
980 setLibcallName(RTLIB::SRL_I128, 0);
981 setLibcallName(RTLIB::SRA_I128, 0);
984 // We have target-specific dag combine patterns for the following nodes:
985 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
986 setTargetDAGCombine(ISD::BUILD_VECTOR);
987 setTargetDAGCombine(ISD::SELECT);
988 setTargetDAGCombine(ISD::SHL);
989 setTargetDAGCombine(ISD::SRA);
990 setTargetDAGCombine(ISD::SRL);
991 setTargetDAGCombine(ISD::OR);
992 setTargetDAGCombine(ISD::STORE);
993 setTargetDAGCombine(ISD::MEMBARRIER);
994 setTargetDAGCombine(ISD::ZERO_EXTEND);
995 if (Subtarget->is64Bit())
996 setTargetDAGCombine(ISD::MUL);
998 computeRegisterProperties();
1000 // Divide and reminder operations have no vector equivalent and can
1001 // trap. Do a custom widening for these operations in which we never
1002 // generate more divides/remainder than the original vector width.
1003 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
1004 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
1005 if (!isTypeLegal((MVT::SimpleValueType)VT)) {
1006 setOperationAction(ISD::SDIV, (MVT::SimpleValueType) VT, Custom);
1007 setOperationAction(ISD::UDIV, (MVT::SimpleValueType) VT, Custom);
1008 setOperationAction(ISD::SREM, (MVT::SimpleValueType) VT, Custom);
1009 setOperationAction(ISD::UREM, (MVT::SimpleValueType) VT, Custom);
1013 // FIXME: These should be based on subtarget info. Plus, the values should
1014 // be smaller when we are in optimizing for size mode.
1015 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1016 maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
1017 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
1018 setPrefLoopAlignment(16);
1019 benefitFromCodePlacementOpt = true;
1023 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1028 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1029 /// the desired ByVal argument alignment.
1030 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1033 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1034 if (VTy->getBitWidth() == 128)
1036 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1037 unsigned EltAlign = 0;
1038 getMaxByValAlign(ATy->getElementType(), EltAlign);
1039 if (EltAlign > MaxAlign)
1040 MaxAlign = EltAlign;
1041 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1042 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1043 unsigned EltAlign = 0;
1044 getMaxByValAlign(STy->getElementType(i), EltAlign);
1045 if (EltAlign > MaxAlign)
1046 MaxAlign = EltAlign;
1054 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1055 /// function arguments in the caller parameter area. For X86, aggregates
1056 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1057 /// are at 4-byte boundaries.
1058 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1059 if (Subtarget->is64Bit()) {
1060 // Max of 8 and alignment of type.
1061 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1068 if (Subtarget->hasSSE1())
1069 getMaxByValAlign(Ty, Align);
1073 /// getOptimalMemOpType - Returns the target specific optimal type for load
1074 /// and store operations as a result of memset, memcpy, and memmove
1075 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
1078 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
1079 bool isSrcConst, bool isSrcStr,
1080 SelectionDAG &DAG) const {
1081 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1082 // linux. This is because the stack realignment code can't handle certain
1083 // cases like PR2962. This should be removed when PR2962 is fixed.
1084 const Function *F = DAG.getMachineFunction().getFunction();
1085 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
1086 if (!NoImplicitFloatOps && Subtarget->getStackAlignment() >= 16) {
1087 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
1089 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
1092 if (Subtarget->is64Bit() && Size >= 8)
1097 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1098 /// current function. The returned value is a member of the
1099 /// MachineJumpTableInfo::JTEntryKind enum.
1100 unsigned X86TargetLowering::getJumpTableEncoding() const {
1101 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1103 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1104 Subtarget->isPICStyleGOT())
1105 return MachineJumpTableInfo::EK_Custom32;
1107 // Otherwise, use the normal jump table encoding heuristics.
1108 return TargetLowering::getJumpTableEncoding();
1112 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1113 const MachineBasicBlock *MBB,
1114 unsigned uid,MCContext &Ctx) const{
1115 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1116 Subtarget->isPICStyleGOT());
1117 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1120 // FIXME: @GOTOFF should be a property of MCSymbolRefExpr not in the MCSymbol.
1121 std::string Name = MBB->getSymbol(Ctx)->getName() + "@GOTOFF";
1122 return MCSymbolRefExpr::Create(Ctx.GetOrCreateSymbol(StringRef(Name)), Ctx);
1125 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1127 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1128 SelectionDAG &DAG) const {
1129 if (!Subtarget->is64Bit())
1130 // This doesn't have DebugLoc associated with it, but is not really the
1131 // same as a Register.
1132 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc::getUnknownLoc(),
1137 /// getFunctionAlignment - Return the Log2 alignment of this function.
1138 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1139 return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1142 //===----------------------------------------------------------------------===//
1143 // Return Value Calling Convention Implementation
1144 //===----------------------------------------------------------------------===//
1146 #include "X86GenCallingConv.inc"
1149 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1150 const SmallVectorImpl<EVT> &OutTys,
1151 const SmallVectorImpl<ISD::ArgFlagsTy> &ArgsFlags,
1152 SelectionDAG &DAG) {
1153 SmallVector<CCValAssign, 16> RVLocs;
1154 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1155 RVLocs, *DAG.getContext());
1156 return CCInfo.CheckReturn(OutTys, ArgsFlags, RetCC_X86);
1160 X86TargetLowering::LowerReturn(SDValue Chain,
1161 CallingConv::ID CallConv, bool isVarArg,
1162 const SmallVectorImpl<ISD::OutputArg> &Outs,
1163 DebugLoc dl, SelectionDAG &DAG) {
1165 SmallVector<CCValAssign, 16> RVLocs;
1166 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1167 RVLocs, *DAG.getContext());
1168 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1170 // If this is the first return lowered for this function, add the regs to the
1171 // liveout set for the function.
1172 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1173 for (unsigned i = 0; i != RVLocs.size(); ++i)
1174 if (RVLocs[i].isRegLoc())
1175 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1180 SmallVector<SDValue, 6> RetOps;
1181 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1182 // Operand #1 = Bytes To Pop
1183 RetOps.push_back(DAG.getTargetConstant(getBytesToPopOnReturn(), MVT::i16));
1185 // Copy the result values into the output registers.
1186 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1187 CCValAssign &VA = RVLocs[i];
1188 assert(VA.isRegLoc() && "Can only return in registers!");
1189 SDValue ValToCopy = Outs[i].Val;
1191 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1192 // the RET instruction and handled by the FP Stackifier.
1193 if (VA.getLocReg() == X86::ST0 ||
1194 VA.getLocReg() == X86::ST1) {
1195 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1196 // change the value to the FP stack register class.
1197 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1198 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1199 RetOps.push_back(ValToCopy);
1200 // Don't emit a copytoreg.
1204 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1205 // which is returned in RAX / RDX.
1206 if (Subtarget->is64Bit()) {
1207 EVT ValVT = ValToCopy.getValueType();
1208 if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1209 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1210 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1211 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1215 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1216 Flag = Chain.getValue(1);
1219 // The x86-64 ABI for returning structs by value requires that we copy
1220 // the sret argument into %rax for the return. We saved the argument into
1221 // a virtual register in the entry block, so now we copy the value out
1223 if (Subtarget->is64Bit() &&
1224 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1225 MachineFunction &MF = DAG.getMachineFunction();
1226 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1227 unsigned Reg = FuncInfo->getSRetReturnReg();
1229 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1230 FuncInfo->setSRetReturnReg(Reg);
1232 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1234 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1235 Flag = Chain.getValue(1);
1237 // RAX now acts like a return value.
1238 MF.getRegInfo().addLiveOut(X86::RAX);
1241 RetOps[0] = Chain; // Update chain.
1243 // Add the flag if we have it.
1245 RetOps.push_back(Flag);
1247 return DAG.getNode(X86ISD::RET_FLAG, dl,
1248 MVT::Other, &RetOps[0], RetOps.size());
1251 /// LowerCallResult - Lower the result values of a call into the
1252 /// appropriate copies out of appropriate physical registers.
1255 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1256 CallingConv::ID CallConv, bool isVarArg,
1257 const SmallVectorImpl<ISD::InputArg> &Ins,
1258 DebugLoc dl, SelectionDAG &DAG,
1259 SmallVectorImpl<SDValue> &InVals) {
1261 // Assign locations to each value returned by this call.
1262 SmallVector<CCValAssign, 16> RVLocs;
1263 bool Is64Bit = Subtarget->is64Bit();
1264 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1265 RVLocs, *DAG.getContext());
1266 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1268 // Copy all of the result registers out of their specified physreg.
1269 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1270 CCValAssign &VA = RVLocs[i];
1271 EVT CopyVT = VA.getValVT();
1273 // If this is x86-64, and we disabled SSE, we can't return FP values
1274 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1275 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1276 llvm_report_error("SSE register return with SSE disabled");
1279 // If this is a call to a function that returns an fp value on the floating
1280 // point stack, but where we prefer to use the value in xmm registers, copy
1281 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1282 if ((VA.getLocReg() == X86::ST0 ||
1283 VA.getLocReg() == X86::ST1) &&
1284 isScalarFPTypeInSSEReg(VA.getValVT())) {
1289 if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1290 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1291 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1292 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1293 MVT::v2i64, InFlag).getValue(1);
1294 Val = Chain.getValue(0);
1295 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1296 Val, DAG.getConstant(0, MVT::i64));
1298 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1299 MVT::i64, InFlag).getValue(1);
1300 Val = Chain.getValue(0);
1302 Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1304 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1305 CopyVT, InFlag).getValue(1);
1306 Val = Chain.getValue(0);
1308 InFlag = Chain.getValue(2);
1310 if (CopyVT != VA.getValVT()) {
1311 // Round the F80 the right size, which also moves to the appropriate xmm
1313 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1314 // This truncation won't change the value.
1315 DAG.getIntPtrConstant(1));
1318 InVals.push_back(Val);
1325 //===----------------------------------------------------------------------===//
1326 // C & StdCall & Fast Calling Convention implementation
1327 //===----------------------------------------------------------------------===//
1328 // StdCall calling convention seems to be standard for many Windows' API
1329 // routines and around. It differs from C calling convention just a little:
1330 // callee should clean up the stack, not caller. Symbols should be also
1331 // decorated in some fancy way :) It doesn't support any vector arguments.
1332 // For info on fast calling convention see Fast Calling Convention (tail call)
1333 // implementation LowerX86_32FastCCCallTo.
1335 /// CallIsStructReturn - Determines whether a call uses struct return
1337 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1341 return Outs[0].Flags.isSRet();
1344 /// ArgsAreStructReturn - Determines whether a function uses struct
1345 /// return semantics.
1347 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1351 return Ins[0].Flags.isSRet();
1354 /// IsCalleePop - Determines whether the callee is required to pop its
1355 /// own arguments. Callee pop is necessary to support tail calls.
1356 bool X86TargetLowering::IsCalleePop(bool IsVarArg, CallingConv::ID CallingConv){
1360 switch (CallingConv) {
1363 case CallingConv::X86_StdCall:
1364 return !Subtarget->is64Bit();
1365 case CallingConv::X86_FastCall:
1366 return !Subtarget->is64Bit();
1367 case CallingConv::Fast:
1368 return PerformTailCallOpt;
1372 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1373 /// given CallingConvention value.
1374 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1375 if (Subtarget->is64Bit()) {
1376 if (Subtarget->isTargetWin64())
1377 return CC_X86_Win64_C;
1382 if (CC == CallingConv::X86_FastCall)
1383 return CC_X86_32_FastCall;
1384 else if (CC == CallingConv::Fast)
1385 return CC_X86_32_FastCC;
1390 /// NameDecorationForCallConv - Selects the appropriate decoration to
1391 /// apply to a MachineFunction containing a given calling convention.
1393 X86TargetLowering::NameDecorationForCallConv(CallingConv::ID CallConv) {
1394 if (CallConv == CallingConv::X86_FastCall)
1396 else if (CallConv == CallingConv::X86_StdCall)
1402 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1403 /// by "Src" to address "Dst" with size and alignment information specified by
1404 /// the specific parameter attribute. The copy will be passed as a byval
1405 /// function parameter.
1407 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1408 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1410 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1411 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1412 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1416 X86TargetLowering::LowerMemArgument(SDValue Chain,
1417 CallingConv::ID CallConv,
1418 const SmallVectorImpl<ISD::InputArg> &Ins,
1419 DebugLoc dl, SelectionDAG &DAG,
1420 const CCValAssign &VA,
1421 MachineFrameInfo *MFI,
1424 // Create the nodes corresponding to a load from this parameter slot.
1425 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1426 bool AlwaysUseMutable = (CallConv==CallingConv::Fast) && PerformTailCallOpt;
1427 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1430 // If value is passed by pointer we have address passed instead of the value
1432 if (VA.getLocInfo() == CCValAssign::Indirect)
1433 ValVT = VA.getLocVT();
1435 ValVT = VA.getValVT();
1437 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1438 // changed with more analysis.
1439 // In case of tail call optimization mark all arguments mutable. Since they
1440 // could be overwritten by lowering of arguments in case of a tail call.
1441 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1442 VA.getLocMemOffset(), isImmutable, false);
1443 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1444 if (Flags.isByVal())
1446 return DAG.getLoad(ValVT, dl, Chain, FIN,
1447 PseudoSourceValue::getFixedStack(FI), 0);
1451 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1452 CallingConv::ID CallConv,
1454 const SmallVectorImpl<ISD::InputArg> &Ins,
1457 SmallVectorImpl<SDValue> &InVals) {
1459 MachineFunction &MF = DAG.getMachineFunction();
1460 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1462 const Function* Fn = MF.getFunction();
1463 if (Fn->hasExternalLinkage() &&
1464 Subtarget->isTargetCygMing() &&
1465 Fn->getName() == "main")
1466 FuncInfo->setForceFramePointer(true);
1468 // Decorate the function name.
1469 FuncInfo->setDecorationStyle(NameDecorationForCallConv(CallConv));
1471 MachineFrameInfo *MFI = MF.getFrameInfo();
1472 bool Is64Bit = Subtarget->is64Bit();
1473 bool IsWin64 = Subtarget->isTargetWin64();
1475 assert(!(isVarArg && CallConv == CallingConv::Fast) &&
1476 "Var args not supported with calling convention fastcc");
1478 // Assign locations to all of the incoming arguments.
1479 SmallVector<CCValAssign, 16> ArgLocs;
1480 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1481 ArgLocs, *DAG.getContext());
1482 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1484 unsigned LastVal = ~0U;
1486 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1487 CCValAssign &VA = ArgLocs[i];
1488 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1490 assert(VA.getValNo() != LastVal &&
1491 "Don't support value assigned to multiple locs yet");
1492 LastVal = VA.getValNo();
1494 if (VA.isRegLoc()) {
1495 EVT RegVT = VA.getLocVT();
1496 TargetRegisterClass *RC = NULL;
1497 if (RegVT == MVT::i32)
1498 RC = X86::GR32RegisterClass;
1499 else if (Is64Bit && RegVT == MVT::i64)
1500 RC = X86::GR64RegisterClass;
1501 else if (RegVT == MVT::f32)
1502 RC = X86::FR32RegisterClass;
1503 else if (RegVT == MVT::f64)
1504 RC = X86::FR64RegisterClass;
1505 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1506 RC = X86::VR128RegisterClass;
1507 else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1508 RC = X86::VR64RegisterClass;
1510 llvm_unreachable("Unknown argument type!");
1512 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1513 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1515 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1516 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1518 if (VA.getLocInfo() == CCValAssign::SExt)
1519 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1520 DAG.getValueType(VA.getValVT()));
1521 else if (VA.getLocInfo() == CCValAssign::ZExt)
1522 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1523 DAG.getValueType(VA.getValVT()));
1524 else if (VA.getLocInfo() == CCValAssign::BCvt)
1525 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1527 if (VA.isExtInLoc()) {
1528 // Handle MMX values passed in XMM regs.
1529 if (RegVT.isVector()) {
1530 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1531 ArgValue, DAG.getConstant(0, MVT::i64));
1532 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1534 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1537 assert(VA.isMemLoc());
1538 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1541 // If value is passed via pointer - do a load.
1542 if (VA.getLocInfo() == CCValAssign::Indirect)
1543 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0);
1545 InVals.push_back(ArgValue);
1548 // The x86-64 ABI for returning structs by value requires that we copy
1549 // the sret argument into %rax for the return. Save the argument into
1550 // a virtual register so that we can access it from the return points.
1551 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1552 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1553 unsigned Reg = FuncInfo->getSRetReturnReg();
1555 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1556 FuncInfo->setSRetReturnReg(Reg);
1558 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1559 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1562 unsigned StackSize = CCInfo.getNextStackOffset();
1563 // align stack specially for tail calls
1564 if (PerformTailCallOpt && CallConv == CallingConv::Fast)
1565 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1567 // If the function takes variable number of arguments, make a frame index for
1568 // the start of the first vararg value... for expansion of llvm.va_start.
1570 if (Is64Bit || CallConv != CallingConv::X86_FastCall) {
1571 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize, true, false);
1574 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1576 // FIXME: We should really autogenerate these arrays
1577 static const unsigned GPR64ArgRegsWin64[] = {
1578 X86::RCX, X86::RDX, X86::R8, X86::R9
1580 static const unsigned XMMArgRegsWin64[] = {
1581 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1583 static const unsigned GPR64ArgRegs64Bit[] = {
1584 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1586 static const unsigned XMMArgRegs64Bit[] = {
1587 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1588 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1590 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1593 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1594 GPR64ArgRegs = GPR64ArgRegsWin64;
1595 XMMArgRegs = XMMArgRegsWin64;
1597 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1598 GPR64ArgRegs = GPR64ArgRegs64Bit;
1599 XMMArgRegs = XMMArgRegs64Bit;
1601 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1603 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1606 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1607 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1608 "SSE register cannot be used when SSE is disabled!");
1609 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1610 "SSE register cannot be used when SSE is disabled!");
1611 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1612 // Kernel mode asks for SSE to be disabled, so don't push them
1614 TotalNumXMMRegs = 0;
1616 // For X86-64, if there are vararg parameters that are passed via
1617 // registers, then we must store them to their spots on the stack so they
1618 // may be loaded by deferencing the result of va_next.
1619 VarArgsGPOffset = NumIntRegs * 8;
1620 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1621 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1622 TotalNumXMMRegs * 16, 16,
1625 // Store the integer parameter registers.
1626 SmallVector<SDValue, 8> MemOps;
1627 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1628 unsigned Offset = VarArgsGPOffset;
1629 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1630 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1631 DAG.getIntPtrConstant(Offset));
1632 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1633 X86::GR64RegisterClass);
1634 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1636 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1637 PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
1639 MemOps.push_back(Store);
1643 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1644 // Now store the XMM (fp + vector) parameter registers.
1645 SmallVector<SDValue, 11> SaveXMMOps;
1646 SaveXMMOps.push_back(Chain);
1648 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1649 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1650 SaveXMMOps.push_back(ALVal);
1652 SaveXMMOps.push_back(DAG.getIntPtrConstant(RegSaveFrameIndex));
1653 SaveXMMOps.push_back(DAG.getIntPtrConstant(VarArgsFPOffset));
1655 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1656 unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1657 X86::VR128RegisterClass);
1658 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1659 SaveXMMOps.push_back(Val);
1661 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1663 &SaveXMMOps[0], SaveXMMOps.size()));
1666 if (!MemOps.empty())
1667 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1668 &MemOps[0], MemOps.size());
1672 // Some CCs need callee pop.
1673 if (IsCalleePop(isVarArg, CallConv)) {
1674 BytesToPopOnReturn = StackSize; // Callee pops everything.
1675 BytesCallerReserves = 0;
1677 BytesToPopOnReturn = 0; // Callee pops nothing.
1678 // If this is an sret function, the return should pop the hidden pointer.
1679 if (!Is64Bit && CallConv != CallingConv::Fast && ArgsAreStructReturn(Ins))
1680 BytesToPopOnReturn = 4;
1681 BytesCallerReserves = StackSize;
1685 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1686 if (CallConv == CallingConv::X86_FastCall)
1687 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1690 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1696 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1697 SDValue StackPtr, SDValue Arg,
1698 DebugLoc dl, SelectionDAG &DAG,
1699 const CCValAssign &VA,
1700 ISD::ArgFlagsTy Flags) {
1701 const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1702 unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1703 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1704 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1705 if (Flags.isByVal()) {
1706 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1708 return DAG.getStore(Chain, dl, Arg, PtrOff,
1709 PseudoSourceValue::getStack(), LocMemOffset);
1712 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1713 /// optimization is performed and it is required.
1715 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1716 SDValue &OutRetAddr,
1722 if (!IsTailCall || FPDiff==0) return Chain;
1724 // Adjust the Return address stack slot.
1725 EVT VT = getPointerTy();
1726 OutRetAddr = getReturnAddressFrameIndex(DAG);
1728 // Load the "old" Return address.
1729 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0);
1730 return SDValue(OutRetAddr.getNode(), 1);
1733 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1734 /// optimization is performed and it is required (FPDiff!=0).
1736 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1737 SDValue Chain, SDValue RetAddrFrIdx,
1738 bool Is64Bit, int FPDiff, DebugLoc dl) {
1739 // Store the return address to the appropriate stack slot.
1740 if (!FPDiff) return Chain;
1741 // Calculate the new stack slot for the return address.
1742 int SlotSize = Is64Bit ? 8 : 4;
1743 int NewReturnAddrFI =
1744 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize,
1746 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1747 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1748 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1749 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1754 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1755 CallingConv::ID CallConv, bool isVarArg,
1757 const SmallVectorImpl<ISD::OutputArg> &Outs,
1758 const SmallVectorImpl<ISD::InputArg> &Ins,
1759 DebugLoc dl, SelectionDAG &DAG,
1760 SmallVectorImpl<SDValue> &InVals) {
1762 MachineFunction &MF = DAG.getMachineFunction();
1763 bool Is64Bit = Subtarget->is64Bit();
1764 bool IsStructRet = CallIsStructReturn(Outs);
1766 assert((!isTailCall ||
1767 (CallConv == CallingConv::Fast && PerformTailCallOpt)) &&
1768 "IsEligibleForTailCallOptimization missed a case!");
1769 assert(!(isVarArg && CallConv == CallingConv::Fast) &&
1770 "Var args not supported with calling convention fastcc");
1772 // Analyze operands of the call, assigning locations to each operand.
1773 SmallVector<CCValAssign, 16> ArgLocs;
1774 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1775 ArgLocs, *DAG.getContext());
1776 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1778 // Get a count of how many bytes are to be pushed on the stack.
1779 unsigned NumBytes = CCInfo.getNextStackOffset();
1780 if (PerformTailCallOpt && CallConv == CallingConv::Fast)
1781 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1785 // Lower arguments at fp - stackoffset + fpdiff.
1786 unsigned NumBytesCallerPushed =
1787 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1788 FPDiff = NumBytesCallerPushed - NumBytes;
1790 // Set the delta of movement of the returnaddr stackslot.
1791 // But only set if delta is greater than previous delta.
1792 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1793 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1796 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1798 SDValue RetAddrFrIdx;
1799 // Load return adress for tail calls.
1800 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall, Is64Bit,
1803 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1804 SmallVector<SDValue, 8> MemOpChains;
1807 // Walk the register/memloc assignments, inserting copies/loads. In the case
1808 // of tail call optimization arguments are handle later.
1809 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1810 CCValAssign &VA = ArgLocs[i];
1811 EVT RegVT = VA.getLocVT();
1812 SDValue Arg = Outs[i].Val;
1813 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1814 bool isByVal = Flags.isByVal();
1816 // Promote the value if needed.
1817 switch (VA.getLocInfo()) {
1818 default: llvm_unreachable("Unknown loc info!");
1819 case CCValAssign::Full: break;
1820 case CCValAssign::SExt:
1821 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1823 case CCValAssign::ZExt:
1824 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1826 case CCValAssign::AExt:
1827 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1828 // Special case: passing MMX values in XMM registers.
1829 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1830 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1831 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1833 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1835 case CCValAssign::BCvt:
1836 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1838 case CCValAssign::Indirect: {
1839 // Store the argument.
1840 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1841 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1842 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1843 PseudoSourceValue::getFixedStack(FI), 0);
1849 if (VA.isRegLoc()) {
1850 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1852 if (!isTailCall || (isTailCall && isByVal)) {
1853 assert(VA.isMemLoc());
1854 if (StackPtr.getNode() == 0)
1855 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1857 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1858 dl, DAG, VA, Flags));
1863 if (!MemOpChains.empty())
1864 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1865 &MemOpChains[0], MemOpChains.size());
1867 // Build a sequence of copy-to-reg nodes chained together with token chain
1868 // and flag operands which copy the outgoing args into registers.
1870 // Tail call byval lowering might overwrite argument registers so in case of
1871 // tail call optimization the copies to registers are lowered later.
1873 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1874 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1875 RegsToPass[i].second, InFlag);
1876 InFlag = Chain.getValue(1);
1880 if (Subtarget->isPICStyleGOT()) {
1881 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1884 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1885 DAG.getNode(X86ISD::GlobalBaseReg,
1886 DebugLoc::getUnknownLoc(),
1889 InFlag = Chain.getValue(1);
1891 // If we are tail calling and generating PIC/GOT style code load the
1892 // address of the callee into ECX. The value in ecx is used as target of
1893 // the tail jump. This is done to circumvent the ebx/callee-saved problem
1894 // for tail calls on PIC/GOT architectures. Normally we would just put the
1895 // address of GOT into ebx and then call target@PLT. But for tail calls
1896 // ebx would be restored (since ebx is callee saved) before jumping to the
1899 // Note: The actual moving to ECX is done further down.
1900 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1901 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1902 !G->getGlobal()->hasProtectedVisibility())
1903 Callee = LowerGlobalAddress(Callee, DAG);
1904 else if (isa<ExternalSymbolSDNode>(Callee))
1905 Callee = LowerExternalSymbol(Callee, DAG);
1909 if (Is64Bit && isVarArg) {
1910 // From AMD64 ABI document:
1911 // For calls that may call functions that use varargs or stdargs
1912 // (prototype-less calls or calls to functions containing ellipsis (...) in
1913 // the declaration) %al is used as hidden argument to specify the number
1914 // of SSE registers used. The contents of %al do not need to match exactly
1915 // the number of registers, but must be an ubound on the number of SSE
1916 // registers used and is in the range 0 - 8 inclusive.
1918 // FIXME: Verify this on Win64
1919 // Count the number of XMM registers allocated.
1920 static const unsigned XMMArgRegs[] = {
1921 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1922 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1924 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1925 assert((Subtarget->hasSSE1() || !NumXMMRegs)
1926 && "SSE registers cannot be used when SSE is disabled");
1928 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1929 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1930 InFlag = Chain.getValue(1);
1934 // For tail calls lower the arguments to the 'real' stack slot.
1936 // Force all the incoming stack arguments to be loaded from the stack
1937 // before any new outgoing arguments are stored to the stack, because the
1938 // outgoing stack slots may alias the incoming argument stack slots, and
1939 // the alias isn't otherwise explicit. This is slightly more conservative
1940 // than necessary, because it means that each store effectively depends
1941 // on every argument instead of just those arguments it would clobber.
1942 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
1944 SmallVector<SDValue, 8> MemOpChains2;
1947 // Do not flag preceeding copytoreg stuff together with the following stuff.
1949 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1950 CCValAssign &VA = ArgLocs[i];
1951 if (!VA.isRegLoc()) {
1952 assert(VA.isMemLoc());
1953 SDValue Arg = Outs[i].Val;
1954 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1955 // Create frame index.
1956 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1957 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1958 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true, false);
1959 FIN = DAG.getFrameIndex(FI, getPointerTy());
1961 if (Flags.isByVal()) {
1962 // Copy relative to framepointer.
1963 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1964 if (StackPtr.getNode() == 0)
1965 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
1967 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
1969 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
1973 // Store relative to framepointer.
1974 MemOpChains2.push_back(
1975 DAG.getStore(ArgChain, dl, Arg, FIN,
1976 PseudoSourceValue::getFixedStack(FI), 0));
1981 if (!MemOpChains2.empty())
1982 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1983 &MemOpChains2[0], MemOpChains2.size());
1985 // Copy arguments to their registers.
1986 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1987 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1988 RegsToPass[i].second, InFlag);
1989 InFlag = Chain.getValue(1);
1993 // Store the return address to the appropriate stack slot.
1994 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1998 bool WasGlobalOrExternal = false;
1999 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2000 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2001 // In the 64-bit large code model, we have to make all calls
2002 // through a register, since the call instruction's 32-bit
2003 // pc-relative offset may not be large enough to hold the whole
2005 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2006 WasGlobalOrExternal = true;
2007 // If the callee is a GlobalAddress node (quite common, every direct call
2008 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2011 // We should use extra load for direct calls to dllimported functions in
2013 GlobalValue *GV = G->getGlobal();
2014 if (!GV->hasDLLImportLinkage()) {
2015 unsigned char OpFlags = 0;
2017 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2018 // external symbols most go through the PLT in PIC mode. If the symbol
2019 // has hidden or protected visibility, or if it is static or local, then
2020 // we don't need to use the PLT - we can directly call it.
2021 if (Subtarget->isTargetELF() &&
2022 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2023 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2024 OpFlags = X86II::MO_PLT;
2025 } else if (Subtarget->isPICStyleStubAny() &&
2026 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2027 Subtarget->getDarwinVers() < 9) {
2028 // PC-relative references to external symbols should go through $stub,
2029 // unless we're building with the leopard linker or later, which
2030 // automatically synthesizes these stubs.
2031 OpFlags = X86II::MO_DARWIN_STUB;
2034 Callee = DAG.getTargetGlobalAddress(GV, getPointerTy(),
2035 G->getOffset(), OpFlags);
2037 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2038 WasGlobalOrExternal = true;
2039 unsigned char OpFlags = 0;
2041 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2042 // symbols should go through the PLT.
2043 if (Subtarget->isTargetELF() &&
2044 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2045 OpFlags = X86II::MO_PLT;
2046 } else if (Subtarget->isPICStyleStubAny() &&
2047 Subtarget->getDarwinVers() < 9) {
2048 // PC-relative references to external symbols should go through $stub,
2049 // unless we're building with the leopard linker or later, which
2050 // automatically synthesizes these stubs.
2051 OpFlags = X86II::MO_DARWIN_STUB;
2054 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2058 if (isTailCall && !WasGlobalOrExternal) {
2059 unsigned Opc = Is64Bit ? X86::R11 : X86::EAX;
2061 Chain = DAG.getCopyToReg(Chain, dl,
2062 DAG.getRegister(Opc, getPointerTy()),
2064 Callee = DAG.getRegister(Opc, getPointerTy());
2065 // Add register as live out.
2066 MF.getRegInfo().addLiveOut(Opc);
2069 // Returns a chain & a flag for retval copy to use.
2070 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2071 SmallVector<SDValue, 8> Ops;
2074 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2075 DAG.getIntPtrConstant(0, true), InFlag);
2076 InFlag = Chain.getValue(1);
2079 Ops.push_back(Chain);
2080 Ops.push_back(Callee);
2083 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2085 // Add argument registers to the end of the list so that they are known live
2087 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2088 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2089 RegsToPass[i].second.getValueType()));
2091 // Add an implicit use GOT pointer in EBX.
2092 if (!isTailCall && Subtarget->isPICStyleGOT())
2093 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2095 // Add an implicit use of AL for x86 vararg functions.
2096 if (Is64Bit && isVarArg)
2097 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2099 if (InFlag.getNode())
2100 Ops.push_back(InFlag);
2103 // If this is the first return lowered for this function, add the regs
2104 // to the liveout set for the function.
2105 if (MF.getRegInfo().liveout_empty()) {
2106 SmallVector<CCValAssign, 16> RVLocs;
2107 CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
2109 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2110 for (unsigned i = 0; i != RVLocs.size(); ++i)
2111 if (RVLocs[i].isRegLoc())
2112 MF.getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2115 assert(((Callee.getOpcode() == ISD::Register &&
2116 (cast<RegisterSDNode>(Callee)->getReg() == X86::EAX ||
2117 cast<RegisterSDNode>(Callee)->getReg() == X86::R11)) ||
2118 Callee.getOpcode() == ISD::TargetExternalSymbol ||
2119 Callee.getOpcode() == ISD::TargetGlobalAddress) &&
2120 "Expecting a global address, external symbol, or scratch register");
2122 return DAG.getNode(X86ISD::TC_RETURN, dl,
2123 NodeTys, &Ops[0], Ops.size());
2126 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2127 InFlag = Chain.getValue(1);
2129 // Create the CALLSEQ_END node.
2130 unsigned NumBytesForCalleeToPush;
2131 if (IsCalleePop(isVarArg, CallConv))
2132 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2133 else if (!Is64Bit && CallConv != CallingConv::Fast && IsStructRet)
2134 // If this is is a call to a struct-return function, the callee
2135 // pops the hidden struct pointer, so we have to push it back.
2136 // This is common for Darwin/X86, Linux & Mingw32 targets.
2137 NumBytesForCalleeToPush = 4;
2139 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2141 // Returns a flag for retval copy to use.
2142 Chain = DAG.getCALLSEQ_END(Chain,
2143 DAG.getIntPtrConstant(NumBytes, true),
2144 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2147 InFlag = Chain.getValue(1);
2149 // Handle result values, copying them out of physregs into vregs that we
2151 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2152 Ins, dl, DAG, InVals);
2156 //===----------------------------------------------------------------------===//
2157 // Fast Calling Convention (tail call) implementation
2158 //===----------------------------------------------------------------------===//
2160 // Like std call, callee cleans arguments, convention except that ECX is
2161 // reserved for storing the tail called function address. Only 2 registers are
2162 // free for argument passing (inreg). Tail call optimization is performed
2164 // * tailcallopt is enabled
2165 // * caller/callee are fastcc
2166 // On X86_64 architecture with GOT-style position independent code only local
2167 // (within module) calls are supported at the moment.
2168 // To keep the stack aligned according to platform abi the function
2169 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2170 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2171 // If a tail called function callee has more arguments than the caller the
2172 // caller needs to make sure that there is room to move the RETADDR to. This is
2173 // achieved by reserving an area the size of the argument delta right after the
2174 // original REtADDR, but before the saved framepointer or the spilled registers
2175 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2187 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2188 /// for a 16 byte align requirement.
2189 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2190 SelectionDAG& DAG) {
2191 MachineFunction &MF = DAG.getMachineFunction();
2192 const TargetMachine &TM = MF.getTarget();
2193 const TargetFrameInfo &TFI = *TM.getFrameInfo();
2194 unsigned StackAlignment = TFI.getStackAlignment();
2195 uint64_t AlignMask = StackAlignment - 1;
2196 int64_t Offset = StackSize;
2197 uint64_t SlotSize = TD->getPointerSize();
2198 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2199 // Number smaller than 12 so just add the difference.
2200 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2202 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2203 Offset = ((~AlignMask) & Offset) + StackAlignment +
2204 (StackAlignment-SlotSize);
2209 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2210 /// for tail call optimization. Targets which want to do tail call
2211 /// optimization should implement this function.
2213 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2214 CallingConv::ID CalleeCC,
2216 const SmallVectorImpl<ISD::InputArg> &Ins,
2217 SelectionDAG& DAG) const {
2218 MachineFunction &MF = DAG.getMachineFunction();
2219 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
2220 return CalleeCC == CallingConv::Fast && CallerCC == CalleeCC;
2224 X86TargetLowering::createFastISel(MachineFunction &mf,
2225 MachineModuleInfo *mmo,
2227 DenseMap<const Value *, unsigned> &vm,
2228 DenseMap<const BasicBlock *,
2229 MachineBasicBlock *> &bm,
2230 DenseMap<const AllocaInst *, int> &am
2232 , SmallSet<Instruction*, 8> &cil
2235 return X86::createFastISel(mf, mmo, dw, vm, bm, am
2243 //===----------------------------------------------------------------------===//
2244 // Other Lowering Hooks
2245 //===----------------------------------------------------------------------===//
2248 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2249 MachineFunction &MF = DAG.getMachineFunction();
2250 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2251 int ReturnAddrIndex = FuncInfo->getRAIndex();
2253 if (ReturnAddrIndex == 0) {
2254 // Set up a frame object for the return address.
2255 uint64_t SlotSize = TD->getPointerSize();
2256 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2258 FuncInfo->setRAIndex(ReturnAddrIndex);
2261 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2265 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2266 bool hasSymbolicDisplacement) {
2267 // Offset should fit into 32 bit immediate field.
2268 if (!isInt32(Offset))
2271 // If we don't have a symbolic displacement - we don't have any extra
2273 if (!hasSymbolicDisplacement)
2276 // FIXME: Some tweaks might be needed for medium code model.
2277 if (M != CodeModel::Small && M != CodeModel::Kernel)
2280 // For small code model we assume that latest object is 16MB before end of 31
2281 // bits boundary. We may also accept pretty large negative constants knowing
2282 // that all objects are in the positive half of address space.
2283 if (M == CodeModel::Small && Offset < 16*1024*1024)
2286 // For kernel code model we know that all object resist in the negative half
2287 // of 32bits address space. We may not accept negative offsets, since they may
2288 // be just off and we may accept pretty large positive ones.
2289 if (M == CodeModel::Kernel && Offset > 0)
2295 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2296 /// specific condition code, returning the condition code and the LHS/RHS of the
2297 /// comparison to make.
2298 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2299 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2301 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2302 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2303 // X > -1 -> X == 0, jump !sign.
2304 RHS = DAG.getConstant(0, RHS.getValueType());
2305 return X86::COND_NS;
2306 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2307 // X < 0 -> X == 0, jump on sign.
2309 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2311 RHS = DAG.getConstant(0, RHS.getValueType());
2312 return X86::COND_LE;
2316 switch (SetCCOpcode) {
2317 default: llvm_unreachable("Invalid integer condition!");
2318 case ISD::SETEQ: return X86::COND_E;
2319 case ISD::SETGT: return X86::COND_G;
2320 case ISD::SETGE: return X86::COND_GE;
2321 case ISD::SETLT: return X86::COND_L;
2322 case ISD::SETLE: return X86::COND_LE;
2323 case ISD::SETNE: return X86::COND_NE;
2324 case ISD::SETULT: return X86::COND_B;
2325 case ISD::SETUGT: return X86::COND_A;
2326 case ISD::SETULE: return X86::COND_BE;
2327 case ISD::SETUGE: return X86::COND_AE;
2331 // First determine if it is required or is profitable to flip the operands.
2333 // If LHS is a foldable load, but RHS is not, flip the condition.
2334 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2335 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2336 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2337 std::swap(LHS, RHS);
2340 switch (SetCCOpcode) {
2346 std::swap(LHS, RHS);
2350 // On a floating point condition, the flags are set as follows:
2352 // 0 | 0 | 0 | X > Y
2353 // 0 | 0 | 1 | X < Y
2354 // 1 | 0 | 0 | X == Y
2355 // 1 | 1 | 1 | unordered
2356 switch (SetCCOpcode) {
2357 default: llvm_unreachable("Condcode should be pre-legalized away");
2359 case ISD::SETEQ: return X86::COND_E;
2360 case ISD::SETOLT: // flipped
2362 case ISD::SETGT: return X86::COND_A;
2363 case ISD::SETOLE: // flipped
2365 case ISD::SETGE: return X86::COND_AE;
2366 case ISD::SETUGT: // flipped
2368 case ISD::SETLT: return X86::COND_B;
2369 case ISD::SETUGE: // flipped
2371 case ISD::SETLE: return X86::COND_BE;
2373 case ISD::SETNE: return X86::COND_NE;
2374 case ISD::SETUO: return X86::COND_P;
2375 case ISD::SETO: return X86::COND_NP;
2377 case ISD::SETUNE: return X86::COND_INVALID;
2381 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2382 /// code. Current x86 isa includes the following FP cmov instructions:
2383 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2384 static bool hasFPCMov(unsigned X86CC) {
2400 /// isFPImmLegal - Returns true if the target can instruction select the
2401 /// specified FP immediate natively. If false, the legalizer will
2402 /// materialize the FP immediate as a load from a constant pool.
2403 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2404 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2405 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2411 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2412 /// the specified range (L, H].
2413 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2414 return (Val < 0) || (Val >= Low && Val < Hi);
2417 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2418 /// specified value.
2419 static bool isUndefOrEqual(int Val, int CmpVal) {
2420 if (Val < 0 || Val == CmpVal)
2425 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2426 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2427 /// the second operand.
2428 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2429 if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2430 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2431 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2432 return (Mask[0] < 2 && Mask[1] < 2);
2436 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2437 SmallVector<int, 8> M;
2439 return ::isPSHUFDMask(M, N->getValueType(0));
2442 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2443 /// is suitable for input to PSHUFHW.
2444 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2445 if (VT != MVT::v8i16)
2448 // Lower quadword copied in order or undef.
2449 for (int i = 0; i != 4; ++i)
2450 if (Mask[i] >= 0 && Mask[i] != i)
2453 // Upper quadword shuffled.
2454 for (int i = 4; i != 8; ++i)
2455 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2461 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2462 SmallVector<int, 8> M;
2464 return ::isPSHUFHWMask(M, N->getValueType(0));
2467 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2468 /// is suitable for input to PSHUFLW.
2469 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2470 if (VT != MVT::v8i16)
2473 // Upper quadword copied in order.
2474 for (int i = 4; i != 8; ++i)
2475 if (Mask[i] >= 0 && Mask[i] != i)
2478 // Lower quadword shuffled.
2479 for (int i = 0; i != 4; ++i)
2486 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2487 SmallVector<int, 8> M;
2489 return ::isPSHUFLWMask(M, N->getValueType(0));
2492 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2493 /// is suitable for input to PALIGNR.
2494 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2496 int i, e = VT.getVectorNumElements();
2498 // Do not handle v2i64 / v2f64 shuffles with palignr.
2499 if (e < 4 || !hasSSSE3)
2502 for (i = 0; i != e; ++i)
2506 // All undef, not a palignr.
2510 // Determine if it's ok to perform a palignr with only the LHS, since we
2511 // don't have access to the actual shuffle elements to see if RHS is undef.
2512 bool Unary = Mask[i] < (int)e;
2513 bool NeedsUnary = false;
2515 int s = Mask[i] - i;
2517 // Check the rest of the elements to see if they are consecutive.
2518 for (++i; i != e; ++i) {
2523 Unary = Unary && (m < (int)e);
2524 NeedsUnary = NeedsUnary || (m < s);
2526 if (NeedsUnary && !Unary)
2528 if (Unary && m != ((s+i) & (e-1)))
2530 if (!Unary && m != (s+i))
2536 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2537 SmallVector<int, 8> M;
2539 return ::isPALIGNRMask(M, N->getValueType(0), true);
2542 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2543 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2544 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2545 int NumElems = VT.getVectorNumElements();
2546 if (NumElems != 2 && NumElems != 4)
2549 int Half = NumElems / 2;
2550 for (int i = 0; i < Half; ++i)
2551 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2553 for (int i = Half; i < NumElems; ++i)
2554 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2560 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2561 SmallVector<int, 8> M;
2563 return ::isSHUFPMask(M, N->getValueType(0));
2566 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2567 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2568 /// half elements to come from vector 1 (which would equal the dest.) and
2569 /// the upper half to come from vector 2.
2570 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2571 int NumElems = VT.getVectorNumElements();
2573 if (NumElems != 2 && NumElems != 4)
2576 int Half = NumElems / 2;
2577 for (int i = 0; i < Half; ++i)
2578 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2580 for (int i = Half; i < NumElems; ++i)
2581 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2586 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2587 SmallVector<int, 8> M;
2589 return isCommutedSHUFPMask(M, N->getValueType(0));
2592 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2593 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2594 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2595 if (N->getValueType(0).getVectorNumElements() != 4)
2598 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2599 return isUndefOrEqual(N->getMaskElt(0), 6) &&
2600 isUndefOrEqual(N->getMaskElt(1), 7) &&
2601 isUndefOrEqual(N->getMaskElt(2), 2) &&
2602 isUndefOrEqual(N->getMaskElt(3), 3);
2605 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2606 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2608 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2609 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2614 return isUndefOrEqual(N->getMaskElt(0), 2) &&
2615 isUndefOrEqual(N->getMaskElt(1), 3) &&
2616 isUndefOrEqual(N->getMaskElt(2), 2) &&
2617 isUndefOrEqual(N->getMaskElt(3), 3);
2620 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2621 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2622 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2623 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2625 if (NumElems != 2 && NumElems != 4)
2628 for (unsigned i = 0; i < NumElems/2; ++i)
2629 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2632 for (unsigned i = NumElems/2; i < NumElems; ++i)
2633 if (!isUndefOrEqual(N->getMaskElt(i), i))
2639 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
2640 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
2641 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
2642 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2644 if (NumElems != 2 && NumElems != 4)
2647 for (unsigned i = 0; i < NumElems/2; ++i)
2648 if (!isUndefOrEqual(N->getMaskElt(i), i))
2651 for (unsigned i = 0; i < NumElems/2; ++i)
2652 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2658 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2659 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2660 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2661 bool V2IsSplat = false) {
2662 int NumElts = VT.getVectorNumElements();
2663 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2666 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2668 int BitI1 = Mask[i+1];
2669 if (!isUndefOrEqual(BitI, j))
2672 if (!isUndefOrEqual(BitI1, NumElts))
2675 if (!isUndefOrEqual(BitI1, j + NumElts))
2682 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2683 SmallVector<int, 8> M;
2685 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2688 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2689 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2690 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
2691 bool V2IsSplat = false) {
2692 int NumElts = VT.getVectorNumElements();
2693 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2696 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2698 int BitI1 = Mask[i+1];
2699 if (!isUndefOrEqual(BitI, j + NumElts/2))
2702 if (isUndefOrEqual(BitI1, NumElts))
2705 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2712 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2713 SmallVector<int, 8> M;
2715 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2718 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2719 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2721 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2722 int NumElems = VT.getVectorNumElements();
2723 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2726 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2728 int BitI1 = Mask[i+1];
2729 if (!isUndefOrEqual(BitI, j))
2731 if (!isUndefOrEqual(BitI1, j))
2737 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2738 SmallVector<int, 8> M;
2740 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2743 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2744 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2746 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2747 int NumElems = VT.getVectorNumElements();
2748 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2751 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2753 int BitI1 = Mask[i+1];
2754 if (!isUndefOrEqual(BitI, j))
2756 if (!isUndefOrEqual(BitI1, j))
2762 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2763 SmallVector<int, 8> M;
2765 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2768 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2769 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2770 /// MOVSD, and MOVD, i.e. setting the lowest element.
2771 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2772 if (VT.getVectorElementType().getSizeInBits() < 32)
2775 int NumElts = VT.getVectorNumElements();
2777 if (!isUndefOrEqual(Mask[0], NumElts))
2780 for (int i = 1; i < NumElts; ++i)
2781 if (!isUndefOrEqual(Mask[i], i))
2787 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2788 SmallVector<int, 8> M;
2790 return ::isMOVLMask(M, N->getValueType(0));
2793 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2794 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2795 /// element of vector 2 and the other elements to come from vector 1 in order.
2796 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2797 bool V2IsSplat = false, bool V2IsUndef = false) {
2798 int NumOps = VT.getVectorNumElements();
2799 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2802 if (!isUndefOrEqual(Mask[0], 0))
2805 for (int i = 1; i < NumOps; ++i)
2806 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
2807 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
2808 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
2814 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
2815 bool V2IsUndef = false) {
2816 SmallVector<int, 8> M;
2818 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
2821 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2822 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2823 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
2824 if (N->getValueType(0).getVectorNumElements() != 4)
2827 // Expect 1, 1, 3, 3
2828 for (unsigned i = 0; i < 2; ++i) {
2829 int Elt = N->getMaskElt(i);
2830 if (Elt >= 0 && Elt != 1)
2835 for (unsigned i = 2; i < 4; ++i) {
2836 int Elt = N->getMaskElt(i);
2837 if (Elt >= 0 && Elt != 3)
2842 // Don't use movshdup if it can be done with a shufps.
2843 // FIXME: verify that matching u, u, 3, 3 is what we want.
2847 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2848 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2849 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
2850 if (N->getValueType(0).getVectorNumElements() != 4)
2853 // Expect 0, 0, 2, 2
2854 for (unsigned i = 0; i < 2; ++i)
2855 if (N->getMaskElt(i) > 0)
2859 for (unsigned i = 2; i < 4; ++i) {
2860 int Elt = N->getMaskElt(i);
2861 if (Elt >= 0 && Elt != 2)
2866 // Don't use movsldup if it can be done with a shufps.
2870 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2871 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2872 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
2873 int e = N->getValueType(0).getVectorNumElements() / 2;
2875 for (int i = 0; i < e; ++i)
2876 if (!isUndefOrEqual(N->getMaskElt(i), i))
2878 for (int i = 0; i < e; ++i)
2879 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
2884 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2885 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
2886 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2887 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2888 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
2890 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2892 for (int i = 0; i < NumOperands; ++i) {
2893 int Val = SVOp->getMaskElt(NumOperands-i-1);
2894 if (Val < 0) Val = 0;
2895 if (Val >= NumOperands) Val -= NumOperands;
2897 if (i != NumOperands - 1)
2903 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2904 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
2905 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2906 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2908 // 8 nodes, but we only care about the last 4.
2909 for (unsigned i = 7; i >= 4; --i) {
2910 int Val = SVOp->getMaskElt(i);
2919 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2920 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
2921 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2922 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2924 // 8 nodes, but we only care about the first 4.
2925 for (int i = 3; i >= 0; --i) {
2926 int Val = SVOp->getMaskElt(i);
2935 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
2936 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
2937 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
2938 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2939 EVT VVT = N->getValueType(0);
2940 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
2944 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
2945 Val = SVOp->getMaskElt(i);
2949 return (Val - i) * EltSize;
2952 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2954 bool X86::isZeroNode(SDValue Elt) {
2955 return ((isa<ConstantSDNode>(Elt) &&
2956 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2957 (isa<ConstantFPSDNode>(Elt) &&
2958 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2961 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
2962 /// their permute mask.
2963 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
2964 SelectionDAG &DAG) {
2965 EVT VT = SVOp->getValueType(0);
2966 unsigned NumElems = VT.getVectorNumElements();
2967 SmallVector<int, 8> MaskVec;
2969 for (unsigned i = 0; i != NumElems; ++i) {
2970 int idx = SVOp->getMaskElt(i);
2972 MaskVec.push_back(idx);
2973 else if (idx < (int)NumElems)
2974 MaskVec.push_back(idx + NumElems);
2976 MaskVec.push_back(idx - NumElems);
2978 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
2979 SVOp->getOperand(0), &MaskVec[0]);
2982 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2983 /// the two vector operands have swapped position.
2984 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
2985 unsigned NumElems = VT.getVectorNumElements();
2986 for (unsigned i = 0; i != NumElems; ++i) {
2990 else if (idx < (int)NumElems)
2991 Mask[i] = idx + NumElems;
2993 Mask[i] = idx - NumElems;
2997 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2998 /// match movhlps. The lower half elements should come from upper half of
2999 /// V1 (and in order), and the upper half elements should come from the upper
3000 /// half of V2 (and in order).
3001 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3002 if (Op->getValueType(0).getVectorNumElements() != 4)
3004 for (unsigned i = 0, e = 2; i != e; ++i)
3005 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3007 for (unsigned i = 2; i != 4; ++i)
3008 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3013 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3014 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3016 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3017 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3019 N = N->getOperand(0).getNode();
3020 if (!ISD::isNON_EXTLoad(N))
3023 *LD = cast<LoadSDNode>(N);
3027 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3028 /// match movlp{s|d}. The lower half elements should come from lower half of
3029 /// V1 (and in order), and the upper half elements should come from the upper
3030 /// half of V2 (and in order). And since V1 will become the source of the
3031 /// MOVLP, it must be either a vector load or a scalar load to vector.
3032 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3033 ShuffleVectorSDNode *Op) {
3034 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3036 // Is V2 is a vector load, don't do this transformation. We will try to use
3037 // load folding shufps op.
3038 if (ISD::isNON_EXTLoad(V2))
3041 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3043 if (NumElems != 2 && NumElems != 4)
3045 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3046 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3048 for (unsigned i = NumElems/2; i != NumElems; ++i)
3049 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3054 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3056 static bool isSplatVector(SDNode *N) {
3057 if (N->getOpcode() != ISD::BUILD_VECTOR)
3060 SDValue SplatValue = N->getOperand(0);
3061 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3062 if (N->getOperand(i) != SplatValue)
3067 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3068 /// to an zero vector.
3069 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3070 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3071 SDValue V1 = N->getOperand(0);
3072 SDValue V2 = N->getOperand(1);
3073 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3074 for (unsigned i = 0; i != NumElems; ++i) {
3075 int Idx = N->getMaskElt(i);
3076 if (Idx >= (int)NumElems) {
3077 unsigned Opc = V2.getOpcode();
3078 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3080 if (Opc != ISD::BUILD_VECTOR ||
3081 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3083 } else if (Idx >= 0) {
3084 unsigned Opc = V1.getOpcode();
3085 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3087 if (Opc != ISD::BUILD_VECTOR ||
3088 !X86::isZeroNode(V1.getOperand(Idx)))
3095 /// getZeroVector - Returns a vector of specified type with all zero elements.
3097 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3099 assert(VT.isVector() && "Expected a vector type");
3101 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3102 // type. This ensures they get CSE'd.
3104 if (VT.getSizeInBits() == 64) { // MMX
3105 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3106 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3107 } else if (HasSSE2) { // SSE2
3108 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3109 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3111 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3112 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3114 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3117 /// getOnesVector - Returns a vector of specified type with all bits set.
3119 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3120 assert(VT.isVector() && "Expected a vector type");
3122 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3123 // type. This ensures they get CSE'd.
3124 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3126 if (VT.getSizeInBits() == 64) // MMX
3127 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3129 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3130 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3134 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3135 /// that point to V2 points to its first element.
3136 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3137 EVT VT = SVOp->getValueType(0);
3138 unsigned NumElems = VT.getVectorNumElements();
3140 bool Changed = false;
3141 SmallVector<int, 8> MaskVec;
3142 SVOp->getMask(MaskVec);
3144 for (unsigned i = 0; i != NumElems; ++i) {
3145 if (MaskVec[i] > (int)NumElems) {
3146 MaskVec[i] = NumElems;
3151 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3152 SVOp->getOperand(1), &MaskVec[0]);
3153 return SDValue(SVOp, 0);
3156 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3157 /// operation of specified width.
3158 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3160 unsigned NumElems = VT.getVectorNumElements();
3161 SmallVector<int, 8> Mask;
3162 Mask.push_back(NumElems);
3163 for (unsigned i = 1; i != NumElems; ++i)
3165 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3168 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3169 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3171 unsigned NumElems = VT.getVectorNumElements();
3172 SmallVector<int, 8> Mask;
3173 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3175 Mask.push_back(i + NumElems);
3177 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3180 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3181 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3183 unsigned NumElems = VT.getVectorNumElements();
3184 unsigned Half = NumElems/2;
3185 SmallVector<int, 8> Mask;
3186 for (unsigned i = 0; i != Half; ++i) {
3187 Mask.push_back(i + Half);
3188 Mask.push_back(i + NumElems + Half);
3190 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3193 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3194 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3196 if (SV->getValueType(0).getVectorNumElements() <= 4)
3197 return SDValue(SV, 0);
3199 EVT PVT = MVT::v4f32;
3200 EVT VT = SV->getValueType(0);
3201 DebugLoc dl = SV->getDebugLoc();
3202 SDValue V1 = SV->getOperand(0);
3203 int NumElems = VT.getVectorNumElements();
3204 int EltNo = SV->getSplatIndex();
3206 // unpack elements to the correct location
3207 while (NumElems > 4) {
3208 if (EltNo < NumElems/2) {
3209 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3211 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3212 EltNo -= NumElems/2;
3217 // Perform the splat.
3218 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3219 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3220 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3221 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3224 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3225 /// vector of zero or undef vector. This produces a shuffle where the low
3226 /// element of V2 is swizzled into the zero/undef vector, landing at element
3227 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3228 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3229 bool isZero, bool HasSSE2,
3230 SelectionDAG &DAG) {
3231 EVT VT = V2.getValueType();
3233 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3234 unsigned NumElems = VT.getVectorNumElements();
3235 SmallVector<int, 16> MaskVec;
3236 for (unsigned i = 0; i != NumElems; ++i)
3237 // If this is the insertion idx, put the low elt of V2 here.
3238 MaskVec.push_back(i == Idx ? NumElems : i);
3239 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3242 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3243 /// a shuffle that is zero.
3245 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3246 bool Low, SelectionDAG &DAG) {
3247 unsigned NumZeros = 0;
3248 for (int i = 0; i < NumElems; ++i) {
3249 unsigned Index = Low ? i : NumElems-i-1;
3250 int Idx = SVOp->getMaskElt(Index);
3255 SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3256 if (Elt.getNode() && X86::isZeroNode(Elt))
3264 /// isVectorShift - Returns true if the shuffle can be implemented as a
3265 /// logical left or right shift of a vector.
3266 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3267 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3268 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3269 int NumElems = SVOp->getValueType(0).getVectorNumElements();
3272 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3275 NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3279 bool SeenV1 = false;
3280 bool SeenV2 = false;
3281 for (int i = NumZeros; i < NumElems; ++i) {
3282 int Val = isLeft ? (i - NumZeros) : i;
3283 int Idx = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3295 if (SeenV1 && SeenV2)
3298 ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3304 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3306 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3307 unsigned NumNonZero, unsigned NumZero,
3308 SelectionDAG &DAG, TargetLowering &TLI) {
3312 DebugLoc dl = Op.getDebugLoc();
3315 for (unsigned i = 0; i < 16; ++i) {
3316 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3317 if (ThisIsNonZero && First) {
3319 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3321 V = DAG.getUNDEF(MVT::v8i16);
3326 SDValue ThisElt(0, 0), LastElt(0, 0);
3327 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3328 if (LastIsNonZero) {
3329 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3330 MVT::i16, Op.getOperand(i-1));
3332 if (ThisIsNonZero) {
3333 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3334 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3335 ThisElt, DAG.getConstant(8, MVT::i8));
3337 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3341 if (ThisElt.getNode())
3342 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3343 DAG.getIntPtrConstant(i/2));
3347 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3350 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3352 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3353 unsigned NumNonZero, unsigned NumZero,
3354 SelectionDAG &DAG, TargetLowering &TLI) {
3358 DebugLoc dl = Op.getDebugLoc();
3361 for (unsigned i = 0; i < 8; ++i) {
3362 bool isNonZero = (NonZeros & (1 << i)) != 0;
3366 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3368 V = DAG.getUNDEF(MVT::v8i16);
3371 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3372 MVT::v8i16, V, Op.getOperand(i),
3373 DAG.getIntPtrConstant(i));
3380 /// getVShift - Return a vector logical shift node.
3382 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3383 unsigned NumBits, SelectionDAG &DAG,
3384 const TargetLowering &TLI, DebugLoc dl) {
3385 bool isMMX = VT.getSizeInBits() == 64;
3386 EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3387 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3388 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3389 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3390 DAG.getNode(Opc, dl, ShVT, SrcOp,
3391 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3395 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3396 SelectionDAG &DAG) {
3398 // Check if the scalar load can be widened into a vector load. And if
3399 // the address is "base + cst" see if the cst can be "absorbed" into
3400 // the shuffle mask.
3401 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3402 SDValue Ptr = LD->getBasePtr();
3403 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3405 EVT PVT = LD->getValueType(0);
3406 if (PVT != MVT::i32 && PVT != MVT::f32)
3411 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3412 FI = FINode->getIndex();
3414 } else if (Ptr.getOpcode() == ISD::ADD &&
3415 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
3416 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
3417 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
3418 Offset = Ptr.getConstantOperandVal(1);
3419 Ptr = Ptr.getOperand(0);
3424 SDValue Chain = LD->getChain();
3425 // Make sure the stack object alignment is at least 16.
3426 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3427 if (DAG.InferPtrAlignment(Ptr) < 16) {
3428 if (MFI->isFixedObjectIndex(FI)) {
3429 // Can't change the alignment. FIXME: It's possible to compute
3430 // the exact stack offset and reference FI + adjust offset instead.
3431 // If someone *really* cares about this. That's the way to implement it.
3434 MFI->setObjectAlignment(FI, 16);
3438 // (Offset % 16) must be multiple of 4. Then address is then
3439 // Ptr + (Offset & ~15).
3442 if ((Offset % 16) & 3)
3444 int64_t StartOffset = Offset & ~15;
3446 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
3447 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
3449 int EltNo = (Offset - StartOffset) >> 2;
3450 int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
3451 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
3452 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,LD->getSrcValue(),0);
3453 // Canonicalize it to a v4i32 shuffle.
3454 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
3455 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3456 DAG.getVectorShuffle(MVT::v4i32, dl, V1,
3457 DAG.getUNDEF(MVT::v4i32), &Mask[0]));
3464 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3465 DebugLoc dl = Op.getDebugLoc();
3466 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3467 if (ISD::isBuildVectorAllZeros(Op.getNode())
3468 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3469 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3470 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3471 // eliminated on x86-32 hosts.
3472 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3475 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3476 return getOnesVector(Op.getValueType(), DAG, dl);
3477 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3480 EVT VT = Op.getValueType();
3481 EVT ExtVT = VT.getVectorElementType();
3482 unsigned EVTBits = ExtVT.getSizeInBits();
3484 unsigned NumElems = Op.getNumOperands();
3485 unsigned NumZero = 0;
3486 unsigned NumNonZero = 0;
3487 unsigned NonZeros = 0;
3488 bool IsAllConstants = true;
3489 SmallSet<SDValue, 8> Values;
3490 for (unsigned i = 0; i < NumElems; ++i) {
3491 SDValue Elt = Op.getOperand(i);
3492 if (Elt.getOpcode() == ISD::UNDEF)
3495 if (Elt.getOpcode() != ISD::Constant &&
3496 Elt.getOpcode() != ISD::ConstantFP)
3497 IsAllConstants = false;
3498 if (X86::isZeroNode(Elt))
3501 NonZeros |= (1 << i);
3506 if (NumNonZero == 0) {
3507 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3508 return DAG.getUNDEF(VT);
3511 // Special case for single non-zero, non-undef, element.
3512 if (NumNonZero == 1) {
3513 unsigned Idx = CountTrailingZeros_32(NonZeros);
3514 SDValue Item = Op.getOperand(Idx);
3516 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3517 // the value are obviously zero, truncate the value to i32 and do the
3518 // insertion that way. Only do this if the value is non-constant or if the
3519 // value is a constant being inserted into element 0. It is cheaper to do
3520 // a constant pool load than it is to do a movd + shuffle.
3521 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3522 (!IsAllConstants || Idx == 0)) {
3523 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3524 // Handle MMX and SSE both.
3525 EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3526 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3528 // Truncate the value (which may itself be a constant) to i32, and
3529 // convert it to a vector with movd (S2V+shuffle to zero extend).
3530 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3531 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3532 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3533 Subtarget->hasSSE2(), DAG);
3535 // Now we have our 32-bit value zero extended in the low element of
3536 // a vector. If Idx != 0, swizzle it into place.
3538 SmallVector<int, 4> Mask;
3539 Mask.push_back(Idx);
3540 for (unsigned i = 1; i != VecElts; ++i)
3542 Item = DAG.getVectorShuffle(VecVT, dl, Item,
3543 DAG.getUNDEF(Item.getValueType()),
3546 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3550 // If we have a constant or non-constant insertion into the low element of
3551 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3552 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3553 // depending on what the source datatype is.
3556 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3557 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3558 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3559 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3560 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3561 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3563 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3564 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3565 EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3566 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3567 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3568 Subtarget->hasSSE2(), DAG);
3569 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3573 // Is it a vector logical left shift?
3574 if (NumElems == 2 && Idx == 1 &&
3575 X86::isZeroNode(Op.getOperand(0)) &&
3576 !X86::isZeroNode(Op.getOperand(1))) {
3577 unsigned NumBits = VT.getSizeInBits();
3578 return getVShift(true, VT,
3579 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3580 VT, Op.getOperand(1)),
3581 NumBits/2, DAG, *this, dl);
3584 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3587 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3588 // is a non-constant being inserted into an element other than the low one,
3589 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3590 // movd/movss) to move this into the low element, then shuffle it into
3592 if (EVTBits == 32) {
3593 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3595 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3596 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3597 Subtarget->hasSSE2(), DAG);
3598 SmallVector<int, 8> MaskVec;
3599 for (unsigned i = 0; i < NumElems; i++)
3600 MaskVec.push_back(i == Idx ? 0 : 1);
3601 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3605 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3606 if (Values.size() == 1) {
3607 if (EVTBits == 32) {
3608 // Instead of a shuffle like this:
3609 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
3610 // Check if it's possible to issue this instead.
3611 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
3612 unsigned Idx = CountTrailingZeros_32(NonZeros);
3613 SDValue Item = Op.getOperand(Idx);
3614 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
3615 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
3620 // A vector full of immediates; various special cases are already
3621 // handled, so this is best done with a single constant-pool load.
3625 // Let legalizer expand 2-wide build_vectors.
3626 if (EVTBits == 64) {
3627 if (NumNonZero == 1) {
3628 // One half is zero or undef.
3629 unsigned Idx = CountTrailingZeros_32(NonZeros);
3630 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3631 Op.getOperand(Idx));
3632 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3633 Subtarget->hasSSE2(), DAG);
3638 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3639 if (EVTBits == 8 && NumElems == 16) {
3640 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3642 if (V.getNode()) return V;
3645 if (EVTBits == 16 && NumElems == 8) {
3646 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3648 if (V.getNode()) return V;
3651 // If element VT is == 32 bits, turn it into a number of shuffles.
3652 SmallVector<SDValue, 8> V;
3654 if (NumElems == 4 && NumZero > 0) {
3655 for (unsigned i = 0; i < 4; ++i) {
3656 bool isZero = !(NonZeros & (1 << i));
3658 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3660 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3663 for (unsigned i = 0; i < 2; ++i) {
3664 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3667 V[i] = V[i*2]; // Must be a zero vector.
3670 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3673 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3676 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3681 SmallVector<int, 8> MaskVec;
3682 bool Reverse = (NonZeros & 0x3) == 2;
3683 for (unsigned i = 0; i < 2; ++i)
3684 MaskVec.push_back(Reverse ? 1-i : i);
3685 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3686 for (unsigned i = 0; i < 2; ++i)
3687 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3688 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3691 if (Values.size() > 2) {
3692 // If we have SSE 4.1, Expand into a number of inserts unless the number of
3693 // values to be inserted is equal to the number of elements, in which case
3694 // use the unpack code below in the hopes of matching the consecutive elts
3695 // load merge pattern for shuffles.
3696 // FIXME: We could probably just check that here directly.
3697 if (Values.size() < NumElems && VT.getSizeInBits() == 128 &&
3698 getSubtarget()->hasSSE41()) {
3699 V[0] = DAG.getUNDEF(VT);
3700 for (unsigned i = 0; i < NumElems; ++i)
3701 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3702 V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3703 Op.getOperand(i), DAG.getIntPtrConstant(i));
3706 // Expand into a number of unpckl*.
3708 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3709 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3710 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3711 for (unsigned i = 0; i < NumElems; ++i)
3712 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3714 while (NumElems != 0) {
3715 for (unsigned i = 0; i < NumElems; ++i)
3716 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3726 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
3727 // We support concatenate two MMX registers and place them in a MMX
3728 // register. This is better than doing a stack convert.
3729 DebugLoc dl = Op.getDebugLoc();
3730 EVT ResVT = Op.getValueType();
3731 assert(Op.getNumOperands() == 2);
3732 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
3733 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
3735 SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
3736 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
3737 InVec = Op.getOperand(1);
3738 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
3739 unsigned NumElts = ResVT.getVectorNumElements();
3740 VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
3741 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
3742 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
3744 InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
3745 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
3746 Mask[0] = 0; Mask[1] = 2;
3747 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
3749 return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
3752 // v8i16 shuffles - Prefer shuffles in the following order:
3753 // 1. [all] pshuflw, pshufhw, optional move
3754 // 2. [ssse3] 1 x pshufb
3755 // 3. [ssse3] 2 x pshufb + 1 x por
3756 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
3758 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
3759 SelectionDAG &DAG, X86TargetLowering &TLI) {
3760 SDValue V1 = SVOp->getOperand(0);
3761 SDValue V2 = SVOp->getOperand(1);
3762 DebugLoc dl = SVOp->getDebugLoc();
3763 SmallVector<int, 8> MaskVals;
3765 // Determine if more than 1 of the words in each of the low and high quadwords
3766 // of the result come from the same quadword of one of the two inputs. Undef
3767 // mask values count as coming from any quadword, for better codegen.
3768 SmallVector<unsigned, 4> LoQuad(4);
3769 SmallVector<unsigned, 4> HiQuad(4);
3770 BitVector InputQuads(4);
3771 for (unsigned i = 0; i < 8; ++i) {
3772 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
3773 int EltIdx = SVOp->getMaskElt(i);
3774 MaskVals.push_back(EltIdx);
3783 InputQuads.set(EltIdx / 4);
3786 int BestLoQuad = -1;
3787 unsigned MaxQuad = 1;
3788 for (unsigned i = 0; i < 4; ++i) {
3789 if (LoQuad[i] > MaxQuad) {
3791 MaxQuad = LoQuad[i];
3795 int BestHiQuad = -1;
3797 for (unsigned i = 0; i < 4; ++i) {
3798 if (HiQuad[i] > MaxQuad) {
3800 MaxQuad = HiQuad[i];
3804 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
3805 // of the two input vectors, shuffle them into one input vector so only a
3806 // single pshufb instruction is necessary. If There are more than 2 input
3807 // quads, disable the next transformation since it does not help SSSE3.
3808 bool V1Used = InputQuads[0] || InputQuads[1];
3809 bool V2Used = InputQuads[2] || InputQuads[3];
3810 if (TLI.getSubtarget()->hasSSSE3()) {
3811 if (InputQuads.count() == 2 && V1Used && V2Used) {
3812 BestLoQuad = InputQuads.find_first();
3813 BestHiQuad = InputQuads.find_next(BestLoQuad);
3815 if (InputQuads.count() > 2) {
3821 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
3822 // the shuffle mask. If a quad is scored as -1, that means that it contains
3823 // words from all 4 input quadwords.
3825 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
3826 SmallVector<int, 8> MaskV;
3827 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
3828 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
3829 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
3830 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
3831 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
3832 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
3834 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
3835 // source words for the shuffle, to aid later transformations.
3836 bool AllWordsInNewV = true;
3837 bool InOrder[2] = { true, true };
3838 for (unsigned i = 0; i != 8; ++i) {
3839 int idx = MaskVals[i];
3841 InOrder[i/4] = false;
3842 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
3844 AllWordsInNewV = false;
3848 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
3849 if (AllWordsInNewV) {
3850 for (int i = 0; i != 8; ++i) {
3851 int idx = MaskVals[i];
3854 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
3855 if ((idx != i) && idx < 4)
3857 if ((idx != i) && idx > 3)
3866 // If we've eliminated the use of V2, and the new mask is a pshuflw or
3867 // pshufhw, that's as cheap as it gets. Return the new shuffle.
3868 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
3869 return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
3870 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
3874 // If we have SSSE3, and all words of the result are from 1 input vector,
3875 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
3876 // is present, fall back to case 4.
3877 if (TLI.getSubtarget()->hasSSSE3()) {
3878 SmallVector<SDValue,16> pshufbMask;
3880 // If we have elements from both input vectors, set the high bit of the
3881 // shuffle mask element to zero out elements that come from V2 in the V1
3882 // mask, and elements that come from V1 in the V2 mask, so that the two
3883 // results can be OR'd together.
3884 bool TwoInputs = V1Used && V2Used;
3885 for (unsigned i = 0; i != 8; ++i) {
3886 int EltIdx = MaskVals[i] * 2;
3887 if (TwoInputs && (EltIdx >= 16)) {
3888 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3889 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3892 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3893 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
3895 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
3896 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3897 DAG.getNode(ISD::BUILD_VECTOR, dl,
3898 MVT::v16i8, &pshufbMask[0], 16));
3900 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3902 // Calculate the shuffle mask for the second input, shuffle it, and
3903 // OR it with the first shuffled input.
3905 for (unsigned i = 0; i != 8; ++i) {
3906 int EltIdx = MaskVals[i] * 2;
3908 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3909 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3912 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3913 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
3915 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
3916 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3917 DAG.getNode(ISD::BUILD_VECTOR, dl,
3918 MVT::v16i8, &pshufbMask[0], 16));
3919 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3920 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3923 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
3924 // and update MaskVals with new element order.
3925 BitVector InOrder(8);
3926 if (BestLoQuad >= 0) {
3927 SmallVector<int, 8> MaskV;
3928 for (int i = 0; i != 4; ++i) {
3929 int idx = MaskVals[i];
3931 MaskV.push_back(-1);
3933 } else if ((idx / 4) == BestLoQuad) {
3934 MaskV.push_back(idx & 3);
3937 MaskV.push_back(-1);
3940 for (unsigned i = 4; i != 8; ++i)
3942 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3946 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
3947 // and update MaskVals with the new element order.
3948 if (BestHiQuad >= 0) {
3949 SmallVector<int, 8> MaskV;
3950 for (unsigned i = 0; i != 4; ++i)
3952 for (unsigned i = 4; i != 8; ++i) {
3953 int idx = MaskVals[i];
3955 MaskV.push_back(-1);
3957 } else if ((idx / 4) == BestHiQuad) {
3958 MaskV.push_back((idx & 3) + 4);
3961 MaskV.push_back(-1);
3964 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3968 // In case BestHi & BestLo were both -1, which means each quadword has a word
3969 // from each of the four input quadwords, calculate the InOrder bitvector now
3970 // before falling through to the insert/extract cleanup.
3971 if (BestLoQuad == -1 && BestHiQuad == -1) {
3973 for (int i = 0; i != 8; ++i)
3974 if (MaskVals[i] < 0 || MaskVals[i] == i)
3978 // The other elements are put in the right place using pextrw and pinsrw.
3979 for (unsigned i = 0; i != 8; ++i) {
3982 int EltIdx = MaskVals[i];
3985 SDValue ExtOp = (EltIdx < 8)
3986 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
3987 DAG.getIntPtrConstant(EltIdx))
3988 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
3989 DAG.getIntPtrConstant(EltIdx - 8));
3990 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3991 DAG.getIntPtrConstant(i));
3996 // v16i8 shuffles - Prefer shuffles in the following order:
3997 // 1. [ssse3] 1 x pshufb
3998 // 2. [ssse3] 2 x pshufb + 1 x por
3999 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
4001 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4002 SelectionDAG &DAG, X86TargetLowering &TLI) {
4003 SDValue V1 = SVOp->getOperand(0);
4004 SDValue V2 = SVOp->getOperand(1);
4005 DebugLoc dl = SVOp->getDebugLoc();
4006 SmallVector<int, 16> MaskVals;
4007 SVOp->getMask(MaskVals);
4009 // If we have SSSE3, case 1 is generated when all result bytes come from
4010 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
4011 // present, fall back to case 3.
4012 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4015 for (unsigned i = 0; i < 16; ++i) {
4016 int EltIdx = MaskVals[i];
4025 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4026 if (TLI.getSubtarget()->hasSSSE3()) {
4027 SmallVector<SDValue,16> pshufbMask;
4029 // If all result elements are from one input vector, then only translate
4030 // undef mask values to 0x80 (zero out result) in the pshufb mask.
4032 // Otherwise, we have elements from both input vectors, and must zero out
4033 // elements that come from V2 in the first mask, and V1 in the second mask
4034 // so that we can OR them together.
4035 bool TwoInputs = !(V1Only || V2Only);
4036 for (unsigned i = 0; i != 16; ++i) {
4037 int EltIdx = MaskVals[i];
4038 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4039 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4042 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4044 // If all the elements are from V2, assign it to V1 and return after
4045 // building the first pshufb.
4048 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4049 DAG.getNode(ISD::BUILD_VECTOR, dl,
4050 MVT::v16i8, &pshufbMask[0], 16));
4054 // Calculate the shuffle mask for the second input, shuffle it, and
4055 // OR it with the first shuffled input.
4057 for (unsigned i = 0; i != 16; ++i) {
4058 int EltIdx = MaskVals[i];
4060 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4063 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4065 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4066 DAG.getNode(ISD::BUILD_VECTOR, dl,
4067 MVT::v16i8, &pshufbMask[0], 16));
4068 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4071 // No SSSE3 - Calculate in place words and then fix all out of place words
4072 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
4073 // the 16 different words that comprise the two doublequadword input vectors.
4074 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4075 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4076 SDValue NewV = V2Only ? V2 : V1;
4077 for (int i = 0; i != 8; ++i) {
4078 int Elt0 = MaskVals[i*2];
4079 int Elt1 = MaskVals[i*2+1];
4081 // This word of the result is all undef, skip it.
4082 if (Elt0 < 0 && Elt1 < 0)
4085 // This word of the result is already in the correct place, skip it.
4086 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4088 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4091 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4092 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4095 // If Elt0 and Elt1 are defined, are consecutive, and can be load
4096 // using a single extract together, load it and store it.
4097 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4098 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4099 DAG.getIntPtrConstant(Elt1 / 2));
4100 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4101 DAG.getIntPtrConstant(i));
4105 // If Elt1 is defined, extract it from the appropriate source. If the
4106 // source byte is not also odd, shift the extracted word left 8 bits
4107 // otherwise clear the bottom 8 bits if we need to do an or.
4109 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4110 DAG.getIntPtrConstant(Elt1 / 2));
4111 if ((Elt1 & 1) == 0)
4112 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4113 DAG.getConstant(8, TLI.getShiftAmountTy()));
4115 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4116 DAG.getConstant(0xFF00, MVT::i16));
4118 // If Elt0 is defined, extract it from the appropriate source. If the
4119 // source byte is not also even, shift the extracted word right 8 bits. If
4120 // Elt1 was also defined, OR the extracted values together before
4121 // inserting them in the result.
4123 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4124 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4125 if ((Elt0 & 1) != 0)
4126 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4127 DAG.getConstant(8, TLI.getShiftAmountTy()));
4129 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4130 DAG.getConstant(0x00FF, MVT::i16));
4131 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4134 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4135 DAG.getIntPtrConstant(i));
4137 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4140 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4141 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
4142 /// done when every pair / quad of shuffle mask elements point to elements in
4143 /// the right sequence. e.g.
4144 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
4146 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4148 TargetLowering &TLI, DebugLoc dl) {
4149 EVT VT = SVOp->getValueType(0);
4150 SDValue V1 = SVOp->getOperand(0);
4151 SDValue V2 = SVOp->getOperand(1);
4152 unsigned NumElems = VT.getVectorNumElements();
4153 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4154 EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
4155 EVT MaskEltVT = MaskVT.getVectorElementType();
4157 switch (VT.getSimpleVT().SimpleTy) {
4158 default: assert(false && "Unexpected!");
4159 case MVT::v4f32: NewVT = MVT::v2f64; break;
4160 case MVT::v4i32: NewVT = MVT::v2i64; break;
4161 case MVT::v8i16: NewVT = MVT::v4i32; break;
4162 case MVT::v16i8: NewVT = MVT::v4i32; break;
4165 if (NewWidth == 2) {
4171 int Scale = NumElems / NewWidth;
4172 SmallVector<int, 8> MaskVec;
4173 for (unsigned i = 0; i < NumElems; i += Scale) {
4175 for (int j = 0; j < Scale; ++j) {
4176 int EltIdx = SVOp->getMaskElt(i+j);
4180 StartIdx = EltIdx - (EltIdx % Scale);
4181 if (EltIdx != StartIdx + j)
4185 MaskVec.push_back(-1);
4187 MaskVec.push_back(StartIdx / Scale);
4190 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4191 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4192 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4195 /// getVZextMovL - Return a zero-extending vector move low node.
4197 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4198 SDValue SrcOp, SelectionDAG &DAG,
4199 const X86Subtarget *Subtarget, DebugLoc dl) {
4200 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4201 LoadSDNode *LD = NULL;
4202 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4203 LD = dyn_cast<LoadSDNode>(SrcOp);
4205 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4207 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4208 if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4209 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4210 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4211 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4213 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4214 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4215 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4216 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4224 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4225 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4226 DAG.getNode(ISD::BIT_CONVERT, dl,
4230 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4233 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4234 SDValue V1 = SVOp->getOperand(0);
4235 SDValue V2 = SVOp->getOperand(1);
4236 DebugLoc dl = SVOp->getDebugLoc();
4237 EVT VT = SVOp->getValueType(0);
4239 SmallVector<std::pair<int, int>, 8> Locs;
4241 SmallVector<int, 8> Mask1(4U, -1);
4242 SmallVector<int, 8> PermMask;
4243 SVOp->getMask(PermMask);
4247 for (unsigned i = 0; i != 4; ++i) {
4248 int Idx = PermMask[i];
4250 Locs[i] = std::make_pair(-1, -1);
4252 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4254 Locs[i] = std::make_pair(0, NumLo);
4258 Locs[i] = std::make_pair(1, NumHi);
4260 Mask1[2+NumHi] = Idx;
4266 if (NumLo <= 2 && NumHi <= 2) {
4267 // If no more than two elements come from either vector. This can be
4268 // implemented with two shuffles. First shuffle gather the elements.
4269 // The second shuffle, which takes the first shuffle as both of its
4270 // vector operands, put the elements into the right order.
4271 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4273 SmallVector<int, 8> Mask2(4U, -1);
4275 for (unsigned i = 0; i != 4; ++i) {
4276 if (Locs[i].first == -1)
4279 unsigned Idx = (i < 2) ? 0 : 4;
4280 Idx += Locs[i].first * 2 + Locs[i].second;
4285 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4286 } else if (NumLo == 3 || NumHi == 3) {
4287 // Otherwise, we must have three elements from one vector, call it X, and
4288 // one element from the other, call it Y. First, use a shufps to build an
4289 // intermediate vector with the one element from Y and the element from X
4290 // that will be in the same half in the final destination (the indexes don't
4291 // matter). Then, use a shufps to build the final vector, taking the half
4292 // containing the element from Y from the intermediate, and the other half
4295 // Normalize it so the 3 elements come from V1.
4296 CommuteVectorShuffleMask(PermMask, VT);
4300 // Find the element from V2.
4302 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4303 int Val = PermMask[HiIndex];
4310 Mask1[0] = PermMask[HiIndex];
4312 Mask1[2] = PermMask[HiIndex^1];
4314 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4317 Mask1[0] = PermMask[0];
4318 Mask1[1] = PermMask[1];
4319 Mask1[2] = HiIndex & 1 ? 6 : 4;
4320 Mask1[3] = HiIndex & 1 ? 4 : 6;
4321 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4323 Mask1[0] = HiIndex & 1 ? 2 : 0;
4324 Mask1[1] = HiIndex & 1 ? 0 : 2;
4325 Mask1[2] = PermMask[2];
4326 Mask1[3] = PermMask[3];
4331 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4335 // Break it into (shuffle shuffle_hi, shuffle_lo).
4337 SmallVector<int,8> LoMask(4U, -1);
4338 SmallVector<int,8> HiMask(4U, -1);
4340 SmallVector<int,8> *MaskPtr = &LoMask;
4341 unsigned MaskIdx = 0;
4344 for (unsigned i = 0; i != 4; ++i) {
4351 int Idx = PermMask[i];
4353 Locs[i] = std::make_pair(-1, -1);
4354 } else if (Idx < 4) {
4355 Locs[i] = std::make_pair(MaskIdx, LoIdx);
4356 (*MaskPtr)[LoIdx] = Idx;
4359 Locs[i] = std::make_pair(MaskIdx, HiIdx);
4360 (*MaskPtr)[HiIdx] = Idx;
4365 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4366 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4367 SmallVector<int, 8> MaskOps;
4368 for (unsigned i = 0; i != 4; ++i) {
4369 if (Locs[i].first == -1) {
4370 MaskOps.push_back(-1);
4372 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4373 MaskOps.push_back(Idx);
4376 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4380 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4381 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4382 SDValue V1 = Op.getOperand(0);
4383 SDValue V2 = Op.getOperand(1);
4384 EVT VT = Op.getValueType();
4385 DebugLoc dl = Op.getDebugLoc();
4386 unsigned NumElems = VT.getVectorNumElements();
4387 bool isMMX = VT.getSizeInBits() == 64;
4388 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4389 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4390 bool V1IsSplat = false;
4391 bool V2IsSplat = false;
4393 if (isZeroShuffle(SVOp))
4394 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4396 // Promote splats to v4f32.
4397 if (SVOp->isSplat()) {
4398 if (isMMX || NumElems < 4)
4400 return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4403 // If the shuffle can be profitably rewritten as a narrower shuffle, then
4405 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4406 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4407 if (NewOp.getNode())
4408 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4409 LowerVECTOR_SHUFFLE(NewOp, DAG));
4410 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4411 // FIXME: Figure out a cleaner way to do this.
4412 // Try to make use of movq to zero out the top part.
4413 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4414 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4415 if (NewOp.getNode()) {
4416 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4417 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4418 DAG, Subtarget, dl);
4420 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4421 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4422 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4423 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4424 DAG, Subtarget, dl);
4428 if (X86::isPSHUFDMask(SVOp))
4431 // Check if this can be converted into a logical shift.
4432 bool isLeft = false;
4435 bool isShift = getSubtarget()->hasSSE2() &&
4436 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4437 if (isShift && ShVal.hasOneUse()) {
4438 // If the shifted value has multiple uses, it may be cheaper to use
4439 // v_set0 + movlhps or movhlps, etc.
4440 EVT EltVT = VT.getVectorElementType();
4441 ShAmt *= EltVT.getSizeInBits();
4442 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4445 if (X86::isMOVLMask(SVOp)) {
4448 if (ISD::isBuildVectorAllZeros(V1.getNode()))
4449 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4454 // FIXME: fold these into legal mask.
4455 if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4456 X86::isMOVSLDUPMask(SVOp) ||
4457 X86::isMOVHLPSMask(SVOp) ||
4458 X86::isMOVLHPSMask(SVOp) ||
4459 X86::isMOVLPMask(SVOp)))
4462 if (ShouldXformToMOVHLPS(SVOp) ||
4463 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4464 return CommuteVectorShuffle(SVOp, DAG);
4467 // No better options. Use a vshl / vsrl.
4468 EVT EltVT = VT.getVectorElementType();
4469 ShAmt *= EltVT.getSizeInBits();
4470 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4473 bool Commuted = false;
4474 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4475 // 1,1,1,1 -> v8i16 though.
4476 V1IsSplat = isSplatVector(V1.getNode());
4477 V2IsSplat = isSplatVector(V2.getNode());
4479 // Canonicalize the splat or undef, if present, to be on the RHS.
4480 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4481 Op = CommuteVectorShuffle(SVOp, DAG);
4482 SVOp = cast<ShuffleVectorSDNode>(Op);
4483 V1 = SVOp->getOperand(0);
4484 V2 = SVOp->getOperand(1);
4485 std::swap(V1IsSplat, V2IsSplat);
4486 std::swap(V1IsUndef, V2IsUndef);
4490 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4491 // Shuffling low element of v1 into undef, just return v1.
4494 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4495 // the instruction selector will not match, so get a canonical MOVL with
4496 // swapped operands to undo the commute.
4497 return getMOVL(DAG, dl, VT, V2, V1);
4500 if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4501 X86::isUNPCKH_v_undef_Mask(SVOp) ||
4502 X86::isUNPCKLMask(SVOp) ||
4503 X86::isUNPCKHMask(SVOp))
4507 // Normalize mask so all entries that point to V2 points to its first
4508 // element then try to match unpck{h|l} again. If match, return a
4509 // new vector_shuffle with the corrected mask.
4510 SDValue NewMask = NormalizeMask(SVOp, DAG);
4511 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4512 if (NSVOp != SVOp) {
4513 if (X86::isUNPCKLMask(NSVOp, true)) {
4515 } else if (X86::isUNPCKHMask(NSVOp, true)) {
4522 // Commute is back and try unpck* again.
4523 // FIXME: this seems wrong.
4524 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4525 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4526 if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4527 X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4528 X86::isUNPCKLMask(NewSVOp) ||
4529 X86::isUNPCKHMask(NewSVOp))
4533 // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4535 // Normalize the node to match x86 shuffle ops if needed
4536 if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4537 return CommuteVectorShuffle(SVOp, DAG);
4539 // Check for legal shuffle and return?
4540 SmallVector<int, 16> PermMask;
4541 SVOp->getMask(PermMask);
4542 if (isShuffleMaskLegal(PermMask, VT))
4545 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4546 if (VT == MVT::v8i16) {
4547 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4548 if (NewOp.getNode())
4552 if (VT == MVT::v16i8) {
4553 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4554 if (NewOp.getNode())
4558 // Handle all 4 wide cases with a number of shuffles except for MMX.
4559 if (NumElems == 4 && !isMMX)
4560 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4566 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4567 SelectionDAG &DAG) {
4568 EVT VT = Op.getValueType();
4569 DebugLoc dl = Op.getDebugLoc();
4570 if (VT.getSizeInBits() == 8) {
4571 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4572 Op.getOperand(0), Op.getOperand(1));
4573 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4574 DAG.getValueType(VT));
4575 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4576 } else if (VT.getSizeInBits() == 16) {
4577 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4578 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4580 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4581 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4582 DAG.getNode(ISD::BIT_CONVERT, dl,
4586 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4587 Op.getOperand(0), Op.getOperand(1));
4588 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4589 DAG.getValueType(VT));
4590 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4591 } else if (VT == MVT::f32) {
4592 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4593 // the result back to FR32 register. It's only worth matching if the
4594 // result has a single use which is a store or a bitcast to i32. And in
4595 // the case of a store, it's not worth it if the index is a constant 0,
4596 // because a MOVSSmr can be used instead, which is smaller and faster.
4597 if (!Op.hasOneUse())
4599 SDNode *User = *Op.getNode()->use_begin();
4600 if ((User->getOpcode() != ISD::STORE ||
4601 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4602 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4603 (User->getOpcode() != ISD::BIT_CONVERT ||
4604 User->getValueType(0) != MVT::i32))
4606 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4607 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4610 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4611 } else if (VT == MVT::i32) {
4612 // ExtractPS works with constant index.
4613 if (isa<ConstantSDNode>(Op.getOperand(1)))
4621 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4622 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4625 if (Subtarget->hasSSE41()) {
4626 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4631 EVT VT = Op.getValueType();
4632 DebugLoc dl = Op.getDebugLoc();
4633 // TODO: handle v16i8.
4634 if (VT.getSizeInBits() == 16) {
4635 SDValue Vec = Op.getOperand(0);
4636 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4638 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4639 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4640 DAG.getNode(ISD::BIT_CONVERT, dl,
4643 // Transform it so it match pextrw which produces a 32-bit result.
4644 EVT EltVT = MVT::i32;
4645 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
4646 Op.getOperand(0), Op.getOperand(1));
4647 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
4648 DAG.getValueType(VT));
4649 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4650 } else if (VT.getSizeInBits() == 32) {
4651 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4655 // SHUFPS the element to the lowest double word, then movss.
4656 int Mask[4] = { Idx, -1, -1, -1 };
4657 EVT VVT = Op.getOperand(0).getValueType();
4658 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4659 DAG.getUNDEF(VVT), Mask);
4660 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4661 DAG.getIntPtrConstant(0));
4662 } else if (VT.getSizeInBits() == 64) {
4663 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4664 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4665 // to match extract_elt for f64.
4666 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4670 // UNPCKHPD the element to the lowest double word, then movsd.
4671 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4672 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4673 int Mask[2] = { 1, -1 };
4674 EVT VVT = Op.getOperand(0).getValueType();
4675 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4676 DAG.getUNDEF(VVT), Mask);
4677 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4678 DAG.getIntPtrConstant(0));
4685 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4686 EVT VT = Op.getValueType();
4687 EVT EltVT = VT.getVectorElementType();
4688 DebugLoc dl = Op.getDebugLoc();
4690 SDValue N0 = Op.getOperand(0);
4691 SDValue N1 = Op.getOperand(1);
4692 SDValue N2 = Op.getOperand(2);
4694 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
4695 isa<ConstantSDNode>(N2)) {
4696 unsigned Opc = (EltVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4698 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4700 if (N1.getValueType() != MVT::i32)
4701 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4702 if (N2.getValueType() != MVT::i32)
4703 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4704 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4705 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4706 // Bits [7:6] of the constant are the source select. This will always be
4707 // zero here. The DAG Combiner may combine an extract_elt index into these
4708 // bits. For example (insert (extract, 3), 2) could be matched by putting
4709 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4710 // Bits [5:4] of the constant are the destination select. This is the
4711 // value of the incoming immediate.
4712 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4713 // combine either bitwise AND or insert of float 0.0 to set these bits.
4714 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4715 // Create this as a scalar to vector..
4716 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
4717 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4718 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
4719 // PINSR* works with constant index.
4726 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4727 EVT VT = Op.getValueType();
4728 EVT EltVT = VT.getVectorElementType();
4730 if (Subtarget->hasSSE41())
4731 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4733 if (EltVT == MVT::i8)
4736 DebugLoc dl = Op.getDebugLoc();
4737 SDValue N0 = Op.getOperand(0);
4738 SDValue N1 = Op.getOperand(1);
4739 SDValue N2 = Op.getOperand(2);
4741 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
4742 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4743 // as its second argument.
4744 if (N1.getValueType() != MVT::i32)
4745 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4746 if (N2.getValueType() != MVT::i32)
4747 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4748 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
4754 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4755 DebugLoc dl = Op.getDebugLoc();
4756 if (Op.getValueType() == MVT::v2f32)
4757 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4758 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4759 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4760 Op.getOperand(0))));
4762 if (Op.getValueType() == MVT::v1i64 && Op.getOperand(0).getValueType() == MVT::i64)
4763 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
4765 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4766 EVT VT = MVT::v2i32;
4767 switch (Op.getValueType().getSimpleVT().SimpleTy) {
4774 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4775 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4778 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4779 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4780 // one of the above mentioned nodes. It has to be wrapped because otherwise
4781 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4782 // be used to form addressing mode. These wrapped nodes will be selected
4785 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4786 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4788 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4790 unsigned char OpFlag = 0;
4791 unsigned WrapperKind = X86ISD::Wrapper;
4792 CodeModel::Model M = getTargetMachine().getCodeModel();
4794 if (Subtarget->isPICStyleRIPRel() &&
4795 (M == CodeModel::Small || M == CodeModel::Kernel))
4796 WrapperKind = X86ISD::WrapperRIP;
4797 else if (Subtarget->isPICStyleGOT())
4798 OpFlag = X86II::MO_GOTOFF;
4799 else if (Subtarget->isPICStyleStubPIC())
4800 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4802 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
4804 CP->getOffset(), OpFlag);
4805 DebugLoc DL = CP->getDebugLoc();
4806 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4807 // With PIC, the address is actually $g + Offset.
4809 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4810 DAG.getNode(X86ISD::GlobalBaseReg,
4811 DebugLoc::getUnknownLoc(), getPointerTy()),
4818 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4819 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4821 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4823 unsigned char OpFlag = 0;
4824 unsigned WrapperKind = X86ISD::Wrapper;
4825 CodeModel::Model M = getTargetMachine().getCodeModel();
4827 if (Subtarget->isPICStyleRIPRel() &&
4828 (M == CodeModel::Small || M == CodeModel::Kernel))
4829 WrapperKind = X86ISD::WrapperRIP;
4830 else if (Subtarget->isPICStyleGOT())
4831 OpFlag = X86II::MO_GOTOFF;
4832 else if (Subtarget->isPICStyleStubPIC())
4833 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4835 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
4837 DebugLoc DL = JT->getDebugLoc();
4838 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4840 // With PIC, the address is actually $g + Offset.
4842 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4843 DAG.getNode(X86ISD::GlobalBaseReg,
4844 DebugLoc::getUnknownLoc(), getPointerTy()),
4852 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4853 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4855 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4857 unsigned char OpFlag = 0;
4858 unsigned WrapperKind = X86ISD::Wrapper;
4859 CodeModel::Model M = getTargetMachine().getCodeModel();
4861 if (Subtarget->isPICStyleRIPRel() &&
4862 (M == CodeModel::Small || M == CodeModel::Kernel))
4863 WrapperKind = X86ISD::WrapperRIP;
4864 else if (Subtarget->isPICStyleGOT())
4865 OpFlag = X86II::MO_GOTOFF;
4866 else if (Subtarget->isPICStyleStubPIC())
4867 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4869 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
4871 DebugLoc DL = Op.getDebugLoc();
4872 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4875 // With PIC, the address is actually $g + Offset.
4876 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4877 !Subtarget->is64Bit()) {
4878 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4879 DAG.getNode(X86ISD::GlobalBaseReg,
4880 DebugLoc::getUnknownLoc(),
4889 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) {
4890 // Create the TargetBlockAddressAddress node.
4891 unsigned char OpFlags =
4892 Subtarget->ClassifyBlockAddressReference();
4893 CodeModel::Model M = getTargetMachine().getCodeModel();
4894 BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
4895 DebugLoc dl = Op.getDebugLoc();
4896 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
4897 /*isTarget=*/true, OpFlags);
4899 if (Subtarget->isPICStyleRIPRel() &&
4900 (M == CodeModel::Small || M == CodeModel::Kernel))
4901 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
4903 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4905 // With PIC, the address is actually $g + Offset.
4906 if (isGlobalRelativeToPICBase(OpFlags)) {
4907 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4908 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4916 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
4918 SelectionDAG &DAG) const {
4919 // Create the TargetGlobalAddress node, folding in the constant
4920 // offset if it is legal.
4921 unsigned char OpFlags =
4922 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
4923 CodeModel::Model M = getTargetMachine().getCodeModel();
4925 if (OpFlags == X86II::MO_NO_FLAG &&
4926 X86::isOffsetSuitableForCodeModel(Offset, M)) {
4927 // A direct static reference to a global.
4928 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4931 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
4934 if (Subtarget->isPICStyleRIPRel() &&
4935 (M == CodeModel::Small || M == CodeModel::Kernel))
4936 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
4938 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4940 // With PIC, the address is actually $g + Offset.
4941 if (isGlobalRelativeToPICBase(OpFlags)) {
4942 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4943 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4947 // For globals that require a load from a stub to get the address, emit the
4949 if (isGlobalStubReference(OpFlags))
4950 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
4951 PseudoSourceValue::getGOT(), 0);
4953 // If there was a non-zero offset that we didn't fold, create an explicit
4956 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
4957 DAG.getConstant(Offset, getPointerTy()));
4963 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4964 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4965 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4966 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
4970 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
4971 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
4972 unsigned char OperandFlags) {
4973 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4974 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4975 DebugLoc dl = GA->getDebugLoc();
4976 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4977 GA->getValueType(0),
4981 SDValue Ops[] = { Chain, TGA, *InFlag };
4982 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
4984 SDValue Ops[] = { Chain, TGA };
4985 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
4988 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
4989 MFI->setHasCalls(true);
4991 SDValue Flag = Chain.getValue(1);
4992 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
4995 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4997 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5000 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
5001 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
5002 DAG.getNode(X86ISD::GlobalBaseReg,
5003 DebugLoc::getUnknownLoc(),
5005 InFlag = Chain.getValue(1);
5007 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
5010 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
5012 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5014 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
5015 X86::RAX, X86II::MO_TLSGD);
5018 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
5019 // "local exec" model.
5020 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5021 const EVT PtrVT, TLSModel::Model model,
5023 DebugLoc dl = GA->getDebugLoc();
5024 // Get the Thread Pointer
5025 SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
5026 DebugLoc::getUnknownLoc(), PtrVT,
5027 DAG.getRegister(is64Bit? X86::FS : X86::GS,
5030 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
5033 unsigned char OperandFlags = 0;
5034 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
5036 unsigned WrapperKind = X86ISD::Wrapper;
5037 if (model == TLSModel::LocalExec) {
5038 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
5039 } else if (is64Bit) {
5040 assert(model == TLSModel::InitialExec);
5041 OperandFlags = X86II::MO_GOTTPOFF;
5042 WrapperKind = X86ISD::WrapperRIP;
5044 assert(model == TLSModel::InitialExec);
5045 OperandFlags = X86II::MO_INDNTPOFF;
5048 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
5050 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
5051 GA->getOffset(), OperandFlags);
5052 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
5054 if (model == TLSModel::InitialExec)
5055 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
5056 PseudoSourceValue::getGOT(), 0);
5058 // The address of the thread local variable is the add of the thread
5059 // pointer with the offset of the variable.
5060 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
5064 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
5065 // TODO: implement the "local dynamic" model
5066 // TODO: implement the "initial exec"model for pic executables
5067 assert(Subtarget->isTargetELF() &&
5068 "TLS not implemented for non-ELF targets");
5069 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5070 const GlobalValue *GV = GA->getGlobal();
5072 // If GV is an alias then use the aliasee for determining
5073 // thread-localness.
5074 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
5075 GV = GA->resolveAliasedGlobal(false);
5077 TLSModel::Model model = getTLSModel(GV,
5078 getTargetMachine().getRelocationModel());
5081 case TLSModel::GeneralDynamic:
5082 case TLSModel::LocalDynamic: // not implemented
5083 if (Subtarget->is64Bit())
5084 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
5085 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
5087 case TLSModel::InitialExec:
5088 case TLSModel::LocalExec:
5089 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
5090 Subtarget->is64Bit());
5093 llvm_unreachable("Unreachable");
5098 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
5099 /// take a 2 x i32 value to shift plus a shift amount.
5100 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
5101 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5102 EVT VT = Op.getValueType();
5103 unsigned VTBits = VT.getSizeInBits();
5104 DebugLoc dl = Op.getDebugLoc();
5105 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
5106 SDValue ShOpLo = Op.getOperand(0);
5107 SDValue ShOpHi = Op.getOperand(1);
5108 SDValue ShAmt = Op.getOperand(2);
5109 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
5110 DAG.getConstant(VTBits - 1, MVT::i8))
5111 : DAG.getConstant(0, VT);
5114 if (Op.getOpcode() == ISD::SHL_PARTS) {
5115 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
5116 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5118 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
5119 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
5122 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
5123 DAG.getConstant(VTBits, MVT::i8));
5124 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, VT,
5125 AndNode, DAG.getConstant(0, MVT::i8));
5128 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5129 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
5130 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
5132 if (Op.getOpcode() == ISD::SHL_PARTS) {
5133 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5134 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5136 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5137 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5140 SDValue Ops[2] = { Lo, Hi };
5141 return DAG.getMergeValues(Ops, 2, dl);
5144 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5145 EVT SrcVT = Op.getOperand(0).getValueType();
5147 if (SrcVT.isVector()) {
5148 if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
5154 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
5155 "Unknown SINT_TO_FP to lower!");
5157 // These are really Legal; return the operand so the caller accepts it as
5159 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
5161 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
5162 Subtarget->is64Bit()) {
5166 DebugLoc dl = Op.getDebugLoc();
5167 unsigned Size = SrcVT.getSizeInBits()/8;
5168 MachineFunction &MF = DAG.getMachineFunction();
5169 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
5170 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5171 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5173 PseudoSourceValue::getFixedStack(SSFI), 0);
5174 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
5177 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
5179 SelectionDAG &DAG) {
5181 DebugLoc dl = Op.getDebugLoc();
5183 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
5185 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
5187 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
5188 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
5189 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
5190 Tys, Ops, array_lengthof(Ops));
5193 Chain = Result.getValue(1);
5194 SDValue InFlag = Result.getValue(2);
5196 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5197 // shouldn't be necessary except that RFP cannot be live across
5198 // multiple blocks. When stackifier is fixed, they can be uncoupled.
5199 MachineFunction &MF = DAG.getMachineFunction();
5200 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5201 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5202 Tys = DAG.getVTList(MVT::Other);
5204 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
5206 Chain = DAG.getNode(X86ISD::FST, dl, Tys, Ops, array_lengthof(Ops));
5207 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5208 PseudoSourceValue::getFixedStack(SSFI), 0);
5214 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5215 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
5216 // This algorithm is not obvious. Here it is in C code, more or less:
5218 double uint64_to_double( uint32_t hi, uint32_t lo ) {
5219 static const __m128i exp = { 0x4330000045300000ULL, 0 };
5220 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5222 // Copy ints to xmm registers.
5223 __m128i xh = _mm_cvtsi32_si128( hi );
5224 __m128i xl = _mm_cvtsi32_si128( lo );
5226 // Combine into low half of a single xmm register.
5227 __m128i x = _mm_unpacklo_epi32( xh, xl );
5231 // Merge in appropriate exponents to give the integer bits the right
5233 x = _mm_unpacklo_epi32( x, exp );
5235 // Subtract away the biases to deal with the IEEE-754 double precision
5237 d = _mm_sub_pd( (__m128d) x, bias );
5239 // All conversions up to here are exact. The correctly rounded result is
5240 // calculated using the current rounding mode using the following
5242 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5243 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
5244 // store doesn't really need to be here (except
5245 // maybe to zero the other double)
5250 DebugLoc dl = Op.getDebugLoc();
5251 LLVMContext *Context = DAG.getContext();
5253 // Build some magic constants.
5254 std::vector<Constant*> CV0;
5255 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
5256 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
5257 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5258 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5259 Constant *C0 = ConstantVector::get(CV0);
5260 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5262 std::vector<Constant*> CV1;
5264 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
5266 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
5267 Constant *C1 = ConstantVector::get(CV1);
5268 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5270 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5271 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5273 DAG.getIntPtrConstant(1)));
5274 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5275 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5277 DAG.getIntPtrConstant(0)));
5278 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
5279 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5280 PseudoSourceValue::getConstantPool(), 0,
5282 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
5283 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5284 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5285 PseudoSourceValue::getConstantPool(), 0,
5287 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5289 // Add the halves; easiest way is to swap them into another reg first.
5290 int ShufMask[2] = { 1, -1 };
5291 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
5292 DAG.getUNDEF(MVT::v2f64), ShufMask);
5293 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5294 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5295 DAG.getIntPtrConstant(0));
5298 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5299 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
5300 DebugLoc dl = Op.getDebugLoc();
5301 // FP constant to bias correct the final result.
5302 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5305 // Load the 32-bit value into an XMM register.
5306 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5307 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5309 DAG.getIntPtrConstant(0)));
5311 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5312 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5313 DAG.getIntPtrConstant(0));
5315 // Or the load with the bias.
5316 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5317 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5318 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5320 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5321 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5322 MVT::v2f64, Bias)));
5323 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5324 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5325 DAG.getIntPtrConstant(0));
5327 // Subtract the bias.
5328 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5330 // Handle final rounding.
5331 EVT DestVT = Op.getValueType();
5333 if (DestVT.bitsLT(MVT::f64)) {
5334 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5335 DAG.getIntPtrConstant(0));
5336 } else if (DestVT.bitsGT(MVT::f64)) {
5337 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5340 // Handle final rounding.
5344 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5345 SDValue N0 = Op.getOperand(0);
5346 DebugLoc dl = Op.getDebugLoc();
5348 // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
5349 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5350 // the optimization here.
5351 if (DAG.SignBitIsZero(N0))
5352 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5354 EVT SrcVT = N0.getValueType();
5355 if (SrcVT == MVT::i64) {
5356 // We only handle SSE2 f64 target here; caller can expand the rest.
5357 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
5360 return LowerUINT_TO_FP_i64(Op, DAG);
5361 } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
5362 return LowerUINT_TO_FP_i32(Op, DAG);
5365 assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
5367 // Make a 64-bit buffer, and use it to build an FILD.
5368 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5369 SDValue WordOff = DAG.getConstant(4, getPointerTy());
5370 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5371 getPointerTy(), StackSlot, WordOff);
5372 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5373 StackSlot, NULL, 0);
5374 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5375 OffsetSlot, NULL, 0);
5376 return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5379 std::pair<SDValue,SDValue> X86TargetLowering::
5380 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) {
5381 DebugLoc dl = Op.getDebugLoc();
5383 EVT DstTy = Op.getValueType();
5386 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5390 assert(DstTy.getSimpleVT() <= MVT::i64 &&
5391 DstTy.getSimpleVT() >= MVT::i16 &&
5392 "Unknown FP_TO_SINT to lower!");
5394 // These are really Legal.
5395 if (DstTy == MVT::i32 &&
5396 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5397 return std::make_pair(SDValue(), SDValue());
5398 if (Subtarget->is64Bit() &&
5399 DstTy == MVT::i64 &&
5400 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5401 return std::make_pair(SDValue(), SDValue());
5403 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5405 MachineFunction &MF = DAG.getMachineFunction();
5406 unsigned MemSize = DstTy.getSizeInBits()/8;
5407 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5408 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5411 switch (DstTy.getSimpleVT().SimpleTy) {
5412 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5413 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5414 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5415 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5418 SDValue Chain = DAG.getEntryNode();
5419 SDValue Value = Op.getOperand(0);
5420 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5421 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5422 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5423 PseudoSourceValue::getFixedStack(SSFI), 0);
5424 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5426 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5428 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5429 Chain = Value.getValue(1);
5430 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5431 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5434 // Build the FP_TO_INT*_IN_MEM
5435 SDValue Ops[] = { Chain, Value, StackSlot };
5436 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5438 return std::make_pair(FIST, StackSlot);
5441 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
5442 if (Op.getValueType().isVector()) {
5443 if (Op.getValueType() == MVT::v2i32 &&
5444 Op.getOperand(0).getValueType() == MVT::v2f64) {
5450 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5451 SDValue FIST = Vals.first, StackSlot = Vals.second;
5452 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5453 if (FIST.getNode() == 0) return Op;
5456 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5457 FIST, StackSlot, NULL, 0);
5460 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG) {
5461 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5462 SDValue FIST = Vals.first, StackSlot = Vals.second;
5463 assert(FIST.getNode() && "Unexpected failure");
5466 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5467 FIST, StackSlot, NULL, 0);
5470 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
5471 LLVMContext *Context = DAG.getContext();
5472 DebugLoc dl = Op.getDebugLoc();
5473 EVT VT = Op.getValueType();
5476 EltVT = VT.getVectorElementType();
5477 std::vector<Constant*> CV;
5478 if (EltVT == MVT::f64) {
5479 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5483 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5489 Constant *C = ConstantVector::get(CV);
5490 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5491 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5492 PseudoSourceValue::getConstantPool(), 0,
5494 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5497 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
5498 LLVMContext *Context = DAG.getContext();
5499 DebugLoc dl = Op.getDebugLoc();
5500 EVT VT = Op.getValueType();
5503 EltVT = VT.getVectorElementType();
5504 std::vector<Constant*> CV;
5505 if (EltVT == MVT::f64) {
5506 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5510 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5516 Constant *C = ConstantVector::get(CV);
5517 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5518 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5519 PseudoSourceValue::getConstantPool(), 0,
5521 if (VT.isVector()) {
5522 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5523 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5524 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5526 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5528 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5532 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5533 LLVMContext *Context = DAG.getContext();
5534 SDValue Op0 = Op.getOperand(0);
5535 SDValue Op1 = Op.getOperand(1);
5536 DebugLoc dl = Op.getDebugLoc();
5537 EVT VT = Op.getValueType();
5538 EVT SrcVT = Op1.getValueType();
5540 // If second operand is smaller, extend it first.
5541 if (SrcVT.bitsLT(VT)) {
5542 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5545 // And if it is bigger, shrink it first.
5546 if (SrcVT.bitsGT(VT)) {
5547 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5551 // At this point the operands and the result should have the same
5552 // type, and that won't be f80 since that is not custom lowered.
5554 // First get the sign bit of second operand.
5555 std::vector<Constant*> CV;
5556 if (SrcVT == MVT::f64) {
5557 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
5558 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5560 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
5561 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5562 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5563 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5565 Constant *C = ConstantVector::get(CV);
5566 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5567 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5568 PseudoSourceValue::getConstantPool(), 0,
5570 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5572 // Shift sign bit right or left if the two operands have different types.
5573 if (SrcVT.bitsGT(VT)) {
5574 // Op0 is MVT::f32, Op1 is MVT::f64.
5575 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5576 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5577 DAG.getConstant(32, MVT::i32));
5578 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5579 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5580 DAG.getIntPtrConstant(0));
5583 // Clear first operand sign bit.
5585 if (VT == MVT::f64) {
5586 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
5587 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5589 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
5590 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5591 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5592 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5594 C = ConstantVector::get(CV);
5595 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5596 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5597 PseudoSourceValue::getConstantPool(), 0,
5599 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5601 // Or the value with the sign bit.
5602 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5605 /// Emit nodes that will be selected as "test Op0,Op0", or something
5607 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5608 SelectionDAG &DAG) {
5609 DebugLoc dl = Op.getDebugLoc();
5611 // CF and OF aren't always set the way we want. Determine which
5612 // of these we need.
5613 bool NeedCF = false;
5614 bool NeedOF = false;
5616 case X86::COND_A: case X86::COND_AE:
5617 case X86::COND_B: case X86::COND_BE:
5620 case X86::COND_G: case X86::COND_GE:
5621 case X86::COND_L: case X86::COND_LE:
5622 case X86::COND_O: case X86::COND_NO:
5628 // See if we can use the EFLAGS value from the operand instead of
5629 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5630 // we prove that the arithmetic won't overflow, we can't use OF or CF.
5631 if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5632 unsigned Opcode = 0;
5633 unsigned NumOperands = 0;
5634 switch (Op.getNode()->getOpcode()) {
5636 // Due to an isel shortcoming, be conservative if this add is likely to
5637 // be selected as part of a load-modify-store instruction. When the root
5638 // node in a match is a store, isel doesn't know how to remap non-chain
5639 // non-flag uses of other nodes in the match, such as the ADD in this
5640 // case. This leads to the ADD being left around and reselected, with
5641 // the result being two adds in the output.
5642 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5643 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5644 if (UI->getOpcode() == ISD::STORE)
5646 if (ConstantSDNode *C =
5647 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5648 // An add of one will be selected as an INC.
5649 if (C->getAPIntValue() == 1) {
5650 Opcode = X86ISD::INC;
5654 // An add of negative one (subtract of one) will be selected as a DEC.
5655 if (C->getAPIntValue().isAllOnesValue()) {
5656 Opcode = X86ISD::DEC;
5661 // Otherwise use a regular EFLAGS-setting add.
5662 Opcode = X86ISD::ADD;
5666 // If the primary and result isn't used, don't bother using X86ISD::AND,
5667 // because a TEST instruction will be better.
5668 bool NonFlagUse = false;
5669 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5670 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
5672 unsigned UOpNo = UI.getOperandNo();
5673 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
5674 // Look pass truncate.
5675 UOpNo = User->use_begin().getOperandNo();
5676 User = *User->use_begin();
5678 if (User->getOpcode() != ISD::BRCOND &&
5679 User->getOpcode() != ISD::SETCC &&
5680 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
5692 // Due to the ISEL shortcoming noted above, be conservative if this op is
5693 // likely to be selected as part of a load-modify-store instruction.
5694 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5695 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5696 if (UI->getOpcode() == ISD::STORE)
5698 // Otherwise use a regular EFLAGS-setting instruction.
5699 switch (Op.getNode()->getOpcode()) {
5700 case ISD::SUB: Opcode = X86ISD::SUB; break;
5701 case ISD::OR: Opcode = X86ISD::OR; break;
5702 case ISD::XOR: Opcode = X86ISD::XOR; break;
5703 case ISD::AND: Opcode = X86ISD::AND; break;
5704 default: llvm_unreachable("unexpected operator!");
5715 return SDValue(Op.getNode(), 1);
5721 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
5722 SmallVector<SDValue, 4> Ops;
5723 for (unsigned i = 0; i != NumOperands; ++i)
5724 Ops.push_back(Op.getOperand(i));
5725 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
5726 DAG.ReplaceAllUsesWith(Op, New);
5727 return SDValue(New.getNode(), 1);
5731 // Otherwise just emit a CMP with 0, which is the TEST pattern.
5732 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5733 DAG.getConstant(0, Op.getValueType()));
5736 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
5738 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5739 SelectionDAG &DAG) {
5740 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5741 if (C->getAPIntValue() == 0)
5742 return EmitTest(Op0, X86CC, DAG);
5744 DebugLoc dl = Op0.getDebugLoc();
5745 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5748 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
5749 /// if it's possible.
5750 static SDValue LowerToBT(SDValue Op0, ISD::CondCode CC,
5751 DebugLoc dl, SelectionDAG &DAG) {
5753 if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
5754 if (ConstantSDNode *Op010C =
5755 dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
5756 if (Op010C->getZExtValue() == 1) {
5757 LHS = Op0.getOperand(0);
5758 RHS = Op0.getOperand(1).getOperand(1);
5760 } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
5761 if (ConstantSDNode *Op000C =
5762 dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
5763 if (Op000C->getZExtValue() == 1) {
5764 LHS = Op0.getOperand(1);
5765 RHS = Op0.getOperand(0).getOperand(1);
5767 } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
5768 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5769 SDValue AndLHS = Op0.getOperand(0);
5770 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5771 LHS = AndLHS.getOperand(0);
5772 RHS = AndLHS.getOperand(1);
5776 if (LHS.getNode()) {
5777 // If LHS is i8, promote it to i16 with any_extend. There is no i8 BT
5778 // instruction. Since the shift amount is in-range-or-undefined, we know
5779 // that doing a bittest on the i16 value is ok. We extend to i32 because
5780 // the encoding for the i16 version is larger than the i32 version.
5781 if (LHS.getValueType() == MVT::i8)
5782 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5784 // If the operand types disagree, extend the shift amount to match. Since
5785 // BT ignores high bits (like shifts) we can use anyextend.
5786 if (LHS.getValueType() != RHS.getValueType())
5787 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5789 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5790 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5791 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5792 DAG.getConstant(Cond, MVT::i8), BT);
5798 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5799 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5800 SDValue Op0 = Op.getOperand(0);
5801 SDValue Op1 = Op.getOperand(1);
5802 DebugLoc dl = Op.getDebugLoc();
5803 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5805 // Optimize to BT if possible.
5806 // Lower (X & (1 << N)) == 0 to BT(X, N).
5807 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5808 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5809 if (Op0.getOpcode() == ISD::AND &&
5811 Op1.getOpcode() == ISD::Constant &&
5812 cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5813 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5814 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
5815 if (NewSetCC.getNode())
5819 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5820 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5821 if (X86CC == X86::COND_INVALID)
5824 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
5826 // Use sbb x, x to materialize carry bit into a GPR.
5827 if (X86CC == X86::COND_B)
5828 return DAG.getNode(ISD::AND, dl, MVT::i8,
5829 DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
5830 DAG.getConstant(X86CC, MVT::i8), Cond),
5831 DAG.getConstant(1, MVT::i8));
5833 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5834 DAG.getConstant(X86CC, MVT::i8), Cond);
5837 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5839 SDValue Op0 = Op.getOperand(0);
5840 SDValue Op1 = Op.getOperand(1);
5841 SDValue CC = Op.getOperand(2);
5842 EVT VT = Op.getValueType();
5843 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5844 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5845 DebugLoc dl = Op.getDebugLoc();
5849 EVT VT0 = Op0.getValueType();
5850 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5851 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5854 switch (SetCCOpcode) {
5857 case ISD::SETEQ: SSECC = 0; break;
5859 case ISD::SETGT: Swap = true; // Fallthrough
5861 case ISD::SETOLT: SSECC = 1; break;
5863 case ISD::SETGE: Swap = true; // Fallthrough
5865 case ISD::SETOLE: SSECC = 2; break;
5866 case ISD::SETUO: SSECC = 3; break;
5868 case ISD::SETNE: SSECC = 4; break;
5869 case ISD::SETULE: Swap = true;
5870 case ISD::SETUGE: SSECC = 5; break;
5871 case ISD::SETULT: Swap = true;
5872 case ISD::SETUGT: SSECC = 6; break;
5873 case ISD::SETO: SSECC = 7; break;
5876 std::swap(Op0, Op1);
5878 // In the two special cases we can't handle, emit two comparisons.
5880 if (SetCCOpcode == ISD::SETUEQ) {
5882 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5883 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5884 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
5886 else if (SetCCOpcode == ISD::SETONE) {
5888 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5889 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5890 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
5892 llvm_unreachable("Illegal FP comparison");
5894 // Handle all other FP comparisons here.
5895 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5898 // We are handling one of the integer comparisons here. Since SSE only has
5899 // GT and EQ comparisons for integer, swapping operands and multiple
5900 // operations may be required for some comparisons.
5901 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5902 bool Swap = false, Invert = false, FlipSigns = false;
5904 switch (VT.getSimpleVT().SimpleTy) {
5907 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5909 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5911 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5912 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5915 switch (SetCCOpcode) {
5917 case ISD::SETNE: Invert = true;
5918 case ISD::SETEQ: Opc = EQOpc; break;
5919 case ISD::SETLT: Swap = true;
5920 case ISD::SETGT: Opc = GTOpc; break;
5921 case ISD::SETGE: Swap = true;
5922 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
5923 case ISD::SETULT: Swap = true;
5924 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5925 case ISD::SETUGE: Swap = true;
5926 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5929 std::swap(Op0, Op1);
5931 // Since SSE has no unsigned integer comparisons, we need to flip the sign
5932 // bits of the inputs before performing those operations.
5934 EVT EltVT = VT.getVectorElementType();
5935 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
5937 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5938 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
5940 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
5941 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
5944 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
5946 // If the logical-not of the result is required, perform that now.
5948 Result = DAG.getNOT(dl, Result, VT);
5953 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5954 static bool isX86LogicalCmp(SDValue Op) {
5955 unsigned Opc = Op.getNode()->getOpcode();
5956 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
5958 if (Op.getResNo() == 1 &&
5959 (Opc == X86ISD::ADD ||
5960 Opc == X86ISD::SUB ||
5961 Opc == X86ISD::SMUL ||
5962 Opc == X86ISD::UMUL ||
5963 Opc == X86ISD::INC ||
5964 Opc == X86ISD::DEC ||
5965 Opc == X86ISD::OR ||
5966 Opc == X86ISD::XOR ||
5967 Opc == X86ISD::AND))
5973 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5974 bool addTest = true;
5975 SDValue Cond = Op.getOperand(0);
5976 DebugLoc dl = Op.getDebugLoc();
5979 if (Cond.getOpcode() == ISD::SETCC) {
5980 SDValue NewCond = LowerSETCC(Cond, DAG);
5981 if (NewCond.getNode())
5985 // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
5986 SDValue Op1 = Op.getOperand(1);
5987 SDValue Op2 = Op.getOperand(2);
5988 if (Cond.getOpcode() == X86ISD::SETCC &&
5989 cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
5990 SDValue Cmp = Cond.getOperand(1);
5991 if (Cmp.getOpcode() == X86ISD::CMP) {
5992 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
5993 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
5994 ConstantSDNode *RHSC =
5995 dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
5996 if (N1C && N1C->isAllOnesValue() &&
5997 N2C && N2C->isNullValue() &&
5998 RHSC && RHSC->isNullValue()) {
5999 SDValue CmpOp0 = Cmp.getOperand(0);
6000 Cmp = DAG.getNode(X86ISD::CMP, dl, Op.getValueType(),
6001 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
6002 return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
6003 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
6008 // Look pass (and (setcc_carry (cmp ...)), 1).
6009 if (Cond.getOpcode() == ISD::AND &&
6010 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6011 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6012 if (C && C->getAPIntValue() == 1)
6013 Cond = Cond.getOperand(0);
6016 // If condition flag is set by a X86ISD::CMP, then use it as the condition
6017 // setting operand in place of the X86ISD::SETCC.
6018 if (Cond.getOpcode() == X86ISD::SETCC ||
6019 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6020 CC = Cond.getOperand(0);
6022 SDValue Cmp = Cond.getOperand(1);
6023 unsigned Opc = Cmp.getOpcode();
6024 EVT VT = Op.getValueType();
6026 bool IllegalFPCMov = false;
6027 if (VT.isFloatingPoint() && !VT.isVector() &&
6028 !isScalarFPTypeInSSEReg(VT)) // FPStack?
6029 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
6031 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
6032 Opc == X86ISD::BT) { // FIXME
6039 // Look pass the truncate.
6040 if (Cond.getOpcode() == ISD::TRUNCATE)
6041 Cond = Cond.getOperand(0);
6043 // We know the result of AND is compared against zero. Try to match
6045 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
6046 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6047 if (NewSetCC.getNode()) {
6048 CC = NewSetCC.getOperand(0);
6049 Cond = NewSetCC.getOperand(1);
6056 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6057 Cond = EmitTest(Cond, X86::COND_NE, DAG);
6060 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
6061 // condition is true.
6062 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
6063 SDValue Ops[] = { Op2, Op1, CC, Cond };
6064 return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
6067 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
6068 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
6069 // from the AND / OR.
6070 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
6071 Opc = Op.getOpcode();
6072 if (Opc != ISD::OR && Opc != ISD::AND)
6074 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6075 Op.getOperand(0).hasOneUse() &&
6076 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
6077 Op.getOperand(1).hasOneUse());
6080 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
6081 // 1 and that the SETCC node has a single use.
6082 static bool isXor1OfSetCC(SDValue Op) {
6083 if (Op.getOpcode() != ISD::XOR)
6085 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6086 if (N1C && N1C->getAPIntValue() == 1) {
6087 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6088 Op.getOperand(0).hasOneUse();
6093 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
6094 bool addTest = true;
6095 SDValue Chain = Op.getOperand(0);
6096 SDValue Cond = Op.getOperand(1);
6097 SDValue Dest = Op.getOperand(2);
6098 DebugLoc dl = Op.getDebugLoc();
6101 if (Cond.getOpcode() == ISD::SETCC) {
6102 SDValue NewCond = LowerSETCC(Cond, DAG);
6103 if (NewCond.getNode())
6107 // FIXME: LowerXALUO doesn't handle these!!
6108 else if (Cond.getOpcode() == X86ISD::ADD ||
6109 Cond.getOpcode() == X86ISD::SUB ||
6110 Cond.getOpcode() == X86ISD::SMUL ||
6111 Cond.getOpcode() == X86ISD::UMUL)
6112 Cond = LowerXALUO(Cond, DAG);
6115 // Look pass (and (setcc_carry (cmp ...)), 1).
6116 if (Cond.getOpcode() == ISD::AND &&
6117 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6118 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6119 if (C && C->getAPIntValue() == 1)
6120 Cond = Cond.getOperand(0);
6123 // If condition flag is set by a X86ISD::CMP, then use it as the condition
6124 // setting operand in place of the X86ISD::SETCC.
6125 if (Cond.getOpcode() == X86ISD::SETCC ||
6126 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6127 CC = Cond.getOperand(0);
6129 SDValue Cmp = Cond.getOperand(1);
6130 unsigned Opc = Cmp.getOpcode();
6131 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
6132 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
6136 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
6140 // These can only come from an arithmetic instruction with overflow,
6141 // e.g. SADDO, UADDO.
6142 Cond = Cond.getNode()->getOperand(1);
6149 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
6150 SDValue Cmp = Cond.getOperand(0).getOperand(1);
6151 if (CondOpc == ISD::OR) {
6152 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
6153 // two branches instead of an explicit OR instruction with a
6155 if (Cmp == Cond.getOperand(1).getOperand(1) &&
6156 isX86LogicalCmp(Cmp)) {
6157 CC = Cond.getOperand(0).getOperand(0);
6158 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6159 Chain, Dest, CC, Cmp);
6160 CC = Cond.getOperand(1).getOperand(0);
6164 } else { // ISD::AND
6165 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
6166 // two branches instead of an explicit AND instruction with a
6167 // separate test. However, we only do this if this block doesn't
6168 // have a fall-through edge, because this requires an explicit
6169 // jmp when the condition is false.
6170 if (Cmp == Cond.getOperand(1).getOperand(1) &&
6171 isX86LogicalCmp(Cmp) &&
6172 Op.getNode()->hasOneUse()) {
6173 X86::CondCode CCode =
6174 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6175 CCode = X86::GetOppositeBranchCondition(CCode);
6176 CC = DAG.getConstant(CCode, MVT::i8);
6177 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
6178 // Look for an unconditional branch following this conditional branch.
6179 // We need this because we need to reverse the successors in order
6180 // to implement FCMP_OEQ.
6181 if (User.getOpcode() == ISD::BR) {
6182 SDValue FalseBB = User.getOperand(1);
6184 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
6185 assert(NewBR == User);
6188 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6189 Chain, Dest, CC, Cmp);
6190 X86::CondCode CCode =
6191 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
6192 CCode = X86::GetOppositeBranchCondition(CCode);
6193 CC = DAG.getConstant(CCode, MVT::i8);
6199 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
6200 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
6201 // It should be transformed during dag combiner except when the condition
6202 // is set by a arithmetics with overflow node.
6203 X86::CondCode CCode =
6204 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6205 CCode = X86::GetOppositeBranchCondition(CCode);
6206 CC = DAG.getConstant(CCode, MVT::i8);
6207 Cond = Cond.getOperand(0).getOperand(1);
6213 // Look pass the truncate.
6214 if (Cond.getOpcode() == ISD::TRUNCATE)
6215 Cond = Cond.getOperand(0);
6217 // We know the result of AND is compared against zero. Try to match
6219 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
6220 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6221 if (NewSetCC.getNode()) {
6222 CC = NewSetCC.getOperand(0);
6223 Cond = NewSetCC.getOperand(1);
6230 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6231 Cond = EmitTest(Cond, X86::COND_NE, DAG);
6233 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6234 Chain, Dest, CC, Cond);
6238 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
6239 // Calls to _alloca is needed to probe the stack when allocating more than 4k
6240 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
6241 // that the guard pages used by the OS virtual memory manager are allocated in
6242 // correct sequence.
6244 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6245 SelectionDAG &DAG) {
6246 assert(Subtarget->isTargetCygMing() &&
6247 "This should be used only on Cygwin/Mingw targets");
6248 DebugLoc dl = Op.getDebugLoc();
6251 SDValue Chain = Op.getOperand(0);
6252 SDValue Size = Op.getOperand(1);
6253 // FIXME: Ensure alignment here
6257 EVT IntPtr = getPointerTy();
6258 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
6260 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
6262 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
6263 Flag = Chain.getValue(1);
6265 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6266 SDValue Ops[] = { Chain,
6267 DAG.getTargetExternalSymbol("_alloca", IntPtr),
6268 DAG.getRegister(X86::EAX, IntPtr),
6269 DAG.getRegister(X86StackPtr, SPTy),
6271 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops, 5);
6272 Flag = Chain.getValue(1);
6274 Chain = DAG.getCALLSEQ_END(Chain,
6275 DAG.getIntPtrConstant(0, true),
6276 DAG.getIntPtrConstant(0, true),
6279 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
6281 SDValue Ops1[2] = { Chain.getValue(0), Chain };
6282 return DAG.getMergeValues(Ops1, 2, dl);
6286 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
6288 SDValue Dst, SDValue Src,
6289 SDValue Size, unsigned Align,
6291 uint64_t DstSVOff) {
6292 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6294 // If not DWORD aligned or size is more than the threshold, call the library.
6295 // The libc version is likely to be faster for these cases. It can use the
6296 // address value and run time information about the CPU.
6297 if ((Align & 3) != 0 ||
6299 ConstantSize->getZExtValue() >
6300 getSubtarget()->getMaxInlineSizeThreshold()) {
6301 SDValue InFlag(0, 0);
6303 // Check to see if there is a specialized entry-point for memory zeroing.
6304 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
6306 if (const char *bzeroEntry = V &&
6307 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
6308 EVT IntPtr = getPointerTy();
6309 const Type *IntPtrTy = TD->getIntPtrType(*DAG.getContext());
6310 TargetLowering::ArgListTy Args;
6311 TargetLowering::ArgListEntry Entry;
6313 Entry.Ty = IntPtrTy;
6314 Args.push_back(Entry);
6316 Args.push_back(Entry);
6317 std::pair<SDValue,SDValue> CallResult =
6318 LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()),
6319 false, false, false, false,
6320 0, CallingConv::C, false, /*isReturnValueUsed=*/false,
6321 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl,
6322 DAG.GetOrdering(Chain.getNode()));
6323 return CallResult.second;
6326 // Otherwise have the target-independent code call memset.
6330 uint64_t SizeVal = ConstantSize->getZExtValue();
6331 SDValue InFlag(0, 0);
6334 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
6335 unsigned BytesLeft = 0;
6336 bool TwoRepStos = false;
6339 uint64_t Val = ValC->getZExtValue() & 255;
6341 // If the value is a constant, then we can potentially use larger sets.
6342 switch (Align & 3) {
6343 case 2: // WORD aligned
6346 Val = (Val << 8) | Val;
6348 case 0: // DWORD aligned
6351 Val = (Val << 8) | Val;
6352 Val = (Val << 16) | Val;
6353 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
6356 Val = (Val << 32) | Val;
6359 default: // Byte aligned
6362 Count = DAG.getIntPtrConstant(SizeVal);
6366 if (AVT.bitsGT(MVT::i8)) {
6367 unsigned UBytes = AVT.getSizeInBits() / 8;
6368 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
6369 BytesLeft = SizeVal % UBytes;
6372 Chain = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
6374 InFlag = Chain.getValue(1);
6377 Count = DAG.getIntPtrConstant(SizeVal);
6378 Chain = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
6379 InFlag = Chain.getValue(1);
6382 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6385 InFlag = Chain.getValue(1);
6386 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6389 InFlag = Chain.getValue(1);
6391 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6392 SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6393 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6396 InFlag = Chain.getValue(1);
6398 EVT CVT = Count.getValueType();
6399 SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
6400 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
6401 Chain = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
6404 InFlag = Chain.getValue(1);
6405 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6406 SDValue Ops[] = { Chain, DAG.getValueType(MVT::i8), InFlag };
6407 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6408 } else if (BytesLeft) {
6409 // Handle the last 1 - 7 bytes.
6410 unsigned Offset = SizeVal - BytesLeft;
6411 EVT AddrVT = Dst.getValueType();
6412 EVT SizeVT = Size.getValueType();
6414 Chain = DAG.getMemset(Chain, dl,
6415 DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
6416 DAG.getConstant(Offset, AddrVT)),
6418 DAG.getConstant(BytesLeft, SizeVT),
6419 Align, DstSV, DstSVOff + Offset);
6422 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
6427 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
6428 SDValue Chain, SDValue Dst, SDValue Src,
6429 SDValue Size, unsigned Align,
6431 const Value *DstSV, uint64_t DstSVOff,
6432 const Value *SrcSV, uint64_t SrcSVOff) {
6433 // This requires the copy size to be a constant, preferrably
6434 // within a subtarget-specific limit.
6435 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6438 uint64_t SizeVal = ConstantSize->getZExtValue();
6439 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
6442 /// If not DWORD aligned, call the library.
6443 if ((Align & 3) != 0)
6448 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
6451 unsigned UBytes = AVT.getSizeInBits() / 8;
6452 unsigned CountVal = SizeVal / UBytes;
6453 SDValue Count = DAG.getIntPtrConstant(CountVal);
6454 unsigned BytesLeft = SizeVal % UBytes;
6456 SDValue InFlag(0, 0);
6457 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6460 InFlag = Chain.getValue(1);
6461 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6464 InFlag = Chain.getValue(1);
6465 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
6468 InFlag = Chain.getValue(1);
6470 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6471 SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6472 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, Ops,
6473 array_lengthof(Ops));
6475 SmallVector<SDValue, 4> Results;
6476 Results.push_back(RepMovs);
6478 // Handle the last 1 - 7 bytes.
6479 unsigned Offset = SizeVal - BytesLeft;
6480 EVT DstVT = Dst.getValueType();
6481 EVT SrcVT = Src.getValueType();
6482 EVT SizeVT = Size.getValueType();
6483 Results.push_back(DAG.getMemcpy(Chain, dl,
6484 DAG.getNode(ISD::ADD, dl, DstVT, Dst,
6485 DAG.getConstant(Offset, DstVT)),
6486 DAG.getNode(ISD::ADD, dl, SrcVT, Src,
6487 DAG.getConstant(Offset, SrcVT)),
6488 DAG.getConstant(BytesLeft, SizeVT),
6489 Align, AlwaysInline,
6490 DstSV, DstSVOff + Offset,
6491 SrcSV, SrcSVOff + Offset));
6494 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6495 &Results[0], Results.size());
6498 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
6499 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6500 DebugLoc dl = Op.getDebugLoc();
6502 if (!Subtarget->is64Bit()) {
6503 // vastart just stores the address of the VarArgsFrameIndex slot into the
6504 // memory location argument.
6505 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6506 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
6510 // gp_offset (0 - 6 * 8)
6511 // fp_offset (48 - 48 + 8 * 16)
6512 // overflow_arg_area (point to parameters coming in memory).
6514 SmallVector<SDValue, 8> MemOps;
6515 SDValue FIN = Op.getOperand(1);
6517 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6518 DAG.getConstant(VarArgsGPOffset, MVT::i32),
6520 MemOps.push_back(Store);
6523 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6524 FIN, DAG.getIntPtrConstant(4));
6525 Store = DAG.getStore(Op.getOperand(0), dl,
6526 DAG.getConstant(VarArgsFPOffset, MVT::i32),
6528 MemOps.push_back(Store);
6530 // Store ptr to overflow_arg_area
6531 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6532 FIN, DAG.getIntPtrConstant(4));
6533 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6534 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0);
6535 MemOps.push_back(Store);
6537 // Store ptr to reg_save_area.
6538 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6539 FIN, DAG.getIntPtrConstant(8));
6540 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
6541 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0);
6542 MemOps.push_back(Store);
6543 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6544 &MemOps[0], MemOps.size());
6547 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
6548 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6549 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6550 SDValue Chain = Op.getOperand(0);
6551 SDValue SrcPtr = Op.getOperand(1);
6552 SDValue SrcSV = Op.getOperand(2);
6554 llvm_report_error("VAArgInst is not yet implemented for x86-64!");
6558 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
6559 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6560 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6561 SDValue Chain = Op.getOperand(0);
6562 SDValue DstPtr = Op.getOperand(1);
6563 SDValue SrcPtr = Op.getOperand(2);
6564 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6565 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6566 DebugLoc dl = Op.getDebugLoc();
6568 return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6569 DAG.getIntPtrConstant(24), 8, false,
6570 DstSV, 0, SrcSV, 0);
6574 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
6575 DebugLoc dl = Op.getDebugLoc();
6576 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6578 default: return SDValue(); // Don't custom lower most intrinsics.
6579 // Comparison intrinsics.
6580 case Intrinsic::x86_sse_comieq_ss:
6581 case Intrinsic::x86_sse_comilt_ss:
6582 case Intrinsic::x86_sse_comile_ss:
6583 case Intrinsic::x86_sse_comigt_ss:
6584 case Intrinsic::x86_sse_comige_ss:
6585 case Intrinsic::x86_sse_comineq_ss:
6586 case Intrinsic::x86_sse_ucomieq_ss:
6587 case Intrinsic::x86_sse_ucomilt_ss:
6588 case Intrinsic::x86_sse_ucomile_ss:
6589 case Intrinsic::x86_sse_ucomigt_ss:
6590 case Intrinsic::x86_sse_ucomige_ss:
6591 case Intrinsic::x86_sse_ucomineq_ss:
6592 case Intrinsic::x86_sse2_comieq_sd:
6593 case Intrinsic::x86_sse2_comilt_sd:
6594 case Intrinsic::x86_sse2_comile_sd:
6595 case Intrinsic::x86_sse2_comigt_sd:
6596 case Intrinsic::x86_sse2_comige_sd:
6597 case Intrinsic::x86_sse2_comineq_sd:
6598 case Intrinsic::x86_sse2_ucomieq_sd:
6599 case Intrinsic::x86_sse2_ucomilt_sd:
6600 case Intrinsic::x86_sse2_ucomile_sd:
6601 case Intrinsic::x86_sse2_ucomigt_sd:
6602 case Intrinsic::x86_sse2_ucomige_sd:
6603 case Intrinsic::x86_sse2_ucomineq_sd: {
6605 ISD::CondCode CC = ISD::SETCC_INVALID;
6608 case Intrinsic::x86_sse_comieq_ss:
6609 case Intrinsic::x86_sse2_comieq_sd:
6613 case Intrinsic::x86_sse_comilt_ss:
6614 case Intrinsic::x86_sse2_comilt_sd:
6618 case Intrinsic::x86_sse_comile_ss:
6619 case Intrinsic::x86_sse2_comile_sd:
6623 case Intrinsic::x86_sse_comigt_ss:
6624 case Intrinsic::x86_sse2_comigt_sd:
6628 case Intrinsic::x86_sse_comige_ss:
6629 case Intrinsic::x86_sse2_comige_sd:
6633 case Intrinsic::x86_sse_comineq_ss:
6634 case Intrinsic::x86_sse2_comineq_sd:
6638 case Intrinsic::x86_sse_ucomieq_ss:
6639 case Intrinsic::x86_sse2_ucomieq_sd:
6640 Opc = X86ISD::UCOMI;
6643 case Intrinsic::x86_sse_ucomilt_ss:
6644 case Intrinsic::x86_sse2_ucomilt_sd:
6645 Opc = X86ISD::UCOMI;
6648 case Intrinsic::x86_sse_ucomile_ss:
6649 case Intrinsic::x86_sse2_ucomile_sd:
6650 Opc = X86ISD::UCOMI;
6653 case Intrinsic::x86_sse_ucomigt_ss:
6654 case Intrinsic::x86_sse2_ucomigt_sd:
6655 Opc = X86ISD::UCOMI;
6658 case Intrinsic::x86_sse_ucomige_ss:
6659 case Intrinsic::x86_sse2_ucomige_sd:
6660 Opc = X86ISD::UCOMI;
6663 case Intrinsic::x86_sse_ucomineq_ss:
6664 case Intrinsic::x86_sse2_ucomineq_sd:
6665 Opc = X86ISD::UCOMI;
6670 SDValue LHS = Op.getOperand(1);
6671 SDValue RHS = Op.getOperand(2);
6672 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6673 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
6674 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6675 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6676 DAG.getConstant(X86CC, MVT::i8), Cond);
6677 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6679 // ptest intrinsics. The intrinsic these come from are designed to return
6680 // an integer value, not just an instruction so lower it to the ptest
6681 // pattern and a setcc for the result.
6682 case Intrinsic::x86_sse41_ptestz:
6683 case Intrinsic::x86_sse41_ptestc:
6684 case Intrinsic::x86_sse41_ptestnzc:{
6687 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
6688 case Intrinsic::x86_sse41_ptestz:
6690 X86CC = X86::COND_E;
6692 case Intrinsic::x86_sse41_ptestc:
6694 X86CC = X86::COND_B;
6696 case Intrinsic::x86_sse41_ptestnzc:
6698 X86CC = X86::COND_A;
6702 SDValue LHS = Op.getOperand(1);
6703 SDValue RHS = Op.getOperand(2);
6704 SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
6705 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
6706 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
6707 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6710 // Fix vector shift instructions where the last operand is a non-immediate
6712 case Intrinsic::x86_sse2_pslli_w:
6713 case Intrinsic::x86_sse2_pslli_d:
6714 case Intrinsic::x86_sse2_pslli_q:
6715 case Intrinsic::x86_sse2_psrli_w:
6716 case Intrinsic::x86_sse2_psrli_d:
6717 case Intrinsic::x86_sse2_psrli_q:
6718 case Intrinsic::x86_sse2_psrai_w:
6719 case Intrinsic::x86_sse2_psrai_d:
6720 case Intrinsic::x86_mmx_pslli_w:
6721 case Intrinsic::x86_mmx_pslli_d:
6722 case Intrinsic::x86_mmx_pslli_q:
6723 case Intrinsic::x86_mmx_psrli_w:
6724 case Intrinsic::x86_mmx_psrli_d:
6725 case Intrinsic::x86_mmx_psrli_q:
6726 case Intrinsic::x86_mmx_psrai_w:
6727 case Intrinsic::x86_mmx_psrai_d: {
6728 SDValue ShAmt = Op.getOperand(2);
6729 if (isa<ConstantSDNode>(ShAmt))
6732 unsigned NewIntNo = 0;
6733 EVT ShAmtVT = MVT::v4i32;
6735 case Intrinsic::x86_sse2_pslli_w:
6736 NewIntNo = Intrinsic::x86_sse2_psll_w;
6738 case Intrinsic::x86_sse2_pslli_d:
6739 NewIntNo = Intrinsic::x86_sse2_psll_d;
6741 case Intrinsic::x86_sse2_pslli_q:
6742 NewIntNo = Intrinsic::x86_sse2_psll_q;
6744 case Intrinsic::x86_sse2_psrli_w:
6745 NewIntNo = Intrinsic::x86_sse2_psrl_w;
6747 case Intrinsic::x86_sse2_psrli_d:
6748 NewIntNo = Intrinsic::x86_sse2_psrl_d;
6750 case Intrinsic::x86_sse2_psrli_q:
6751 NewIntNo = Intrinsic::x86_sse2_psrl_q;
6753 case Intrinsic::x86_sse2_psrai_w:
6754 NewIntNo = Intrinsic::x86_sse2_psra_w;
6756 case Intrinsic::x86_sse2_psrai_d:
6757 NewIntNo = Intrinsic::x86_sse2_psra_d;
6760 ShAmtVT = MVT::v2i32;
6762 case Intrinsic::x86_mmx_pslli_w:
6763 NewIntNo = Intrinsic::x86_mmx_psll_w;
6765 case Intrinsic::x86_mmx_pslli_d:
6766 NewIntNo = Intrinsic::x86_mmx_psll_d;
6768 case Intrinsic::x86_mmx_pslli_q:
6769 NewIntNo = Intrinsic::x86_mmx_psll_q;
6771 case Intrinsic::x86_mmx_psrli_w:
6772 NewIntNo = Intrinsic::x86_mmx_psrl_w;
6774 case Intrinsic::x86_mmx_psrli_d:
6775 NewIntNo = Intrinsic::x86_mmx_psrl_d;
6777 case Intrinsic::x86_mmx_psrli_q:
6778 NewIntNo = Intrinsic::x86_mmx_psrl_q;
6780 case Intrinsic::x86_mmx_psrai_w:
6781 NewIntNo = Intrinsic::x86_mmx_psra_w;
6783 case Intrinsic::x86_mmx_psrai_d:
6784 NewIntNo = Intrinsic::x86_mmx_psra_d;
6786 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
6792 // The vector shift intrinsics with scalars uses 32b shift amounts but
6793 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
6797 ShOps[1] = DAG.getConstant(0, MVT::i32);
6798 if (ShAmtVT == MVT::v4i32) {
6799 ShOps[2] = DAG.getUNDEF(MVT::i32);
6800 ShOps[3] = DAG.getUNDEF(MVT::i32);
6801 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
6803 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
6806 EVT VT = Op.getValueType();
6807 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
6808 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6809 DAG.getConstant(NewIntNo, MVT::i32),
6810 Op.getOperand(1), ShAmt);
6815 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
6816 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6817 DebugLoc dl = Op.getDebugLoc();
6820 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6822 DAG.getConstant(TD->getPointerSize(),
6823 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6824 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6825 DAG.getNode(ISD::ADD, dl, getPointerTy(),
6830 // Just load the return address.
6831 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6832 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6833 RetAddrFI, NULL, 0);
6836 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
6837 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6838 MFI->setFrameAddressIsTaken(true);
6839 EVT VT = Op.getValueType();
6840 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
6841 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6842 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6843 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6845 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
6849 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6850 SelectionDAG &DAG) {
6851 return DAG.getIntPtrConstant(2*TD->getPointerSize());
6854 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
6856 MachineFunction &MF = DAG.getMachineFunction();
6857 SDValue Chain = Op.getOperand(0);
6858 SDValue Offset = Op.getOperand(1);
6859 SDValue Handler = Op.getOperand(2);
6860 DebugLoc dl = Op.getDebugLoc();
6862 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6864 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6866 SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
6867 DAG.getIntPtrConstant(-TD->getPointerSize()));
6868 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
6869 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0);
6870 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
6871 MF.getRegInfo().addLiveOut(StoreAddrReg);
6873 return DAG.getNode(X86ISD::EH_RETURN, dl,
6875 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6878 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6879 SelectionDAG &DAG) {
6880 SDValue Root = Op.getOperand(0);
6881 SDValue Trmp = Op.getOperand(1); // trampoline
6882 SDValue FPtr = Op.getOperand(2); // nested function
6883 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6884 DebugLoc dl = Op.getDebugLoc();
6886 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6888 const X86InstrInfo *TII =
6889 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
6891 if (Subtarget->is64Bit()) {
6892 SDValue OutChains[6];
6894 // Large code-model.
6896 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
6897 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
6899 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
6900 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
6902 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
6904 // Load the pointer to the nested function into R11.
6905 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
6906 SDValue Addr = Trmp;
6907 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6910 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6911 DAG.getConstant(2, MVT::i64));
6912 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2, false, 2);
6914 // Load the 'nest' parameter value into R10.
6915 // R10 is specified in X86CallingConv.td
6916 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
6917 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6918 DAG.getConstant(10, MVT::i64));
6919 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6920 Addr, TrmpAddr, 10);
6922 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6923 DAG.getConstant(12, MVT::i64));
6924 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12, false, 2);
6926 // Jump to the nested function.
6927 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
6928 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6929 DAG.getConstant(20, MVT::i64));
6930 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6931 Addr, TrmpAddr, 20);
6933 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
6934 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6935 DAG.getConstant(22, MVT::i64));
6936 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
6940 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
6941 return DAG.getMergeValues(Ops, 2, dl);
6943 const Function *Func =
6944 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
6945 CallingConv::ID CC = Func->getCallingConv();
6950 llvm_unreachable("Unsupported calling convention");
6951 case CallingConv::C:
6952 case CallingConv::X86_StdCall: {
6953 // Pass 'nest' parameter in ECX.
6954 // Must be kept in sync with X86CallingConv.td
6957 // Check that ECX wasn't needed by an 'inreg' parameter.
6958 const FunctionType *FTy = Func->getFunctionType();
6959 const AttrListPtr &Attrs = Func->getAttributes();
6961 if (!Attrs.isEmpty() && !Func->isVarArg()) {
6962 unsigned InRegCount = 0;
6965 for (FunctionType::param_iterator I = FTy->param_begin(),
6966 E = FTy->param_end(); I != E; ++I, ++Idx)
6967 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6968 // FIXME: should only count parameters that are lowered to integers.
6969 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6971 if (InRegCount > 2) {
6972 llvm_report_error("Nest register in use - reduce number of inreg parameters!");
6977 case CallingConv::X86_FastCall:
6978 case CallingConv::Fast:
6979 // Pass 'nest' parameter in EAX.
6980 // Must be kept in sync with X86CallingConv.td
6985 SDValue OutChains[4];
6988 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6989 DAG.getConstant(10, MVT::i32));
6990 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
6992 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
6993 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
6994 OutChains[0] = DAG.getStore(Root, dl,
6995 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
6998 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6999 DAG.getConstant(1, MVT::i32));
7000 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1, false, 1);
7002 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
7003 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7004 DAG.getConstant(5, MVT::i32));
7005 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
7006 TrmpAddr, 5, false, 1);
7008 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7009 DAG.getConstant(6, MVT::i32));
7010 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6, false, 1);
7013 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
7014 return DAG.getMergeValues(Ops, 2, dl);
7018 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
7020 The rounding mode is in bits 11:10 of FPSR, and has the following
7027 FLT_ROUNDS, on the other hand, expects the following:
7034 To perform the conversion, we do:
7035 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
7038 MachineFunction &MF = DAG.getMachineFunction();
7039 const TargetMachine &TM = MF.getTarget();
7040 const TargetFrameInfo &TFI = *TM.getFrameInfo();
7041 unsigned StackAlignment = TFI.getStackAlignment();
7042 EVT VT = Op.getValueType();
7043 DebugLoc dl = Op.getDebugLoc();
7045 // Save FP Control Word to stack slot
7046 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
7047 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7049 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
7050 DAG.getEntryNode(), StackSlot);
7052 // Load FP Control Word from stack slot
7053 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0);
7055 // Transform as necessary
7057 DAG.getNode(ISD::SRL, dl, MVT::i16,
7058 DAG.getNode(ISD::AND, dl, MVT::i16,
7059 CWD, DAG.getConstant(0x800, MVT::i16)),
7060 DAG.getConstant(11, MVT::i8));
7062 DAG.getNode(ISD::SRL, dl, MVT::i16,
7063 DAG.getNode(ISD::AND, dl, MVT::i16,
7064 CWD, DAG.getConstant(0x400, MVT::i16)),
7065 DAG.getConstant(9, MVT::i8));
7068 DAG.getNode(ISD::AND, dl, MVT::i16,
7069 DAG.getNode(ISD::ADD, dl, MVT::i16,
7070 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
7071 DAG.getConstant(1, MVT::i16)),
7072 DAG.getConstant(3, MVT::i16));
7075 return DAG.getNode((VT.getSizeInBits() < 16 ?
7076 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7079 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
7080 EVT VT = Op.getValueType();
7082 unsigned NumBits = VT.getSizeInBits();
7083 DebugLoc dl = Op.getDebugLoc();
7085 Op = Op.getOperand(0);
7086 if (VT == MVT::i8) {
7087 // Zero extend to i32 since there is not an i8 bsr.
7089 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7092 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
7093 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7094 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
7096 // If src is zero (i.e. bsr sets ZF), returns NumBits.
7099 DAG.getConstant(NumBits+NumBits-1, OpVT),
7100 DAG.getConstant(X86::COND_E, MVT::i8),
7103 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7105 // Finally xor with NumBits-1.
7106 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
7109 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7113 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
7114 EVT VT = Op.getValueType();
7116 unsigned NumBits = VT.getSizeInBits();
7117 DebugLoc dl = Op.getDebugLoc();
7119 Op = Op.getOperand(0);
7120 if (VT == MVT::i8) {
7122 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7125 // Issue a bsf (scan bits forward) which also sets EFLAGS.
7126 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7127 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
7129 // If src is zero (i.e. bsf sets ZF), returns NumBits.
7132 DAG.getConstant(NumBits, OpVT),
7133 DAG.getConstant(X86::COND_E, MVT::i8),
7136 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7139 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7143 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
7144 EVT VT = Op.getValueType();
7145 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
7146 DebugLoc dl = Op.getDebugLoc();
7148 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
7149 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
7150 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
7151 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
7152 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
7154 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
7155 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
7156 // return AloBlo + AloBhi + AhiBlo;
7158 SDValue A = Op.getOperand(0);
7159 SDValue B = Op.getOperand(1);
7161 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7162 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7163 A, DAG.getConstant(32, MVT::i32));
7164 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7165 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7166 B, DAG.getConstant(32, MVT::i32));
7167 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7168 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7170 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7171 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7173 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7174 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7176 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7177 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7178 AloBhi, DAG.getConstant(32, MVT::i32));
7179 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7180 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7181 AhiBlo, DAG.getConstant(32, MVT::i32));
7182 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
7183 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
7188 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
7189 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
7190 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
7191 // looks for this combo and may remove the "setcc" instruction if the "setcc"
7192 // has only one use.
7193 SDNode *N = Op.getNode();
7194 SDValue LHS = N->getOperand(0);
7195 SDValue RHS = N->getOperand(1);
7196 unsigned BaseOp = 0;
7198 DebugLoc dl = Op.getDebugLoc();
7200 switch (Op.getOpcode()) {
7201 default: llvm_unreachable("Unknown ovf instruction!");
7203 // A subtract of one will be selected as a INC. Note that INC doesn't
7204 // set CF, so we can't do this for UADDO.
7205 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7206 if (C->getAPIntValue() == 1) {
7207 BaseOp = X86ISD::INC;
7211 BaseOp = X86ISD::ADD;
7215 BaseOp = X86ISD::ADD;
7219 // A subtract of one will be selected as a DEC. Note that DEC doesn't
7220 // set CF, so we can't do this for USUBO.
7221 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7222 if (C->getAPIntValue() == 1) {
7223 BaseOp = X86ISD::DEC;
7227 BaseOp = X86ISD::SUB;
7231 BaseOp = X86ISD::SUB;
7235 BaseOp = X86ISD::SMUL;
7239 BaseOp = X86ISD::UMUL;
7244 // Also sets EFLAGS.
7245 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
7246 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
7249 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
7250 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
7252 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
7256 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
7257 EVT T = Op.getValueType();
7258 DebugLoc dl = Op.getDebugLoc();
7261 switch(T.getSimpleVT().SimpleTy) {
7263 assert(false && "Invalid value type!");
7264 case MVT::i8: Reg = X86::AL; size = 1; break;
7265 case MVT::i16: Reg = X86::AX; size = 2; break;
7266 case MVT::i32: Reg = X86::EAX; size = 4; break;
7268 assert(Subtarget->is64Bit() && "Node not type legal!");
7269 Reg = X86::RAX; size = 8;
7272 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
7273 Op.getOperand(2), SDValue());
7274 SDValue Ops[] = { cpIn.getValue(0),
7277 DAG.getTargetConstant(size, MVT::i8),
7279 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7280 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
7282 DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
7286 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
7287 SelectionDAG &DAG) {
7288 assert(Subtarget->is64Bit() && "Result not type legalized?");
7289 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7290 SDValue TheChain = Op.getOperand(0);
7291 DebugLoc dl = Op.getDebugLoc();
7292 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7293 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
7294 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
7296 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
7297 DAG.getConstant(32, MVT::i8));
7299 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
7302 return DAG.getMergeValues(Ops, 2, dl);
7305 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
7306 SDNode *Node = Op.getNode();
7307 DebugLoc dl = Node->getDebugLoc();
7308 EVT T = Node->getValueType(0);
7309 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
7310 DAG.getConstant(0, T), Node->getOperand(2));
7311 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
7312 cast<AtomicSDNode>(Node)->getMemoryVT(),
7313 Node->getOperand(0),
7314 Node->getOperand(1), negOp,
7315 cast<AtomicSDNode>(Node)->getSrcValue(),
7316 cast<AtomicSDNode>(Node)->getAlignment());
7319 /// LowerOperation - Provide custom lowering hooks for some operations.
7321 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
7322 switch (Op.getOpcode()) {
7323 default: llvm_unreachable("Should not custom lower this!");
7324 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
7325 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
7326 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
7327 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
7328 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7329 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7330 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7331 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
7332 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
7333 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
7334 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7335 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
7336 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
7337 case ISD::SHL_PARTS:
7338 case ISD::SRA_PARTS:
7339 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
7340 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
7341 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
7342 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
7343 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
7344 case ISD::FABS: return LowerFABS(Op, DAG);
7345 case ISD::FNEG: return LowerFNEG(Op, DAG);
7346 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
7347 case ISD::SETCC: return LowerSETCC(Op, DAG);
7348 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
7349 case ISD::SELECT: return LowerSELECT(Op, DAG);
7350 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
7351 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
7352 case ISD::VASTART: return LowerVASTART(Op, DAG);
7353 case ISD::VAARG: return LowerVAARG(Op, DAG);
7354 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
7355 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7356 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
7357 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
7358 case ISD::FRAME_TO_ARGS_OFFSET:
7359 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
7360 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
7361 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
7362 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
7363 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
7364 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
7365 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
7366 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
7372 case ISD::UMULO: return LowerXALUO(Op, DAG);
7373 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
7377 void X86TargetLowering::
7378 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
7379 SelectionDAG &DAG, unsigned NewOp) {
7380 EVT T = Node->getValueType(0);
7381 DebugLoc dl = Node->getDebugLoc();
7382 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
7384 SDValue Chain = Node->getOperand(0);
7385 SDValue In1 = Node->getOperand(1);
7386 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7387 Node->getOperand(2), DAG.getIntPtrConstant(0));
7388 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7389 Node->getOperand(2), DAG.getIntPtrConstant(1));
7390 SDValue Ops[] = { Chain, In1, In2L, In2H };
7391 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7393 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
7394 cast<MemSDNode>(Node)->getMemOperand());
7395 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7396 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7397 Results.push_back(Result.getValue(2));
7400 /// ReplaceNodeResults - Replace a node with an illegal result type
7401 /// with a new node built out of custom code.
7402 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7403 SmallVectorImpl<SDValue>&Results,
7404 SelectionDAG &DAG) {
7405 DebugLoc dl = N->getDebugLoc();
7406 switch (N->getOpcode()) {
7408 assert(false && "Do not know how to custom type legalize this operation!");
7410 case ISD::FP_TO_SINT: {
7411 std::pair<SDValue,SDValue> Vals =
7412 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
7413 SDValue FIST = Vals.first, StackSlot = Vals.second;
7414 if (FIST.getNode() != 0) {
7415 EVT VT = N->getValueType(0);
7416 // Return a load from the stack slot.
7417 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0));
7421 case ISD::READCYCLECOUNTER: {
7422 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7423 SDValue TheChain = N->getOperand(0);
7424 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7425 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7427 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7429 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7430 SDValue Ops[] = { eax, edx };
7431 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7432 Results.push_back(edx.getValue(1));
7439 EVT WidenVT = getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
7440 Results.push_back(DAG.UnrollVectorOp(N, WidenVT.getVectorNumElements()));
7443 case ISD::ATOMIC_CMP_SWAP: {
7444 EVT T = N->getValueType(0);
7445 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7446 SDValue cpInL, cpInH;
7447 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7448 DAG.getConstant(0, MVT::i32));
7449 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7450 DAG.getConstant(1, MVT::i32));
7451 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7452 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7454 SDValue swapInL, swapInH;
7455 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7456 DAG.getConstant(0, MVT::i32));
7457 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7458 DAG.getConstant(1, MVT::i32));
7459 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7461 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7462 swapInL.getValue(1));
7463 SDValue Ops[] = { swapInH.getValue(0),
7465 swapInH.getValue(1) };
7466 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7467 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7468 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7469 MVT::i32, Result.getValue(1));
7470 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7471 MVT::i32, cpOutL.getValue(2));
7472 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7473 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7474 Results.push_back(cpOutH.getValue(1));
7477 case ISD::ATOMIC_LOAD_ADD:
7478 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7480 case ISD::ATOMIC_LOAD_AND:
7481 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7483 case ISD::ATOMIC_LOAD_NAND:
7484 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7486 case ISD::ATOMIC_LOAD_OR:
7487 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7489 case ISD::ATOMIC_LOAD_SUB:
7490 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7492 case ISD::ATOMIC_LOAD_XOR:
7493 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7495 case ISD::ATOMIC_SWAP:
7496 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7501 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7503 default: return NULL;
7504 case X86ISD::BSF: return "X86ISD::BSF";
7505 case X86ISD::BSR: return "X86ISD::BSR";
7506 case X86ISD::SHLD: return "X86ISD::SHLD";
7507 case X86ISD::SHRD: return "X86ISD::SHRD";
7508 case X86ISD::FAND: return "X86ISD::FAND";
7509 case X86ISD::FOR: return "X86ISD::FOR";
7510 case X86ISD::FXOR: return "X86ISD::FXOR";
7511 case X86ISD::FSRL: return "X86ISD::FSRL";
7512 case X86ISD::FILD: return "X86ISD::FILD";
7513 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
7514 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7515 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7516 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7517 case X86ISD::FLD: return "X86ISD::FLD";
7518 case X86ISD::FST: return "X86ISD::FST";
7519 case X86ISD::CALL: return "X86ISD::CALL";
7520 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
7521 case X86ISD::BT: return "X86ISD::BT";
7522 case X86ISD::CMP: return "X86ISD::CMP";
7523 case X86ISD::COMI: return "X86ISD::COMI";
7524 case X86ISD::UCOMI: return "X86ISD::UCOMI";
7525 case X86ISD::SETCC: return "X86ISD::SETCC";
7526 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
7527 case X86ISD::CMOV: return "X86ISD::CMOV";
7528 case X86ISD::BRCOND: return "X86ISD::BRCOND";
7529 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
7530 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
7531 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
7532 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
7533 case X86ISD::Wrapper: return "X86ISD::Wrapper";
7534 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
7535 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
7536 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
7537 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
7538 case X86ISD::PINSRB: return "X86ISD::PINSRB";
7539 case X86ISD::PINSRW: return "X86ISD::PINSRW";
7540 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
7541 case X86ISD::FMAX: return "X86ISD::FMAX";
7542 case X86ISD::FMIN: return "X86ISD::FMIN";
7543 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
7544 case X86ISD::FRCP: return "X86ISD::FRCP";
7545 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
7546 case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7547 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
7548 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
7549 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
7550 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
7551 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
7552 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
7553 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
7554 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
7555 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
7556 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
7557 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
7558 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
7559 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
7560 case X86ISD::VSHL: return "X86ISD::VSHL";
7561 case X86ISD::VSRL: return "X86ISD::VSRL";
7562 case X86ISD::CMPPD: return "X86ISD::CMPPD";
7563 case X86ISD::CMPPS: return "X86ISD::CMPPS";
7564 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
7565 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
7566 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
7567 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
7568 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
7569 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
7570 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
7571 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
7572 case X86ISD::ADD: return "X86ISD::ADD";
7573 case X86ISD::SUB: return "X86ISD::SUB";
7574 case X86ISD::SMUL: return "X86ISD::SMUL";
7575 case X86ISD::UMUL: return "X86ISD::UMUL";
7576 case X86ISD::INC: return "X86ISD::INC";
7577 case X86ISD::DEC: return "X86ISD::DEC";
7578 case X86ISD::OR: return "X86ISD::OR";
7579 case X86ISD::XOR: return "X86ISD::XOR";
7580 case X86ISD::AND: return "X86ISD::AND";
7581 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
7582 case X86ISD::PTEST: return "X86ISD::PTEST";
7583 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
7587 // isLegalAddressingMode - Return true if the addressing mode represented
7588 // by AM is legal for this target, for a load/store of the specified type.
7589 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7590 const Type *Ty) const {
7591 // X86 supports extremely general addressing modes.
7592 CodeModel::Model M = getTargetMachine().getCodeModel();
7594 // X86 allows a sign-extended 32-bit immediate field as a displacement.
7595 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
7600 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7602 // If a reference to this global requires an extra load, we can't fold it.
7603 if (isGlobalStubReference(GVFlags))
7606 // If BaseGV requires a register for the PIC base, we cannot also have a
7607 // BaseReg specified.
7608 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
7611 // If lower 4G is not available, then we must use rip-relative addressing.
7612 if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
7622 // These scales always work.
7627 // These scales are formed with basereg+scalereg. Only accept if there is
7632 default: // Other stuff never works.
7640 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7641 if (!Ty1->isInteger() || !Ty2->isInteger())
7643 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7644 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7645 if (NumBits1 <= NumBits2)
7647 return Subtarget->is64Bit() || NumBits1 < 64;
7650 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7651 if (!VT1.isInteger() || !VT2.isInteger())
7653 unsigned NumBits1 = VT1.getSizeInBits();
7654 unsigned NumBits2 = VT2.getSizeInBits();
7655 if (NumBits1 <= NumBits2)
7657 return Subtarget->is64Bit() || NumBits1 < 64;
7660 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7661 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7662 return Ty1->isInteger(32) && Ty2->isInteger(64) && Subtarget->is64Bit();
7665 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7666 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7667 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7670 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
7671 // i16 instructions are longer (0x66 prefix) and potentially slower.
7672 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7675 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7676 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7677 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7678 /// are assumed to be legal.
7680 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
7682 // Only do shuffles on 128-bit vector types for now.
7683 if (VT.getSizeInBits() == 64)
7686 // FIXME: pshufb, blends, shifts.
7687 return (VT.getVectorNumElements() == 2 ||
7688 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7689 isMOVLMask(M, VT) ||
7690 isSHUFPMask(M, VT) ||
7691 isPSHUFDMask(M, VT) ||
7692 isPSHUFHWMask(M, VT) ||
7693 isPSHUFLWMask(M, VT) ||
7694 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
7695 isUNPCKLMask(M, VT) ||
7696 isUNPCKHMask(M, VT) ||
7697 isUNPCKL_v_undef_Mask(M, VT) ||
7698 isUNPCKH_v_undef_Mask(M, VT));
7702 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
7704 unsigned NumElts = VT.getVectorNumElements();
7705 // FIXME: This collection of masks seems suspect.
7708 if (NumElts == 4 && VT.getSizeInBits() == 128) {
7709 return (isMOVLMask(Mask, VT) ||
7710 isCommutedMOVLMask(Mask, VT, true) ||
7711 isSHUFPMask(Mask, VT) ||
7712 isCommutedSHUFPMask(Mask, VT));
7717 //===----------------------------------------------------------------------===//
7718 // X86 Scheduler Hooks
7719 //===----------------------------------------------------------------------===//
7721 // private utility function
7723 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7724 MachineBasicBlock *MBB,
7732 TargetRegisterClass *RC,
7733 bool invSrc) const {
7734 // For the atomic bitwise operator, we generate
7737 // ld t1 = [bitinstr.addr]
7738 // op t2 = t1, [bitinstr.val]
7740 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7742 // fallthrough -->nextMBB
7743 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7744 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7745 MachineFunction::iterator MBBIter = MBB;
7748 /// First build the CFG
7749 MachineFunction *F = MBB->getParent();
7750 MachineBasicBlock *thisMBB = MBB;
7751 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7752 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7753 F->insert(MBBIter, newMBB);
7754 F->insert(MBBIter, nextMBB);
7756 // Move all successors to thisMBB to nextMBB
7757 nextMBB->transferSuccessors(thisMBB);
7759 // Update thisMBB to fall through to newMBB
7760 thisMBB->addSuccessor(newMBB);
7762 // newMBB jumps to itself and fall through to nextMBB
7763 newMBB->addSuccessor(nextMBB);
7764 newMBB->addSuccessor(newMBB);
7766 // Insert instructions into newMBB based on incoming instruction
7767 assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7768 "unexpected number of operands");
7769 DebugLoc dl = bInstr->getDebugLoc();
7770 MachineOperand& destOper = bInstr->getOperand(0);
7771 MachineOperand* argOpers[2 + X86AddrNumOperands];
7772 int numArgs = bInstr->getNumOperands() - 1;
7773 for (int i=0; i < numArgs; ++i)
7774 argOpers[i] = &bInstr->getOperand(i+1);
7776 // x86 address has 4 operands: base, index, scale, and displacement
7777 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7778 int valArgIndx = lastAddrIndx + 1;
7780 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7781 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7782 for (int i=0; i <= lastAddrIndx; ++i)
7783 (*MIB).addOperand(*argOpers[i]);
7785 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7787 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7792 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7793 assert((argOpers[valArgIndx]->isReg() ||
7794 argOpers[valArgIndx]->isImm()) &&
7796 if (argOpers[valArgIndx]->isReg())
7797 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7799 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7801 (*MIB).addOperand(*argOpers[valArgIndx]);
7803 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7806 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7807 for (int i=0; i <= lastAddrIndx; ++i)
7808 (*MIB).addOperand(*argOpers[i]);
7810 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7811 (*MIB).setMemRefs(bInstr->memoperands_begin(),
7812 bInstr->memoperands_end());
7814 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7818 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7820 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7824 // private utility function: 64 bit atomics on 32 bit host.
7826 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7827 MachineBasicBlock *MBB,
7832 bool invSrc) const {
7833 // For the atomic bitwise operator, we generate
7834 // thisMBB (instructions are in pairs, except cmpxchg8b)
7835 // ld t1,t2 = [bitinstr.addr]
7837 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7838 // op t5, t6 <- out1, out2, [bitinstr.val]
7839 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
7840 // mov ECX, EBX <- t5, t6
7841 // mov EAX, EDX <- t1, t2
7842 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
7843 // mov t3, t4 <- EAX, EDX
7845 // result in out1, out2
7846 // fallthrough -->nextMBB
7848 const TargetRegisterClass *RC = X86::GR32RegisterClass;
7849 const unsigned LoadOpc = X86::MOV32rm;
7850 const unsigned copyOpc = X86::MOV32rr;
7851 const unsigned NotOpc = X86::NOT32r;
7852 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7853 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7854 MachineFunction::iterator MBBIter = MBB;
7857 /// First build the CFG
7858 MachineFunction *F = MBB->getParent();
7859 MachineBasicBlock *thisMBB = MBB;
7860 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7861 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7862 F->insert(MBBIter, newMBB);
7863 F->insert(MBBIter, nextMBB);
7865 // Move all successors to thisMBB to nextMBB
7866 nextMBB->transferSuccessors(thisMBB);
7868 // Update thisMBB to fall through to newMBB
7869 thisMBB->addSuccessor(newMBB);
7871 // newMBB jumps to itself and fall through to nextMBB
7872 newMBB->addSuccessor(nextMBB);
7873 newMBB->addSuccessor(newMBB);
7875 DebugLoc dl = bInstr->getDebugLoc();
7876 // Insert instructions into newMBB based on incoming instruction
7877 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7878 assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
7879 "unexpected number of operands");
7880 MachineOperand& dest1Oper = bInstr->getOperand(0);
7881 MachineOperand& dest2Oper = bInstr->getOperand(1);
7882 MachineOperand* argOpers[2 + X86AddrNumOperands];
7883 for (int i=0; i < 2 + X86AddrNumOperands; ++i)
7884 argOpers[i] = &bInstr->getOperand(i+2);
7886 // x86 address has 5 operands: base, index, scale, displacement, and segment.
7887 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7889 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7890 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
7891 for (int i=0; i <= lastAddrIndx; ++i)
7892 (*MIB).addOperand(*argOpers[i]);
7893 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7894 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
7895 // add 4 to displacement.
7896 for (int i=0; i <= lastAddrIndx-2; ++i)
7897 (*MIB).addOperand(*argOpers[i]);
7898 MachineOperand newOp3 = *(argOpers[3]);
7900 newOp3.setImm(newOp3.getImm()+4);
7902 newOp3.setOffset(newOp3.getOffset()+4);
7903 (*MIB).addOperand(newOp3);
7904 (*MIB).addOperand(*argOpers[lastAddrIndx]);
7906 // t3/4 are defined later, at the bottom of the loop
7907 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
7908 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
7909 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
7910 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
7911 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
7912 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
7914 // The subsequent operations should be using the destination registers of
7915 //the PHI instructions.
7917 t1 = F->getRegInfo().createVirtualRegister(RC);
7918 t2 = F->getRegInfo().createVirtualRegister(RC);
7919 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
7920 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
7922 t1 = dest1Oper.getReg();
7923 t2 = dest2Oper.getReg();
7926 int valArgIndx = lastAddrIndx + 1;
7927 assert((argOpers[valArgIndx]->isReg() ||
7928 argOpers[valArgIndx]->isImm()) &&
7930 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
7931 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
7932 if (argOpers[valArgIndx]->isReg())
7933 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
7935 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
7936 if (regOpcL != X86::MOV32rr)
7938 (*MIB).addOperand(*argOpers[valArgIndx]);
7939 assert(argOpers[valArgIndx + 1]->isReg() ==
7940 argOpers[valArgIndx]->isReg());
7941 assert(argOpers[valArgIndx + 1]->isImm() ==
7942 argOpers[valArgIndx]->isImm());
7943 if (argOpers[valArgIndx + 1]->isReg())
7944 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
7946 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
7947 if (regOpcH != X86::MOV32rr)
7949 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
7951 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
7953 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
7956 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
7958 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
7961 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
7962 for (int i=0; i <= lastAddrIndx; ++i)
7963 (*MIB).addOperand(*argOpers[i]);
7965 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7966 (*MIB).setMemRefs(bInstr->memoperands_begin(),
7967 bInstr->memoperands_end());
7969 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
7970 MIB.addReg(X86::EAX);
7971 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
7972 MIB.addReg(X86::EDX);
7975 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7977 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7981 // private utility function
7983 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
7984 MachineBasicBlock *MBB,
7985 unsigned cmovOpc) const {
7986 // For the atomic min/max operator, we generate
7989 // ld t1 = [min/max.addr]
7990 // mov t2 = [min/max.val]
7992 // cmov[cond] t2 = t1
7994 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7996 // fallthrough -->nextMBB
7998 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7999 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8000 MachineFunction::iterator MBBIter = MBB;
8003 /// First build the CFG
8004 MachineFunction *F = MBB->getParent();
8005 MachineBasicBlock *thisMBB = MBB;
8006 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8007 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8008 F->insert(MBBIter, newMBB);
8009 F->insert(MBBIter, nextMBB);
8011 // Move all successors of thisMBB to nextMBB
8012 nextMBB->transferSuccessors(thisMBB);
8014 // Update thisMBB to fall through to newMBB
8015 thisMBB->addSuccessor(newMBB);
8017 // newMBB jumps to newMBB and fall through to nextMBB
8018 newMBB->addSuccessor(nextMBB);
8019 newMBB->addSuccessor(newMBB);
8021 DebugLoc dl = mInstr->getDebugLoc();
8022 // Insert instructions into newMBB based on incoming instruction
8023 assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
8024 "unexpected number of operands");
8025 MachineOperand& destOper = mInstr->getOperand(0);
8026 MachineOperand* argOpers[2 + X86AddrNumOperands];
8027 int numArgs = mInstr->getNumOperands() - 1;
8028 for (int i=0; i < numArgs; ++i)
8029 argOpers[i] = &mInstr->getOperand(i+1);
8031 // x86 address has 4 operands: base, index, scale, and displacement
8032 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8033 int valArgIndx = lastAddrIndx + 1;
8035 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8036 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
8037 for (int i=0; i <= lastAddrIndx; ++i)
8038 (*MIB).addOperand(*argOpers[i]);
8040 // We only support register and immediate values
8041 assert((argOpers[valArgIndx]->isReg() ||
8042 argOpers[valArgIndx]->isImm()) &&
8045 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8046 if (argOpers[valArgIndx]->isReg())
8047 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8049 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8050 (*MIB).addOperand(*argOpers[valArgIndx]);
8052 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
8055 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
8060 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8061 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
8065 // Cmp and exchange if none has modified the memory location
8066 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
8067 for (int i=0; i <= lastAddrIndx; ++i)
8068 (*MIB).addOperand(*argOpers[i]);
8070 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8071 (*MIB).setMemRefs(mInstr->memoperands_begin(),
8072 mInstr->memoperands_end());
8074 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
8075 MIB.addReg(X86::EAX);
8078 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
8080 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
8084 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
8085 // all of this code can be replaced with that in the .td file.
8087 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
8088 unsigned numArgs, bool memArg) const {
8090 MachineFunction *F = BB->getParent();
8091 DebugLoc dl = MI->getDebugLoc();
8092 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8096 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
8098 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
8100 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
8102 for (unsigned i = 0; i < numArgs; ++i) {
8103 MachineOperand &Op = MI->getOperand(i+1);
8105 if (!(Op.isReg() && Op.isImplicit()))
8109 BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
8112 F->DeleteMachineInstr(MI);
8118 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
8120 MachineBasicBlock *MBB) const {
8121 // Emit code to save XMM registers to the stack. The ABI says that the
8122 // number of registers to save is given in %al, so it's theoretically
8123 // possible to do an indirect jump trick to avoid saving all of them,
8124 // however this code takes a simpler approach and just executes all
8125 // of the stores if %al is non-zero. It's less code, and it's probably
8126 // easier on the hardware branch predictor, and stores aren't all that
8127 // expensive anyway.
8129 // Create the new basic blocks. One block contains all the XMM stores,
8130 // and one block is the final destination regardless of whether any
8131 // stores were performed.
8132 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8133 MachineFunction *F = MBB->getParent();
8134 MachineFunction::iterator MBBIter = MBB;
8136 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
8137 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
8138 F->insert(MBBIter, XMMSaveMBB);
8139 F->insert(MBBIter, EndMBB);
8142 // Move any original successors of MBB to the end block.
8143 EndMBB->transferSuccessors(MBB);
8144 // The original block will now fall through to the XMM save block.
8145 MBB->addSuccessor(XMMSaveMBB);
8146 // The XMMSaveMBB will fall through to the end block.
8147 XMMSaveMBB->addSuccessor(EndMBB);
8149 // Now add the instructions.
8150 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8151 DebugLoc DL = MI->getDebugLoc();
8153 unsigned CountReg = MI->getOperand(0).getReg();
8154 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
8155 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
8157 if (!Subtarget->isTargetWin64()) {
8158 // If %al is 0, branch around the XMM save block.
8159 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
8160 BuildMI(MBB, DL, TII->get(X86::JE)).addMBB(EndMBB);
8161 MBB->addSuccessor(EndMBB);
8164 // In the XMM save block, save all the XMM argument registers.
8165 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
8166 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
8167 MachineMemOperand *MMO =
8168 F->getMachineMemOperand(
8169 PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
8170 MachineMemOperand::MOStore, Offset,
8171 /*Size=*/16, /*Align=*/16);
8172 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
8173 .addFrameIndex(RegSaveFrameIndex)
8174 .addImm(/*Scale=*/1)
8175 .addReg(/*IndexReg=*/0)
8176 .addImm(/*Disp=*/Offset)
8177 .addReg(/*Segment=*/0)
8178 .addReg(MI->getOperand(i).getReg())
8179 .addMemOperand(MMO);
8182 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8188 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
8189 MachineBasicBlock *BB,
8190 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8191 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8192 DebugLoc DL = MI->getDebugLoc();
8194 // To "insert" a SELECT_CC instruction, we actually have to insert the
8195 // diamond control-flow pattern. The incoming instruction knows the
8196 // destination vreg to set, the condition code register to branch on, the
8197 // true/false values to select between, and a branch opcode to use.
8198 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8199 MachineFunction::iterator It = BB;
8205 // cmpTY ccX, r1, r2
8207 // fallthrough --> copy0MBB
8208 MachineBasicBlock *thisMBB = BB;
8209 MachineFunction *F = BB->getParent();
8210 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8211 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8213 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
8214 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
8215 F->insert(It, copy0MBB);
8216 F->insert(It, sinkMBB);
8217 // Update machine-CFG edges by first adding all successors of the current
8218 // block to the new block which will contain the Phi node for the select.
8219 // Also inform sdisel of the edge changes.
8220 for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
8221 E = BB->succ_end(); I != E; ++I) {
8222 EM->insert(std::make_pair(*I, sinkMBB));
8223 sinkMBB->addSuccessor(*I);
8225 // Next, remove all successors of the current block, and add the true
8226 // and fallthrough blocks as its successors.
8227 while (!BB->succ_empty())
8228 BB->removeSuccessor(BB->succ_begin());
8229 // Add the true and fallthrough blocks as its successors.
8230 BB->addSuccessor(copy0MBB);
8231 BB->addSuccessor(sinkMBB);
8234 // %FalseValue = ...
8235 // # fallthrough to sinkMBB
8238 // Update machine-CFG edges
8239 BB->addSuccessor(sinkMBB);
8242 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8245 BuildMI(BB, DL, TII->get(X86::PHI), MI->getOperand(0).getReg())
8246 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8247 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8249 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8255 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8256 MachineBasicBlock *BB,
8257 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8258 switch (MI->getOpcode()) {
8259 default: assert(false && "Unexpected instr type to insert");
8261 case X86::CMOV_V1I64:
8262 case X86::CMOV_FR32:
8263 case X86::CMOV_FR64:
8264 case X86::CMOV_V4F32:
8265 case X86::CMOV_V2F64:
8266 case X86::CMOV_V2I64:
8267 return EmitLoweredSelect(MI, BB, EM);
8269 case X86::FP32_TO_INT16_IN_MEM:
8270 case X86::FP32_TO_INT32_IN_MEM:
8271 case X86::FP32_TO_INT64_IN_MEM:
8272 case X86::FP64_TO_INT16_IN_MEM:
8273 case X86::FP64_TO_INT32_IN_MEM:
8274 case X86::FP64_TO_INT64_IN_MEM:
8275 case X86::FP80_TO_INT16_IN_MEM:
8276 case X86::FP80_TO_INT32_IN_MEM:
8277 case X86::FP80_TO_INT64_IN_MEM: {
8278 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8279 DebugLoc DL = MI->getDebugLoc();
8281 // Change the floating point control register to use "round towards zero"
8282 // mode when truncating to an integer value.
8283 MachineFunction *F = BB->getParent();
8284 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
8285 addFrameReference(BuildMI(BB, DL, TII->get(X86::FNSTCW16m)), CWFrameIdx);
8287 // Load the old value of the high byte of the control word...
8289 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
8290 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16rm), OldCW),
8293 // Set the high part to be round to zero...
8294 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
8297 // Reload the modified control word now...
8298 addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8300 // Restore the memory image of control word to original value
8301 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
8304 // Get the X86 opcode to use.
8306 switch (MI->getOpcode()) {
8307 default: llvm_unreachable("illegal opcode!");
8308 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
8309 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
8310 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
8311 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
8312 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
8313 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
8314 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
8315 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
8316 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
8320 MachineOperand &Op = MI->getOperand(0);
8322 AM.BaseType = X86AddressMode::RegBase;
8323 AM.Base.Reg = Op.getReg();
8325 AM.BaseType = X86AddressMode::FrameIndexBase;
8326 AM.Base.FrameIndex = Op.getIndex();
8328 Op = MI->getOperand(1);
8330 AM.Scale = Op.getImm();
8331 Op = MI->getOperand(2);
8333 AM.IndexReg = Op.getImm();
8334 Op = MI->getOperand(3);
8335 if (Op.isGlobal()) {
8336 AM.GV = Op.getGlobal();
8338 AM.Disp = Op.getImm();
8340 addFullAddress(BuildMI(BB, DL, TII->get(Opc)), AM)
8341 .addReg(MI->getOperand(X86AddrNumOperands).getReg());
8343 // Reload the original control word now.
8344 addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8346 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8349 // String/text processing lowering.
8350 case X86::PCMPISTRM128REG:
8351 return EmitPCMP(MI, BB, 3, false /* in-mem */);
8352 case X86::PCMPISTRM128MEM:
8353 return EmitPCMP(MI, BB, 3, true /* in-mem */);
8354 case X86::PCMPESTRM128REG:
8355 return EmitPCMP(MI, BB, 5, false /* in mem */);
8356 case X86::PCMPESTRM128MEM:
8357 return EmitPCMP(MI, BB, 5, true /* in mem */);
8360 case X86::ATOMAND32:
8361 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8362 X86::AND32ri, X86::MOV32rm,
8363 X86::LCMPXCHG32, X86::MOV32rr,
8364 X86::NOT32r, X86::EAX,
8365 X86::GR32RegisterClass);
8367 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
8368 X86::OR32ri, X86::MOV32rm,
8369 X86::LCMPXCHG32, X86::MOV32rr,
8370 X86::NOT32r, X86::EAX,
8371 X86::GR32RegisterClass);
8372 case X86::ATOMXOR32:
8373 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
8374 X86::XOR32ri, X86::MOV32rm,
8375 X86::LCMPXCHG32, X86::MOV32rr,
8376 X86::NOT32r, X86::EAX,
8377 X86::GR32RegisterClass);
8378 case X86::ATOMNAND32:
8379 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8380 X86::AND32ri, X86::MOV32rm,
8381 X86::LCMPXCHG32, X86::MOV32rr,
8382 X86::NOT32r, X86::EAX,
8383 X86::GR32RegisterClass, true);
8384 case X86::ATOMMIN32:
8385 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
8386 case X86::ATOMMAX32:
8387 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
8388 case X86::ATOMUMIN32:
8389 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
8390 case X86::ATOMUMAX32:
8391 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
8393 case X86::ATOMAND16:
8394 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8395 X86::AND16ri, X86::MOV16rm,
8396 X86::LCMPXCHG16, X86::MOV16rr,
8397 X86::NOT16r, X86::AX,
8398 X86::GR16RegisterClass);
8400 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
8401 X86::OR16ri, X86::MOV16rm,
8402 X86::LCMPXCHG16, X86::MOV16rr,
8403 X86::NOT16r, X86::AX,
8404 X86::GR16RegisterClass);
8405 case X86::ATOMXOR16:
8406 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
8407 X86::XOR16ri, X86::MOV16rm,
8408 X86::LCMPXCHG16, X86::MOV16rr,
8409 X86::NOT16r, X86::AX,
8410 X86::GR16RegisterClass);
8411 case X86::ATOMNAND16:
8412 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8413 X86::AND16ri, X86::MOV16rm,
8414 X86::LCMPXCHG16, X86::MOV16rr,
8415 X86::NOT16r, X86::AX,
8416 X86::GR16RegisterClass, true);
8417 case X86::ATOMMIN16:
8418 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
8419 case X86::ATOMMAX16:
8420 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
8421 case X86::ATOMUMIN16:
8422 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
8423 case X86::ATOMUMAX16:
8424 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
8427 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8428 X86::AND8ri, X86::MOV8rm,
8429 X86::LCMPXCHG8, X86::MOV8rr,
8430 X86::NOT8r, X86::AL,
8431 X86::GR8RegisterClass);
8433 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
8434 X86::OR8ri, X86::MOV8rm,
8435 X86::LCMPXCHG8, X86::MOV8rr,
8436 X86::NOT8r, X86::AL,
8437 X86::GR8RegisterClass);
8439 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
8440 X86::XOR8ri, X86::MOV8rm,
8441 X86::LCMPXCHG8, X86::MOV8rr,
8442 X86::NOT8r, X86::AL,
8443 X86::GR8RegisterClass);
8444 case X86::ATOMNAND8:
8445 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8446 X86::AND8ri, X86::MOV8rm,
8447 X86::LCMPXCHG8, X86::MOV8rr,
8448 X86::NOT8r, X86::AL,
8449 X86::GR8RegisterClass, true);
8450 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
8451 // This group is for 64-bit host.
8452 case X86::ATOMAND64:
8453 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8454 X86::AND64ri32, X86::MOV64rm,
8455 X86::LCMPXCHG64, X86::MOV64rr,
8456 X86::NOT64r, X86::RAX,
8457 X86::GR64RegisterClass);
8459 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
8460 X86::OR64ri32, X86::MOV64rm,
8461 X86::LCMPXCHG64, X86::MOV64rr,
8462 X86::NOT64r, X86::RAX,
8463 X86::GR64RegisterClass);
8464 case X86::ATOMXOR64:
8465 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
8466 X86::XOR64ri32, X86::MOV64rm,
8467 X86::LCMPXCHG64, X86::MOV64rr,
8468 X86::NOT64r, X86::RAX,
8469 X86::GR64RegisterClass);
8470 case X86::ATOMNAND64:
8471 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8472 X86::AND64ri32, X86::MOV64rm,
8473 X86::LCMPXCHG64, X86::MOV64rr,
8474 X86::NOT64r, X86::RAX,
8475 X86::GR64RegisterClass, true);
8476 case X86::ATOMMIN64:
8477 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
8478 case X86::ATOMMAX64:
8479 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
8480 case X86::ATOMUMIN64:
8481 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
8482 case X86::ATOMUMAX64:
8483 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
8485 // This group does 64-bit operations on a 32-bit host.
8486 case X86::ATOMAND6432:
8487 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8488 X86::AND32rr, X86::AND32rr,
8489 X86::AND32ri, X86::AND32ri,
8491 case X86::ATOMOR6432:
8492 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8493 X86::OR32rr, X86::OR32rr,
8494 X86::OR32ri, X86::OR32ri,
8496 case X86::ATOMXOR6432:
8497 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8498 X86::XOR32rr, X86::XOR32rr,
8499 X86::XOR32ri, X86::XOR32ri,
8501 case X86::ATOMNAND6432:
8502 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8503 X86::AND32rr, X86::AND32rr,
8504 X86::AND32ri, X86::AND32ri,
8506 case X86::ATOMADD6432:
8507 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8508 X86::ADD32rr, X86::ADC32rr,
8509 X86::ADD32ri, X86::ADC32ri,
8511 case X86::ATOMSUB6432:
8512 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8513 X86::SUB32rr, X86::SBB32rr,
8514 X86::SUB32ri, X86::SBB32ri,
8516 case X86::ATOMSWAP6432:
8517 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8518 X86::MOV32rr, X86::MOV32rr,
8519 X86::MOV32ri, X86::MOV32ri,
8521 case X86::VASTART_SAVE_XMM_REGS:
8522 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
8526 //===----------------------------------------------------------------------===//
8527 // X86 Optimization Hooks
8528 //===----------------------------------------------------------------------===//
8530 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8534 const SelectionDAG &DAG,
8535 unsigned Depth) const {
8536 unsigned Opc = Op.getOpcode();
8537 assert((Opc >= ISD::BUILTIN_OP_END ||
8538 Opc == ISD::INTRINSIC_WO_CHAIN ||
8539 Opc == ISD::INTRINSIC_W_CHAIN ||
8540 Opc == ISD::INTRINSIC_VOID) &&
8541 "Should use MaskedValueIsZero if you don't know whether Op"
8542 " is a target node!");
8544 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
8556 // These nodes' second result is a boolean.
8557 if (Op.getResNo() == 0)
8561 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
8562 Mask.getBitWidth() - 1);
8567 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
8568 /// node is a GlobalAddress + offset.
8569 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
8570 GlobalValue* &GA, int64_t &Offset) const{
8571 if (N->getOpcode() == X86ISD::Wrapper) {
8572 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
8573 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
8574 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
8578 return TargetLowering::isGAPlusOffset(N, GA, Offset);
8581 static bool EltsFromConsecutiveLoads(ShuffleVectorSDNode *N, unsigned NumElems,
8582 EVT EltVT, LoadSDNode *&LDBase,
8583 unsigned &LastLoadedElt,
8584 SelectionDAG &DAG, MachineFrameInfo *MFI,
8585 const TargetLowering &TLI) {
8587 LastLoadedElt = -1U;
8588 for (unsigned i = 0; i < NumElems; ++i) {
8589 if (N->getMaskElt(i) < 0) {
8595 SDValue Elt = DAG.getShuffleScalarElt(N, i);
8596 if (!Elt.getNode() ||
8597 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
8600 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
8602 LDBase = cast<LoadSDNode>(Elt.getNode());
8606 if (Elt.getOpcode() == ISD::UNDEF)
8609 LoadSDNode *LD = cast<LoadSDNode>(Elt);
8610 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
8617 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8618 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8619 /// if the load addresses are consecutive, non-overlapping, and in the right
8620 /// order. In the case of v2i64, it will see if it can rewrite the
8621 /// shuffle to be an appropriate build vector so it can take advantage of
8622 // performBuildVectorCombine.
8623 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8624 const TargetLowering &TLI) {
8625 DebugLoc dl = N->getDebugLoc();
8626 EVT VT = N->getValueType(0);
8627 EVT EltVT = VT.getVectorElementType();
8628 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8629 unsigned NumElems = VT.getVectorNumElements();
8631 if (VT.getSizeInBits() != 128)
8634 // Try to combine a vector_shuffle into a 128-bit load.
8635 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8636 LoadSDNode *LD = NULL;
8637 unsigned LastLoadedElt;
8638 if (!EltsFromConsecutiveLoads(SVN, NumElems, EltVT, LD, LastLoadedElt, DAG,
8642 if (LastLoadedElt == NumElems - 1) {
8643 if (DAG.InferPtrAlignment(LD->getBasePtr()) >= 16)
8644 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8645 LD->getSrcValue(), LD->getSrcValueOffset(),
8647 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8648 LD->getSrcValue(), LD->getSrcValueOffset(),
8649 LD->isVolatile(), LD->getAlignment());
8650 } else if (NumElems == 4 && LastLoadedElt == 1) {
8651 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
8652 SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
8653 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
8654 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
8659 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
8660 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
8661 const X86Subtarget *Subtarget) {
8662 DebugLoc DL = N->getDebugLoc();
8663 SDValue Cond = N->getOperand(0);
8664 // Get the LHS/RHS of the select.
8665 SDValue LHS = N->getOperand(1);
8666 SDValue RHS = N->getOperand(2);
8668 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
8669 // instructions have the peculiarity that if either operand is a NaN,
8670 // they chose what we call the RHS operand (and as such are not symmetric).
8671 // It happens that this matches the semantics of the common C idiom
8672 // x<y?x:y and related forms, so we can recognize these cases.
8673 if (Subtarget->hasSSE2() &&
8674 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
8675 Cond.getOpcode() == ISD::SETCC) {
8676 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
8678 unsigned Opcode = 0;
8679 // Check for x CC y ? x : y.
8680 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
8684 // This can be a min if we can prove that at least one of the operands
8686 if (!FiniteOnlyFPMath()) {
8687 if (DAG.isKnownNeverNaN(RHS)) {
8688 // Put the potential NaN in the RHS so that SSE will preserve it.
8689 std::swap(LHS, RHS);
8690 } else if (!DAG.isKnownNeverNaN(LHS))
8693 Opcode = X86ISD::FMIN;
8696 // This can be a min if we can prove that at least one of the operands
8698 if (!FiniteOnlyFPMath()) {
8699 if (DAG.isKnownNeverNaN(LHS)) {
8700 // Put the potential NaN in the RHS so that SSE will preserve it.
8701 std::swap(LHS, RHS);
8702 } else if (!DAG.isKnownNeverNaN(RHS))
8705 Opcode = X86ISD::FMIN;
8708 // This can be a min, but if either operand is a NaN we need it to
8709 // preserve the original LHS.
8710 std::swap(LHS, RHS);
8714 Opcode = X86ISD::FMIN;
8718 // This can be a max if we can prove that at least one of the operands
8720 if (!FiniteOnlyFPMath()) {
8721 if (DAG.isKnownNeverNaN(LHS)) {
8722 // Put the potential NaN in the RHS so that SSE will preserve it.
8723 std::swap(LHS, RHS);
8724 } else if (!DAG.isKnownNeverNaN(RHS))
8727 Opcode = X86ISD::FMAX;
8730 // This can be a max if we can prove that at least one of the operands
8732 if (!FiniteOnlyFPMath()) {
8733 if (DAG.isKnownNeverNaN(RHS)) {
8734 // Put the potential NaN in the RHS so that SSE will preserve it.
8735 std::swap(LHS, RHS);
8736 } else if (!DAG.isKnownNeverNaN(LHS))
8739 Opcode = X86ISD::FMAX;
8742 // This can be a max, but if either operand is a NaN we need it to
8743 // preserve the original LHS.
8744 std::swap(LHS, RHS);
8748 Opcode = X86ISD::FMAX;
8751 // Check for x CC y ? y : x -- a min/max with reversed arms.
8752 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
8756 // This can be a min if we can prove that at least one of the operands
8758 if (!FiniteOnlyFPMath()) {
8759 if (DAG.isKnownNeverNaN(RHS)) {
8760 // Put the potential NaN in the RHS so that SSE will preserve it.
8761 std::swap(LHS, RHS);
8762 } else if (!DAG.isKnownNeverNaN(LHS))
8765 Opcode = X86ISD::FMIN;
8768 // This can be a min if we can prove that at least one of the operands
8770 if (!FiniteOnlyFPMath()) {
8771 if (DAG.isKnownNeverNaN(LHS)) {
8772 // Put the potential NaN in the RHS so that SSE will preserve it.
8773 std::swap(LHS, RHS);
8774 } else if (!DAG.isKnownNeverNaN(RHS))
8777 Opcode = X86ISD::FMIN;
8780 // This can be a min, but if either operand is a NaN we need it to
8781 // preserve the original LHS.
8782 std::swap(LHS, RHS);
8786 Opcode = X86ISD::FMIN;
8790 // This can be a max if we can prove that at least one of the operands
8792 if (!FiniteOnlyFPMath()) {
8793 if (DAG.isKnownNeverNaN(LHS)) {
8794 // Put the potential NaN in the RHS so that SSE will preserve it.
8795 std::swap(LHS, RHS);
8796 } else if (!DAG.isKnownNeverNaN(RHS))
8799 Opcode = X86ISD::FMAX;
8802 // This can be a max if we can prove that at least one of the operands
8804 if (!FiniteOnlyFPMath()) {
8805 if (DAG.isKnownNeverNaN(RHS)) {
8806 // Put the potential NaN in the RHS so that SSE will preserve it.
8807 std::swap(LHS, RHS);
8808 } else if (!DAG.isKnownNeverNaN(LHS))
8811 Opcode = X86ISD::FMAX;
8814 // This can be a max, but if either operand is a NaN we need it to
8815 // preserve the original LHS.
8816 std::swap(LHS, RHS);
8820 Opcode = X86ISD::FMAX;
8826 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
8829 // If this is a select between two integer constants, try to do some
8831 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
8832 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
8833 // Don't do this for crazy integer types.
8834 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
8835 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
8836 // so that TrueC (the true value) is larger than FalseC.
8837 bool NeedsCondInvert = false;
8839 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
8840 // Efficiently invertible.
8841 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
8842 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
8843 isa<ConstantSDNode>(Cond.getOperand(1))))) {
8844 NeedsCondInvert = true;
8845 std::swap(TrueC, FalseC);
8848 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
8849 if (FalseC->getAPIntValue() == 0 &&
8850 TrueC->getAPIntValue().isPowerOf2()) {
8851 if (NeedsCondInvert) // Invert the condition if needed.
8852 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8853 DAG.getConstant(1, Cond.getValueType()));
8855 // Zero extend the condition if needed.
8856 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
8858 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8859 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
8860 DAG.getConstant(ShAmt, MVT::i8));
8863 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
8864 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8865 if (NeedsCondInvert) // Invert the condition if needed.
8866 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8867 DAG.getConstant(1, Cond.getValueType()));
8869 // Zero extend the condition if needed.
8870 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8871 FalseC->getValueType(0), Cond);
8872 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8873 SDValue(FalseC, 0));
8876 // Optimize cases that will turn into an LEA instruction. This requires
8877 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8878 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8879 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8880 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8882 bool isFastMultiplier = false;
8884 switch ((unsigned char)Diff) {
8886 case 1: // result = add base, cond
8887 case 2: // result = lea base( , cond*2)
8888 case 3: // result = lea base(cond, cond*2)
8889 case 4: // result = lea base( , cond*4)
8890 case 5: // result = lea base(cond, cond*4)
8891 case 8: // result = lea base( , cond*8)
8892 case 9: // result = lea base(cond, cond*8)
8893 isFastMultiplier = true;
8898 if (isFastMultiplier) {
8899 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8900 if (NeedsCondInvert) // Invert the condition if needed.
8901 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8902 DAG.getConstant(1, Cond.getValueType()));
8904 // Zero extend the condition if needed.
8905 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8907 // Scale the condition by the difference.
8909 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8910 DAG.getConstant(Diff, Cond.getValueType()));
8912 // Add the base if non-zero.
8913 if (FalseC->getAPIntValue() != 0)
8914 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8915 SDValue(FalseC, 0));
8925 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
8926 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
8927 TargetLowering::DAGCombinerInfo &DCI) {
8928 DebugLoc DL = N->getDebugLoc();
8930 // If the flag operand isn't dead, don't touch this CMOV.
8931 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
8934 // If this is a select between two integer constants, try to do some
8935 // optimizations. Note that the operands are ordered the opposite of SELECT
8937 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
8938 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8939 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
8940 // larger than FalseC (the false value).
8941 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
8943 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
8944 CC = X86::GetOppositeBranchCondition(CC);
8945 std::swap(TrueC, FalseC);
8948 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
8949 // This is efficient for any integer data type (including i8/i16) and
8951 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
8952 SDValue Cond = N->getOperand(3);
8953 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8954 DAG.getConstant(CC, MVT::i8), Cond);
8956 // Zero extend the condition if needed.
8957 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
8959 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8960 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
8961 DAG.getConstant(ShAmt, MVT::i8));
8962 if (N->getNumValues() == 2) // Dead flag value?
8963 return DCI.CombineTo(N, Cond, SDValue());
8967 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
8968 // for any integer data type, including i8/i16.
8969 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8970 SDValue Cond = N->getOperand(3);
8971 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8972 DAG.getConstant(CC, MVT::i8), Cond);
8974 // Zero extend the condition if needed.
8975 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8976 FalseC->getValueType(0), Cond);
8977 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8978 SDValue(FalseC, 0));
8980 if (N->getNumValues() == 2) // Dead flag value?
8981 return DCI.CombineTo(N, Cond, SDValue());
8985 // Optimize cases that will turn into an LEA instruction. This requires
8986 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8987 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8988 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8989 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8991 bool isFastMultiplier = false;
8993 switch ((unsigned char)Diff) {
8995 case 1: // result = add base, cond
8996 case 2: // result = lea base( , cond*2)
8997 case 3: // result = lea base(cond, cond*2)
8998 case 4: // result = lea base( , cond*4)
8999 case 5: // result = lea base(cond, cond*4)
9000 case 8: // result = lea base( , cond*8)
9001 case 9: // result = lea base(cond, cond*8)
9002 isFastMultiplier = true;
9007 if (isFastMultiplier) {
9008 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9009 SDValue Cond = N->getOperand(3);
9010 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9011 DAG.getConstant(CC, MVT::i8), Cond);
9012 // Zero extend the condition if needed.
9013 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9015 // Scale the condition by the difference.
9017 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9018 DAG.getConstant(Diff, Cond.getValueType()));
9020 // Add the base if non-zero.
9021 if (FalseC->getAPIntValue() != 0)
9022 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9023 SDValue(FalseC, 0));
9024 if (N->getNumValues() == 2) // Dead flag value?
9025 return DCI.CombineTo(N, Cond, SDValue());
9035 /// PerformMulCombine - Optimize a single multiply with constant into two
9036 /// in order to implement it with two cheaper instructions, e.g.
9037 /// LEA + SHL, LEA + LEA.
9038 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
9039 TargetLowering::DAGCombinerInfo &DCI) {
9040 if (DAG.getMachineFunction().
9041 getFunction()->hasFnAttr(Attribute::OptimizeForSize))
9044 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9047 EVT VT = N->getValueType(0);
9051 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9054 uint64_t MulAmt = C->getZExtValue();
9055 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
9058 uint64_t MulAmt1 = 0;
9059 uint64_t MulAmt2 = 0;
9060 if ((MulAmt % 9) == 0) {
9062 MulAmt2 = MulAmt / 9;
9063 } else if ((MulAmt % 5) == 0) {
9065 MulAmt2 = MulAmt / 5;
9066 } else if ((MulAmt % 3) == 0) {
9068 MulAmt2 = MulAmt / 3;
9071 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
9072 DebugLoc DL = N->getDebugLoc();
9074 if (isPowerOf2_64(MulAmt2) &&
9075 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
9076 // If second multiplifer is pow2, issue it first. We want the multiply by
9077 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
9079 std::swap(MulAmt1, MulAmt2);
9082 if (isPowerOf2_64(MulAmt1))
9083 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
9084 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
9086 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
9087 DAG.getConstant(MulAmt1, VT));
9089 if (isPowerOf2_64(MulAmt2))
9090 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
9091 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
9093 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
9094 DAG.getConstant(MulAmt2, VT));
9096 // Do not add new nodes to DAG combiner worklist.
9097 DCI.CombineTo(N, NewMul, false);
9102 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
9103 SDValue N0 = N->getOperand(0);
9104 SDValue N1 = N->getOperand(1);
9105 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9106 EVT VT = N0.getValueType();
9108 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
9109 // since the result of setcc_c is all zero's or all ones.
9110 if (N1C && N0.getOpcode() == ISD::AND &&
9111 N0.getOperand(1).getOpcode() == ISD::Constant) {
9112 SDValue N00 = N0.getOperand(0);
9113 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
9114 ((N00.getOpcode() == ISD::ANY_EXTEND ||
9115 N00.getOpcode() == ISD::ZERO_EXTEND) &&
9116 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
9117 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
9118 APInt ShAmt = N1C->getAPIntValue();
9119 Mask = Mask.shl(ShAmt);
9121 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
9122 N00, DAG.getConstant(Mask, VT));
9129 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
9131 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
9132 const X86Subtarget *Subtarget) {
9133 EVT VT = N->getValueType(0);
9134 if (!VT.isVector() && VT.isInteger() &&
9135 N->getOpcode() == ISD::SHL)
9136 return PerformSHLCombine(N, DAG);
9138 // On X86 with SSE2 support, we can transform this to a vector shift if
9139 // all elements are shifted by the same amount. We can't do this in legalize
9140 // because the a constant vector is typically transformed to a constant pool
9141 // so we have no knowledge of the shift amount.
9142 if (!Subtarget->hasSSE2())
9145 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
9148 SDValue ShAmtOp = N->getOperand(1);
9149 EVT EltVT = VT.getVectorElementType();
9150 DebugLoc DL = N->getDebugLoc();
9151 SDValue BaseShAmt = SDValue();
9152 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
9153 unsigned NumElts = VT.getVectorNumElements();
9155 for (; i != NumElts; ++i) {
9156 SDValue Arg = ShAmtOp.getOperand(i);
9157 if (Arg.getOpcode() == ISD::UNDEF) continue;
9161 for (; i != NumElts; ++i) {
9162 SDValue Arg = ShAmtOp.getOperand(i);
9163 if (Arg.getOpcode() == ISD::UNDEF) continue;
9164 if (Arg != BaseShAmt) {
9168 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
9169 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
9170 SDValue InVec = ShAmtOp.getOperand(0);
9171 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
9172 unsigned NumElts = InVec.getValueType().getVectorNumElements();
9174 for (; i != NumElts; ++i) {
9175 SDValue Arg = InVec.getOperand(i);
9176 if (Arg.getOpcode() == ISD::UNDEF) continue;
9180 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
9181 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
9182 unsigned SplatIdx = cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
9183 if (C->getZExtValue() == SplatIdx)
9184 BaseShAmt = InVec.getOperand(1);
9187 if (BaseShAmt.getNode() == 0)
9188 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
9189 DAG.getIntPtrConstant(0));
9193 // The shift amount is an i32.
9194 if (EltVT.bitsGT(MVT::i32))
9195 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
9196 else if (EltVT.bitsLT(MVT::i32))
9197 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
9199 // The shift amount is identical so we can do a vector shift.
9200 SDValue ValOp = N->getOperand(0);
9201 switch (N->getOpcode()) {
9203 llvm_unreachable("Unknown shift opcode!");
9206 if (VT == MVT::v2i64)
9207 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9208 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9210 if (VT == MVT::v4i32)
9211 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9212 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9214 if (VT == MVT::v8i16)
9215 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9216 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9220 if (VT == MVT::v4i32)
9221 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9222 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9224 if (VT == MVT::v8i16)
9225 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9226 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9230 if (VT == MVT::v2i64)
9231 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9232 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9234 if (VT == MVT::v4i32)
9235 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9236 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9238 if (VT == MVT::v8i16)
9239 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9240 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9247 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
9248 const X86Subtarget *Subtarget) {
9249 EVT VT = N->getValueType(0);
9250 if (VT != MVT::i64 || !Subtarget->is64Bit())
9253 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
9254 SDValue N0 = N->getOperand(0);
9255 SDValue N1 = N->getOperand(1);
9256 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
9258 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
9261 SDValue ShAmt0 = N0.getOperand(1);
9262 if (ShAmt0.getValueType() != MVT::i8)
9264 SDValue ShAmt1 = N1.getOperand(1);
9265 if (ShAmt1.getValueType() != MVT::i8)
9267 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
9268 ShAmt0 = ShAmt0.getOperand(0);
9269 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
9270 ShAmt1 = ShAmt1.getOperand(0);
9272 DebugLoc DL = N->getDebugLoc();
9273 unsigned Opc = X86ISD::SHLD;
9274 SDValue Op0 = N0.getOperand(0);
9275 SDValue Op1 = N1.getOperand(0);
9276 if (ShAmt0.getOpcode() == ISD::SUB) {
9278 std::swap(Op0, Op1);
9279 std::swap(ShAmt0, ShAmt1);
9282 if (ShAmt1.getOpcode() == ISD::SUB) {
9283 SDValue Sum = ShAmt1.getOperand(0);
9284 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
9285 if (SumC->getSExtValue() == 64 &&
9286 ShAmt1.getOperand(1) == ShAmt0)
9287 return DAG.getNode(Opc, DL, VT,
9289 DAG.getNode(ISD::TRUNCATE, DL,
9292 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
9293 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
9295 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == 64)
9296 return DAG.getNode(Opc, DL, VT,
9297 N0.getOperand(0), N1.getOperand(0),
9298 DAG.getNode(ISD::TRUNCATE, DL,
9305 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
9306 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
9307 const X86Subtarget *Subtarget) {
9308 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
9309 // the FP state in cases where an emms may be missing.
9310 // A preferable solution to the general problem is to figure out the right
9311 // places to insert EMMS. This qualifies as a quick hack.
9313 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
9314 StoreSDNode *St = cast<StoreSDNode>(N);
9315 EVT VT = St->getValue().getValueType();
9316 if (VT.getSizeInBits() != 64)
9319 const Function *F = DAG.getMachineFunction().getFunction();
9320 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
9321 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
9322 && Subtarget->hasSSE2();
9323 if ((VT.isVector() ||
9324 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
9325 isa<LoadSDNode>(St->getValue()) &&
9326 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
9327 St->getChain().hasOneUse() && !St->isVolatile()) {
9328 SDNode* LdVal = St->getValue().getNode();
9330 int TokenFactorIndex = -1;
9331 SmallVector<SDValue, 8> Ops;
9332 SDNode* ChainVal = St->getChain().getNode();
9333 // Must be a store of a load. We currently handle two cases: the load
9334 // is a direct child, and it's under an intervening TokenFactor. It is
9335 // possible to dig deeper under nested TokenFactors.
9336 if (ChainVal == LdVal)
9337 Ld = cast<LoadSDNode>(St->getChain());
9338 else if (St->getValue().hasOneUse() &&
9339 ChainVal->getOpcode() == ISD::TokenFactor) {
9340 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
9341 if (ChainVal->getOperand(i).getNode() == LdVal) {
9342 TokenFactorIndex = i;
9343 Ld = cast<LoadSDNode>(St->getValue());
9345 Ops.push_back(ChainVal->getOperand(i));
9349 if (!Ld || !ISD::isNormalLoad(Ld))
9352 // If this is not the MMX case, i.e. we are just turning i64 load/store
9353 // into f64 load/store, avoid the transformation if there are multiple
9354 // uses of the loaded value.
9355 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
9358 DebugLoc LdDL = Ld->getDebugLoc();
9359 DebugLoc StDL = N->getDebugLoc();
9360 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
9361 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
9363 if (Subtarget->is64Bit() || F64IsLegal) {
9364 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
9365 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
9366 Ld->getBasePtr(), Ld->getSrcValue(),
9367 Ld->getSrcValueOffset(), Ld->isVolatile(),
9368 Ld->getAlignment());
9369 SDValue NewChain = NewLd.getValue(1);
9370 if (TokenFactorIndex != -1) {
9371 Ops.push_back(NewChain);
9372 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9375 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
9376 St->getSrcValue(), St->getSrcValueOffset(),
9377 St->isVolatile(), St->getAlignment());
9380 // Otherwise, lower to two pairs of 32-bit loads / stores.
9381 SDValue LoAddr = Ld->getBasePtr();
9382 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
9383 DAG.getConstant(4, MVT::i32));
9385 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
9386 Ld->getSrcValue(), Ld->getSrcValueOffset(),
9387 Ld->isVolatile(), Ld->getAlignment());
9388 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
9389 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
9391 MinAlign(Ld->getAlignment(), 4));
9393 SDValue NewChain = LoLd.getValue(1);
9394 if (TokenFactorIndex != -1) {
9395 Ops.push_back(LoLd);
9396 Ops.push_back(HiLd);
9397 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9401 LoAddr = St->getBasePtr();
9402 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
9403 DAG.getConstant(4, MVT::i32));
9405 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
9406 St->getSrcValue(), St->getSrcValueOffset(),
9407 St->isVolatile(), St->getAlignment());
9408 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
9410 St->getSrcValueOffset() + 4,
9412 MinAlign(St->getAlignment(), 4));
9413 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
9418 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
9419 /// X86ISD::FXOR nodes.
9420 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
9421 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
9422 // F[X]OR(0.0, x) -> x
9423 // F[X]OR(x, 0.0) -> x
9424 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9425 if (C->getValueAPF().isPosZero())
9426 return N->getOperand(1);
9427 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9428 if (C->getValueAPF().isPosZero())
9429 return N->getOperand(0);
9433 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
9434 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
9435 // FAND(0.0, x) -> 0.0
9436 // FAND(x, 0.0) -> 0.0
9437 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9438 if (C->getValueAPF().isPosZero())
9439 return N->getOperand(0);
9440 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9441 if (C->getValueAPF().isPosZero())
9442 return N->getOperand(1);
9446 static SDValue PerformBTCombine(SDNode *N,
9448 TargetLowering::DAGCombinerInfo &DCI) {
9449 // BT ignores high bits in the bit index operand.
9450 SDValue Op1 = N->getOperand(1);
9451 if (Op1.hasOneUse()) {
9452 unsigned BitWidth = Op1.getValueSizeInBits();
9453 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
9454 APInt KnownZero, KnownOne;
9455 TargetLowering::TargetLoweringOpt TLO(DAG);
9456 TargetLowering &TLI = DAG.getTargetLoweringInfo();
9457 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
9458 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
9459 DCI.CommitTargetLoweringOpt(TLO);
9464 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
9465 SDValue Op = N->getOperand(0);
9466 if (Op.getOpcode() == ISD::BIT_CONVERT)
9467 Op = Op.getOperand(0);
9468 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
9469 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
9470 VT.getVectorElementType().getSizeInBits() ==
9471 OpVT.getVectorElementType().getSizeInBits()) {
9472 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
9477 // On X86 and X86-64, atomic operations are lowered to locked instructions.
9478 // Locked instructions, in turn, have implicit fence semantics (all memory
9479 // operations are flushed before issuing the locked instruction, and the
9480 // are not buffered), so we can fold away the common pattern of
9481 // fence-atomic-fence.
9482 static SDValue PerformMEMBARRIERCombine(SDNode* N, SelectionDAG &DAG) {
9483 SDValue atomic = N->getOperand(0);
9484 switch (atomic.getOpcode()) {
9485 case ISD::ATOMIC_CMP_SWAP:
9486 case ISD::ATOMIC_SWAP:
9487 case ISD::ATOMIC_LOAD_ADD:
9488 case ISD::ATOMIC_LOAD_SUB:
9489 case ISD::ATOMIC_LOAD_AND:
9490 case ISD::ATOMIC_LOAD_OR:
9491 case ISD::ATOMIC_LOAD_XOR:
9492 case ISD::ATOMIC_LOAD_NAND:
9493 case ISD::ATOMIC_LOAD_MIN:
9494 case ISD::ATOMIC_LOAD_MAX:
9495 case ISD::ATOMIC_LOAD_UMIN:
9496 case ISD::ATOMIC_LOAD_UMAX:
9502 SDValue fence = atomic.getOperand(0);
9503 if (fence.getOpcode() != ISD::MEMBARRIER)
9506 switch (atomic.getOpcode()) {
9507 case ISD::ATOMIC_CMP_SWAP:
9508 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9509 atomic.getOperand(1), atomic.getOperand(2),
9510 atomic.getOperand(3));
9511 case ISD::ATOMIC_SWAP:
9512 case ISD::ATOMIC_LOAD_ADD:
9513 case ISD::ATOMIC_LOAD_SUB:
9514 case ISD::ATOMIC_LOAD_AND:
9515 case ISD::ATOMIC_LOAD_OR:
9516 case ISD::ATOMIC_LOAD_XOR:
9517 case ISD::ATOMIC_LOAD_NAND:
9518 case ISD::ATOMIC_LOAD_MIN:
9519 case ISD::ATOMIC_LOAD_MAX:
9520 case ISD::ATOMIC_LOAD_UMIN:
9521 case ISD::ATOMIC_LOAD_UMAX:
9522 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9523 atomic.getOperand(1), atomic.getOperand(2));
9529 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
9530 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
9531 // (and (i32 x86isd::setcc_carry), 1)
9532 // This eliminates the zext. This transformation is necessary because
9533 // ISD::SETCC is always legalized to i8.
9534 DebugLoc dl = N->getDebugLoc();
9535 SDValue N0 = N->getOperand(0);
9536 EVT VT = N->getValueType(0);
9537 if (N0.getOpcode() == ISD::AND &&
9539 N0.getOperand(0).hasOneUse()) {
9540 SDValue N00 = N0.getOperand(0);
9541 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
9543 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9544 if (!C || C->getZExtValue() != 1)
9546 return DAG.getNode(ISD::AND, dl, VT,
9547 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
9548 N00.getOperand(0), N00.getOperand(1)),
9549 DAG.getConstant(1, VT));
9555 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
9556 DAGCombinerInfo &DCI) const {
9557 SelectionDAG &DAG = DCI.DAG;
9558 switch (N->getOpcode()) {
9560 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
9561 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
9562 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
9563 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
9566 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
9567 case ISD::OR: return PerformOrCombine(N, DAG, Subtarget);
9568 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
9570 case X86ISD::FOR: return PerformFORCombine(N, DAG);
9571 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
9572 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
9573 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
9574 case ISD::MEMBARRIER: return PerformMEMBARRIERCombine(N, DAG);
9575 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
9581 //===----------------------------------------------------------------------===//
9582 // X86 Inline Assembly Support
9583 //===----------------------------------------------------------------------===//
9585 static bool LowerToBSwap(CallInst *CI) {
9586 // FIXME: this should verify that we are targetting a 486 or better. If not,
9587 // we will turn this bswap into something that will be lowered to logical ops
9588 // instead of emitting the bswap asm. For now, we don't support 486 or lower
9589 // so don't worry about this.
9591 // Verify this is a simple bswap.
9592 if (CI->getNumOperands() != 2 ||
9593 CI->getType() != CI->getOperand(1)->getType() ||
9594 !CI->getType()->isInteger())
9597 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9598 if (!Ty || Ty->getBitWidth() % 16 != 0)
9601 // Okay, we can do this xform, do so now.
9602 const Type *Tys[] = { Ty };
9603 Module *M = CI->getParent()->getParent()->getParent();
9604 Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
9606 Value *Op = CI->getOperand(1);
9607 Op = CallInst::Create(Int, Op, CI->getName(), CI);
9609 CI->replaceAllUsesWith(Op);
9610 CI->eraseFromParent();
9614 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
9615 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9616 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
9618 std::string AsmStr = IA->getAsmString();
9620 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
9621 SmallVector<StringRef, 4> AsmPieces;
9622 SplitString(AsmStr, AsmPieces, "\n"); // ; as separator?
9624 switch (AsmPieces.size()) {
9625 default: return false;
9627 AsmStr = AsmPieces[0];
9629 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
9632 if (AsmPieces.size() == 2 &&
9633 (AsmPieces[0] == "bswap" ||
9634 AsmPieces[0] == "bswapq" ||
9635 AsmPieces[0] == "bswapl") &&
9636 (AsmPieces[1] == "$0" ||
9637 AsmPieces[1] == "${0:q}")) {
9638 // No need to check constraints, nothing other than the equivalent of
9639 // "=r,0" would be valid here.
9640 return LowerToBSwap(CI);
9642 // rorw $$8, ${0:w} --> llvm.bswap.i16
9643 if (CI->getType()->isInteger(16) &&
9644 AsmPieces.size() == 3 &&
9645 AsmPieces[0] == "rorw" &&
9646 AsmPieces[1] == "$$8," &&
9647 AsmPieces[2] == "${0:w}" &&
9648 IA->getConstraintString() == "=r,0,~{dirflag},~{fpsr},~{flags},~{cc}") {
9649 return LowerToBSwap(CI);
9653 if (CI->getType()->isInteger(64) &&
9654 Constraints.size() >= 2 &&
9655 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
9656 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
9657 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
9658 SmallVector<StringRef, 4> Words;
9659 SplitString(AsmPieces[0], Words, " \t");
9660 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
9662 SplitString(AsmPieces[1], Words, " \t");
9663 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
9665 SplitString(AsmPieces[2], Words, " \t,");
9666 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
9667 Words[2] == "%edx") {
9668 return LowerToBSwap(CI);
9680 /// getConstraintType - Given a constraint letter, return the type of
9681 /// constraint it is for this target.
9682 X86TargetLowering::ConstraintType
9683 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
9684 if (Constraint.size() == 1) {
9685 switch (Constraint[0]) {
9697 return C_RegisterClass;
9705 return TargetLowering::getConstraintType(Constraint);
9708 /// LowerXConstraint - try to replace an X constraint, which matches anything,
9709 /// with another that has more specific requirements based on the type of the
9710 /// corresponding operand.
9711 const char *X86TargetLowering::
9712 LowerXConstraint(EVT ConstraintVT) const {
9713 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
9714 // 'f' like normal targets.
9715 if (ConstraintVT.isFloatingPoint()) {
9716 if (Subtarget->hasSSE2())
9718 if (Subtarget->hasSSE1())
9722 return TargetLowering::LowerXConstraint(ConstraintVT);
9725 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9726 /// vector. If it is invalid, don't add anything to Ops.
9727 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9730 std::vector<SDValue>&Ops,
9731 SelectionDAG &DAG) const {
9732 SDValue Result(0, 0);
9734 switch (Constraint) {
9737 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9738 if (C->getZExtValue() <= 31) {
9739 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9745 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9746 if (C->getZExtValue() <= 63) {
9747 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9753 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9754 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
9755 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9761 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9762 if (C->getZExtValue() <= 255) {
9763 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9769 // 32-bit signed value
9770 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9771 const ConstantInt *CI = C->getConstantIntValue();
9772 if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
9773 C->getSExtValue())) {
9774 // Widen to 64 bits here to get it sign extended.
9775 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
9778 // FIXME gcc accepts some relocatable values here too, but only in certain
9779 // memory models; it's complicated.
9784 // 32-bit unsigned value
9785 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9786 const ConstantInt *CI = C->getConstantIntValue();
9787 if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
9788 C->getZExtValue())) {
9789 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9793 // FIXME gcc accepts some relocatable values here too, but only in certain
9794 // memory models; it's complicated.
9798 // Literal immediates are always ok.
9799 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
9800 // Widen to 64 bits here to get it sign extended.
9801 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
9805 // If we are in non-pic codegen mode, we allow the address of a global (with
9806 // an optional displacement) to be used with 'i'.
9807 GlobalAddressSDNode *GA = 0;
9810 // Match either (GA), (GA+C), (GA+C1+C2), etc.
9812 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
9813 Offset += GA->getOffset();
9815 } else if (Op.getOpcode() == ISD::ADD) {
9816 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9817 Offset += C->getZExtValue();
9818 Op = Op.getOperand(0);
9821 } else if (Op.getOpcode() == ISD::SUB) {
9822 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9823 Offset += -C->getZExtValue();
9824 Op = Op.getOperand(0);
9829 // Otherwise, this isn't something we can handle, reject it.
9833 GlobalValue *GV = GA->getGlobal();
9834 // If we require an extra load to get this address, as in PIC mode, we
9836 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
9837 getTargetMachine())))
9841 Op = LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
9843 Op = DAG.getTargetGlobalAddress(GV, GA->getValueType(0), Offset);
9849 if (Result.getNode()) {
9850 Ops.push_back(Result);
9853 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
9857 std::vector<unsigned> X86TargetLowering::
9858 getRegClassForInlineAsmConstraint(const std::string &Constraint,
9860 if (Constraint.size() == 1) {
9861 // FIXME: not handling fp-stack yet!
9862 switch (Constraint[0]) { // GCC X86 Constraint Letters
9863 default: break; // Unknown constraint letter
9864 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
9865 if (Subtarget->is64Bit()) {
9867 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
9868 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
9869 X86::R10D,X86::R11D,X86::R12D,
9870 X86::R13D,X86::R14D,X86::R15D,
9871 X86::EBP, X86::ESP, 0);
9872 else if (VT == MVT::i16)
9873 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
9874 X86::SI, X86::DI, X86::R8W,X86::R9W,
9875 X86::R10W,X86::R11W,X86::R12W,
9876 X86::R13W,X86::R14W,X86::R15W,
9877 X86::BP, X86::SP, 0);
9878 else if (VT == MVT::i8)
9879 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
9880 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
9881 X86::R10B,X86::R11B,X86::R12B,
9882 X86::R13B,X86::R14B,X86::R15B,
9883 X86::BPL, X86::SPL, 0);
9885 else if (VT == MVT::i64)
9886 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
9887 X86::RSI, X86::RDI, X86::R8, X86::R9,
9888 X86::R10, X86::R11, X86::R12,
9889 X86::R13, X86::R14, X86::R15,
9890 X86::RBP, X86::RSP, 0);
9894 // 32-bit fallthrough
9897 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
9898 else if (VT == MVT::i16)
9899 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
9900 else if (VT == MVT::i8)
9901 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
9902 else if (VT == MVT::i64)
9903 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
9908 return std::vector<unsigned>();
9911 std::pair<unsigned, const TargetRegisterClass*>
9912 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9914 // First, see if this is a constraint that directly corresponds to an LLVM
9916 if (Constraint.size() == 1) {
9917 // GCC Constraint Letters
9918 switch (Constraint[0]) {
9920 case 'r': // GENERAL_REGS
9921 case 'l': // INDEX_REGS
9923 return std::make_pair(0U, X86::GR8RegisterClass);
9925 return std::make_pair(0U, X86::GR16RegisterClass);
9926 if (VT == MVT::i32 || !Subtarget->is64Bit())
9927 return std::make_pair(0U, X86::GR32RegisterClass);
9928 return std::make_pair(0U, X86::GR64RegisterClass);
9929 case 'R': // LEGACY_REGS
9931 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
9933 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
9934 if (VT == MVT::i32 || !Subtarget->is64Bit())
9935 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
9936 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
9937 case 'f': // FP Stack registers.
9938 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
9939 // value to the correct fpstack register class.
9940 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
9941 return std::make_pair(0U, X86::RFP32RegisterClass);
9942 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
9943 return std::make_pair(0U, X86::RFP64RegisterClass);
9944 return std::make_pair(0U, X86::RFP80RegisterClass);
9945 case 'y': // MMX_REGS if MMX allowed.
9946 if (!Subtarget->hasMMX()) break;
9947 return std::make_pair(0U, X86::VR64RegisterClass);
9948 case 'Y': // SSE_REGS if SSE2 allowed
9949 if (!Subtarget->hasSSE2()) break;
9951 case 'x': // SSE_REGS if SSE1 allowed
9952 if (!Subtarget->hasSSE1()) break;
9954 switch (VT.getSimpleVT().SimpleTy) {
9956 // Scalar SSE types.
9959 return std::make_pair(0U, X86::FR32RegisterClass);
9962 return std::make_pair(0U, X86::FR64RegisterClass);
9970 return std::make_pair(0U, X86::VR128RegisterClass);
9976 // Use the default implementation in TargetLowering to convert the register
9977 // constraint into a member of a register class.
9978 std::pair<unsigned, const TargetRegisterClass*> Res;
9979 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9981 // Not found as a standard register?
9982 if (Res.second == 0) {
9983 // Map st(0) -> st(7) -> ST0
9984 if (Constraint.size() == 7 && Constraint[0] == '{' &&
9985 tolower(Constraint[1]) == 's' &&
9986 tolower(Constraint[2]) == 't' &&
9987 Constraint[3] == '(' &&
9988 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
9989 Constraint[5] == ')' &&
9990 Constraint[6] == '}') {
9992 Res.first = X86::ST0+Constraint[4]-'0';
9993 Res.second = X86::RFP80RegisterClass;
9997 // GCC allows "st(0)" to be called just plain "st".
9998 if (StringRef("{st}").equals_lower(Constraint)) {
9999 Res.first = X86::ST0;
10000 Res.second = X86::RFP80RegisterClass;
10005 if (StringRef("{flags}").equals_lower(Constraint)) {
10006 Res.first = X86::EFLAGS;
10007 Res.second = X86::CCRRegisterClass;
10011 // 'A' means EAX + EDX.
10012 if (Constraint == "A") {
10013 Res.first = X86::EAX;
10014 Res.second = X86::GR32_ADRegisterClass;
10020 // Otherwise, check to see if this is a register class of the wrong value
10021 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
10022 // turn into {ax},{dx}.
10023 if (Res.second->hasType(VT))
10024 return Res; // Correct type already, nothing to do.
10026 // All of the single-register GCC register classes map their values onto
10027 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
10028 // really want an 8-bit or 32-bit register, map to the appropriate register
10029 // class and return the appropriate register.
10030 if (Res.second == X86::GR16RegisterClass) {
10031 if (VT == MVT::i8) {
10032 unsigned DestReg = 0;
10033 switch (Res.first) {
10035 case X86::AX: DestReg = X86::AL; break;
10036 case X86::DX: DestReg = X86::DL; break;
10037 case X86::CX: DestReg = X86::CL; break;
10038 case X86::BX: DestReg = X86::BL; break;
10041 Res.first = DestReg;
10042 Res.second = X86::GR8RegisterClass;
10044 } else if (VT == MVT::i32) {
10045 unsigned DestReg = 0;
10046 switch (Res.first) {
10048 case X86::AX: DestReg = X86::EAX; break;
10049 case X86::DX: DestReg = X86::EDX; break;
10050 case X86::CX: DestReg = X86::ECX; break;
10051 case X86::BX: DestReg = X86::EBX; break;
10052 case X86::SI: DestReg = X86::ESI; break;
10053 case X86::DI: DestReg = X86::EDI; break;
10054 case X86::BP: DestReg = X86::EBP; break;
10055 case X86::SP: DestReg = X86::ESP; break;
10058 Res.first = DestReg;
10059 Res.second = X86::GR32RegisterClass;
10061 } else if (VT == MVT::i64) {
10062 unsigned DestReg = 0;
10063 switch (Res.first) {
10065 case X86::AX: DestReg = X86::RAX; break;
10066 case X86::DX: DestReg = X86::RDX; break;
10067 case X86::CX: DestReg = X86::RCX; break;
10068 case X86::BX: DestReg = X86::RBX; break;
10069 case X86::SI: DestReg = X86::RSI; break;
10070 case X86::DI: DestReg = X86::RDI; break;
10071 case X86::BP: DestReg = X86::RBP; break;
10072 case X86::SP: DestReg = X86::RSP; break;
10075 Res.first = DestReg;
10076 Res.second = X86::GR64RegisterClass;
10079 } else if (Res.second == X86::FR32RegisterClass ||
10080 Res.second == X86::FR64RegisterClass ||
10081 Res.second == X86::VR128RegisterClass) {
10082 // Handle references to XMM physical registers that got mapped into the
10083 // wrong class. This can happen with constraints like {xmm0} where the
10084 // target independent register mapper will just pick the first match it can
10085 // find, ignoring the required type.
10086 if (VT == MVT::f32)
10087 Res.second = X86::FR32RegisterClass;
10088 else if (VT == MVT::f64)
10089 Res.second = X86::FR64RegisterClass;
10090 else if (X86::VR128RegisterClass->hasType(VT))
10091 Res.second = X86::VR128RegisterClass;
10097 //===----------------------------------------------------------------------===//
10098 // X86 Widen vector type
10099 //===----------------------------------------------------------------------===//
10101 /// getWidenVectorType: given a vector type, returns the type to widen
10102 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
10103 /// If there is no vector type that we want to widen to, returns MVT::Other
10104 /// When and where to widen is target dependent based on the cost of
10105 /// scalarizing vs using the wider vector type.
10107 EVT X86TargetLowering::getWidenVectorType(EVT VT) const {
10108 assert(VT.isVector());
10109 if (isTypeLegal(VT))
10112 // TODO: In computeRegisterProperty, we can compute the list of legal vector
10113 // type based on element type. This would speed up our search (though
10114 // it may not be worth it since the size of the list is relatively
10116 EVT EltVT = VT.getVectorElementType();
10117 unsigned NElts = VT.getVectorNumElements();
10119 // On X86, it make sense to widen any vector wider than 1
10123 for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
10124 nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
10125 EVT SVT = (MVT::SimpleValueType)nVT;
10127 if (isTypeLegal(SVT) &&
10128 SVT.getVectorElementType() == EltVT &&
10129 SVT.getVectorNumElements() > NElts)