1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "x86-isel"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86MCTargetExpr.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/PseudoSourceValue.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCSectionMachO.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/BitVector.h"
43 #include "llvm/ADT/SmallSet.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/VectorExtras.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/Dwarf.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
54 using namespace dwarf;
56 STATISTIC(NumTailCalls, "Number of tail calls");
59 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
61 // Disable16Bit - 16-bit operations typically have a larger encoding than
62 // corresponding 32-bit instructions, and 16-bit code is slow on some
63 // processors. This is an experimental flag to disable 16-bit operations
64 // (which forces them to be Legalized to 32-bit operations).
66 Disable16Bit("disable-16bit", cl::Hidden,
67 cl::desc("Disable use of 16-bit instructions"));
69 // Forward declarations.
70 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
73 // FIXME: This is for a test.
75 EnableX86EHTest("enable-x86-eh-test", cl::Hidden);
78 class X86_test_MachoTargetObjectFile : public TargetLoweringObjectFileMachO {
80 virtual void Initialize(MCContext &Ctx, const TargetMachine &TM) {
81 TargetLoweringObjectFileMachO::Initialize(Ctx, TM);
83 // Exception Handling.
84 LSDASection = getMachOSection("__TEXT", "__gcc_except_tab", 0,
85 SectionKind::getReadOnlyWithRel());
88 virtual unsigned getTTypeEncoding() const {
89 return DW_EH_PE_indirect | DW_EH_PE_pcrel | DW_EH_PE_sdata4;
93 class X8664_test_MachoTargetObjectFile : public X8664_MachoTargetObjectFile {
95 virtual void Initialize(MCContext &Ctx, const TargetMachine &TM) {
96 TargetLoweringObjectFileMachO::Initialize(Ctx, TM);
98 // Exception Handling.
99 LSDASection = getMachOSection("__TEXT", "__gcc_except_tab", 0,
100 SectionKind::getReadOnlyWithRel());
103 virtual unsigned getTTypeEncoding() const {
104 return DW_EH_PE_indirect | DW_EH_PE_pcrel | DW_EH_PE_sdata4;
109 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
110 switch (TM.getSubtarget<X86Subtarget>().TargetType) {
111 default: llvm_unreachable("unknown subtarget type");
112 case X86Subtarget::isDarwin:
113 // FIXME: This is for an EH test.
114 if (EnableX86EHTest) {
115 if (TM.getSubtarget<X86Subtarget>().is64Bit())
116 return new X8664_test_MachoTargetObjectFile();
118 return new X86_test_MachoTargetObjectFile();
121 if (TM.getSubtarget<X86Subtarget>().is64Bit())
122 return new X8664_MachoTargetObjectFile();
123 return new TargetLoweringObjectFileMachO();
124 case X86Subtarget::isELF:
125 if (TM.getSubtarget<X86Subtarget>().is64Bit())
126 return new X8664_ELFTargetObjectFile(TM);
127 return new X8632_ELFTargetObjectFile(TM);
128 case X86Subtarget::isMingw:
129 case X86Subtarget::isCygwin:
130 case X86Subtarget::isWindows:
131 return new TargetLoweringObjectFileCOFF();
135 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
136 : TargetLowering(TM, createTLOF(TM)) {
137 Subtarget = &TM.getSubtarget<X86Subtarget>();
138 X86ScalarSSEf64 = Subtarget->hasSSE2();
139 X86ScalarSSEf32 = Subtarget->hasSSE1();
140 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
142 RegInfo = TM.getRegisterInfo();
143 TD = getTargetData();
145 // Set up the TargetLowering object.
147 // X86 is weird, it always uses i8 for shift amounts and setcc results.
148 setShiftAmountType(MVT::i8);
149 setBooleanContents(ZeroOrOneBooleanContent);
150 setSchedulingPreference(SchedulingForRegPressure);
151 setStackPointerRegisterToSaveRestore(X86StackPtr);
153 if (Subtarget->isTargetDarwin()) {
154 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
155 setUseUnderscoreSetJmp(false);
156 setUseUnderscoreLongJmp(false);
157 } else if (Subtarget->isTargetMingw()) {
158 // MS runtime is weird: it exports _setjmp, but longjmp!
159 setUseUnderscoreSetJmp(true);
160 setUseUnderscoreLongJmp(false);
162 setUseUnderscoreSetJmp(true);
163 setUseUnderscoreLongJmp(true);
166 // Set up the register classes.
167 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
169 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
170 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
171 if (Subtarget->is64Bit())
172 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
174 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
176 // We don't accept any truncstore of integer registers.
177 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
179 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
180 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
182 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
183 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
184 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
186 // SETOEQ and SETUNE require checking two conditions.
187 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
188 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
189 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
190 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
191 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
192 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
194 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
196 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
197 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
198 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
200 if (Subtarget->is64Bit()) {
201 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
202 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
203 } else if (!UseSoftFloat) {
204 if (X86ScalarSSEf64) {
205 // We have an impenetrably clever algorithm for ui64->double only.
206 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
208 // We have an algorithm for SSE2, and we turn this into a 64-bit
209 // FILD for other targets.
210 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
213 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
215 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
216 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
219 // SSE has no i16 to fp conversion, only i32
220 if (X86ScalarSSEf32) {
221 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
222 // f32 and f64 cases are Legal, f80 case is not
223 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
225 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
226 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
229 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
230 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
233 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
234 // are Legal, f80 is custom lowered.
235 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
236 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
238 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
240 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
241 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
243 if (X86ScalarSSEf32) {
244 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
245 // f32 and f64 cases are Legal, f80 case is not
246 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
248 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
249 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
252 // Handle FP_TO_UINT by promoting the destination to a larger signed
254 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
255 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
256 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
258 if (Subtarget->is64Bit()) {
259 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
260 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
261 } else if (!UseSoftFloat) {
262 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
263 // Expand FP_TO_UINT into a select.
264 // FIXME: We would like to use a Custom expander here eventually to do
265 // the optimal thing for SSE vs. the default expansion in the legalizer.
266 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
268 // With SSE3 we can use fisttpll to convert to a signed i64; without
269 // SSE, we're stuck with a fistpll.
270 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
273 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
274 if (!X86ScalarSSEf64) {
275 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
276 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
279 // Scalar integer divide and remainder are lowered to use operations that
280 // produce two results, to match the available instructions. This exposes
281 // the two-result form to trivial CSE, which is able to combine x/y and x%y
282 // into a single instruction.
284 // Scalar integer multiply-high is also lowered to use two-result
285 // operations, to match the available instructions. However, plain multiply
286 // (low) operations are left as Legal, as there are single-result
287 // instructions for this in x86. Using the two-result multiply instructions
288 // when both high and low results are needed must be arranged by dagcombine.
289 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
290 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
291 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
292 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
293 setOperationAction(ISD::SREM , MVT::i8 , Expand);
294 setOperationAction(ISD::UREM , MVT::i8 , Expand);
295 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
296 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
297 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
298 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
299 setOperationAction(ISD::SREM , MVT::i16 , Expand);
300 setOperationAction(ISD::UREM , MVT::i16 , Expand);
301 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
302 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
303 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
304 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
305 setOperationAction(ISD::SREM , MVT::i32 , Expand);
306 setOperationAction(ISD::UREM , MVT::i32 , Expand);
307 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
308 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
309 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
310 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
311 setOperationAction(ISD::SREM , MVT::i64 , Expand);
312 setOperationAction(ISD::UREM , MVT::i64 , Expand);
314 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
315 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
316 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
317 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
318 if (Subtarget->is64Bit())
319 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
320 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
321 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
322 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
323 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
324 setOperationAction(ISD::FREM , MVT::f32 , Expand);
325 setOperationAction(ISD::FREM , MVT::f64 , Expand);
326 setOperationAction(ISD::FREM , MVT::f80 , Expand);
327 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
329 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
330 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
331 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
332 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
334 setOperationAction(ISD::CTTZ , MVT::i16 , Expand);
335 setOperationAction(ISD::CTLZ , MVT::i16 , Expand);
337 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
338 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
340 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
341 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
342 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
343 if (Subtarget->is64Bit()) {
344 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
345 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
346 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
349 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
350 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
352 // These should be promoted to a larger select which is supported.
353 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
354 // X86 wants to expand cmov itself.
355 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
357 setOperationAction(ISD::SELECT , MVT::i16 , Expand);
359 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
360 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
361 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
362 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
363 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
364 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
366 setOperationAction(ISD::SETCC , MVT::i16 , Expand);
368 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
369 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
370 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
371 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
372 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
373 if (Subtarget->is64Bit()) {
374 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
375 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
377 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
380 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
381 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
382 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
383 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
384 if (Subtarget->is64Bit())
385 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
386 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
387 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
388 if (Subtarget->is64Bit()) {
389 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
390 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
391 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
392 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
393 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
395 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
396 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
397 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
398 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
399 if (Subtarget->is64Bit()) {
400 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
401 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
402 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
405 if (Subtarget->hasSSE1())
406 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
408 if (!Subtarget->hasSSE2())
409 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
411 // Expand certain atomics
412 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
413 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
414 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
415 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
417 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
418 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
419 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
420 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
422 if (!Subtarget->is64Bit()) {
423 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
424 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
425 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
426 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
427 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
428 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
429 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
432 // FIXME - use subtarget debug flags
433 if (!Subtarget->isTargetDarwin() &&
434 !Subtarget->isTargetELF() &&
435 !Subtarget->isTargetCygMing()) {
436 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
439 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
440 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
441 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
442 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
443 if (Subtarget->is64Bit()) {
444 setExceptionPointerRegister(X86::RAX);
445 setExceptionSelectorRegister(X86::RDX);
447 setExceptionPointerRegister(X86::EAX);
448 setExceptionSelectorRegister(X86::EDX);
450 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
451 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
453 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
455 setOperationAction(ISD::TRAP, MVT::Other, Legal);
457 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
458 setOperationAction(ISD::VASTART , MVT::Other, Custom);
459 setOperationAction(ISD::VAEND , MVT::Other, Expand);
460 if (Subtarget->is64Bit()) {
461 setOperationAction(ISD::VAARG , MVT::Other, Custom);
462 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
464 setOperationAction(ISD::VAARG , MVT::Other, Expand);
465 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
468 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
469 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
470 if (Subtarget->is64Bit())
471 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
472 if (Subtarget->isTargetCygMing())
473 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
475 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
477 if (!UseSoftFloat && X86ScalarSSEf64) {
478 // f32 and f64 use SSE.
479 // Set up the FP register classes.
480 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
481 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
483 // Use ANDPD to simulate FABS.
484 setOperationAction(ISD::FABS , MVT::f64, Custom);
485 setOperationAction(ISD::FABS , MVT::f32, Custom);
487 // Use XORP to simulate FNEG.
488 setOperationAction(ISD::FNEG , MVT::f64, Custom);
489 setOperationAction(ISD::FNEG , MVT::f32, Custom);
491 // Use ANDPD and ORPD to simulate FCOPYSIGN.
492 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
493 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
495 // We don't support sin/cos/fmod
496 setOperationAction(ISD::FSIN , MVT::f64, Expand);
497 setOperationAction(ISD::FCOS , MVT::f64, Expand);
498 setOperationAction(ISD::FSIN , MVT::f32, Expand);
499 setOperationAction(ISD::FCOS , MVT::f32, Expand);
501 // Expand FP immediates into loads from the stack, except for the special
503 addLegalFPImmediate(APFloat(+0.0)); // xorpd
504 addLegalFPImmediate(APFloat(+0.0f)); // xorps
505 } else if (!UseSoftFloat && X86ScalarSSEf32) {
506 // Use SSE for f32, x87 for f64.
507 // Set up the FP register classes.
508 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
509 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
511 // Use ANDPS to simulate FABS.
512 setOperationAction(ISD::FABS , MVT::f32, Custom);
514 // Use XORP to simulate FNEG.
515 setOperationAction(ISD::FNEG , MVT::f32, Custom);
517 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
519 // Use ANDPS and ORPS to simulate FCOPYSIGN.
520 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
521 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
523 // We don't support sin/cos/fmod
524 setOperationAction(ISD::FSIN , MVT::f32, Expand);
525 setOperationAction(ISD::FCOS , MVT::f32, Expand);
527 // Special cases we handle for FP constants.
528 addLegalFPImmediate(APFloat(+0.0f)); // xorps
529 addLegalFPImmediate(APFloat(+0.0)); // FLD0
530 addLegalFPImmediate(APFloat(+1.0)); // FLD1
531 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
532 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
535 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
536 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
538 } else if (!UseSoftFloat) {
539 // f32 and f64 in x87.
540 // Set up the FP register classes.
541 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
542 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
544 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
545 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
546 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
547 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
550 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
551 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
553 addLegalFPImmediate(APFloat(+0.0)); // FLD0
554 addLegalFPImmediate(APFloat(+1.0)); // FLD1
555 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
556 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
557 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
558 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
559 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
560 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
563 // Long double always uses X87.
565 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
566 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
567 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
570 APFloat TmpFlt(+0.0);
571 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
573 addLegalFPImmediate(TmpFlt); // FLD0
575 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
576 APFloat TmpFlt2(+1.0);
577 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
579 addLegalFPImmediate(TmpFlt2); // FLD1
580 TmpFlt2.changeSign();
581 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
585 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
586 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
590 // Always use a library call for pow.
591 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
592 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
593 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
595 setOperationAction(ISD::FLOG, MVT::f80, Expand);
596 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
597 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
598 setOperationAction(ISD::FEXP, MVT::f80, Expand);
599 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
601 // First set operation action for all vector types to either promote
602 // (for widening) or expand (for scalarization). Then we will selectively
603 // turn on ones that can be effectively codegen'd.
604 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
605 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
606 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
607 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
608 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
609 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
610 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
611 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
612 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
613 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
614 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
615 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
616 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
617 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
618 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
619 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
620 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
621 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
622 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
623 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
624 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
625 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
626 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
627 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
628 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
629 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
630 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
631 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
632 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
633 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
634 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
635 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
636 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
637 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
638 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
639 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
640 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
641 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
642 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
643 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
644 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
645 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
646 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
647 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
648 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
649 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
650 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
651 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
652 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
653 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
654 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
655 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
656 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
657 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
658 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
659 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
660 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
661 setTruncStoreAction((MVT::SimpleValueType)VT,
662 (MVT::SimpleValueType)InnerVT, Expand);
663 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
664 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
665 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
668 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
669 // with -msoft-float, disable use of MMX as well.
670 if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
671 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
672 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
673 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
674 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
675 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
677 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
678 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
679 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
680 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
682 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
683 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
684 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
685 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
687 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
688 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
690 setOperationAction(ISD::AND, MVT::v8i8, Promote);
691 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
692 setOperationAction(ISD::AND, MVT::v4i16, Promote);
693 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
694 setOperationAction(ISD::AND, MVT::v2i32, Promote);
695 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
696 setOperationAction(ISD::AND, MVT::v1i64, Legal);
698 setOperationAction(ISD::OR, MVT::v8i8, Promote);
699 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
700 setOperationAction(ISD::OR, MVT::v4i16, Promote);
701 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
702 setOperationAction(ISD::OR, MVT::v2i32, Promote);
703 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
704 setOperationAction(ISD::OR, MVT::v1i64, Legal);
706 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
707 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
708 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
709 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
710 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
711 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
712 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
714 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
715 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
716 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
717 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
718 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
719 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
720 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
721 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
722 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
724 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
725 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
726 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
727 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
728 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
730 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
731 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
732 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
733 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
735 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
736 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
737 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
738 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
740 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
742 setOperationAction(ISD::SELECT, MVT::v8i8, Promote);
743 setOperationAction(ISD::SELECT, MVT::v4i16, Promote);
744 setOperationAction(ISD::SELECT, MVT::v2i32, Promote);
745 setOperationAction(ISD::SELECT, MVT::v1i64, Custom);
746 setOperationAction(ISD::VSETCC, MVT::v8i8, Custom);
747 setOperationAction(ISD::VSETCC, MVT::v4i16, Custom);
748 setOperationAction(ISD::VSETCC, MVT::v2i32, Custom);
751 if (!UseSoftFloat && Subtarget->hasSSE1()) {
752 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
754 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
755 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
756 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
757 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
758 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
759 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
760 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
761 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
762 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
763 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
764 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
765 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
768 if (!UseSoftFloat && Subtarget->hasSSE2()) {
769 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
771 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
772 // registers cannot be used even for integer operations.
773 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
774 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
775 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
776 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
778 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
779 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
780 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
781 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
782 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
783 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
784 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
785 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
786 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
787 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
788 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
789 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
790 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
791 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
792 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
793 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
795 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
796 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
797 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
798 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
800 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
801 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
802 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
803 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
804 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
806 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
807 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
808 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
809 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
810 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
812 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
813 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
814 EVT VT = (MVT::SimpleValueType)i;
815 // Do not attempt to custom lower non-power-of-2 vectors
816 if (!isPowerOf2_32(VT.getVectorNumElements()))
818 // Do not attempt to custom lower non-128-bit vectors
819 if (!VT.is128BitVector())
821 setOperationAction(ISD::BUILD_VECTOR,
822 VT.getSimpleVT().SimpleTy, Custom);
823 setOperationAction(ISD::VECTOR_SHUFFLE,
824 VT.getSimpleVT().SimpleTy, Custom);
825 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
826 VT.getSimpleVT().SimpleTy, Custom);
829 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
830 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
831 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
832 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
833 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
834 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
836 if (Subtarget->is64Bit()) {
837 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
838 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
841 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
842 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
843 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
846 // Do not attempt to promote non-128-bit vectors
847 if (!VT.is128BitVector()) {
850 setOperationAction(ISD::AND, SVT, Promote);
851 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
852 setOperationAction(ISD::OR, SVT, Promote);
853 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
854 setOperationAction(ISD::XOR, SVT, Promote);
855 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
856 setOperationAction(ISD::LOAD, SVT, Promote);
857 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
858 setOperationAction(ISD::SELECT, SVT, Promote);
859 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
862 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
864 // Custom lower v2i64 and v2f64 selects.
865 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
866 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
867 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
868 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
870 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
871 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
872 if (!DisableMMX && Subtarget->hasMMX()) {
873 setOperationAction(ISD::FP_TO_SINT, MVT::v2i32, Custom);
874 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
878 if (Subtarget->hasSSE41()) {
879 // FIXME: Do we need to handle scalar-to-vector here?
880 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
882 // i8 and i16 vectors are custom , because the source register and source
883 // source memory operand types are not the same width. f32 vectors are
884 // custom since the immediate controlling the insert encodes additional
886 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
887 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
888 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
889 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
891 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
892 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
893 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
894 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
896 if (Subtarget->is64Bit()) {
897 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
898 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
902 if (Subtarget->hasSSE42()) {
903 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
906 if (!UseSoftFloat && Subtarget->hasAVX()) {
907 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
908 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
909 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
910 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
912 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
913 setOperationAction(ISD::LOAD, MVT::v8i32, Legal);
914 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
915 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
916 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
917 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
918 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
919 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
920 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
921 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
922 //setOperationAction(ISD::BUILD_VECTOR, MVT::v8f32, Custom);
923 //setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Custom);
924 //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
925 //setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
926 //setOperationAction(ISD::VSETCC, MVT::v8f32, Custom);
928 // Operations to consider commented out -v16i16 v32i8
929 //setOperationAction(ISD::ADD, MVT::v16i16, Legal);
930 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
931 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
932 //setOperationAction(ISD::SUB, MVT::v32i8, Legal);
933 //setOperationAction(ISD::SUB, MVT::v16i16, Legal);
934 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
935 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
936 //setOperationAction(ISD::MUL, MVT::v16i16, Legal);
937 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
938 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
939 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
940 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
941 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
942 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
944 setOperationAction(ISD::VSETCC, MVT::v4f64, Custom);
945 // setOperationAction(ISD::VSETCC, MVT::v32i8, Custom);
946 // setOperationAction(ISD::VSETCC, MVT::v16i16, Custom);
947 setOperationAction(ISD::VSETCC, MVT::v8i32, Custom);
949 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v32i8, Custom);
950 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i16, Custom);
951 // setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i16, Custom);
952 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i32, Custom);
953 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8f32, Custom);
955 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
956 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i64, Custom);
957 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f64, Custom);
958 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i64, Custom);
959 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f64, Custom);
960 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
963 // Not sure we want to do this since there are no 256-bit integer
966 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
967 // This includes 256-bit vectors
968 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
969 EVT VT = (MVT::SimpleValueType)i;
971 // Do not attempt to custom lower non-power-of-2 vectors
972 if (!isPowerOf2_32(VT.getVectorNumElements()))
975 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
976 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
977 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
980 if (Subtarget->is64Bit()) {
981 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i64, Custom);
982 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
987 // Not sure we want to do this since there are no 256-bit integer
990 // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
991 // Including 256-bit vectors
992 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
993 EVT VT = (MVT::SimpleValueType)i;
995 if (!VT.is256BitVector()) {
998 setOperationAction(ISD::AND, VT, Promote);
999 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
1000 setOperationAction(ISD::OR, VT, Promote);
1001 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
1002 setOperationAction(ISD::XOR, VT, Promote);
1003 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
1004 setOperationAction(ISD::LOAD, VT, Promote);
1005 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
1006 setOperationAction(ISD::SELECT, VT, Promote);
1007 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1010 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1014 // We want to custom lower some of our intrinsics.
1015 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1017 // Add/Sub/Mul with overflow operations are custom lowered.
1018 setOperationAction(ISD::SADDO, MVT::i32, Custom);
1019 setOperationAction(ISD::SADDO, MVT::i64, Custom);
1020 setOperationAction(ISD::UADDO, MVT::i32, Custom);
1021 setOperationAction(ISD::UADDO, MVT::i64, Custom);
1022 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
1023 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
1024 setOperationAction(ISD::USUBO, MVT::i32, Custom);
1025 setOperationAction(ISD::USUBO, MVT::i64, Custom);
1026 setOperationAction(ISD::SMULO, MVT::i32, Custom);
1027 setOperationAction(ISD::SMULO, MVT::i64, Custom);
1029 if (!Subtarget->is64Bit()) {
1030 // These libcalls are not available in 32-bit.
1031 setLibcallName(RTLIB::SHL_I128, 0);
1032 setLibcallName(RTLIB::SRL_I128, 0);
1033 setLibcallName(RTLIB::SRA_I128, 0);
1036 // We have target-specific dag combine patterns for the following nodes:
1037 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1038 setTargetDAGCombine(ISD::BUILD_VECTOR);
1039 setTargetDAGCombine(ISD::SELECT);
1040 setTargetDAGCombine(ISD::SHL);
1041 setTargetDAGCombine(ISD::SRA);
1042 setTargetDAGCombine(ISD::SRL);
1043 setTargetDAGCombine(ISD::OR);
1044 setTargetDAGCombine(ISD::STORE);
1045 setTargetDAGCombine(ISD::MEMBARRIER);
1046 setTargetDAGCombine(ISD::ZERO_EXTEND);
1047 if (Subtarget->is64Bit())
1048 setTargetDAGCombine(ISD::MUL);
1050 computeRegisterProperties();
1052 // FIXME: These should be based on subtarget info. Plus, the values should
1053 // be smaller when we are in optimizing for size mode.
1054 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1055 maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
1056 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
1057 setPrefLoopAlignment(16);
1058 benefitFromCodePlacementOpt = true;
1062 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1067 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1068 /// the desired ByVal argument alignment.
1069 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1072 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1073 if (VTy->getBitWidth() == 128)
1075 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1076 unsigned EltAlign = 0;
1077 getMaxByValAlign(ATy->getElementType(), EltAlign);
1078 if (EltAlign > MaxAlign)
1079 MaxAlign = EltAlign;
1080 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1081 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1082 unsigned EltAlign = 0;
1083 getMaxByValAlign(STy->getElementType(i), EltAlign);
1084 if (EltAlign > MaxAlign)
1085 MaxAlign = EltAlign;
1093 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1094 /// function arguments in the caller parameter area. For X86, aggregates
1095 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1096 /// are at 4-byte boundaries.
1097 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1098 if (Subtarget->is64Bit()) {
1099 // Max of 8 and alignment of type.
1100 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1107 if (Subtarget->hasSSE1())
1108 getMaxByValAlign(Ty, Align);
1112 /// getOptimalMemOpType - Returns the target specific optimal type for load
1113 /// and store operations as a result of memset, memcpy, and memmove
1114 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
1117 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
1118 bool isSrcConst, bool isSrcStr,
1119 SelectionDAG &DAG) const {
1120 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1121 // linux. This is because the stack realignment code can't handle certain
1122 // cases like PR2962. This should be removed when PR2962 is fixed.
1123 const Function *F = DAG.getMachineFunction().getFunction();
1124 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
1125 if (!NoImplicitFloatOps && Subtarget->getStackAlignment() >= 16) {
1126 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
1128 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
1131 if (Subtarget->is64Bit() && Size >= 8)
1136 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1137 /// current function. The returned value is a member of the
1138 /// MachineJumpTableInfo::JTEntryKind enum.
1139 unsigned X86TargetLowering::getJumpTableEncoding() const {
1140 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1142 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1143 Subtarget->isPICStyleGOT())
1144 return MachineJumpTableInfo::EK_Custom32;
1146 // Otherwise, use the normal jump table encoding heuristics.
1147 return TargetLowering::getJumpTableEncoding();
1150 /// getPICBaseSymbol - Return the X86-32 PIC base.
1152 X86TargetLowering::getPICBaseSymbol(const MachineFunction *MF,
1153 MCContext &Ctx) const {
1154 const MCAsmInfo &MAI = *getTargetMachine().getMCAsmInfo();
1155 return Ctx.GetOrCreateTemporarySymbol(Twine(MAI.getPrivateGlobalPrefix())+
1156 Twine(MF->getFunctionNumber())+"$pb");
1161 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1162 const MachineBasicBlock *MBB,
1163 unsigned uid,MCContext &Ctx) const{
1164 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1165 Subtarget->isPICStyleGOT());
1166 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1168 return X86MCTargetExpr::Create(MBB->getSymbol(Ctx),
1169 X86MCTargetExpr::GOTOFF, Ctx);
1172 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1174 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1175 SelectionDAG &DAG) const {
1176 if (!Subtarget->is64Bit())
1177 // This doesn't have DebugLoc associated with it, but is not really the
1178 // same as a Register.
1179 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc::getUnknownLoc(),
1184 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1185 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1187 const MCExpr *X86TargetLowering::
1188 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1189 MCContext &Ctx) const {
1190 // X86-64 uses RIP relative addressing based on the jump table label.
1191 if (Subtarget->isPICStyleRIPRel())
1192 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1194 // Otherwise, the reference is relative to the PIC base.
1195 return MCSymbolRefExpr::Create(getPICBaseSymbol(MF, Ctx), Ctx);
1198 /// getFunctionAlignment - Return the Log2 alignment of this function.
1199 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1200 return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1203 //===----------------------------------------------------------------------===//
1204 // Return Value Calling Convention Implementation
1205 //===----------------------------------------------------------------------===//
1207 #include "X86GenCallingConv.inc"
1210 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1211 const SmallVectorImpl<EVT> &OutTys,
1212 const SmallVectorImpl<ISD::ArgFlagsTy> &ArgsFlags,
1213 SelectionDAG &DAG) {
1214 SmallVector<CCValAssign, 16> RVLocs;
1215 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1216 RVLocs, *DAG.getContext());
1217 return CCInfo.CheckReturn(OutTys, ArgsFlags, RetCC_X86);
1221 X86TargetLowering::LowerReturn(SDValue Chain,
1222 CallingConv::ID CallConv, bool isVarArg,
1223 const SmallVectorImpl<ISD::OutputArg> &Outs,
1224 DebugLoc dl, SelectionDAG &DAG) {
1226 SmallVector<CCValAssign, 16> RVLocs;
1227 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1228 RVLocs, *DAG.getContext());
1229 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1231 // Add the regs to the liveout set for the function.
1232 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1233 for (unsigned i = 0; i != RVLocs.size(); ++i)
1234 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1235 MRI.addLiveOut(RVLocs[i].getLocReg());
1239 SmallVector<SDValue, 6> RetOps;
1240 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1241 // Operand #1 = Bytes To Pop
1242 RetOps.push_back(DAG.getTargetConstant(getBytesToPopOnReturn(), MVT::i16));
1244 // Copy the result values into the output registers.
1245 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1246 CCValAssign &VA = RVLocs[i];
1247 assert(VA.isRegLoc() && "Can only return in registers!");
1248 SDValue ValToCopy = Outs[i].Val;
1250 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1251 // the RET instruction and handled by the FP Stackifier.
1252 if (VA.getLocReg() == X86::ST0 ||
1253 VA.getLocReg() == X86::ST1) {
1254 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1255 // change the value to the FP stack register class.
1256 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1257 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1258 RetOps.push_back(ValToCopy);
1259 // Don't emit a copytoreg.
1263 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1264 // which is returned in RAX / RDX.
1265 if (Subtarget->is64Bit()) {
1266 EVT ValVT = ValToCopy.getValueType();
1267 if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1268 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1269 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1270 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1274 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1275 Flag = Chain.getValue(1);
1278 // The x86-64 ABI for returning structs by value requires that we copy
1279 // the sret argument into %rax for the return. We saved the argument into
1280 // a virtual register in the entry block, so now we copy the value out
1282 if (Subtarget->is64Bit() &&
1283 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1284 MachineFunction &MF = DAG.getMachineFunction();
1285 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1286 unsigned Reg = FuncInfo->getSRetReturnReg();
1288 Reg = MRI.createVirtualRegister(getRegClassFor(MVT::i64));
1289 FuncInfo->setSRetReturnReg(Reg);
1291 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1293 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1294 Flag = Chain.getValue(1);
1296 // RAX now acts like a return value.
1297 MRI.addLiveOut(X86::RAX);
1300 RetOps[0] = Chain; // Update chain.
1302 // Add the flag if we have it.
1304 RetOps.push_back(Flag);
1306 return DAG.getNode(X86ISD::RET_FLAG, dl,
1307 MVT::Other, &RetOps[0], RetOps.size());
1310 /// LowerCallResult - Lower the result values of a call into the
1311 /// appropriate copies out of appropriate physical registers.
1314 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1315 CallingConv::ID CallConv, bool isVarArg,
1316 const SmallVectorImpl<ISD::InputArg> &Ins,
1317 DebugLoc dl, SelectionDAG &DAG,
1318 SmallVectorImpl<SDValue> &InVals) {
1320 // Assign locations to each value returned by this call.
1321 SmallVector<CCValAssign, 16> RVLocs;
1322 bool Is64Bit = Subtarget->is64Bit();
1323 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1324 RVLocs, *DAG.getContext());
1325 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1327 // Copy all of the result registers out of their specified physreg.
1328 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1329 CCValAssign &VA = RVLocs[i];
1330 EVT CopyVT = VA.getValVT();
1332 // If this is x86-64, and we disabled SSE, we can't return FP values
1333 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1334 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1335 llvm_report_error("SSE register return with SSE disabled");
1338 // If this is a call to a function that returns an fp value on the floating
1339 // point stack, but where we prefer to use the value in xmm registers, copy
1340 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1341 if ((VA.getLocReg() == X86::ST0 ||
1342 VA.getLocReg() == X86::ST1) &&
1343 isScalarFPTypeInSSEReg(VA.getValVT())) {
1348 if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1349 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1350 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1351 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1352 MVT::v2i64, InFlag).getValue(1);
1353 Val = Chain.getValue(0);
1354 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1355 Val, DAG.getConstant(0, MVT::i64));
1357 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1358 MVT::i64, InFlag).getValue(1);
1359 Val = Chain.getValue(0);
1361 Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1363 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1364 CopyVT, InFlag).getValue(1);
1365 Val = Chain.getValue(0);
1367 InFlag = Chain.getValue(2);
1369 if (CopyVT != VA.getValVT()) {
1370 // Round the F80 the right size, which also moves to the appropriate xmm
1372 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1373 // This truncation won't change the value.
1374 DAG.getIntPtrConstant(1));
1377 InVals.push_back(Val);
1384 //===----------------------------------------------------------------------===//
1385 // C & StdCall & Fast Calling Convention implementation
1386 //===----------------------------------------------------------------------===//
1387 // StdCall calling convention seems to be standard for many Windows' API
1388 // routines and around. It differs from C calling convention just a little:
1389 // callee should clean up the stack, not caller. Symbols should be also
1390 // decorated in some fancy way :) It doesn't support any vector arguments.
1391 // For info on fast calling convention see Fast Calling Convention (tail call)
1392 // implementation LowerX86_32FastCCCallTo.
1394 /// CallIsStructReturn - Determines whether a call uses struct return
1396 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1400 return Outs[0].Flags.isSRet();
1403 /// ArgsAreStructReturn - Determines whether a function uses struct
1404 /// return semantics.
1406 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1410 return Ins[0].Flags.isSRet();
1413 /// IsCalleePop - Determines whether the callee is required to pop its
1414 /// own arguments. Callee pop is necessary to support tail calls.
1415 bool X86TargetLowering::IsCalleePop(bool IsVarArg, CallingConv::ID CallingConv){
1419 switch (CallingConv) {
1422 case CallingConv::X86_StdCall:
1423 return !Subtarget->is64Bit();
1424 case CallingConv::X86_FastCall:
1425 return !Subtarget->is64Bit();
1426 case CallingConv::Fast:
1427 return GuaranteedTailCallOpt;
1428 case CallingConv::GHC:
1429 return GuaranteedTailCallOpt;
1433 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1434 /// given CallingConvention value.
1435 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1436 if (Subtarget->is64Bit()) {
1437 if (CC == CallingConv::GHC)
1438 return CC_X86_64_GHC;
1439 else if (Subtarget->isTargetWin64())
1440 return CC_X86_Win64_C;
1445 if (CC == CallingConv::X86_FastCall)
1446 return CC_X86_32_FastCall;
1447 else if (CC == CallingConv::Fast)
1448 return CC_X86_32_FastCC;
1449 else if (CC == CallingConv::GHC)
1450 return CC_X86_32_GHC;
1455 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1456 /// by "Src" to address "Dst" with size and alignment information specified by
1457 /// the specific parameter attribute. The copy will be passed as a byval
1458 /// function parameter.
1460 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1461 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1463 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1464 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1465 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1468 /// IsTailCallConvention - Return true if the calling convention is one that
1469 /// supports tail call optimization.
1470 static bool IsTailCallConvention(CallingConv::ID CC) {
1471 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1474 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1475 /// a tailcall target by changing its ABI.
1476 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1477 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1481 X86TargetLowering::LowerMemArgument(SDValue Chain,
1482 CallingConv::ID CallConv,
1483 const SmallVectorImpl<ISD::InputArg> &Ins,
1484 DebugLoc dl, SelectionDAG &DAG,
1485 const CCValAssign &VA,
1486 MachineFrameInfo *MFI,
1488 // Create the nodes corresponding to a load from this parameter slot.
1489 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1490 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1491 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1494 // If value is passed by pointer we have address passed instead of the value
1496 if (VA.getLocInfo() == CCValAssign::Indirect)
1497 ValVT = VA.getLocVT();
1499 ValVT = VA.getValVT();
1501 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1502 // changed with more analysis.
1503 // In case of tail call optimization mark all arguments mutable. Since they
1504 // could be overwritten by lowering of arguments in case of a tail call.
1505 if (Flags.isByVal()) {
1506 int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1507 VA.getLocMemOffset(), isImmutable, false);
1508 return DAG.getFrameIndex(FI, getPointerTy());
1510 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1511 VA.getLocMemOffset(), isImmutable, false);
1512 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1513 return DAG.getLoad(ValVT, dl, Chain, FIN,
1514 PseudoSourceValue::getFixedStack(FI), 0,
1520 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1521 CallingConv::ID CallConv,
1523 const SmallVectorImpl<ISD::InputArg> &Ins,
1526 SmallVectorImpl<SDValue> &InVals) {
1528 MachineFunction &MF = DAG.getMachineFunction();
1529 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1531 const Function* Fn = MF.getFunction();
1532 if (Fn->hasExternalLinkage() &&
1533 Subtarget->isTargetCygMing() &&
1534 Fn->getName() == "main")
1535 FuncInfo->setForceFramePointer(true);
1537 MachineFrameInfo *MFI = MF.getFrameInfo();
1538 bool Is64Bit = Subtarget->is64Bit();
1539 bool IsWin64 = Subtarget->isTargetWin64();
1541 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1542 "Var args not supported with calling convention fastcc or ghc");
1544 // Assign locations to all of the incoming arguments.
1545 SmallVector<CCValAssign, 16> ArgLocs;
1546 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1547 ArgLocs, *DAG.getContext());
1548 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1550 unsigned LastVal = ~0U;
1552 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1553 CCValAssign &VA = ArgLocs[i];
1554 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1556 assert(VA.getValNo() != LastVal &&
1557 "Don't support value assigned to multiple locs yet");
1558 LastVal = VA.getValNo();
1560 if (VA.isRegLoc()) {
1561 EVT RegVT = VA.getLocVT();
1562 TargetRegisterClass *RC = NULL;
1563 if (RegVT == MVT::i32)
1564 RC = X86::GR32RegisterClass;
1565 else if (Is64Bit && RegVT == MVT::i64)
1566 RC = X86::GR64RegisterClass;
1567 else if (RegVT == MVT::f32)
1568 RC = X86::FR32RegisterClass;
1569 else if (RegVT == MVT::f64)
1570 RC = X86::FR64RegisterClass;
1571 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1572 RC = X86::VR128RegisterClass;
1573 else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1574 RC = X86::VR64RegisterClass;
1576 llvm_unreachable("Unknown argument type!");
1578 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1579 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1581 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1582 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1584 if (VA.getLocInfo() == CCValAssign::SExt)
1585 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1586 DAG.getValueType(VA.getValVT()));
1587 else if (VA.getLocInfo() == CCValAssign::ZExt)
1588 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1589 DAG.getValueType(VA.getValVT()));
1590 else if (VA.getLocInfo() == CCValAssign::BCvt)
1591 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1593 if (VA.isExtInLoc()) {
1594 // Handle MMX values passed in XMM regs.
1595 if (RegVT.isVector()) {
1596 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1597 ArgValue, DAG.getConstant(0, MVT::i64));
1598 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1600 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1603 assert(VA.isMemLoc());
1604 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1607 // If value is passed via pointer - do a load.
1608 if (VA.getLocInfo() == CCValAssign::Indirect)
1609 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0,
1612 InVals.push_back(ArgValue);
1615 // The x86-64 ABI for returning structs by value requires that we copy
1616 // the sret argument into %rax for the return. Save the argument into
1617 // a virtual register so that we can access it from the return points.
1618 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1619 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1620 unsigned Reg = FuncInfo->getSRetReturnReg();
1622 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1623 FuncInfo->setSRetReturnReg(Reg);
1625 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1626 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1629 unsigned StackSize = CCInfo.getNextStackOffset();
1630 // Align stack specially for tail calls.
1631 if (FuncIsMadeTailCallSafe(CallConv))
1632 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1634 // If the function takes variable number of arguments, make a frame index for
1635 // the start of the first vararg value... for expansion of llvm.va_start.
1637 if (Is64Bit || CallConv != CallingConv::X86_FastCall) {
1638 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize, true, false);
1641 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1643 // FIXME: We should really autogenerate these arrays
1644 static const unsigned GPR64ArgRegsWin64[] = {
1645 X86::RCX, X86::RDX, X86::R8, X86::R9
1647 static const unsigned XMMArgRegsWin64[] = {
1648 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1650 static const unsigned GPR64ArgRegs64Bit[] = {
1651 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1653 static const unsigned XMMArgRegs64Bit[] = {
1654 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1655 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1657 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1660 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1661 GPR64ArgRegs = GPR64ArgRegsWin64;
1662 XMMArgRegs = XMMArgRegsWin64;
1664 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1665 GPR64ArgRegs = GPR64ArgRegs64Bit;
1666 XMMArgRegs = XMMArgRegs64Bit;
1668 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1670 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1673 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1674 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1675 "SSE register cannot be used when SSE is disabled!");
1676 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1677 "SSE register cannot be used when SSE is disabled!");
1678 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1679 // Kernel mode asks for SSE to be disabled, so don't push them
1681 TotalNumXMMRegs = 0;
1683 // For X86-64, if there are vararg parameters that are passed via
1684 // registers, then we must store them to their spots on the stack so they
1685 // may be loaded by deferencing the result of va_next.
1686 VarArgsGPOffset = NumIntRegs * 8;
1687 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1688 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1689 TotalNumXMMRegs * 16, 16,
1692 // Store the integer parameter registers.
1693 SmallVector<SDValue, 8> MemOps;
1694 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1695 unsigned Offset = VarArgsGPOffset;
1696 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1697 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1698 DAG.getIntPtrConstant(Offset));
1699 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1700 X86::GR64RegisterClass);
1701 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1703 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1704 PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
1705 Offset, false, false, 0);
1706 MemOps.push_back(Store);
1710 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1711 // Now store the XMM (fp + vector) parameter registers.
1712 SmallVector<SDValue, 11> SaveXMMOps;
1713 SaveXMMOps.push_back(Chain);
1715 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1716 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1717 SaveXMMOps.push_back(ALVal);
1719 SaveXMMOps.push_back(DAG.getIntPtrConstant(RegSaveFrameIndex));
1720 SaveXMMOps.push_back(DAG.getIntPtrConstant(VarArgsFPOffset));
1722 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1723 unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1724 X86::VR128RegisterClass);
1725 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1726 SaveXMMOps.push_back(Val);
1728 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1730 &SaveXMMOps[0], SaveXMMOps.size()));
1733 if (!MemOps.empty())
1734 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1735 &MemOps[0], MemOps.size());
1739 // Some CCs need callee pop.
1740 if (IsCalleePop(isVarArg, CallConv)) {
1741 BytesToPopOnReturn = StackSize; // Callee pops everything.
1743 BytesToPopOnReturn = 0; // Callee pops nothing.
1744 // If this is an sret function, the return should pop the hidden pointer.
1745 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1746 BytesToPopOnReturn = 4;
1750 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1751 if (CallConv == CallingConv::X86_FastCall)
1752 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1755 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1761 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1762 SDValue StackPtr, SDValue Arg,
1763 DebugLoc dl, SelectionDAG &DAG,
1764 const CCValAssign &VA,
1765 ISD::ArgFlagsTy Flags) {
1766 const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1767 unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1768 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1769 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1770 if (Flags.isByVal()) {
1771 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1773 return DAG.getStore(Chain, dl, Arg, PtrOff,
1774 PseudoSourceValue::getStack(), LocMemOffset,
1778 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1779 /// optimization is performed and it is required.
1781 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1782 SDValue &OutRetAddr, SDValue Chain,
1783 bool IsTailCall, bool Is64Bit,
1784 int FPDiff, DebugLoc dl) {
1785 // Adjust the Return address stack slot.
1786 EVT VT = getPointerTy();
1787 OutRetAddr = getReturnAddressFrameIndex(DAG);
1789 // Load the "old" Return address.
1790 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0, false, false, 0);
1791 return SDValue(OutRetAddr.getNode(), 1);
1794 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1795 /// optimization is performed and it is required (FPDiff!=0).
1797 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1798 SDValue Chain, SDValue RetAddrFrIdx,
1799 bool Is64Bit, int FPDiff, DebugLoc dl) {
1800 // Store the return address to the appropriate stack slot.
1801 if (!FPDiff) return Chain;
1802 // Calculate the new stack slot for the return address.
1803 int SlotSize = Is64Bit ? 8 : 4;
1804 int NewReturnAddrFI =
1805 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false, false);
1806 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1807 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1808 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1809 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0,
1815 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1816 CallingConv::ID CallConv, bool isVarArg,
1818 const SmallVectorImpl<ISD::OutputArg> &Outs,
1819 const SmallVectorImpl<ISD::InputArg> &Ins,
1820 DebugLoc dl, SelectionDAG &DAG,
1821 SmallVectorImpl<SDValue> &InVals) {
1822 MachineFunction &MF = DAG.getMachineFunction();
1823 bool Is64Bit = Subtarget->is64Bit();
1824 bool IsStructRet = CallIsStructReturn(Outs);
1825 bool IsSibcall = false;
1828 // Check if it's really possible to do a tail call.
1829 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg,
1832 // Sibcalls are automatically detected tailcalls which do not require
1834 if (!GuaranteedTailCallOpt && isTailCall)
1841 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1842 "Var args not supported with calling convention fastcc or ghc");
1844 // Analyze operands of the call, assigning locations to each operand.
1845 SmallVector<CCValAssign, 16> ArgLocs;
1846 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1847 ArgLocs, *DAG.getContext());
1848 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1850 // Get a count of how many bytes are to be pushed on the stack.
1851 unsigned NumBytes = CCInfo.getNextStackOffset();
1853 // This is a sibcall. The memory operands are available in caller's
1854 // own caller's stack.
1856 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1857 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1860 if (isTailCall && !IsSibcall) {
1861 // Lower arguments at fp - stackoffset + fpdiff.
1862 unsigned NumBytesCallerPushed =
1863 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1864 FPDiff = NumBytesCallerPushed - NumBytes;
1866 // Set the delta of movement of the returnaddr stackslot.
1867 // But only set if delta is greater than previous delta.
1868 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1869 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1873 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1875 SDValue RetAddrFrIdx;
1876 // Load return adress for tail calls.
1877 if (isTailCall && FPDiff)
1878 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1879 Is64Bit, FPDiff, dl);
1881 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1882 SmallVector<SDValue, 8> MemOpChains;
1885 // Walk the register/memloc assignments, inserting copies/loads. In the case
1886 // of tail call optimization arguments are handle later.
1887 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1888 CCValAssign &VA = ArgLocs[i];
1889 EVT RegVT = VA.getLocVT();
1890 SDValue Arg = Outs[i].Val;
1891 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1892 bool isByVal = Flags.isByVal();
1894 // Promote the value if needed.
1895 switch (VA.getLocInfo()) {
1896 default: llvm_unreachable("Unknown loc info!");
1897 case CCValAssign::Full: break;
1898 case CCValAssign::SExt:
1899 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1901 case CCValAssign::ZExt:
1902 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1904 case CCValAssign::AExt:
1905 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1906 // Special case: passing MMX values in XMM registers.
1907 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1908 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1909 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1911 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1913 case CCValAssign::BCvt:
1914 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1916 case CCValAssign::Indirect: {
1917 // Store the argument.
1918 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1919 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1920 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1921 PseudoSourceValue::getFixedStack(FI), 0,
1928 if (VA.isRegLoc()) {
1929 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1930 } else if (!IsSibcall && (!isTailCall || isByVal)) {
1931 assert(VA.isMemLoc());
1932 if (StackPtr.getNode() == 0)
1933 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1934 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1935 dl, DAG, VA, Flags));
1939 if (!MemOpChains.empty())
1940 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1941 &MemOpChains[0], MemOpChains.size());
1943 // Build a sequence of copy-to-reg nodes chained together with token chain
1944 // and flag operands which copy the outgoing args into registers.
1946 // Tail call byval lowering might overwrite argument registers so in case of
1947 // tail call optimization the copies to registers are lowered later.
1949 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1950 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1951 RegsToPass[i].second, InFlag);
1952 InFlag = Chain.getValue(1);
1955 if (Subtarget->isPICStyleGOT()) {
1956 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1959 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1960 DAG.getNode(X86ISD::GlobalBaseReg,
1961 DebugLoc::getUnknownLoc(),
1964 InFlag = Chain.getValue(1);
1966 // If we are tail calling and generating PIC/GOT style code load the
1967 // address of the callee into ECX. The value in ecx is used as target of
1968 // the tail jump. This is done to circumvent the ebx/callee-saved problem
1969 // for tail calls on PIC/GOT architectures. Normally we would just put the
1970 // address of GOT into ebx and then call target@PLT. But for tail calls
1971 // ebx would be restored (since ebx is callee saved) before jumping to the
1974 // Note: The actual moving to ECX is done further down.
1975 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1976 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1977 !G->getGlobal()->hasProtectedVisibility())
1978 Callee = LowerGlobalAddress(Callee, DAG);
1979 else if (isa<ExternalSymbolSDNode>(Callee))
1980 Callee = LowerExternalSymbol(Callee, DAG);
1984 if (Is64Bit && isVarArg) {
1985 // From AMD64 ABI document:
1986 // For calls that may call functions that use varargs or stdargs
1987 // (prototype-less calls or calls to functions containing ellipsis (...) in
1988 // the declaration) %al is used as hidden argument to specify the number
1989 // of SSE registers used. The contents of %al do not need to match exactly
1990 // the number of registers, but must be an ubound on the number of SSE
1991 // registers used and is in the range 0 - 8 inclusive.
1993 // FIXME: Verify this on Win64
1994 // Count the number of XMM registers allocated.
1995 static const unsigned XMMArgRegs[] = {
1996 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1997 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1999 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2000 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2001 && "SSE registers cannot be used when SSE is disabled");
2003 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2004 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2005 InFlag = Chain.getValue(1);
2009 // For tail calls lower the arguments to the 'real' stack slot.
2011 // Force all the incoming stack arguments to be loaded from the stack
2012 // before any new outgoing arguments are stored to the stack, because the
2013 // outgoing stack slots may alias the incoming argument stack slots, and
2014 // the alias isn't otherwise explicit. This is slightly more conservative
2015 // than necessary, because it means that each store effectively depends
2016 // on every argument instead of just those arguments it would clobber.
2017 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2019 SmallVector<SDValue, 8> MemOpChains2;
2022 // Do not flag preceeding copytoreg stuff together with the following stuff.
2024 if (GuaranteedTailCallOpt) {
2025 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2026 CCValAssign &VA = ArgLocs[i];
2029 assert(VA.isMemLoc());
2030 SDValue Arg = Outs[i].Val;
2031 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2032 // Create frame index.
2033 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2034 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2035 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true, false);
2036 FIN = DAG.getFrameIndex(FI, getPointerTy());
2038 if (Flags.isByVal()) {
2039 // Copy relative to framepointer.
2040 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2041 if (StackPtr.getNode() == 0)
2042 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2044 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2046 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2050 // Store relative to framepointer.
2051 MemOpChains2.push_back(
2052 DAG.getStore(ArgChain, dl, Arg, FIN,
2053 PseudoSourceValue::getFixedStack(FI), 0,
2059 if (!MemOpChains2.empty())
2060 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2061 &MemOpChains2[0], MemOpChains2.size());
2063 // Copy arguments to their registers.
2064 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2065 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2066 RegsToPass[i].second, InFlag);
2067 InFlag = Chain.getValue(1);
2071 // Store the return address to the appropriate stack slot.
2072 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2076 bool WasGlobalOrExternal = false;
2077 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2078 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2079 // In the 64-bit large code model, we have to make all calls
2080 // through a register, since the call instruction's 32-bit
2081 // pc-relative offset may not be large enough to hold the whole
2083 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2084 WasGlobalOrExternal = true;
2085 // If the callee is a GlobalAddress node (quite common, every direct call
2086 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2089 // We should use extra load for direct calls to dllimported functions in
2091 GlobalValue *GV = G->getGlobal();
2092 if (!GV->hasDLLImportLinkage()) {
2093 unsigned char OpFlags = 0;
2095 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2096 // external symbols most go through the PLT in PIC mode. If the symbol
2097 // has hidden or protected visibility, or if it is static or local, then
2098 // we don't need to use the PLT - we can directly call it.
2099 if (Subtarget->isTargetELF() &&
2100 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2101 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2102 OpFlags = X86II::MO_PLT;
2103 } else if (Subtarget->isPICStyleStubAny() &&
2104 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2105 Subtarget->getDarwinVers() < 9) {
2106 // PC-relative references to external symbols should go through $stub,
2107 // unless we're building with the leopard linker or later, which
2108 // automatically synthesizes these stubs.
2109 OpFlags = X86II::MO_DARWIN_STUB;
2112 Callee = DAG.getTargetGlobalAddress(GV, getPointerTy(),
2113 G->getOffset(), OpFlags);
2115 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2116 WasGlobalOrExternal = true;
2117 unsigned char OpFlags = 0;
2119 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2120 // symbols should go through the PLT.
2121 if (Subtarget->isTargetELF() &&
2122 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2123 OpFlags = X86II::MO_PLT;
2124 } else if (Subtarget->isPICStyleStubAny() &&
2125 Subtarget->getDarwinVers() < 9) {
2126 // PC-relative references to external symbols should go through $stub,
2127 // unless we're building with the leopard linker or later, which
2128 // automatically synthesizes these stubs.
2129 OpFlags = X86II::MO_DARWIN_STUB;
2132 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2136 if (isTailCall && !WasGlobalOrExternal) {
2137 // Force the address into a (call preserved) caller-saved register since
2138 // tailcall must happen after callee-saved registers are poped.
2139 // FIXME: Give it a special register class that contains caller-saved
2140 // register instead?
2141 unsigned TCReg = Is64Bit ? X86::R11 : X86::EAX;
2142 Chain = DAG.getCopyToReg(Chain, dl,
2143 DAG.getRegister(TCReg, getPointerTy()),
2145 Callee = DAG.getRegister(TCReg, getPointerTy());
2148 // Returns a chain & a flag for retval copy to use.
2149 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2150 SmallVector<SDValue, 8> Ops;
2152 if (!IsSibcall && isTailCall) {
2153 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2154 DAG.getIntPtrConstant(0, true), InFlag);
2155 InFlag = Chain.getValue(1);
2158 Ops.push_back(Chain);
2159 Ops.push_back(Callee);
2162 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2164 // Add argument registers to the end of the list so that they are known live
2166 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2167 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2168 RegsToPass[i].second.getValueType()));
2170 // Add an implicit use GOT pointer in EBX.
2171 if (!isTailCall && Subtarget->isPICStyleGOT())
2172 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2174 // Add an implicit use of AL for x86 vararg functions.
2175 if (Is64Bit && isVarArg)
2176 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2178 if (InFlag.getNode())
2179 Ops.push_back(InFlag);
2182 // If this is the first return lowered for this function, add the regs
2183 // to the liveout set for the function.
2184 if (MF.getRegInfo().liveout_empty()) {
2185 SmallVector<CCValAssign, 16> RVLocs;
2186 CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
2188 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2189 for (unsigned i = 0; i != RVLocs.size(); ++i)
2190 if (RVLocs[i].isRegLoc())
2191 MF.getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2194 assert(((Callee.getOpcode() == ISD::Register &&
2195 (cast<RegisterSDNode>(Callee)->getReg() == X86::EAX ||
2196 cast<RegisterSDNode>(Callee)->getReg() == X86::R11)) ||
2197 Callee.getOpcode() == ISD::TargetExternalSymbol ||
2198 Callee.getOpcode() == ISD::TargetGlobalAddress) &&
2199 "Expecting a global address, external symbol, or scratch register");
2201 return DAG.getNode(X86ISD::TC_RETURN, dl,
2202 NodeTys, &Ops[0], Ops.size());
2205 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2206 InFlag = Chain.getValue(1);
2208 // Create the CALLSEQ_END node.
2209 unsigned NumBytesForCalleeToPush;
2210 if (IsCalleePop(isVarArg, CallConv))
2211 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2212 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2213 // If this is a call to a struct-return function, the callee
2214 // pops the hidden struct pointer, so we have to push it back.
2215 // This is common for Darwin/X86, Linux & Mingw32 targets.
2216 NumBytesForCalleeToPush = 4;
2218 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2220 // Returns a flag for retval copy to use.
2222 Chain = DAG.getCALLSEQ_END(Chain,
2223 DAG.getIntPtrConstant(NumBytes, true),
2224 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2227 InFlag = Chain.getValue(1);
2230 // Handle result values, copying them out of physregs into vregs that we
2232 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2233 Ins, dl, DAG, InVals);
2237 //===----------------------------------------------------------------------===//
2238 // Fast Calling Convention (tail call) implementation
2239 //===----------------------------------------------------------------------===//
2241 // Like std call, callee cleans arguments, convention except that ECX is
2242 // reserved for storing the tail called function address. Only 2 registers are
2243 // free for argument passing (inreg). Tail call optimization is performed
2245 // * tailcallopt is enabled
2246 // * caller/callee are fastcc
2247 // On X86_64 architecture with GOT-style position independent code only local
2248 // (within module) calls are supported at the moment.
2249 // To keep the stack aligned according to platform abi the function
2250 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2251 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2252 // If a tail called function callee has more arguments than the caller the
2253 // caller needs to make sure that there is room to move the RETADDR to. This is
2254 // achieved by reserving an area the size of the argument delta right after the
2255 // original REtADDR, but before the saved framepointer or the spilled registers
2256 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2268 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2269 /// for a 16 byte align requirement.
2270 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2271 SelectionDAG& DAG) {
2272 MachineFunction &MF = DAG.getMachineFunction();
2273 const TargetMachine &TM = MF.getTarget();
2274 const TargetFrameInfo &TFI = *TM.getFrameInfo();
2275 unsigned StackAlignment = TFI.getStackAlignment();
2276 uint64_t AlignMask = StackAlignment - 1;
2277 int64_t Offset = StackSize;
2278 uint64_t SlotSize = TD->getPointerSize();
2279 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2280 // Number smaller than 12 so just add the difference.
2281 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2283 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2284 Offset = ((~AlignMask) & Offset) + StackAlignment +
2285 (StackAlignment-SlotSize);
2290 /// MatchingStackOffset - Return true if the given stack call argument is
2291 /// already available in the same position (relatively) of the caller's
2292 /// incoming argument stack.
2294 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2295 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2296 const X86InstrInfo *TII) {
2297 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2299 if (Arg.getOpcode() == ISD::CopyFromReg) {
2300 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2301 if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2303 MachineInstr *Def = MRI->getVRegDef(VR);
2306 if (!Flags.isByVal()) {
2307 if (!TII->isLoadFromStackSlot(Def, FI))
2310 unsigned Opcode = Def->getOpcode();
2311 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2312 Def->getOperand(1).isFI()) {
2313 FI = Def->getOperand(1).getIndex();
2314 Bytes = Flags.getByValSize();
2318 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2319 if (Flags.isByVal())
2320 // ByVal argument is passed in as a pointer but it's now being
2321 // dereferenced. e.g.
2322 // define @foo(%struct.X* %A) {
2323 // tail call @bar(%struct.X* byval %A)
2326 SDValue Ptr = Ld->getBasePtr();
2327 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2330 FI = FINode->getIndex();
2334 assert(FI != INT_MAX);
2335 if (!MFI->isFixedObjectIndex(FI))
2337 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2340 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2341 /// for tail call optimization. Targets which want to do tail call
2342 /// optimization should implement this function.
2344 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2345 CallingConv::ID CalleeCC,
2347 const SmallVectorImpl<ISD::OutputArg> &Outs,
2348 const SmallVectorImpl<ISD::InputArg> &Ins,
2349 SelectionDAG& DAG) const {
2350 if (!IsTailCallConvention(CalleeCC) &&
2351 CalleeCC != CallingConv::C)
2354 // If -tailcallopt is specified, make fastcc functions tail-callable.
2355 const Function *CallerF = DAG.getMachineFunction().getFunction();
2356 if (GuaranteedTailCallOpt) {
2357 if (IsTailCallConvention(CalleeCC) &&
2358 CallerF->getCallingConv() == CalleeCC)
2363 // Look for obvious safe cases to perform tail call optimization that does not
2364 // requite ABI changes. This is what gcc calls sibcall.
2366 // Do not tail call optimize vararg calls for now.
2370 // If the callee takes no arguments then go on to check the results of the
2372 if (!Outs.empty()) {
2373 // Check if stack adjustment is needed. For now, do not do this if any
2374 // argument is passed on the stack.
2375 SmallVector<CCValAssign, 16> ArgLocs;
2376 CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2377 ArgLocs, *DAG.getContext());
2378 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
2379 if (CCInfo.getNextStackOffset()) {
2380 MachineFunction &MF = DAG.getMachineFunction();
2381 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2383 if (Subtarget->isTargetWin64())
2384 // Win64 ABI has additional complications.
2387 // Check if the arguments are already laid out in the right way as
2388 // the caller's fixed stack objects.
2389 MachineFrameInfo *MFI = MF.getFrameInfo();
2390 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2391 const X86InstrInfo *TII =
2392 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2393 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2394 CCValAssign &VA = ArgLocs[i];
2395 EVT RegVT = VA.getLocVT();
2396 SDValue Arg = Outs[i].Val;
2397 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2398 if (VA.getLocInfo() == CCValAssign::Indirect)
2400 if (!VA.isRegLoc()) {
2401 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2413 X86TargetLowering::createFastISel(MachineFunction &mf, MachineModuleInfo *mmo,
2415 DenseMap<const Value *, unsigned> &vm,
2416 DenseMap<const BasicBlock*, MachineBasicBlock*> &bm,
2417 DenseMap<const AllocaInst *, int> &am
2419 , SmallSet<Instruction*, 8> &cil
2422 return X86::createFastISel(mf, mmo, dw, vm, bm, am
2430 //===----------------------------------------------------------------------===//
2431 // Other Lowering Hooks
2432 //===----------------------------------------------------------------------===//
2435 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2436 MachineFunction &MF = DAG.getMachineFunction();
2437 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2438 int ReturnAddrIndex = FuncInfo->getRAIndex();
2440 if (ReturnAddrIndex == 0) {
2441 // Set up a frame object for the return address.
2442 uint64_t SlotSize = TD->getPointerSize();
2443 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2445 FuncInfo->setRAIndex(ReturnAddrIndex);
2448 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2452 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2453 bool hasSymbolicDisplacement) {
2454 // Offset should fit into 32 bit immediate field.
2455 if (!isInt32(Offset))
2458 // If we don't have a symbolic displacement - we don't have any extra
2460 if (!hasSymbolicDisplacement)
2463 // FIXME: Some tweaks might be needed for medium code model.
2464 if (M != CodeModel::Small && M != CodeModel::Kernel)
2467 // For small code model we assume that latest object is 16MB before end of 31
2468 // bits boundary. We may also accept pretty large negative constants knowing
2469 // that all objects are in the positive half of address space.
2470 if (M == CodeModel::Small && Offset < 16*1024*1024)
2473 // For kernel code model we know that all object resist in the negative half
2474 // of 32bits address space. We may not accept negative offsets, since they may
2475 // be just off and we may accept pretty large positive ones.
2476 if (M == CodeModel::Kernel && Offset > 0)
2482 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2483 /// specific condition code, returning the condition code and the LHS/RHS of the
2484 /// comparison to make.
2485 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2486 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2488 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2489 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2490 // X > -1 -> X == 0, jump !sign.
2491 RHS = DAG.getConstant(0, RHS.getValueType());
2492 return X86::COND_NS;
2493 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2494 // X < 0 -> X == 0, jump on sign.
2496 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2498 RHS = DAG.getConstant(0, RHS.getValueType());
2499 return X86::COND_LE;
2503 switch (SetCCOpcode) {
2504 default: llvm_unreachable("Invalid integer condition!");
2505 case ISD::SETEQ: return X86::COND_E;
2506 case ISD::SETGT: return X86::COND_G;
2507 case ISD::SETGE: return X86::COND_GE;
2508 case ISD::SETLT: return X86::COND_L;
2509 case ISD::SETLE: return X86::COND_LE;
2510 case ISD::SETNE: return X86::COND_NE;
2511 case ISD::SETULT: return X86::COND_B;
2512 case ISD::SETUGT: return X86::COND_A;
2513 case ISD::SETULE: return X86::COND_BE;
2514 case ISD::SETUGE: return X86::COND_AE;
2518 // First determine if it is required or is profitable to flip the operands.
2520 // If LHS is a foldable load, but RHS is not, flip the condition.
2521 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2522 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2523 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2524 std::swap(LHS, RHS);
2527 switch (SetCCOpcode) {
2533 std::swap(LHS, RHS);
2537 // On a floating point condition, the flags are set as follows:
2539 // 0 | 0 | 0 | X > Y
2540 // 0 | 0 | 1 | X < Y
2541 // 1 | 0 | 0 | X == Y
2542 // 1 | 1 | 1 | unordered
2543 switch (SetCCOpcode) {
2544 default: llvm_unreachable("Condcode should be pre-legalized away");
2546 case ISD::SETEQ: return X86::COND_E;
2547 case ISD::SETOLT: // flipped
2549 case ISD::SETGT: return X86::COND_A;
2550 case ISD::SETOLE: // flipped
2552 case ISD::SETGE: return X86::COND_AE;
2553 case ISD::SETUGT: // flipped
2555 case ISD::SETLT: return X86::COND_B;
2556 case ISD::SETUGE: // flipped
2558 case ISD::SETLE: return X86::COND_BE;
2560 case ISD::SETNE: return X86::COND_NE;
2561 case ISD::SETUO: return X86::COND_P;
2562 case ISD::SETO: return X86::COND_NP;
2564 case ISD::SETUNE: return X86::COND_INVALID;
2568 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2569 /// code. Current x86 isa includes the following FP cmov instructions:
2570 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2571 static bool hasFPCMov(unsigned X86CC) {
2587 /// isFPImmLegal - Returns true if the target can instruction select the
2588 /// specified FP immediate natively. If false, the legalizer will
2589 /// materialize the FP immediate as a load from a constant pool.
2590 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2591 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2592 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2598 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2599 /// the specified range (L, H].
2600 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2601 return (Val < 0) || (Val >= Low && Val < Hi);
2604 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2605 /// specified value.
2606 static bool isUndefOrEqual(int Val, int CmpVal) {
2607 if (Val < 0 || Val == CmpVal)
2612 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2613 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2614 /// the second operand.
2615 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2616 if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2617 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2618 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2619 return (Mask[0] < 2 && Mask[1] < 2);
2623 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2624 SmallVector<int, 8> M;
2626 return ::isPSHUFDMask(M, N->getValueType(0));
2629 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2630 /// is suitable for input to PSHUFHW.
2631 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2632 if (VT != MVT::v8i16)
2635 // Lower quadword copied in order or undef.
2636 for (int i = 0; i != 4; ++i)
2637 if (Mask[i] >= 0 && Mask[i] != i)
2640 // Upper quadword shuffled.
2641 for (int i = 4; i != 8; ++i)
2642 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2648 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2649 SmallVector<int, 8> M;
2651 return ::isPSHUFHWMask(M, N->getValueType(0));
2654 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2655 /// is suitable for input to PSHUFLW.
2656 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2657 if (VT != MVT::v8i16)
2660 // Upper quadword copied in order.
2661 for (int i = 4; i != 8; ++i)
2662 if (Mask[i] >= 0 && Mask[i] != i)
2665 // Lower quadword shuffled.
2666 for (int i = 0; i != 4; ++i)
2673 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2674 SmallVector<int, 8> M;
2676 return ::isPSHUFLWMask(M, N->getValueType(0));
2679 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2680 /// is suitable for input to PALIGNR.
2681 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2683 int i, e = VT.getVectorNumElements();
2685 // Do not handle v2i64 / v2f64 shuffles with palignr.
2686 if (e < 4 || !hasSSSE3)
2689 for (i = 0; i != e; ++i)
2693 // All undef, not a palignr.
2697 // Determine if it's ok to perform a palignr with only the LHS, since we
2698 // don't have access to the actual shuffle elements to see if RHS is undef.
2699 bool Unary = Mask[i] < (int)e;
2700 bool NeedsUnary = false;
2702 int s = Mask[i] - i;
2704 // Check the rest of the elements to see if they are consecutive.
2705 for (++i; i != e; ++i) {
2710 Unary = Unary && (m < (int)e);
2711 NeedsUnary = NeedsUnary || (m < s);
2713 if (NeedsUnary && !Unary)
2715 if (Unary && m != ((s+i) & (e-1)))
2717 if (!Unary && m != (s+i))
2723 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2724 SmallVector<int, 8> M;
2726 return ::isPALIGNRMask(M, N->getValueType(0), true);
2729 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2730 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2731 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2732 int NumElems = VT.getVectorNumElements();
2733 if (NumElems != 2 && NumElems != 4)
2736 int Half = NumElems / 2;
2737 for (int i = 0; i < Half; ++i)
2738 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2740 for (int i = Half; i < NumElems; ++i)
2741 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2747 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2748 SmallVector<int, 8> M;
2750 return ::isSHUFPMask(M, N->getValueType(0));
2753 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2754 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2755 /// half elements to come from vector 1 (which would equal the dest.) and
2756 /// the upper half to come from vector 2.
2757 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2758 int NumElems = VT.getVectorNumElements();
2760 if (NumElems != 2 && NumElems != 4)
2763 int Half = NumElems / 2;
2764 for (int i = 0; i < Half; ++i)
2765 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2767 for (int i = Half; i < NumElems; ++i)
2768 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2773 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2774 SmallVector<int, 8> M;
2776 return isCommutedSHUFPMask(M, N->getValueType(0));
2779 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2780 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2781 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2782 if (N->getValueType(0).getVectorNumElements() != 4)
2785 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2786 return isUndefOrEqual(N->getMaskElt(0), 6) &&
2787 isUndefOrEqual(N->getMaskElt(1), 7) &&
2788 isUndefOrEqual(N->getMaskElt(2), 2) &&
2789 isUndefOrEqual(N->getMaskElt(3), 3);
2792 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2793 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2795 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2796 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2801 return isUndefOrEqual(N->getMaskElt(0), 2) &&
2802 isUndefOrEqual(N->getMaskElt(1), 3) &&
2803 isUndefOrEqual(N->getMaskElt(2), 2) &&
2804 isUndefOrEqual(N->getMaskElt(3), 3);
2807 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2808 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2809 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2810 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2812 if (NumElems != 2 && NumElems != 4)
2815 for (unsigned i = 0; i < NumElems/2; ++i)
2816 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2819 for (unsigned i = NumElems/2; i < NumElems; ++i)
2820 if (!isUndefOrEqual(N->getMaskElt(i), i))
2826 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
2827 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
2828 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
2829 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2831 if (NumElems != 2 && NumElems != 4)
2834 for (unsigned i = 0; i < NumElems/2; ++i)
2835 if (!isUndefOrEqual(N->getMaskElt(i), i))
2838 for (unsigned i = 0; i < NumElems/2; ++i)
2839 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2845 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2846 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2847 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2848 bool V2IsSplat = false) {
2849 int NumElts = VT.getVectorNumElements();
2850 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2853 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2855 int BitI1 = Mask[i+1];
2856 if (!isUndefOrEqual(BitI, j))
2859 if (!isUndefOrEqual(BitI1, NumElts))
2862 if (!isUndefOrEqual(BitI1, j + NumElts))
2869 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2870 SmallVector<int, 8> M;
2872 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2875 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2876 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2877 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
2878 bool V2IsSplat = false) {
2879 int NumElts = VT.getVectorNumElements();
2880 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2883 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2885 int BitI1 = Mask[i+1];
2886 if (!isUndefOrEqual(BitI, j + NumElts/2))
2889 if (isUndefOrEqual(BitI1, NumElts))
2892 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2899 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2900 SmallVector<int, 8> M;
2902 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2905 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2906 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2908 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2909 int NumElems = VT.getVectorNumElements();
2910 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2913 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2915 int BitI1 = Mask[i+1];
2916 if (!isUndefOrEqual(BitI, j))
2918 if (!isUndefOrEqual(BitI1, j))
2924 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2925 SmallVector<int, 8> M;
2927 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2930 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2931 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2933 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2934 int NumElems = VT.getVectorNumElements();
2935 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2938 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2940 int BitI1 = Mask[i+1];
2941 if (!isUndefOrEqual(BitI, j))
2943 if (!isUndefOrEqual(BitI1, j))
2949 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2950 SmallVector<int, 8> M;
2952 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2955 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2956 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2957 /// MOVSD, and MOVD, i.e. setting the lowest element.
2958 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2959 if (VT.getVectorElementType().getSizeInBits() < 32)
2962 int NumElts = VT.getVectorNumElements();
2964 if (!isUndefOrEqual(Mask[0], NumElts))
2967 for (int i = 1; i < NumElts; ++i)
2968 if (!isUndefOrEqual(Mask[i], i))
2974 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2975 SmallVector<int, 8> M;
2977 return ::isMOVLMask(M, N->getValueType(0));
2980 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2981 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2982 /// element of vector 2 and the other elements to come from vector 1 in order.
2983 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2984 bool V2IsSplat = false, bool V2IsUndef = false) {
2985 int NumOps = VT.getVectorNumElements();
2986 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2989 if (!isUndefOrEqual(Mask[0], 0))
2992 for (int i = 1; i < NumOps; ++i)
2993 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
2994 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
2995 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3001 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3002 bool V2IsUndef = false) {
3003 SmallVector<int, 8> M;
3005 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3008 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3009 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3010 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3011 if (N->getValueType(0).getVectorNumElements() != 4)
3014 // Expect 1, 1, 3, 3
3015 for (unsigned i = 0; i < 2; ++i) {
3016 int Elt = N->getMaskElt(i);
3017 if (Elt >= 0 && Elt != 1)
3022 for (unsigned i = 2; i < 4; ++i) {
3023 int Elt = N->getMaskElt(i);
3024 if (Elt >= 0 && Elt != 3)
3029 // Don't use movshdup if it can be done with a shufps.
3030 // FIXME: verify that matching u, u, 3, 3 is what we want.
3034 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3035 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3036 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3037 if (N->getValueType(0).getVectorNumElements() != 4)
3040 // Expect 0, 0, 2, 2
3041 for (unsigned i = 0; i < 2; ++i)
3042 if (N->getMaskElt(i) > 0)
3046 for (unsigned i = 2; i < 4; ++i) {
3047 int Elt = N->getMaskElt(i);
3048 if (Elt >= 0 && Elt != 2)
3053 // Don't use movsldup if it can be done with a shufps.
3057 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3058 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3059 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3060 int e = N->getValueType(0).getVectorNumElements() / 2;
3062 for (int i = 0; i < e; ++i)
3063 if (!isUndefOrEqual(N->getMaskElt(i), i))
3065 for (int i = 0; i < e; ++i)
3066 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3071 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3072 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3073 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3074 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3075 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3077 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3079 for (int i = 0; i < NumOperands; ++i) {
3080 int Val = SVOp->getMaskElt(NumOperands-i-1);
3081 if (Val < 0) Val = 0;
3082 if (Val >= NumOperands) Val -= NumOperands;
3084 if (i != NumOperands - 1)
3090 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3091 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3092 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3093 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3095 // 8 nodes, but we only care about the last 4.
3096 for (unsigned i = 7; i >= 4; --i) {
3097 int Val = SVOp->getMaskElt(i);
3106 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3107 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3108 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3109 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3111 // 8 nodes, but we only care about the first 4.
3112 for (int i = 3; i >= 0; --i) {
3113 int Val = SVOp->getMaskElt(i);
3122 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3123 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3124 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3125 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3126 EVT VVT = N->getValueType(0);
3127 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3131 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3132 Val = SVOp->getMaskElt(i);
3136 return (Val - i) * EltSize;
3139 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3141 bool X86::isZeroNode(SDValue Elt) {
3142 return ((isa<ConstantSDNode>(Elt) &&
3143 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
3144 (isa<ConstantFPSDNode>(Elt) &&
3145 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3148 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3149 /// their permute mask.
3150 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3151 SelectionDAG &DAG) {
3152 EVT VT = SVOp->getValueType(0);
3153 unsigned NumElems = VT.getVectorNumElements();
3154 SmallVector<int, 8> MaskVec;
3156 for (unsigned i = 0; i != NumElems; ++i) {
3157 int idx = SVOp->getMaskElt(i);
3159 MaskVec.push_back(idx);
3160 else if (idx < (int)NumElems)
3161 MaskVec.push_back(idx + NumElems);
3163 MaskVec.push_back(idx - NumElems);
3165 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3166 SVOp->getOperand(0), &MaskVec[0]);
3169 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3170 /// the two vector operands have swapped position.
3171 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3172 unsigned NumElems = VT.getVectorNumElements();
3173 for (unsigned i = 0; i != NumElems; ++i) {
3177 else if (idx < (int)NumElems)
3178 Mask[i] = idx + NumElems;
3180 Mask[i] = idx - NumElems;
3184 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3185 /// match movhlps. The lower half elements should come from upper half of
3186 /// V1 (and in order), and the upper half elements should come from the upper
3187 /// half of V2 (and in order).
3188 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3189 if (Op->getValueType(0).getVectorNumElements() != 4)
3191 for (unsigned i = 0, e = 2; i != e; ++i)
3192 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3194 for (unsigned i = 2; i != 4; ++i)
3195 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3200 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3201 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3203 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3204 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3206 N = N->getOperand(0).getNode();
3207 if (!ISD::isNON_EXTLoad(N))
3210 *LD = cast<LoadSDNode>(N);
3214 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3215 /// match movlp{s|d}. The lower half elements should come from lower half of
3216 /// V1 (and in order), and the upper half elements should come from the upper
3217 /// half of V2 (and in order). And since V1 will become the source of the
3218 /// MOVLP, it must be either a vector load or a scalar load to vector.
3219 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3220 ShuffleVectorSDNode *Op) {
3221 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3223 // Is V2 is a vector load, don't do this transformation. We will try to use
3224 // load folding shufps op.
3225 if (ISD::isNON_EXTLoad(V2))
3228 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3230 if (NumElems != 2 && NumElems != 4)
3232 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3233 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3235 for (unsigned i = NumElems/2; i != NumElems; ++i)
3236 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3241 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3243 static bool isSplatVector(SDNode *N) {
3244 if (N->getOpcode() != ISD::BUILD_VECTOR)
3247 SDValue SplatValue = N->getOperand(0);
3248 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3249 if (N->getOperand(i) != SplatValue)
3254 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3255 /// to an zero vector.
3256 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3257 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3258 SDValue V1 = N->getOperand(0);
3259 SDValue V2 = N->getOperand(1);
3260 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3261 for (unsigned i = 0; i != NumElems; ++i) {
3262 int Idx = N->getMaskElt(i);
3263 if (Idx >= (int)NumElems) {
3264 unsigned Opc = V2.getOpcode();
3265 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3267 if (Opc != ISD::BUILD_VECTOR ||
3268 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3270 } else if (Idx >= 0) {
3271 unsigned Opc = V1.getOpcode();
3272 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3274 if (Opc != ISD::BUILD_VECTOR ||
3275 !X86::isZeroNode(V1.getOperand(Idx)))
3282 /// getZeroVector - Returns a vector of specified type with all zero elements.
3284 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3286 assert(VT.isVector() && "Expected a vector type");
3288 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3289 // type. This ensures they get CSE'd.
3291 if (VT.getSizeInBits() == 64) { // MMX
3292 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3293 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3294 } else if (HasSSE2) { // SSE2
3295 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3296 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3298 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3299 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3301 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3304 /// getOnesVector - Returns a vector of specified type with all bits set.
3306 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3307 assert(VT.isVector() && "Expected a vector type");
3309 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3310 // type. This ensures they get CSE'd.
3311 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3313 if (VT.getSizeInBits() == 64) // MMX
3314 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3316 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3317 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3321 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3322 /// that point to V2 points to its first element.
3323 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3324 EVT VT = SVOp->getValueType(0);
3325 unsigned NumElems = VT.getVectorNumElements();
3327 bool Changed = false;
3328 SmallVector<int, 8> MaskVec;
3329 SVOp->getMask(MaskVec);
3331 for (unsigned i = 0; i != NumElems; ++i) {
3332 if (MaskVec[i] > (int)NumElems) {
3333 MaskVec[i] = NumElems;
3338 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3339 SVOp->getOperand(1), &MaskVec[0]);
3340 return SDValue(SVOp, 0);
3343 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3344 /// operation of specified width.
3345 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3347 unsigned NumElems = VT.getVectorNumElements();
3348 SmallVector<int, 8> Mask;
3349 Mask.push_back(NumElems);
3350 for (unsigned i = 1; i != NumElems; ++i)
3352 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3355 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3356 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3358 unsigned NumElems = VT.getVectorNumElements();
3359 SmallVector<int, 8> Mask;
3360 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3362 Mask.push_back(i + NumElems);
3364 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3367 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3368 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3370 unsigned NumElems = VT.getVectorNumElements();
3371 unsigned Half = NumElems/2;
3372 SmallVector<int, 8> Mask;
3373 for (unsigned i = 0; i != Half; ++i) {
3374 Mask.push_back(i + Half);
3375 Mask.push_back(i + NumElems + Half);
3377 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3380 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3381 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3383 if (SV->getValueType(0).getVectorNumElements() <= 4)
3384 return SDValue(SV, 0);
3386 EVT PVT = MVT::v4f32;
3387 EVT VT = SV->getValueType(0);
3388 DebugLoc dl = SV->getDebugLoc();
3389 SDValue V1 = SV->getOperand(0);
3390 int NumElems = VT.getVectorNumElements();
3391 int EltNo = SV->getSplatIndex();
3393 // unpack elements to the correct location
3394 while (NumElems > 4) {
3395 if (EltNo < NumElems/2) {
3396 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3398 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3399 EltNo -= NumElems/2;
3404 // Perform the splat.
3405 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3406 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3407 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3408 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3411 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3412 /// vector of zero or undef vector. This produces a shuffle where the low
3413 /// element of V2 is swizzled into the zero/undef vector, landing at element
3414 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3415 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3416 bool isZero, bool HasSSE2,
3417 SelectionDAG &DAG) {
3418 EVT VT = V2.getValueType();
3420 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3421 unsigned NumElems = VT.getVectorNumElements();
3422 SmallVector<int, 16> MaskVec;
3423 for (unsigned i = 0; i != NumElems; ++i)
3424 // If this is the insertion idx, put the low elt of V2 here.
3425 MaskVec.push_back(i == Idx ? NumElems : i);
3426 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3429 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3430 /// a shuffle that is zero.
3432 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3433 bool Low, SelectionDAG &DAG) {
3434 unsigned NumZeros = 0;
3435 for (int i = 0; i < NumElems; ++i) {
3436 unsigned Index = Low ? i : NumElems-i-1;
3437 int Idx = SVOp->getMaskElt(Index);
3442 SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3443 if (Elt.getNode() && X86::isZeroNode(Elt))
3451 /// isVectorShift - Returns true if the shuffle can be implemented as a
3452 /// logical left or right shift of a vector.
3453 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3454 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3455 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3456 int NumElems = SVOp->getValueType(0).getVectorNumElements();
3459 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3462 NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3466 bool SeenV1 = false;
3467 bool SeenV2 = false;
3468 for (int i = NumZeros; i < NumElems; ++i) {
3469 int Val = isLeft ? (i - NumZeros) : i;
3470 int Idx = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3482 if (SeenV1 && SeenV2)
3485 ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3491 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3493 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3494 unsigned NumNonZero, unsigned NumZero,
3495 SelectionDAG &DAG, TargetLowering &TLI) {
3499 DebugLoc dl = Op.getDebugLoc();
3502 for (unsigned i = 0; i < 16; ++i) {
3503 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3504 if (ThisIsNonZero && First) {
3506 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3508 V = DAG.getUNDEF(MVT::v8i16);
3513 SDValue ThisElt(0, 0), LastElt(0, 0);
3514 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3515 if (LastIsNonZero) {
3516 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3517 MVT::i16, Op.getOperand(i-1));
3519 if (ThisIsNonZero) {
3520 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3521 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3522 ThisElt, DAG.getConstant(8, MVT::i8));
3524 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3528 if (ThisElt.getNode())
3529 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3530 DAG.getIntPtrConstant(i/2));
3534 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3537 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3539 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3540 unsigned NumNonZero, unsigned NumZero,
3541 SelectionDAG &DAG, TargetLowering &TLI) {
3545 DebugLoc dl = Op.getDebugLoc();
3548 for (unsigned i = 0; i < 8; ++i) {
3549 bool isNonZero = (NonZeros & (1 << i)) != 0;
3553 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3555 V = DAG.getUNDEF(MVT::v8i16);
3558 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3559 MVT::v8i16, V, Op.getOperand(i),
3560 DAG.getIntPtrConstant(i));
3567 /// getVShift - Return a vector logical shift node.
3569 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3570 unsigned NumBits, SelectionDAG &DAG,
3571 const TargetLowering &TLI, DebugLoc dl) {
3572 bool isMMX = VT.getSizeInBits() == 64;
3573 EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3574 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3575 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3576 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3577 DAG.getNode(Opc, dl, ShVT, SrcOp,
3578 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3582 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3583 SelectionDAG &DAG) {
3585 // Check if the scalar load can be widened into a vector load. And if
3586 // the address is "base + cst" see if the cst can be "absorbed" into
3587 // the shuffle mask.
3588 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3589 SDValue Ptr = LD->getBasePtr();
3590 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3592 EVT PVT = LD->getValueType(0);
3593 if (PVT != MVT::i32 && PVT != MVT::f32)
3598 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3599 FI = FINode->getIndex();
3601 } else if (Ptr.getOpcode() == ISD::ADD &&
3602 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
3603 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
3604 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
3605 Offset = Ptr.getConstantOperandVal(1);
3606 Ptr = Ptr.getOperand(0);
3611 SDValue Chain = LD->getChain();
3612 // Make sure the stack object alignment is at least 16.
3613 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3614 if (DAG.InferPtrAlignment(Ptr) < 16) {
3615 if (MFI->isFixedObjectIndex(FI)) {
3616 // Can't change the alignment. FIXME: It's possible to compute
3617 // the exact stack offset and reference FI + adjust offset instead.
3618 // If someone *really* cares about this. That's the way to implement it.
3621 MFI->setObjectAlignment(FI, 16);
3625 // (Offset % 16) must be multiple of 4. Then address is then
3626 // Ptr + (Offset & ~15).
3629 if ((Offset % 16) & 3)
3631 int64_t StartOffset = Offset & ~15;
3633 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
3634 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
3636 int EltNo = (Offset - StartOffset) >> 2;
3637 int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
3638 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
3639 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,LD->getSrcValue(),0,
3641 // Canonicalize it to a v4i32 shuffle.
3642 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
3643 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3644 DAG.getVectorShuffle(MVT::v4i32, dl, V1,
3645 DAG.getUNDEF(MVT::v4i32), &Mask[0]));
3652 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3653 DebugLoc dl = Op.getDebugLoc();
3654 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3655 if (ISD::isBuildVectorAllZeros(Op.getNode())
3656 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3657 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3658 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3659 // eliminated on x86-32 hosts.
3660 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3663 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3664 return getOnesVector(Op.getValueType(), DAG, dl);
3665 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3668 EVT VT = Op.getValueType();
3669 EVT ExtVT = VT.getVectorElementType();
3670 unsigned EVTBits = ExtVT.getSizeInBits();
3672 unsigned NumElems = Op.getNumOperands();
3673 unsigned NumZero = 0;
3674 unsigned NumNonZero = 0;
3675 unsigned NonZeros = 0;
3676 bool IsAllConstants = true;
3677 SmallSet<SDValue, 8> Values;
3678 for (unsigned i = 0; i < NumElems; ++i) {
3679 SDValue Elt = Op.getOperand(i);
3680 if (Elt.getOpcode() == ISD::UNDEF)
3683 if (Elt.getOpcode() != ISD::Constant &&
3684 Elt.getOpcode() != ISD::ConstantFP)
3685 IsAllConstants = false;
3686 if (X86::isZeroNode(Elt))
3689 NonZeros |= (1 << i);
3694 if (NumNonZero == 0) {
3695 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3696 return DAG.getUNDEF(VT);
3699 // Special case for single non-zero, non-undef, element.
3700 if (NumNonZero == 1) {
3701 unsigned Idx = CountTrailingZeros_32(NonZeros);
3702 SDValue Item = Op.getOperand(Idx);
3704 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3705 // the value are obviously zero, truncate the value to i32 and do the
3706 // insertion that way. Only do this if the value is non-constant or if the
3707 // value is a constant being inserted into element 0. It is cheaper to do
3708 // a constant pool load than it is to do a movd + shuffle.
3709 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3710 (!IsAllConstants || Idx == 0)) {
3711 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3712 // Handle MMX and SSE both.
3713 EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3714 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3716 // Truncate the value (which may itself be a constant) to i32, and
3717 // convert it to a vector with movd (S2V+shuffle to zero extend).
3718 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3719 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3720 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3721 Subtarget->hasSSE2(), DAG);
3723 // Now we have our 32-bit value zero extended in the low element of
3724 // a vector. If Idx != 0, swizzle it into place.
3726 SmallVector<int, 4> Mask;
3727 Mask.push_back(Idx);
3728 for (unsigned i = 1; i != VecElts; ++i)
3730 Item = DAG.getVectorShuffle(VecVT, dl, Item,
3731 DAG.getUNDEF(Item.getValueType()),
3734 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3738 // If we have a constant or non-constant insertion into the low element of
3739 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3740 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3741 // depending on what the source datatype is.
3744 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3745 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3746 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3747 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3748 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3749 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3751 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3752 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3753 EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3754 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3755 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3756 Subtarget->hasSSE2(), DAG);
3757 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3761 // Is it a vector logical left shift?
3762 if (NumElems == 2 && Idx == 1 &&
3763 X86::isZeroNode(Op.getOperand(0)) &&
3764 !X86::isZeroNode(Op.getOperand(1))) {
3765 unsigned NumBits = VT.getSizeInBits();
3766 return getVShift(true, VT,
3767 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3768 VT, Op.getOperand(1)),
3769 NumBits/2, DAG, *this, dl);
3772 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3775 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3776 // is a non-constant being inserted into an element other than the low one,
3777 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3778 // movd/movss) to move this into the low element, then shuffle it into
3780 if (EVTBits == 32) {
3781 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3783 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3784 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3785 Subtarget->hasSSE2(), DAG);
3786 SmallVector<int, 8> MaskVec;
3787 for (unsigned i = 0; i < NumElems; i++)
3788 MaskVec.push_back(i == Idx ? 0 : 1);
3789 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3793 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3794 if (Values.size() == 1) {
3795 if (EVTBits == 32) {
3796 // Instead of a shuffle like this:
3797 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
3798 // Check if it's possible to issue this instead.
3799 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
3800 unsigned Idx = CountTrailingZeros_32(NonZeros);
3801 SDValue Item = Op.getOperand(Idx);
3802 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
3803 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
3808 // A vector full of immediates; various special cases are already
3809 // handled, so this is best done with a single constant-pool load.
3813 // Let legalizer expand 2-wide build_vectors.
3814 if (EVTBits == 64) {
3815 if (NumNonZero == 1) {
3816 // One half is zero or undef.
3817 unsigned Idx = CountTrailingZeros_32(NonZeros);
3818 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3819 Op.getOperand(Idx));
3820 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3821 Subtarget->hasSSE2(), DAG);
3826 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3827 if (EVTBits == 8 && NumElems == 16) {
3828 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3830 if (V.getNode()) return V;
3833 if (EVTBits == 16 && NumElems == 8) {
3834 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3836 if (V.getNode()) return V;
3839 // If element VT is == 32 bits, turn it into a number of shuffles.
3840 SmallVector<SDValue, 8> V;
3842 if (NumElems == 4 && NumZero > 0) {
3843 for (unsigned i = 0; i < 4; ++i) {
3844 bool isZero = !(NonZeros & (1 << i));
3846 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3848 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3851 for (unsigned i = 0; i < 2; ++i) {
3852 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3855 V[i] = V[i*2]; // Must be a zero vector.
3858 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3861 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3864 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3869 SmallVector<int, 8> MaskVec;
3870 bool Reverse = (NonZeros & 0x3) == 2;
3871 for (unsigned i = 0; i < 2; ++i)
3872 MaskVec.push_back(Reverse ? 1-i : i);
3873 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3874 for (unsigned i = 0; i < 2; ++i)
3875 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3876 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3879 if (Values.size() > 2) {
3880 // If we have SSE 4.1, Expand into a number of inserts unless the number of
3881 // values to be inserted is equal to the number of elements, in which case
3882 // use the unpack code below in the hopes of matching the consecutive elts
3883 // load merge pattern for shuffles.
3884 // FIXME: We could probably just check that here directly.
3885 if (Values.size() < NumElems && VT.getSizeInBits() == 128 &&
3886 getSubtarget()->hasSSE41()) {
3887 V[0] = DAG.getUNDEF(VT);
3888 for (unsigned i = 0; i < NumElems; ++i)
3889 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3890 V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3891 Op.getOperand(i), DAG.getIntPtrConstant(i));
3894 // Expand into a number of unpckl*.
3896 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3897 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3898 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3899 for (unsigned i = 0; i < NumElems; ++i)
3900 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3902 while (NumElems != 0) {
3903 for (unsigned i = 0; i < NumElems; ++i)
3904 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3914 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
3915 // We support concatenate two MMX registers and place them in a MMX
3916 // register. This is better than doing a stack convert.
3917 DebugLoc dl = Op.getDebugLoc();
3918 EVT ResVT = Op.getValueType();
3919 assert(Op.getNumOperands() == 2);
3920 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
3921 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
3923 SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
3924 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
3925 InVec = Op.getOperand(1);
3926 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
3927 unsigned NumElts = ResVT.getVectorNumElements();
3928 VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
3929 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
3930 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
3932 InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
3933 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
3934 Mask[0] = 0; Mask[1] = 2;
3935 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
3937 return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
3940 // v8i16 shuffles - Prefer shuffles in the following order:
3941 // 1. [all] pshuflw, pshufhw, optional move
3942 // 2. [ssse3] 1 x pshufb
3943 // 3. [ssse3] 2 x pshufb + 1 x por
3944 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
3946 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
3947 SelectionDAG &DAG, X86TargetLowering &TLI) {
3948 SDValue V1 = SVOp->getOperand(0);
3949 SDValue V2 = SVOp->getOperand(1);
3950 DebugLoc dl = SVOp->getDebugLoc();
3951 SmallVector<int, 8> MaskVals;
3953 // Determine if more than 1 of the words in each of the low and high quadwords
3954 // of the result come from the same quadword of one of the two inputs. Undef
3955 // mask values count as coming from any quadword, for better codegen.
3956 SmallVector<unsigned, 4> LoQuad(4);
3957 SmallVector<unsigned, 4> HiQuad(4);
3958 BitVector InputQuads(4);
3959 for (unsigned i = 0; i < 8; ++i) {
3960 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
3961 int EltIdx = SVOp->getMaskElt(i);
3962 MaskVals.push_back(EltIdx);
3971 InputQuads.set(EltIdx / 4);
3974 int BestLoQuad = -1;
3975 unsigned MaxQuad = 1;
3976 for (unsigned i = 0; i < 4; ++i) {
3977 if (LoQuad[i] > MaxQuad) {
3979 MaxQuad = LoQuad[i];
3983 int BestHiQuad = -1;
3985 for (unsigned i = 0; i < 4; ++i) {
3986 if (HiQuad[i] > MaxQuad) {
3988 MaxQuad = HiQuad[i];
3992 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
3993 // of the two input vectors, shuffle them into one input vector so only a
3994 // single pshufb instruction is necessary. If There are more than 2 input
3995 // quads, disable the next transformation since it does not help SSSE3.
3996 bool V1Used = InputQuads[0] || InputQuads[1];
3997 bool V2Used = InputQuads[2] || InputQuads[3];
3998 if (TLI.getSubtarget()->hasSSSE3()) {
3999 if (InputQuads.count() == 2 && V1Used && V2Used) {
4000 BestLoQuad = InputQuads.find_first();
4001 BestHiQuad = InputQuads.find_next(BestLoQuad);
4003 if (InputQuads.count() > 2) {
4009 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4010 // the shuffle mask. If a quad is scored as -1, that means that it contains
4011 // words from all 4 input quadwords.
4013 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4014 SmallVector<int, 8> MaskV;
4015 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4016 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4017 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4018 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
4019 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
4020 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
4022 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4023 // source words for the shuffle, to aid later transformations.
4024 bool AllWordsInNewV = true;
4025 bool InOrder[2] = { true, true };
4026 for (unsigned i = 0; i != 8; ++i) {
4027 int idx = MaskVals[i];
4029 InOrder[i/4] = false;
4030 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4032 AllWordsInNewV = false;
4036 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4037 if (AllWordsInNewV) {
4038 for (int i = 0; i != 8; ++i) {
4039 int idx = MaskVals[i];
4042 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4043 if ((idx != i) && idx < 4)
4045 if ((idx != i) && idx > 3)
4054 // If we've eliminated the use of V2, and the new mask is a pshuflw or
4055 // pshufhw, that's as cheap as it gets. Return the new shuffle.
4056 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4057 return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4058 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4062 // If we have SSSE3, and all words of the result are from 1 input vector,
4063 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
4064 // is present, fall back to case 4.
4065 if (TLI.getSubtarget()->hasSSSE3()) {
4066 SmallVector<SDValue,16> pshufbMask;
4068 // If we have elements from both input vectors, set the high bit of the
4069 // shuffle mask element to zero out elements that come from V2 in the V1
4070 // mask, and elements that come from V1 in the V2 mask, so that the two
4071 // results can be OR'd together.
4072 bool TwoInputs = V1Used && V2Used;
4073 for (unsigned i = 0; i != 8; ++i) {
4074 int EltIdx = MaskVals[i] * 2;
4075 if (TwoInputs && (EltIdx >= 16)) {
4076 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4077 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4080 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4081 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4083 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
4084 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4085 DAG.getNode(ISD::BUILD_VECTOR, dl,
4086 MVT::v16i8, &pshufbMask[0], 16));
4088 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4090 // Calculate the shuffle mask for the second input, shuffle it, and
4091 // OR it with the first shuffled input.
4093 for (unsigned i = 0; i != 8; ++i) {
4094 int EltIdx = MaskVals[i] * 2;
4096 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4097 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4100 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4101 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4103 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
4104 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4105 DAG.getNode(ISD::BUILD_VECTOR, dl,
4106 MVT::v16i8, &pshufbMask[0], 16));
4107 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4108 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4111 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4112 // and update MaskVals with new element order.
4113 BitVector InOrder(8);
4114 if (BestLoQuad >= 0) {
4115 SmallVector<int, 8> MaskV;
4116 for (int i = 0; i != 4; ++i) {
4117 int idx = MaskVals[i];
4119 MaskV.push_back(-1);
4121 } else if ((idx / 4) == BestLoQuad) {
4122 MaskV.push_back(idx & 3);
4125 MaskV.push_back(-1);
4128 for (unsigned i = 4; i != 8; ++i)
4130 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4134 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4135 // and update MaskVals with the new element order.
4136 if (BestHiQuad >= 0) {
4137 SmallVector<int, 8> MaskV;
4138 for (unsigned i = 0; i != 4; ++i)
4140 for (unsigned i = 4; i != 8; ++i) {
4141 int idx = MaskVals[i];
4143 MaskV.push_back(-1);
4145 } else if ((idx / 4) == BestHiQuad) {
4146 MaskV.push_back((idx & 3) + 4);
4149 MaskV.push_back(-1);
4152 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4156 // In case BestHi & BestLo were both -1, which means each quadword has a word
4157 // from each of the four input quadwords, calculate the InOrder bitvector now
4158 // before falling through to the insert/extract cleanup.
4159 if (BestLoQuad == -1 && BestHiQuad == -1) {
4161 for (int i = 0; i != 8; ++i)
4162 if (MaskVals[i] < 0 || MaskVals[i] == i)
4166 // The other elements are put in the right place using pextrw and pinsrw.
4167 for (unsigned i = 0; i != 8; ++i) {
4170 int EltIdx = MaskVals[i];
4173 SDValue ExtOp = (EltIdx < 8)
4174 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4175 DAG.getIntPtrConstant(EltIdx))
4176 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4177 DAG.getIntPtrConstant(EltIdx - 8));
4178 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4179 DAG.getIntPtrConstant(i));
4184 // v16i8 shuffles - Prefer shuffles in the following order:
4185 // 1. [ssse3] 1 x pshufb
4186 // 2. [ssse3] 2 x pshufb + 1 x por
4187 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
4189 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4190 SelectionDAG &DAG, X86TargetLowering &TLI) {
4191 SDValue V1 = SVOp->getOperand(0);
4192 SDValue V2 = SVOp->getOperand(1);
4193 DebugLoc dl = SVOp->getDebugLoc();
4194 SmallVector<int, 16> MaskVals;
4195 SVOp->getMask(MaskVals);
4197 // If we have SSSE3, case 1 is generated when all result bytes come from
4198 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
4199 // present, fall back to case 3.
4200 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4203 for (unsigned i = 0; i < 16; ++i) {
4204 int EltIdx = MaskVals[i];
4213 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4214 if (TLI.getSubtarget()->hasSSSE3()) {
4215 SmallVector<SDValue,16> pshufbMask;
4217 // If all result elements are from one input vector, then only translate
4218 // undef mask values to 0x80 (zero out result) in the pshufb mask.
4220 // Otherwise, we have elements from both input vectors, and must zero out
4221 // elements that come from V2 in the first mask, and V1 in the second mask
4222 // so that we can OR them together.
4223 bool TwoInputs = !(V1Only || V2Only);
4224 for (unsigned i = 0; i != 16; ++i) {
4225 int EltIdx = MaskVals[i];
4226 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4227 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4230 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4232 // If all the elements are from V2, assign it to V1 and return after
4233 // building the first pshufb.
4236 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4237 DAG.getNode(ISD::BUILD_VECTOR, dl,
4238 MVT::v16i8, &pshufbMask[0], 16));
4242 // Calculate the shuffle mask for the second input, shuffle it, and
4243 // OR it with the first shuffled input.
4245 for (unsigned i = 0; i != 16; ++i) {
4246 int EltIdx = MaskVals[i];
4248 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4251 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4253 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4254 DAG.getNode(ISD::BUILD_VECTOR, dl,
4255 MVT::v16i8, &pshufbMask[0], 16));
4256 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4259 // No SSSE3 - Calculate in place words and then fix all out of place words
4260 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
4261 // the 16 different words that comprise the two doublequadword input vectors.
4262 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4263 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4264 SDValue NewV = V2Only ? V2 : V1;
4265 for (int i = 0; i != 8; ++i) {
4266 int Elt0 = MaskVals[i*2];
4267 int Elt1 = MaskVals[i*2+1];
4269 // This word of the result is all undef, skip it.
4270 if (Elt0 < 0 && Elt1 < 0)
4273 // This word of the result is already in the correct place, skip it.
4274 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4276 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4279 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4280 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4283 // If Elt0 and Elt1 are defined, are consecutive, and can be load
4284 // using a single extract together, load it and store it.
4285 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4286 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4287 DAG.getIntPtrConstant(Elt1 / 2));
4288 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4289 DAG.getIntPtrConstant(i));
4293 // If Elt1 is defined, extract it from the appropriate source. If the
4294 // source byte is not also odd, shift the extracted word left 8 bits
4295 // otherwise clear the bottom 8 bits if we need to do an or.
4297 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4298 DAG.getIntPtrConstant(Elt1 / 2));
4299 if ((Elt1 & 1) == 0)
4300 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4301 DAG.getConstant(8, TLI.getShiftAmountTy()));
4303 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4304 DAG.getConstant(0xFF00, MVT::i16));
4306 // If Elt0 is defined, extract it from the appropriate source. If the
4307 // source byte is not also even, shift the extracted word right 8 bits. If
4308 // Elt1 was also defined, OR the extracted values together before
4309 // inserting them in the result.
4311 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4312 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4313 if ((Elt0 & 1) != 0)
4314 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4315 DAG.getConstant(8, TLI.getShiftAmountTy()));
4317 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4318 DAG.getConstant(0x00FF, MVT::i16));
4319 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4322 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4323 DAG.getIntPtrConstant(i));
4325 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4328 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4329 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
4330 /// done when every pair / quad of shuffle mask elements point to elements in
4331 /// the right sequence. e.g.
4332 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
4334 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4336 TargetLowering &TLI, DebugLoc dl) {
4337 EVT VT = SVOp->getValueType(0);
4338 SDValue V1 = SVOp->getOperand(0);
4339 SDValue V2 = SVOp->getOperand(1);
4340 unsigned NumElems = VT.getVectorNumElements();
4341 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4342 EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
4343 EVT MaskEltVT = MaskVT.getVectorElementType();
4345 switch (VT.getSimpleVT().SimpleTy) {
4346 default: assert(false && "Unexpected!");
4347 case MVT::v4f32: NewVT = MVT::v2f64; break;
4348 case MVT::v4i32: NewVT = MVT::v2i64; break;
4349 case MVT::v8i16: NewVT = MVT::v4i32; break;
4350 case MVT::v16i8: NewVT = MVT::v4i32; break;
4353 if (NewWidth == 2) {
4359 int Scale = NumElems / NewWidth;
4360 SmallVector<int, 8> MaskVec;
4361 for (unsigned i = 0; i < NumElems; i += Scale) {
4363 for (int j = 0; j < Scale; ++j) {
4364 int EltIdx = SVOp->getMaskElt(i+j);
4368 StartIdx = EltIdx - (EltIdx % Scale);
4369 if (EltIdx != StartIdx + j)
4373 MaskVec.push_back(-1);
4375 MaskVec.push_back(StartIdx / Scale);
4378 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4379 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4380 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4383 /// getVZextMovL - Return a zero-extending vector move low node.
4385 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4386 SDValue SrcOp, SelectionDAG &DAG,
4387 const X86Subtarget *Subtarget, DebugLoc dl) {
4388 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4389 LoadSDNode *LD = NULL;
4390 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4391 LD = dyn_cast<LoadSDNode>(SrcOp);
4393 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4395 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4396 if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4397 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4398 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4399 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4401 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4402 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4403 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4404 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4412 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4413 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4414 DAG.getNode(ISD::BIT_CONVERT, dl,
4418 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4421 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4422 SDValue V1 = SVOp->getOperand(0);
4423 SDValue V2 = SVOp->getOperand(1);
4424 DebugLoc dl = SVOp->getDebugLoc();
4425 EVT VT = SVOp->getValueType(0);
4427 SmallVector<std::pair<int, int>, 8> Locs;
4429 SmallVector<int, 8> Mask1(4U, -1);
4430 SmallVector<int, 8> PermMask;
4431 SVOp->getMask(PermMask);
4435 for (unsigned i = 0; i != 4; ++i) {
4436 int Idx = PermMask[i];
4438 Locs[i] = std::make_pair(-1, -1);
4440 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4442 Locs[i] = std::make_pair(0, NumLo);
4446 Locs[i] = std::make_pair(1, NumHi);
4448 Mask1[2+NumHi] = Idx;
4454 if (NumLo <= 2 && NumHi <= 2) {
4455 // If no more than two elements come from either vector. This can be
4456 // implemented with two shuffles. First shuffle gather the elements.
4457 // The second shuffle, which takes the first shuffle as both of its
4458 // vector operands, put the elements into the right order.
4459 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4461 SmallVector<int, 8> Mask2(4U, -1);
4463 for (unsigned i = 0; i != 4; ++i) {
4464 if (Locs[i].first == -1)
4467 unsigned Idx = (i < 2) ? 0 : 4;
4468 Idx += Locs[i].first * 2 + Locs[i].second;
4473 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4474 } else if (NumLo == 3 || NumHi == 3) {
4475 // Otherwise, we must have three elements from one vector, call it X, and
4476 // one element from the other, call it Y. First, use a shufps to build an
4477 // intermediate vector with the one element from Y and the element from X
4478 // that will be in the same half in the final destination (the indexes don't
4479 // matter). Then, use a shufps to build the final vector, taking the half
4480 // containing the element from Y from the intermediate, and the other half
4483 // Normalize it so the 3 elements come from V1.
4484 CommuteVectorShuffleMask(PermMask, VT);
4488 // Find the element from V2.
4490 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4491 int Val = PermMask[HiIndex];
4498 Mask1[0] = PermMask[HiIndex];
4500 Mask1[2] = PermMask[HiIndex^1];
4502 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4505 Mask1[0] = PermMask[0];
4506 Mask1[1] = PermMask[1];
4507 Mask1[2] = HiIndex & 1 ? 6 : 4;
4508 Mask1[3] = HiIndex & 1 ? 4 : 6;
4509 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4511 Mask1[0] = HiIndex & 1 ? 2 : 0;
4512 Mask1[1] = HiIndex & 1 ? 0 : 2;
4513 Mask1[2] = PermMask[2];
4514 Mask1[3] = PermMask[3];
4519 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4523 // Break it into (shuffle shuffle_hi, shuffle_lo).
4525 SmallVector<int,8> LoMask(4U, -1);
4526 SmallVector<int,8> HiMask(4U, -1);
4528 SmallVector<int,8> *MaskPtr = &LoMask;
4529 unsigned MaskIdx = 0;
4532 for (unsigned i = 0; i != 4; ++i) {
4539 int Idx = PermMask[i];
4541 Locs[i] = std::make_pair(-1, -1);
4542 } else if (Idx < 4) {
4543 Locs[i] = std::make_pair(MaskIdx, LoIdx);
4544 (*MaskPtr)[LoIdx] = Idx;
4547 Locs[i] = std::make_pair(MaskIdx, HiIdx);
4548 (*MaskPtr)[HiIdx] = Idx;
4553 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4554 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4555 SmallVector<int, 8> MaskOps;
4556 for (unsigned i = 0; i != 4; ++i) {
4557 if (Locs[i].first == -1) {
4558 MaskOps.push_back(-1);
4560 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4561 MaskOps.push_back(Idx);
4564 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4568 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4569 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4570 SDValue V1 = Op.getOperand(0);
4571 SDValue V2 = Op.getOperand(1);
4572 EVT VT = Op.getValueType();
4573 DebugLoc dl = Op.getDebugLoc();
4574 unsigned NumElems = VT.getVectorNumElements();
4575 bool isMMX = VT.getSizeInBits() == 64;
4576 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4577 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4578 bool V1IsSplat = false;
4579 bool V2IsSplat = false;
4581 if (isZeroShuffle(SVOp))
4582 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4584 // Promote splats to v4f32.
4585 if (SVOp->isSplat()) {
4586 if (isMMX || NumElems < 4)
4588 return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4591 // If the shuffle can be profitably rewritten as a narrower shuffle, then
4593 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4594 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4595 if (NewOp.getNode())
4596 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4597 LowerVECTOR_SHUFFLE(NewOp, DAG));
4598 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4599 // FIXME: Figure out a cleaner way to do this.
4600 // Try to make use of movq to zero out the top part.
4601 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4602 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4603 if (NewOp.getNode()) {
4604 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4605 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4606 DAG, Subtarget, dl);
4608 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4609 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4610 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4611 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4612 DAG, Subtarget, dl);
4616 if (X86::isPSHUFDMask(SVOp))
4619 // Check if this can be converted into a logical shift.
4620 bool isLeft = false;
4623 bool isShift = getSubtarget()->hasSSE2() &&
4624 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4625 if (isShift && ShVal.hasOneUse()) {
4626 // If the shifted value has multiple uses, it may be cheaper to use
4627 // v_set0 + movlhps or movhlps, etc.
4628 EVT EltVT = VT.getVectorElementType();
4629 ShAmt *= EltVT.getSizeInBits();
4630 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4633 if (X86::isMOVLMask(SVOp)) {
4636 if (ISD::isBuildVectorAllZeros(V1.getNode()))
4637 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4642 // FIXME: fold these into legal mask.
4643 if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4644 X86::isMOVSLDUPMask(SVOp) ||
4645 X86::isMOVHLPSMask(SVOp) ||
4646 X86::isMOVLHPSMask(SVOp) ||
4647 X86::isMOVLPMask(SVOp)))
4650 if (ShouldXformToMOVHLPS(SVOp) ||
4651 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4652 return CommuteVectorShuffle(SVOp, DAG);
4655 // No better options. Use a vshl / vsrl.
4656 EVT EltVT = VT.getVectorElementType();
4657 ShAmt *= EltVT.getSizeInBits();
4658 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4661 bool Commuted = false;
4662 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4663 // 1,1,1,1 -> v8i16 though.
4664 V1IsSplat = isSplatVector(V1.getNode());
4665 V2IsSplat = isSplatVector(V2.getNode());
4667 // Canonicalize the splat or undef, if present, to be on the RHS.
4668 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4669 Op = CommuteVectorShuffle(SVOp, DAG);
4670 SVOp = cast<ShuffleVectorSDNode>(Op);
4671 V1 = SVOp->getOperand(0);
4672 V2 = SVOp->getOperand(1);
4673 std::swap(V1IsSplat, V2IsSplat);
4674 std::swap(V1IsUndef, V2IsUndef);
4678 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4679 // Shuffling low element of v1 into undef, just return v1.
4682 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4683 // the instruction selector will not match, so get a canonical MOVL with
4684 // swapped operands to undo the commute.
4685 return getMOVL(DAG, dl, VT, V2, V1);
4688 if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4689 X86::isUNPCKH_v_undef_Mask(SVOp) ||
4690 X86::isUNPCKLMask(SVOp) ||
4691 X86::isUNPCKHMask(SVOp))
4695 // Normalize mask so all entries that point to V2 points to its first
4696 // element then try to match unpck{h|l} again. If match, return a
4697 // new vector_shuffle with the corrected mask.
4698 SDValue NewMask = NormalizeMask(SVOp, DAG);
4699 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4700 if (NSVOp != SVOp) {
4701 if (X86::isUNPCKLMask(NSVOp, true)) {
4703 } else if (X86::isUNPCKHMask(NSVOp, true)) {
4710 // Commute is back and try unpck* again.
4711 // FIXME: this seems wrong.
4712 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4713 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4714 if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4715 X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4716 X86::isUNPCKLMask(NewSVOp) ||
4717 X86::isUNPCKHMask(NewSVOp))
4721 // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4723 // Normalize the node to match x86 shuffle ops if needed
4724 if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4725 return CommuteVectorShuffle(SVOp, DAG);
4727 // Check for legal shuffle and return?
4728 SmallVector<int, 16> PermMask;
4729 SVOp->getMask(PermMask);
4730 if (isShuffleMaskLegal(PermMask, VT))
4733 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4734 if (VT == MVT::v8i16) {
4735 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4736 if (NewOp.getNode())
4740 if (VT == MVT::v16i8) {
4741 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4742 if (NewOp.getNode())
4746 // Handle all 4 wide cases with a number of shuffles except for MMX.
4747 if (NumElems == 4 && !isMMX)
4748 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4754 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4755 SelectionDAG &DAG) {
4756 EVT VT = Op.getValueType();
4757 DebugLoc dl = Op.getDebugLoc();
4758 if (VT.getSizeInBits() == 8) {
4759 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4760 Op.getOperand(0), Op.getOperand(1));
4761 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4762 DAG.getValueType(VT));
4763 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4764 } else if (VT.getSizeInBits() == 16) {
4765 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4766 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4768 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4769 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4770 DAG.getNode(ISD::BIT_CONVERT, dl,
4774 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4775 Op.getOperand(0), Op.getOperand(1));
4776 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4777 DAG.getValueType(VT));
4778 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4779 } else if (VT == MVT::f32) {
4780 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4781 // the result back to FR32 register. It's only worth matching if the
4782 // result has a single use which is a store or a bitcast to i32. And in
4783 // the case of a store, it's not worth it if the index is a constant 0,
4784 // because a MOVSSmr can be used instead, which is smaller and faster.
4785 if (!Op.hasOneUse())
4787 SDNode *User = *Op.getNode()->use_begin();
4788 if ((User->getOpcode() != ISD::STORE ||
4789 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4790 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4791 (User->getOpcode() != ISD::BIT_CONVERT ||
4792 User->getValueType(0) != MVT::i32))
4794 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4795 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4798 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4799 } else if (VT == MVT::i32) {
4800 // ExtractPS works with constant index.
4801 if (isa<ConstantSDNode>(Op.getOperand(1)))
4809 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4810 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4813 if (Subtarget->hasSSE41()) {
4814 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4819 EVT VT = Op.getValueType();
4820 DebugLoc dl = Op.getDebugLoc();
4821 // TODO: handle v16i8.
4822 if (VT.getSizeInBits() == 16) {
4823 SDValue Vec = Op.getOperand(0);
4824 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4826 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4827 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4828 DAG.getNode(ISD::BIT_CONVERT, dl,
4831 // Transform it so it match pextrw which produces a 32-bit result.
4832 EVT EltVT = MVT::i32;
4833 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
4834 Op.getOperand(0), Op.getOperand(1));
4835 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
4836 DAG.getValueType(VT));
4837 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4838 } else if (VT.getSizeInBits() == 32) {
4839 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4843 // SHUFPS the element to the lowest double word, then movss.
4844 int Mask[4] = { Idx, -1, -1, -1 };
4845 EVT VVT = Op.getOperand(0).getValueType();
4846 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4847 DAG.getUNDEF(VVT), Mask);
4848 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4849 DAG.getIntPtrConstant(0));
4850 } else if (VT.getSizeInBits() == 64) {
4851 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4852 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4853 // to match extract_elt for f64.
4854 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4858 // UNPCKHPD the element to the lowest double word, then movsd.
4859 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4860 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4861 int Mask[2] = { 1, -1 };
4862 EVT VVT = Op.getOperand(0).getValueType();
4863 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4864 DAG.getUNDEF(VVT), Mask);
4865 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4866 DAG.getIntPtrConstant(0));
4873 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4874 EVT VT = Op.getValueType();
4875 EVT EltVT = VT.getVectorElementType();
4876 DebugLoc dl = Op.getDebugLoc();
4878 SDValue N0 = Op.getOperand(0);
4879 SDValue N1 = Op.getOperand(1);
4880 SDValue N2 = Op.getOperand(2);
4882 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
4883 isa<ConstantSDNode>(N2)) {
4885 if (VT == MVT::v8i16)
4886 Opc = X86ISD::PINSRW;
4887 else if (VT == MVT::v4i16)
4888 Opc = X86ISD::MMX_PINSRW;
4889 else if (VT == MVT::v16i8)
4890 Opc = X86ISD::PINSRB;
4892 Opc = X86ISD::PINSRB;
4894 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4896 if (N1.getValueType() != MVT::i32)
4897 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4898 if (N2.getValueType() != MVT::i32)
4899 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4900 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4901 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4902 // Bits [7:6] of the constant are the source select. This will always be
4903 // zero here. The DAG Combiner may combine an extract_elt index into these
4904 // bits. For example (insert (extract, 3), 2) could be matched by putting
4905 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4906 // Bits [5:4] of the constant are the destination select. This is the
4907 // value of the incoming immediate.
4908 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4909 // combine either bitwise AND or insert of float 0.0 to set these bits.
4910 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4911 // Create this as a scalar to vector..
4912 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
4913 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4914 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
4915 // PINSR* works with constant index.
4922 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4923 EVT VT = Op.getValueType();
4924 EVT EltVT = VT.getVectorElementType();
4926 if (Subtarget->hasSSE41())
4927 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4929 if (EltVT == MVT::i8)
4932 DebugLoc dl = Op.getDebugLoc();
4933 SDValue N0 = Op.getOperand(0);
4934 SDValue N1 = Op.getOperand(1);
4935 SDValue N2 = Op.getOperand(2);
4937 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
4938 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4939 // as its second argument.
4940 if (N1.getValueType() != MVT::i32)
4941 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4942 if (N2.getValueType() != MVT::i32)
4943 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4944 return DAG.getNode(VT == MVT::v8i16 ? X86ISD::PINSRW : X86ISD::MMX_PINSRW,
4945 dl, VT, N0, N1, N2);
4951 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4952 DebugLoc dl = Op.getDebugLoc();
4953 if (Op.getValueType() == MVT::v2f32)
4954 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4955 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4956 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4957 Op.getOperand(0))));
4959 if (Op.getValueType() == MVT::v1i64 && Op.getOperand(0).getValueType() == MVT::i64)
4960 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
4962 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4963 EVT VT = MVT::v2i32;
4964 switch (Op.getValueType().getSimpleVT().SimpleTy) {
4971 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4972 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4975 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4976 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4977 // one of the above mentioned nodes. It has to be wrapped because otherwise
4978 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4979 // be used to form addressing mode. These wrapped nodes will be selected
4982 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4983 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4985 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4987 unsigned char OpFlag = 0;
4988 unsigned WrapperKind = X86ISD::Wrapper;
4989 CodeModel::Model M = getTargetMachine().getCodeModel();
4991 if (Subtarget->isPICStyleRIPRel() &&
4992 (M == CodeModel::Small || M == CodeModel::Kernel))
4993 WrapperKind = X86ISD::WrapperRIP;
4994 else if (Subtarget->isPICStyleGOT())
4995 OpFlag = X86II::MO_GOTOFF;
4996 else if (Subtarget->isPICStyleStubPIC())
4997 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4999 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5001 CP->getOffset(), OpFlag);
5002 DebugLoc DL = CP->getDebugLoc();
5003 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5004 // With PIC, the address is actually $g + Offset.
5006 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5007 DAG.getNode(X86ISD::GlobalBaseReg,
5008 DebugLoc::getUnknownLoc(), getPointerTy()),
5015 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
5016 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5018 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5020 unsigned char OpFlag = 0;
5021 unsigned WrapperKind = X86ISD::Wrapper;
5022 CodeModel::Model M = getTargetMachine().getCodeModel();
5024 if (Subtarget->isPICStyleRIPRel() &&
5025 (M == CodeModel::Small || M == CodeModel::Kernel))
5026 WrapperKind = X86ISD::WrapperRIP;
5027 else if (Subtarget->isPICStyleGOT())
5028 OpFlag = X86II::MO_GOTOFF;
5029 else if (Subtarget->isPICStyleStubPIC())
5030 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5032 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5034 DebugLoc DL = JT->getDebugLoc();
5035 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5037 // With PIC, the address is actually $g + Offset.
5039 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5040 DAG.getNode(X86ISD::GlobalBaseReg,
5041 DebugLoc::getUnknownLoc(), getPointerTy()),
5049 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
5050 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5052 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5054 unsigned char OpFlag = 0;
5055 unsigned WrapperKind = X86ISD::Wrapper;
5056 CodeModel::Model M = getTargetMachine().getCodeModel();
5058 if (Subtarget->isPICStyleRIPRel() &&
5059 (M == CodeModel::Small || M == CodeModel::Kernel))
5060 WrapperKind = X86ISD::WrapperRIP;
5061 else if (Subtarget->isPICStyleGOT())
5062 OpFlag = X86II::MO_GOTOFF;
5063 else if (Subtarget->isPICStyleStubPIC())
5064 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5066 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5068 DebugLoc DL = Op.getDebugLoc();
5069 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5072 // With PIC, the address is actually $g + Offset.
5073 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
5074 !Subtarget->is64Bit()) {
5075 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5076 DAG.getNode(X86ISD::GlobalBaseReg,
5077 DebugLoc::getUnknownLoc(),
5086 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) {
5087 // Create the TargetBlockAddressAddress node.
5088 unsigned char OpFlags =
5089 Subtarget->ClassifyBlockAddressReference();
5090 CodeModel::Model M = getTargetMachine().getCodeModel();
5091 BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5092 DebugLoc dl = Op.getDebugLoc();
5093 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5094 /*isTarget=*/true, OpFlags);
5096 if (Subtarget->isPICStyleRIPRel() &&
5097 (M == CodeModel::Small || M == CodeModel::Kernel))
5098 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5100 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5102 // With PIC, the address is actually $g + Offset.
5103 if (isGlobalRelativeToPICBase(OpFlags)) {
5104 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5105 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5113 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
5115 SelectionDAG &DAG) const {
5116 // Create the TargetGlobalAddress node, folding in the constant
5117 // offset if it is legal.
5118 unsigned char OpFlags =
5119 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5120 CodeModel::Model M = getTargetMachine().getCodeModel();
5122 if (OpFlags == X86II::MO_NO_FLAG &&
5123 X86::isOffsetSuitableForCodeModel(Offset, M)) {
5124 // A direct static reference to a global.
5125 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
5128 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
5131 if (Subtarget->isPICStyleRIPRel() &&
5132 (M == CodeModel::Small || M == CodeModel::Kernel))
5133 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5135 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5137 // With PIC, the address is actually $g + Offset.
5138 if (isGlobalRelativeToPICBase(OpFlags)) {
5139 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5140 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5144 // For globals that require a load from a stub to get the address, emit the
5146 if (isGlobalStubReference(OpFlags))
5147 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
5148 PseudoSourceValue::getGOT(), 0, false, false, 0);
5150 // If there was a non-zero offset that we didn't fold, create an explicit
5153 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
5154 DAG.getConstant(Offset, getPointerTy()));
5160 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
5161 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
5162 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
5163 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
5167 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
5168 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
5169 unsigned char OperandFlags) {
5170 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5171 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5172 DebugLoc dl = GA->getDebugLoc();
5173 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
5174 GA->getValueType(0),
5178 SDValue Ops[] = { Chain, TGA, *InFlag };
5179 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
5181 SDValue Ops[] = { Chain, TGA };
5182 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
5185 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
5186 MFI->setHasCalls(true);
5188 SDValue Flag = Chain.getValue(1);
5189 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
5192 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
5194 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5197 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
5198 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
5199 DAG.getNode(X86ISD::GlobalBaseReg,
5200 DebugLoc::getUnknownLoc(),
5202 InFlag = Chain.getValue(1);
5204 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
5207 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
5209 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5211 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
5212 X86::RAX, X86II::MO_TLSGD);
5215 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
5216 // "local exec" model.
5217 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5218 const EVT PtrVT, TLSModel::Model model,
5220 DebugLoc dl = GA->getDebugLoc();
5221 // Get the Thread Pointer
5222 SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
5223 DebugLoc::getUnknownLoc(), PtrVT,
5224 DAG.getRegister(is64Bit? X86::FS : X86::GS,
5227 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
5228 NULL, 0, false, false, 0);
5230 unsigned char OperandFlags = 0;
5231 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
5233 unsigned WrapperKind = X86ISD::Wrapper;
5234 if (model == TLSModel::LocalExec) {
5235 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
5236 } else if (is64Bit) {
5237 assert(model == TLSModel::InitialExec);
5238 OperandFlags = X86II::MO_GOTTPOFF;
5239 WrapperKind = X86ISD::WrapperRIP;
5241 assert(model == TLSModel::InitialExec);
5242 OperandFlags = X86II::MO_INDNTPOFF;
5245 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
5247 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
5248 GA->getOffset(), OperandFlags);
5249 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
5251 if (model == TLSModel::InitialExec)
5252 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
5253 PseudoSourceValue::getGOT(), 0, false, false, 0);
5255 // The address of the thread local variable is the add of the thread
5256 // pointer with the offset of the variable.
5257 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
5261 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
5262 // TODO: implement the "local dynamic" model
5263 // TODO: implement the "initial exec"model for pic executables
5264 assert(Subtarget->isTargetELF() &&
5265 "TLS not implemented for non-ELF targets");
5266 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5267 const GlobalValue *GV = GA->getGlobal();
5269 // If GV is an alias then use the aliasee for determining
5270 // thread-localness.
5271 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
5272 GV = GA->resolveAliasedGlobal(false);
5274 TLSModel::Model model = getTLSModel(GV,
5275 getTargetMachine().getRelocationModel());
5278 case TLSModel::GeneralDynamic:
5279 case TLSModel::LocalDynamic: // not implemented
5280 if (Subtarget->is64Bit())
5281 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
5282 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
5284 case TLSModel::InitialExec:
5285 case TLSModel::LocalExec:
5286 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
5287 Subtarget->is64Bit());
5290 llvm_unreachable("Unreachable");
5295 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
5296 /// take a 2 x i32 value to shift plus a shift amount.
5297 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
5298 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5299 EVT VT = Op.getValueType();
5300 unsigned VTBits = VT.getSizeInBits();
5301 DebugLoc dl = Op.getDebugLoc();
5302 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
5303 SDValue ShOpLo = Op.getOperand(0);
5304 SDValue ShOpHi = Op.getOperand(1);
5305 SDValue ShAmt = Op.getOperand(2);
5306 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
5307 DAG.getConstant(VTBits - 1, MVT::i8))
5308 : DAG.getConstant(0, VT);
5311 if (Op.getOpcode() == ISD::SHL_PARTS) {
5312 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
5313 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5315 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
5316 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
5319 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
5320 DAG.getConstant(VTBits, MVT::i8));
5321 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
5322 AndNode, DAG.getConstant(0, MVT::i8));
5325 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5326 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
5327 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
5329 if (Op.getOpcode() == ISD::SHL_PARTS) {
5330 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5331 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5333 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5334 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5337 SDValue Ops[2] = { Lo, Hi };
5338 return DAG.getMergeValues(Ops, 2, dl);
5341 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5342 EVT SrcVT = Op.getOperand(0).getValueType();
5344 if (SrcVT.isVector()) {
5345 if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
5351 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
5352 "Unknown SINT_TO_FP to lower!");
5354 // These are really Legal; return the operand so the caller accepts it as
5356 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
5358 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
5359 Subtarget->is64Bit()) {
5363 DebugLoc dl = Op.getDebugLoc();
5364 unsigned Size = SrcVT.getSizeInBits()/8;
5365 MachineFunction &MF = DAG.getMachineFunction();
5366 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
5367 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5368 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5370 PseudoSourceValue::getFixedStack(SSFI), 0,
5372 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
5375 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
5377 SelectionDAG &DAG) {
5379 DebugLoc dl = Op.getDebugLoc();
5381 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
5383 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
5385 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
5386 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
5387 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
5388 Tys, Ops, array_lengthof(Ops));
5391 Chain = Result.getValue(1);
5392 SDValue InFlag = Result.getValue(2);
5394 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5395 // shouldn't be necessary except that RFP cannot be live across
5396 // multiple blocks. When stackifier is fixed, they can be uncoupled.
5397 MachineFunction &MF = DAG.getMachineFunction();
5398 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5399 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5400 Tys = DAG.getVTList(MVT::Other);
5402 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
5404 Chain = DAG.getNode(X86ISD::FST, dl, Tys, Ops, array_lengthof(Ops));
5405 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5406 PseudoSourceValue::getFixedStack(SSFI), 0,
5413 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5414 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
5415 // This algorithm is not obvious. Here it is in C code, more or less:
5417 double uint64_to_double( uint32_t hi, uint32_t lo ) {
5418 static const __m128i exp = { 0x4330000045300000ULL, 0 };
5419 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5421 // Copy ints to xmm registers.
5422 __m128i xh = _mm_cvtsi32_si128( hi );
5423 __m128i xl = _mm_cvtsi32_si128( lo );
5425 // Combine into low half of a single xmm register.
5426 __m128i x = _mm_unpacklo_epi32( xh, xl );
5430 // Merge in appropriate exponents to give the integer bits the right
5432 x = _mm_unpacklo_epi32( x, exp );
5434 // Subtract away the biases to deal with the IEEE-754 double precision
5436 d = _mm_sub_pd( (__m128d) x, bias );
5438 // All conversions up to here are exact. The correctly rounded result is
5439 // calculated using the current rounding mode using the following
5441 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5442 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
5443 // store doesn't really need to be here (except
5444 // maybe to zero the other double)
5449 DebugLoc dl = Op.getDebugLoc();
5450 LLVMContext *Context = DAG.getContext();
5452 // Build some magic constants.
5453 std::vector<Constant*> CV0;
5454 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
5455 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
5456 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5457 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5458 Constant *C0 = ConstantVector::get(CV0);
5459 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5461 std::vector<Constant*> CV1;
5463 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
5465 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
5466 Constant *C1 = ConstantVector::get(CV1);
5467 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5469 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5470 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5472 DAG.getIntPtrConstant(1)));
5473 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5474 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5476 DAG.getIntPtrConstant(0)));
5477 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
5478 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5479 PseudoSourceValue::getConstantPool(), 0,
5481 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
5482 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5483 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5484 PseudoSourceValue::getConstantPool(), 0,
5486 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5488 // Add the halves; easiest way is to swap them into another reg first.
5489 int ShufMask[2] = { 1, -1 };
5490 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
5491 DAG.getUNDEF(MVT::v2f64), ShufMask);
5492 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5493 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5494 DAG.getIntPtrConstant(0));
5497 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5498 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
5499 DebugLoc dl = Op.getDebugLoc();
5500 // FP constant to bias correct the final result.
5501 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5504 // Load the 32-bit value into an XMM register.
5505 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5506 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5508 DAG.getIntPtrConstant(0)));
5510 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5511 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5512 DAG.getIntPtrConstant(0));
5514 // Or the load with the bias.
5515 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5516 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5517 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5519 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5520 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5521 MVT::v2f64, Bias)));
5522 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5523 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5524 DAG.getIntPtrConstant(0));
5526 // Subtract the bias.
5527 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5529 // Handle final rounding.
5530 EVT DestVT = Op.getValueType();
5532 if (DestVT.bitsLT(MVT::f64)) {
5533 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5534 DAG.getIntPtrConstant(0));
5535 } else if (DestVT.bitsGT(MVT::f64)) {
5536 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5539 // Handle final rounding.
5543 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5544 SDValue N0 = Op.getOperand(0);
5545 DebugLoc dl = Op.getDebugLoc();
5547 // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
5548 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5549 // the optimization here.
5550 if (DAG.SignBitIsZero(N0))
5551 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5553 EVT SrcVT = N0.getValueType();
5554 if (SrcVT == MVT::i64) {
5555 // We only handle SSE2 f64 target here; caller can expand the rest.
5556 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
5559 return LowerUINT_TO_FP_i64(Op, DAG);
5560 } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
5561 return LowerUINT_TO_FP_i32(Op, DAG);
5564 assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
5566 // Make a 64-bit buffer, and use it to build an FILD.
5567 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5568 SDValue WordOff = DAG.getConstant(4, getPointerTy());
5569 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5570 getPointerTy(), StackSlot, WordOff);
5571 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5572 StackSlot, NULL, 0, false, false, 0);
5573 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5574 OffsetSlot, NULL, 0, false, false, 0);
5575 return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5578 std::pair<SDValue,SDValue> X86TargetLowering::
5579 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) {
5580 DebugLoc dl = Op.getDebugLoc();
5582 EVT DstTy = Op.getValueType();
5585 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5589 assert(DstTy.getSimpleVT() <= MVT::i64 &&
5590 DstTy.getSimpleVT() >= MVT::i16 &&
5591 "Unknown FP_TO_SINT to lower!");
5593 // These are really Legal.
5594 if (DstTy == MVT::i32 &&
5595 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5596 return std::make_pair(SDValue(), SDValue());
5597 if (Subtarget->is64Bit() &&
5598 DstTy == MVT::i64 &&
5599 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5600 return std::make_pair(SDValue(), SDValue());
5602 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5604 MachineFunction &MF = DAG.getMachineFunction();
5605 unsigned MemSize = DstTy.getSizeInBits()/8;
5606 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5607 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5610 switch (DstTy.getSimpleVT().SimpleTy) {
5611 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5612 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5613 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5614 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5617 SDValue Chain = DAG.getEntryNode();
5618 SDValue Value = Op.getOperand(0);
5619 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5620 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5621 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5622 PseudoSourceValue::getFixedStack(SSFI), 0,
5624 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5626 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5628 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5629 Chain = Value.getValue(1);
5630 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5631 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5634 // Build the FP_TO_INT*_IN_MEM
5635 SDValue Ops[] = { Chain, Value, StackSlot };
5636 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5638 return std::make_pair(FIST, StackSlot);
5641 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
5642 if (Op.getValueType().isVector()) {
5643 if (Op.getValueType() == MVT::v2i32 &&
5644 Op.getOperand(0).getValueType() == MVT::v2f64) {
5650 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5651 SDValue FIST = Vals.first, StackSlot = Vals.second;
5652 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5653 if (FIST.getNode() == 0) return Op;
5656 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5657 FIST, StackSlot, NULL, 0, false, false, 0);
5660 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG) {
5661 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5662 SDValue FIST = Vals.first, StackSlot = Vals.second;
5663 assert(FIST.getNode() && "Unexpected failure");
5666 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5667 FIST, StackSlot, NULL, 0, false, false, 0);
5670 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
5671 LLVMContext *Context = DAG.getContext();
5672 DebugLoc dl = Op.getDebugLoc();
5673 EVT VT = Op.getValueType();
5676 EltVT = VT.getVectorElementType();
5677 std::vector<Constant*> CV;
5678 if (EltVT == MVT::f64) {
5679 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5683 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5689 Constant *C = ConstantVector::get(CV);
5690 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5691 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5692 PseudoSourceValue::getConstantPool(), 0,
5694 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5697 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
5698 LLVMContext *Context = DAG.getContext();
5699 DebugLoc dl = Op.getDebugLoc();
5700 EVT VT = Op.getValueType();
5703 EltVT = VT.getVectorElementType();
5704 std::vector<Constant*> CV;
5705 if (EltVT == MVT::f64) {
5706 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5710 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5716 Constant *C = ConstantVector::get(CV);
5717 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5718 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5719 PseudoSourceValue::getConstantPool(), 0,
5721 if (VT.isVector()) {
5722 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5723 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5724 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5726 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5728 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5732 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5733 LLVMContext *Context = DAG.getContext();
5734 SDValue Op0 = Op.getOperand(0);
5735 SDValue Op1 = Op.getOperand(1);
5736 DebugLoc dl = Op.getDebugLoc();
5737 EVT VT = Op.getValueType();
5738 EVT SrcVT = Op1.getValueType();
5740 // If second operand is smaller, extend it first.
5741 if (SrcVT.bitsLT(VT)) {
5742 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5745 // And if it is bigger, shrink it first.
5746 if (SrcVT.bitsGT(VT)) {
5747 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5751 // At this point the operands and the result should have the same
5752 // type, and that won't be f80 since that is not custom lowered.
5754 // First get the sign bit of second operand.
5755 std::vector<Constant*> CV;
5756 if (SrcVT == MVT::f64) {
5757 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
5758 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5760 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
5761 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5762 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5763 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5765 Constant *C = ConstantVector::get(CV);
5766 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5767 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5768 PseudoSourceValue::getConstantPool(), 0,
5770 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5772 // Shift sign bit right or left if the two operands have different types.
5773 if (SrcVT.bitsGT(VT)) {
5774 // Op0 is MVT::f32, Op1 is MVT::f64.
5775 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5776 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5777 DAG.getConstant(32, MVT::i32));
5778 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5779 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5780 DAG.getIntPtrConstant(0));
5783 // Clear first operand sign bit.
5785 if (VT == MVT::f64) {
5786 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
5787 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5789 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
5790 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5791 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5792 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5794 C = ConstantVector::get(CV);
5795 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5796 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5797 PseudoSourceValue::getConstantPool(), 0,
5799 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5801 // Or the value with the sign bit.
5802 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5805 /// Emit nodes that will be selected as "test Op0,Op0", or something
5807 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5808 SelectionDAG &DAG) {
5809 DebugLoc dl = Op.getDebugLoc();
5811 // CF and OF aren't always set the way we want. Determine which
5812 // of these we need.
5813 bool NeedCF = false;
5814 bool NeedOF = false;
5816 case X86::COND_A: case X86::COND_AE:
5817 case X86::COND_B: case X86::COND_BE:
5820 case X86::COND_G: case X86::COND_GE:
5821 case X86::COND_L: case X86::COND_LE:
5822 case X86::COND_O: case X86::COND_NO:
5828 // See if we can use the EFLAGS value from the operand instead of
5829 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5830 // we prove that the arithmetic won't overflow, we can't use OF or CF.
5831 if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5832 unsigned Opcode = 0;
5833 unsigned NumOperands = 0;
5834 switch (Op.getNode()->getOpcode()) {
5836 // Due to an isel shortcoming, be conservative if this add is likely to
5837 // be selected as part of a load-modify-store instruction. When the root
5838 // node in a match is a store, isel doesn't know how to remap non-chain
5839 // non-flag uses of other nodes in the match, such as the ADD in this
5840 // case. This leads to the ADD being left around and reselected, with
5841 // the result being two adds in the output.
5842 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5843 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5844 if (UI->getOpcode() == ISD::STORE)
5846 if (ConstantSDNode *C =
5847 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5848 // An add of one will be selected as an INC.
5849 if (C->getAPIntValue() == 1) {
5850 Opcode = X86ISD::INC;
5854 // An add of negative one (subtract of one) will be selected as a DEC.
5855 if (C->getAPIntValue().isAllOnesValue()) {
5856 Opcode = X86ISD::DEC;
5861 // Otherwise use a regular EFLAGS-setting add.
5862 Opcode = X86ISD::ADD;
5866 // If the primary and result isn't used, don't bother using X86ISD::AND,
5867 // because a TEST instruction will be better.
5868 bool NonFlagUse = false;
5869 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5870 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
5872 unsigned UOpNo = UI.getOperandNo();
5873 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
5874 // Look pass truncate.
5875 UOpNo = User->use_begin().getOperandNo();
5876 User = *User->use_begin();
5878 if (User->getOpcode() != ISD::BRCOND &&
5879 User->getOpcode() != ISD::SETCC &&
5880 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
5892 // Due to the ISEL shortcoming noted above, be conservative if this op is
5893 // likely to be selected as part of a load-modify-store instruction.
5894 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5895 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5896 if (UI->getOpcode() == ISD::STORE)
5898 // Otherwise use a regular EFLAGS-setting instruction.
5899 switch (Op.getNode()->getOpcode()) {
5900 case ISD::SUB: Opcode = X86ISD::SUB; break;
5901 case ISD::OR: Opcode = X86ISD::OR; break;
5902 case ISD::XOR: Opcode = X86ISD::XOR; break;
5903 case ISD::AND: Opcode = X86ISD::AND; break;
5904 default: llvm_unreachable("unexpected operator!");
5915 return SDValue(Op.getNode(), 1);
5921 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
5922 SmallVector<SDValue, 4> Ops;
5923 for (unsigned i = 0; i != NumOperands; ++i)
5924 Ops.push_back(Op.getOperand(i));
5925 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
5926 DAG.ReplaceAllUsesWith(Op, New);
5927 return SDValue(New.getNode(), 1);
5931 // Otherwise just emit a CMP with 0, which is the TEST pattern.
5932 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5933 DAG.getConstant(0, Op.getValueType()));
5936 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
5938 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5939 SelectionDAG &DAG) {
5940 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5941 if (C->getAPIntValue() == 0)
5942 return EmitTest(Op0, X86CC, DAG);
5944 DebugLoc dl = Op0.getDebugLoc();
5945 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5948 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
5949 /// if it's possible.
5950 static SDValue LowerToBT(SDValue And, ISD::CondCode CC,
5951 DebugLoc dl, SelectionDAG &DAG) {
5952 SDValue Op0 = And.getOperand(0);
5953 SDValue Op1 = And.getOperand(1);
5954 if (Op0.getOpcode() == ISD::TRUNCATE)
5955 Op0 = Op0.getOperand(0);
5956 if (Op1.getOpcode() == ISD::TRUNCATE)
5957 Op1 = Op1.getOperand(0);
5960 if (Op1.getOpcode() == ISD::SHL) {
5961 if (ConstantSDNode *And10C = dyn_cast<ConstantSDNode>(Op1.getOperand(0)))
5962 if (And10C->getZExtValue() == 1) {
5964 RHS = Op1.getOperand(1);
5966 } else if (Op0.getOpcode() == ISD::SHL) {
5967 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
5968 if (And00C->getZExtValue() == 1) {
5970 RHS = Op0.getOperand(1);
5972 } else if (Op1.getOpcode() == ISD::Constant) {
5973 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
5974 SDValue AndLHS = Op0;
5975 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5976 LHS = AndLHS.getOperand(0);
5977 RHS = AndLHS.getOperand(1);
5981 if (LHS.getNode()) {
5982 // If LHS is i8, promote it to i16 with any_extend. There is no i8 BT
5983 // instruction. Since the shift amount is in-range-or-undefined, we know
5984 // that doing a bittest on the i16 value is ok. We extend to i32 because
5985 // the encoding for the i16 version is larger than the i32 version.
5986 if (LHS.getValueType() == MVT::i8)
5987 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5989 // If the operand types disagree, extend the shift amount to match. Since
5990 // BT ignores high bits (like shifts) we can use anyextend.
5991 if (LHS.getValueType() != RHS.getValueType())
5992 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5994 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5995 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5996 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5997 DAG.getConstant(Cond, MVT::i8), BT);
6003 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
6004 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
6005 SDValue Op0 = Op.getOperand(0);
6006 SDValue Op1 = Op.getOperand(1);
6007 DebugLoc dl = Op.getDebugLoc();
6008 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6010 // Optimize to BT if possible.
6011 // Lower (X & (1 << N)) == 0 to BT(X, N).
6012 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
6013 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
6014 if (Op0.getOpcode() == ISD::AND &&
6016 Op1.getOpcode() == ISD::Constant &&
6017 cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
6018 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6019 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
6020 if (NewSetCC.getNode())
6024 // Look for "(setcc) == / != 1" to avoid unncessary setcc.
6025 if (Op0.getOpcode() == X86ISD::SETCC &&
6026 Op1.getOpcode() == ISD::Constant &&
6027 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
6028 cast<ConstantSDNode>(Op1)->isNullValue()) &&
6029 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6030 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
6031 bool Invert = (CC == ISD::SETNE) ^
6032 cast<ConstantSDNode>(Op1)->isNullValue();
6034 CCode = X86::GetOppositeBranchCondition(CCode);
6035 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6036 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
6039 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
6040 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
6041 if (X86CC == X86::COND_INVALID)
6044 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
6046 // Use sbb x, x to materialize carry bit into a GPR.
6047 if (X86CC == X86::COND_B)
6048 return DAG.getNode(ISD::AND, dl, MVT::i8,
6049 DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
6050 DAG.getConstant(X86CC, MVT::i8), Cond),
6051 DAG.getConstant(1, MVT::i8));
6053 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6054 DAG.getConstant(X86CC, MVT::i8), Cond);
6057 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
6059 SDValue Op0 = Op.getOperand(0);
6060 SDValue Op1 = Op.getOperand(1);
6061 SDValue CC = Op.getOperand(2);
6062 EVT VT = Op.getValueType();
6063 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6064 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
6065 DebugLoc dl = Op.getDebugLoc();
6069 EVT VT0 = Op0.getValueType();
6070 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
6071 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
6074 switch (SetCCOpcode) {
6077 case ISD::SETEQ: SSECC = 0; break;
6079 case ISD::SETGT: Swap = true; // Fallthrough
6081 case ISD::SETOLT: SSECC = 1; break;
6083 case ISD::SETGE: Swap = true; // Fallthrough
6085 case ISD::SETOLE: SSECC = 2; break;
6086 case ISD::SETUO: SSECC = 3; break;
6088 case ISD::SETNE: SSECC = 4; break;
6089 case ISD::SETULE: Swap = true;
6090 case ISD::SETUGE: SSECC = 5; break;
6091 case ISD::SETULT: Swap = true;
6092 case ISD::SETUGT: SSECC = 6; break;
6093 case ISD::SETO: SSECC = 7; break;
6096 std::swap(Op0, Op1);
6098 // In the two special cases we can't handle, emit two comparisons.
6100 if (SetCCOpcode == ISD::SETUEQ) {
6102 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
6103 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
6104 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
6106 else if (SetCCOpcode == ISD::SETONE) {
6108 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
6109 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
6110 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
6112 llvm_unreachable("Illegal FP comparison");
6114 // Handle all other FP comparisons here.
6115 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
6118 // We are handling one of the integer comparisons here. Since SSE only has
6119 // GT and EQ comparisons for integer, swapping operands and multiple
6120 // operations may be required for some comparisons.
6121 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
6122 bool Swap = false, Invert = false, FlipSigns = false;
6124 switch (VT.getSimpleVT().SimpleTy) {
6127 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
6129 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
6131 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
6132 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
6135 switch (SetCCOpcode) {
6137 case ISD::SETNE: Invert = true;
6138 case ISD::SETEQ: Opc = EQOpc; break;
6139 case ISD::SETLT: Swap = true;
6140 case ISD::SETGT: Opc = GTOpc; break;
6141 case ISD::SETGE: Swap = true;
6142 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
6143 case ISD::SETULT: Swap = true;
6144 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
6145 case ISD::SETUGE: Swap = true;
6146 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
6149 std::swap(Op0, Op1);
6151 // Since SSE has no unsigned integer comparisons, we need to flip the sign
6152 // bits of the inputs before performing those operations.
6154 EVT EltVT = VT.getVectorElementType();
6155 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
6157 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
6158 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
6160 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
6161 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
6164 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
6166 // If the logical-not of the result is required, perform that now.
6168 Result = DAG.getNOT(dl, Result, VT);
6173 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
6174 static bool isX86LogicalCmp(SDValue Op) {
6175 unsigned Opc = Op.getNode()->getOpcode();
6176 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
6178 if (Op.getResNo() == 1 &&
6179 (Opc == X86ISD::ADD ||
6180 Opc == X86ISD::SUB ||
6181 Opc == X86ISD::SMUL ||
6182 Opc == X86ISD::UMUL ||
6183 Opc == X86ISD::INC ||
6184 Opc == X86ISD::DEC ||
6185 Opc == X86ISD::OR ||
6186 Opc == X86ISD::XOR ||
6187 Opc == X86ISD::AND))
6193 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
6194 bool addTest = true;
6195 SDValue Cond = Op.getOperand(0);
6196 DebugLoc dl = Op.getDebugLoc();
6199 if (Cond.getOpcode() == ISD::SETCC) {
6200 SDValue NewCond = LowerSETCC(Cond, DAG);
6201 if (NewCond.getNode())
6205 // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
6206 SDValue Op1 = Op.getOperand(1);
6207 SDValue Op2 = Op.getOperand(2);
6208 if (Cond.getOpcode() == X86ISD::SETCC &&
6209 cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
6210 SDValue Cmp = Cond.getOperand(1);
6211 if (Cmp.getOpcode() == X86ISD::CMP) {
6212 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
6213 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
6214 ConstantSDNode *RHSC =
6215 dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
6216 if (N1C && N1C->isAllOnesValue() &&
6217 N2C && N2C->isNullValue() &&
6218 RHSC && RHSC->isNullValue()) {
6219 SDValue CmpOp0 = Cmp.getOperand(0);
6220 Cmp = DAG.getNode(X86ISD::CMP, dl, CmpOp0.getValueType(),
6221 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
6222 return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
6223 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
6228 // Look pass (and (setcc_carry (cmp ...)), 1).
6229 if (Cond.getOpcode() == ISD::AND &&
6230 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6231 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6232 if (C && C->getAPIntValue() == 1)
6233 Cond = Cond.getOperand(0);
6236 // If condition flag is set by a X86ISD::CMP, then use it as the condition
6237 // setting operand in place of the X86ISD::SETCC.
6238 if (Cond.getOpcode() == X86ISD::SETCC ||
6239 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6240 CC = Cond.getOperand(0);
6242 SDValue Cmp = Cond.getOperand(1);
6243 unsigned Opc = Cmp.getOpcode();
6244 EVT VT = Op.getValueType();
6246 bool IllegalFPCMov = false;
6247 if (VT.isFloatingPoint() && !VT.isVector() &&
6248 !isScalarFPTypeInSSEReg(VT)) // FPStack?
6249 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
6251 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
6252 Opc == X86ISD::BT) { // FIXME
6259 // Look pass the truncate.
6260 if (Cond.getOpcode() == ISD::TRUNCATE)
6261 Cond = Cond.getOperand(0);
6263 // We know the result of AND is compared against zero. Try to match
6265 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
6266 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6267 if (NewSetCC.getNode()) {
6268 CC = NewSetCC.getOperand(0);
6269 Cond = NewSetCC.getOperand(1);
6276 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6277 Cond = EmitTest(Cond, X86::COND_NE, DAG);
6280 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
6281 // condition is true.
6282 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
6283 SDValue Ops[] = { Op2, Op1, CC, Cond };
6284 return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
6287 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
6288 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
6289 // from the AND / OR.
6290 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
6291 Opc = Op.getOpcode();
6292 if (Opc != ISD::OR && Opc != ISD::AND)
6294 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6295 Op.getOperand(0).hasOneUse() &&
6296 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
6297 Op.getOperand(1).hasOneUse());
6300 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
6301 // 1 and that the SETCC node has a single use.
6302 static bool isXor1OfSetCC(SDValue Op) {
6303 if (Op.getOpcode() != ISD::XOR)
6305 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6306 if (N1C && N1C->getAPIntValue() == 1) {
6307 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6308 Op.getOperand(0).hasOneUse();
6313 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
6314 bool addTest = true;
6315 SDValue Chain = Op.getOperand(0);
6316 SDValue Cond = Op.getOperand(1);
6317 SDValue Dest = Op.getOperand(2);
6318 DebugLoc dl = Op.getDebugLoc();
6321 if (Cond.getOpcode() == ISD::SETCC) {
6322 SDValue NewCond = LowerSETCC(Cond, DAG);
6323 if (NewCond.getNode())
6327 // FIXME: LowerXALUO doesn't handle these!!
6328 else if (Cond.getOpcode() == X86ISD::ADD ||
6329 Cond.getOpcode() == X86ISD::SUB ||
6330 Cond.getOpcode() == X86ISD::SMUL ||
6331 Cond.getOpcode() == X86ISD::UMUL)
6332 Cond = LowerXALUO(Cond, DAG);
6335 // Look pass (and (setcc_carry (cmp ...)), 1).
6336 if (Cond.getOpcode() == ISD::AND &&
6337 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6338 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6339 if (C && C->getAPIntValue() == 1)
6340 Cond = Cond.getOperand(0);
6343 // If condition flag is set by a X86ISD::CMP, then use it as the condition
6344 // setting operand in place of the X86ISD::SETCC.
6345 if (Cond.getOpcode() == X86ISD::SETCC ||
6346 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6347 CC = Cond.getOperand(0);
6349 SDValue Cmp = Cond.getOperand(1);
6350 unsigned Opc = Cmp.getOpcode();
6351 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
6352 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
6356 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
6360 // These can only come from an arithmetic instruction with overflow,
6361 // e.g. SADDO, UADDO.
6362 Cond = Cond.getNode()->getOperand(1);
6369 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
6370 SDValue Cmp = Cond.getOperand(0).getOperand(1);
6371 if (CondOpc == ISD::OR) {
6372 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
6373 // two branches instead of an explicit OR instruction with a
6375 if (Cmp == Cond.getOperand(1).getOperand(1) &&
6376 isX86LogicalCmp(Cmp)) {
6377 CC = Cond.getOperand(0).getOperand(0);
6378 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6379 Chain, Dest, CC, Cmp);
6380 CC = Cond.getOperand(1).getOperand(0);
6384 } else { // ISD::AND
6385 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
6386 // two branches instead of an explicit AND instruction with a
6387 // separate test. However, we only do this if this block doesn't
6388 // have a fall-through edge, because this requires an explicit
6389 // jmp when the condition is false.
6390 if (Cmp == Cond.getOperand(1).getOperand(1) &&
6391 isX86LogicalCmp(Cmp) &&
6392 Op.getNode()->hasOneUse()) {
6393 X86::CondCode CCode =
6394 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6395 CCode = X86::GetOppositeBranchCondition(CCode);
6396 CC = DAG.getConstant(CCode, MVT::i8);
6397 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
6398 // Look for an unconditional branch following this conditional branch.
6399 // We need this because we need to reverse the successors in order
6400 // to implement FCMP_OEQ.
6401 if (User.getOpcode() == ISD::BR) {
6402 SDValue FalseBB = User.getOperand(1);
6404 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
6405 assert(NewBR == User);
6408 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6409 Chain, Dest, CC, Cmp);
6410 X86::CondCode CCode =
6411 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
6412 CCode = X86::GetOppositeBranchCondition(CCode);
6413 CC = DAG.getConstant(CCode, MVT::i8);
6419 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
6420 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
6421 // It should be transformed during dag combiner except when the condition
6422 // is set by a arithmetics with overflow node.
6423 X86::CondCode CCode =
6424 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6425 CCode = X86::GetOppositeBranchCondition(CCode);
6426 CC = DAG.getConstant(CCode, MVT::i8);
6427 Cond = Cond.getOperand(0).getOperand(1);
6433 // Look pass the truncate.
6434 if (Cond.getOpcode() == ISD::TRUNCATE)
6435 Cond = Cond.getOperand(0);
6437 // We know the result of AND is compared against zero. Try to match
6439 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
6440 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6441 if (NewSetCC.getNode()) {
6442 CC = NewSetCC.getOperand(0);
6443 Cond = NewSetCC.getOperand(1);
6450 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6451 Cond = EmitTest(Cond, X86::COND_NE, DAG);
6453 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6454 Chain, Dest, CC, Cond);
6458 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
6459 // Calls to _alloca is needed to probe the stack when allocating more than 4k
6460 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
6461 // that the guard pages used by the OS virtual memory manager are allocated in
6462 // correct sequence.
6464 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6465 SelectionDAG &DAG) {
6466 assert(Subtarget->isTargetCygMing() &&
6467 "This should be used only on Cygwin/Mingw targets");
6468 DebugLoc dl = Op.getDebugLoc();
6471 SDValue Chain = Op.getOperand(0);
6472 SDValue Size = Op.getOperand(1);
6473 // FIXME: Ensure alignment here
6477 EVT IntPtr = getPointerTy();
6478 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
6480 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
6481 Flag = Chain.getValue(1);
6483 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6485 Chain = DAG.getNode(X86ISD::MINGW_ALLOCA, dl, NodeTys, Chain, Flag);
6486 Flag = Chain.getValue(1);
6488 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
6490 SDValue Ops1[2] = { Chain.getValue(0), Chain };
6491 return DAG.getMergeValues(Ops1, 2, dl);
6495 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
6497 SDValue Dst, SDValue Src,
6498 SDValue Size, unsigned Align,
6500 uint64_t DstSVOff) {
6501 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6503 // If not DWORD aligned or size is more than the threshold, call the library.
6504 // The libc version is likely to be faster for these cases. It can use the
6505 // address value and run time information about the CPU.
6506 if ((Align & 3) != 0 ||
6508 ConstantSize->getZExtValue() >
6509 getSubtarget()->getMaxInlineSizeThreshold()) {
6510 SDValue InFlag(0, 0);
6512 // Check to see if there is a specialized entry-point for memory zeroing.
6513 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
6515 if (const char *bzeroEntry = V &&
6516 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
6517 EVT IntPtr = getPointerTy();
6518 const Type *IntPtrTy = TD->getIntPtrType(*DAG.getContext());
6519 TargetLowering::ArgListTy Args;
6520 TargetLowering::ArgListEntry Entry;
6522 Entry.Ty = IntPtrTy;
6523 Args.push_back(Entry);
6525 Args.push_back(Entry);
6526 std::pair<SDValue,SDValue> CallResult =
6527 LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()),
6528 false, false, false, false,
6529 0, CallingConv::C, false, /*isReturnValueUsed=*/false,
6530 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl);
6531 return CallResult.second;
6534 // Otherwise have the target-independent code call memset.
6538 uint64_t SizeVal = ConstantSize->getZExtValue();
6539 SDValue InFlag(0, 0);
6542 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
6543 unsigned BytesLeft = 0;
6544 bool TwoRepStos = false;
6547 uint64_t Val = ValC->getZExtValue() & 255;
6549 // If the value is a constant, then we can potentially use larger sets.
6550 switch (Align & 3) {
6551 case 2: // WORD aligned
6554 Val = (Val << 8) | Val;
6556 case 0: // DWORD aligned
6559 Val = (Val << 8) | Val;
6560 Val = (Val << 16) | Val;
6561 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
6564 Val = (Val << 32) | Val;
6567 default: // Byte aligned
6570 Count = DAG.getIntPtrConstant(SizeVal);
6574 if (AVT.bitsGT(MVT::i8)) {
6575 unsigned UBytes = AVT.getSizeInBits() / 8;
6576 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
6577 BytesLeft = SizeVal % UBytes;
6580 Chain = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
6582 InFlag = Chain.getValue(1);
6585 Count = DAG.getIntPtrConstant(SizeVal);
6586 Chain = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
6587 InFlag = Chain.getValue(1);
6590 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6593 InFlag = Chain.getValue(1);
6594 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6597 InFlag = Chain.getValue(1);
6599 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6600 SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6601 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6604 InFlag = Chain.getValue(1);
6606 EVT CVT = Count.getValueType();
6607 SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
6608 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
6609 Chain = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
6612 InFlag = Chain.getValue(1);
6613 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6614 SDValue Ops[] = { Chain, DAG.getValueType(MVT::i8), InFlag };
6615 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6616 } else if (BytesLeft) {
6617 // Handle the last 1 - 7 bytes.
6618 unsigned Offset = SizeVal - BytesLeft;
6619 EVT AddrVT = Dst.getValueType();
6620 EVT SizeVT = Size.getValueType();
6622 Chain = DAG.getMemset(Chain, dl,
6623 DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
6624 DAG.getConstant(Offset, AddrVT)),
6626 DAG.getConstant(BytesLeft, SizeVT),
6627 Align, DstSV, DstSVOff + Offset);
6630 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
6635 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
6636 SDValue Chain, SDValue Dst, SDValue Src,
6637 SDValue Size, unsigned Align,
6639 const Value *DstSV, uint64_t DstSVOff,
6640 const Value *SrcSV, uint64_t SrcSVOff) {
6641 // This requires the copy size to be a constant, preferrably
6642 // within a subtarget-specific limit.
6643 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6646 uint64_t SizeVal = ConstantSize->getZExtValue();
6647 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
6650 /// If not DWORD aligned, call the library.
6651 if ((Align & 3) != 0)
6656 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
6659 unsigned UBytes = AVT.getSizeInBits() / 8;
6660 unsigned CountVal = SizeVal / UBytes;
6661 SDValue Count = DAG.getIntPtrConstant(CountVal);
6662 unsigned BytesLeft = SizeVal % UBytes;
6664 SDValue InFlag(0, 0);
6665 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6668 InFlag = Chain.getValue(1);
6669 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6672 InFlag = Chain.getValue(1);
6673 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
6676 InFlag = Chain.getValue(1);
6678 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6679 SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6680 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, Ops,
6681 array_lengthof(Ops));
6683 SmallVector<SDValue, 4> Results;
6684 Results.push_back(RepMovs);
6686 // Handle the last 1 - 7 bytes.
6687 unsigned Offset = SizeVal - BytesLeft;
6688 EVT DstVT = Dst.getValueType();
6689 EVT SrcVT = Src.getValueType();
6690 EVT SizeVT = Size.getValueType();
6691 Results.push_back(DAG.getMemcpy(Chain, dl,
6692 DAG.getNode(ISD::ADD, dl, DstVT, Dst,
6693 DAG.getConstant(Offset, DstVT)),
6694 DAG.getNode(ISD::ADD, dl, SrcVT, Src,
6695 DAG.getConstant(Offset, SrcVT)),
6696 DAG.getConstant(BytesLeft, SizeVT),
6697 Align, AlwaysInline,
6698 DstSV, DstSVOff + Offset,
6699 SrcSV, SrcSVOff + Offset));
6702 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6703 &Results[0], Results.size());
6706 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
6707 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6708 DebugLoc dl = Op.getDebugLoc();
6710 if (!Subtarget->is64Bit()) {
6711 // vastart just stores the address of the VarArgsFrameIndex slot into the
6712 // memory location argument.
6713 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6714 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0,
6719 // gp_offset (0 - 6 * 8)
6720 // fp_offset (48 - 48 + 8 * 16)
6721 // overflow_arg_area (point to parameters coming in memory).
6723 SmallVector<SDValue, 8> MemOps;
6724 SDValue FIN = Op.getOperand(1);
6726 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6727 DAG.getConstant(VarArgsGPOffset, MVT::i32),
6728 FIN, SV, 0, false, false, 0);
6729 MemOps.push_back(Store);
6732 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6733 FIN, DAG.getIntPtrConstant(4));
6734 Store = DAG.getStore(Op.getOperand(0), dl,
6735 DAG.getConstant(VarArgsFPOffset, MVT::i32),
6736 FIN, SV, 0, false, false, 0);
6737 MemOps.push_back(Store);
6739 // Store ptr to overflow_arg_area
6740 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6741 FIN, DAG.getIntPtrConstant(4));
6742 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6743 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0,
6745 MemOps.push_back(Store);
6747 // Store ptr to reg_save_area.
6748 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6749 FIN, DAG.getIntPtrConstant(8));
6750 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
6751 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0,
6753 MemOps.push_back(Store);
6754 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6755 &MemOps[0], MemOps.size());
6758 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
6759 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6760 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6761 SDValue Chain = Op.getOperand(0);
6762 SDValue SrcPtr = Op.getOperand(1);
6763 SDValue SrcSV = Op.getOperand(2);
6765 llvm_report_error("VAArgInst is not yet implemented for x86-64!");
6769 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
6770 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6771 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6772 SDValue Chain = Op.getOperand(0);
6773 SDValue DstPtr = Op.getOperand(1);
6774 SDValue SrcPtr = Op.getOperand(2);
6775 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6776 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6777 DebugLoc dl = Op.getDebugLoc();
6779 return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6780 DAG.getIntPtrConstant(24), 8, false,
6781 DstSV, 0, SrcSV, 0);
6785 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
6786 DebugLoc dl = Op.getDebugLoc();
6787 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6789 default: return SDValue(); // Don't custom lower most intrinsics.
6790 // Comparison intrinsics.
6791 case Intrinsic::x86_sse_comieq_ss:
6792 case Intrinsic::x86_sse_comilt_ss:
6793 case Intrinsic::x86_sse_comile_ss:
6794 case Intrinsic::x86_sse_comigt_ss:
6795 case Intrinsic::x86_sse_comige_ss:
6796 case Intrinsic::x86_sse_comineq_ss:
6797 case Intrinsic::x86_sse_ucomieq_ss:
6798 case Intrinsic::x86_sse_ucomilt_ss:
6799 case Intrinsic::x86_sse_ucomile_ss:
6800 case Intrinsic::x86_sse_ucomigt_ss:
6801 case Intrinsic::x86_sse_ucomige_ss:
6802 case Intrinsic::x86_sse_ucomineq_ss:
6803 case Intrinsic::x86_sse2_comieq_sd:
6804 case Intrinsic::x86_sse2_comilt_sd:
6805 case Intrinsic::x86_sse2_comile_sd:
6806 case Intrinsic::x86_sse2_comigt_sd:
6807 case Intrinsic::x86_sse2_comige_sd:
6808 case Intrinsic::x86_sse2_comineq_sd:
6809 case Intrinsic::x86_sse2_ucomieq_sd:
6810 case Intrinsic::x86_sse2_ucomilt_sd:
6811 case Intrinsic::x86_sse2_ucomile_sd:
6812 case Intrinsic::x86_sse2_ucomigt_sd:
6813 case Intrinsic::x86_sse2_ucomige_sd:
6814 case Intrinsic::x86_sse2_ucomineq_sd: {
6816 ISD::CondCode CC = ISD::SETCC_INVALID;
6819 case Intrinsic::x86_sse_comieq_ss:
6820 case Intrinsic::x86_sse2_comieq_sd:
6824 case Intrinsic::x86_sse_comilt_ss:
6825 case Intrinsic::x86_sse2_comilt_sd:
6829 case Intrinsic::x86_sse_comile_ss:
6830 case Intrinsic::x86_sse2_comile_sd:
6834 case Intrinsic::x86_sse_comigt_ss:
6835 case Intrinsic::x86_sse2_comigt_sd:
6839 case Intrinsic::x86_sse_comige_ss:
6840 case Intrinsic::x86_sse2_comige_sd:
6844 case Intrinsic::x86_sse_comineq_ss:
6845 case Intrinsic::x86_sse2_comineq_sd:
6849 case Intrinsic::x86_sse_ucomieq_ss:
6850 case Intrinsic::x86_sse2_ucomieq_sd:
6851 Opc = X86ISD::UCOMI;
6854 case Intrinsic::x86_sse_ucomilt_ss:
6855 case Intrinsic::x86_sse2_ucomilt_sd:
6856 Opc = X86ISD::UCOMI;
6859 case Intrinsic::x86_sse_ucomile_ss:
6860 case Intrinsic::x86_sse2_ucomile_sd:
6861 Opc = X86ISD::UCOMI;
6864 case Intrinsic::x86_sse_ucomigt_ss:
6865 case Intrinsic::x86_sse2_ucomigt_sd:
6866 Opc = X86ISD::UCOMI;
6869 case Intrinsic::x86_sse_ucomige_ss:
6870 case Intrinsic::x86_sse2_ucomige_sd:
6871 Opc = X86ISD::UCOMI;
6874 case Intrinsic::x86_sse_ucomineq_ss:
6875 case Intrinsic::x86_sse2_ucomineq_sd:
6876 Opc = X86ISD::UCOMI;
6881 SDValue LHS = Op.getOperand(1);
6882 SDValue RHS = Op.getOperand(2);
6883 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6884 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
6885 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6886 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6887 DAG.getConstant(X86CC, MVT::i8), Cond);
6888 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6890 // ptest intrinsics. The intrinsic these come from are designed to return
6891 // an integer value, not just an instruction so lower it to the ptest
6892 // pattern and a setcc for the result.
6893 case Intrinsic::x86_sse41_ptestz:
6894 case Intrinsic::x86_sse41_ptestc:
6895 case Intrinsic::x86_sse41_ptestnzc:{
6898 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
6899 case Intrinsic::x86_sse41_ptestz:
6901 X86CC = X86::COND_E;
6903 case Intrinsic::x86_sse41_ptestc:
6905 X86CC = X86::COND_B;
6907 case Intrinsic::x86_sse41_ptestnzc:
6909 X86CC = X86::COND_A;
6913 SDValue LHS = Op.getOperand(1);
6914 SDValue RHS = Op.getOperand(2);
6915 SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
6916 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
6917 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
6918 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6921 // Fix vector shift instructions where the last operand is a non-immediate
6923 case Intrinsic::x86_sse2_pslli_w:
6924 case Intrinsic::x86_sse2_pslli_d:
6925 case Intrinsic::x86_sse2_pslli_q:
6926 case Intrinsic::x86_sse2_psrli_w:
6927 case Intrinsic::x86_sse2_psrli_d:
6928 case Intrinsic::x86_sse2_psrli_q:
6929 case Intrinsic::x86_sse2_psrai_w:
6930 case Intrinsic::x86_sse2_psrai_d:
6931 case Intrinsic::x86_mmx_pslli_w:
6932 case Intrinsic::x86_mmx_pslli_d:
6933 case Intrinsic::x86_mmx_pslli_q:
6934 case Intrinsic::x86_mmx_psrli_w:
6935 case Intrinsic::x86_mmx_psrli_d:
6936 case Intrinsic::x86_mmx_psrli_q:
6937 case Intrinsic::x86_mmx_psrai_w:
6938 case Intrinsic::x86_mmx_psrai_d: {
6939 SDValue ShAmt = Op.getOperand(2);
6940 if (isa<ConstantSDNode>(ShAmt))
6943 unsigned NewIntNo = 0;
6944 EVT ShAmtVT = MVT::v4i32;
6946 case Intrinsic::x86_sse2_pslli_w:
6947 NewIntNo = Intrinsic::x86_sse2_psll_w;
6949 case Intrinsic::x86_sse2_pslli_d:
6950 NewIntNo = Intrinsic::x86_sse2_psll_d;
6952 case Intrinsic::x86_sse2_pslli_q:
6953 NewIntNo = Intrinsic::x86_sse2_psll_q;
6955 case Intrinsic::x86_sse2_psrli_w:
6956 NewIntNo = Intrinsic::x86_sse2_psrl_w;
6958 case Intrinsic::x86_sse2_psrli_d:
6959 NewIntNo = Intrinsic::x86_sse2_psrl_d;
6961 case Intrinsic::x86_sse2_psrli_q:
6962 NewIntNo = Intrinsic::x86_sse2_psrl_q;
6964 case Intrinsic::x86_sse2_psrai_w:
6965 NewIntNo = Intrinsic::x86_sse2_psra_w;
6967 case Intrinsic::x86_sse2_psrai_d:
6968 NewIntNo = Intrinsic::x86_sse2_psra_d;
6971 ShAmtVT = MVT::v2i32;
6973 case Intrinsic::x86_mmx_pslli_w:
6974 NewIntNo = Intrinsic::x86_mmx_psll_w;
6976 case Intrinsic::x86_mmx_pslli_d:
6977 NewIntNo = Intrinsic::x86_mmx_psll_d;
6979 case Intrinsic::x86_mmx_pslli_q:
6980 NewIntNo = Intrinsic::x86_mmx_psll_q;
6982 case Intrinsic::x86_mmx_psrli_w:
6983 NewIntNo = Intrinsic::x86_mmx_psrl_w;
6985 case Intrinsic::x86_mmx_psrli_d:
6986 NewIntNo = Intrinsic::x86_mmx_psrl_d;
6988 case Intrinsic::x86_mmx_psrli_q:
6989 NewIntNo = Intrinsic::x86_mmx_psrl_q;
6991 case Intrinsic::x86_mmx_psrai_w:
6992 NewIntNo = Intrinsic::x86_mmx_psra_w;
6994 case Intrinsic::x86_mmx_psrai_d:
6995 NewIntNo = Intrinsic::x86_mmx_psra_d;
6997 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7003 // The vector shift intrinsics with scalars uses 32b shift amounts but
7004 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
7008 ShOps[1] = DAG.getConstant(0, MVT::i32);
7009 if (ShAmtVT == MVT::v4i32) {
7010 ShOps[2] = DAG.getUNDEF(MVT::i32);
7011 ShOps[3] = DAG.getUNDEF(MVT::i32);
7012 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
7014 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
7017 EVT VT = Op.getValueType();
7018 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
7019 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7020 DAG.getConstant(NewIntNo, MVT::i32),
7021 Op.getOperand(1), ShAmt);
7026 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
7027 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7028 DebugLoc dl = Op.getDebugLoc();
7031 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7033 DAG.getConstant(TD->getPointerSize(),
7034 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
7035 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7036 DAG.getNode(ISD::ADD, dl, getPointerTy(),
7038 NULL, 0, false, false, 0);
7041 // Just load the return address.
7042 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
7043 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7044 RetAddrFI, NULL, 0, false, false, 0);
7047 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
7048 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7049 MFI->setFrameAddressIsTaken(true);
7050 EVT VT = Op.getValueType();
7051 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
7052 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7053 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
7054 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
7056 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0,
7061 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
7062 SelectionDAG &DAG) {
7063 return DAG.getIntPtrConstant(2*TD->getPointerSize());
7066 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
7068 MachineFunction &MF = DAG.getMachineFunction();
7069 SDValue Chain = Op.getOperand(0);
7070 SDValue Offset = Op.getOperand(1);
7071 SDValue Handler = Op.getOperand(2);
7072 DebugLoc dl = Op.getDebugLoc();
7074 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
7076 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
7078 SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
7079 DAG.getIntPtrConstant(-TD->getPointerSize()));
7080 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
7081 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0, false, false, 0);
7082 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
7083 MF.getRegInfo().addLiveOut(StoreAddrReg);
7085 return DAG.getNode(X86ISD::EH_RETURN, dl,
7087 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
7090 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
7091 SelectionDAG &DAG) {
7092 SDValue Root = Op.getOperand(0);
7093 SDValue Trmp = Op.getOperand(1); // trampoline
7094 SDValue FPtr = Op.getOperand(2); // nested function
7095 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
7096 DebugLoc dl = Op.getDebugLoc();
7098 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7100 if (Subtarget->is64Bit()) {
7101 SDValue OutChains[6];
7103 // Large code-model.
7104 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
7105 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
7107 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
7108 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
7110 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
7112 // Load the pointer to the nested function into R11.
7113 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
7114 SDValue Addr = Trmp;
7115 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7116 Addr, TrmpAddr, 0, false, false, 0);
7118 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7119 DAG.getConstant(2, MVT::i64));
7120 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2,
7123 // Load the 'nest' parameter value into R10.
7124 // R10 is specified in X86CallingConv.td
7125 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
7126 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7127 DAG.getConstant(10, MVT::i64));
7128 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7129 Addr, TrmpAddr, 10, false, false, 0);
7131 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7132 DAG.getConstant(12, MVT::i64));
7133 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12,
7136 // Jump to the nested function.
7137 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
7138 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7139 DAG.getConstant(20, MVT::i64));
7140 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7141 Addr, TrmpAddr, 20, false, false, 0);
7143 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
7144 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7145 DAG.getConstant(22, MVT::i64));
7146 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
7147 TrmpAddr, 22, false, false, 0);
7150 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
7151 return DAG.getMergeValues(Ops, 2, dl);
7153 const Function *Func =
7154 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
7155 CallingConv::ID CC = Func->getCallingConv();
7160 llvm_unreachable("Unsupported calling convention");
7161 case CallingConv::C:
7162 case CallingConv::X86_StdCall: {
7163 // Pass 'nest' parameter in ECX.
7164 // Must be kept in sync with X86CallingConv.td
7167 // Check that ECX wasn't needed by an 'inreg' parameter.
7168 const FunctionType *FTy = Func->getFunctionType();
7169 const AttrListPtr &Attrs = Func->getAttributes();
7171 if (!Attrs.isEmpty() && !Func->isVarArg()) {
7172 unsigned InRegCount = 0;
7175 for (FunctionType::param_iterator I = FTy->param_begin(),
7176 E = FTy->param_end(); I != E; ++I, ++Idx)
7177 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
7178 // FIXME: should only count parameters that are lowered to integers.
7179 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
7181 if (InRegCount > 2) {
7182 llvm_report_error("Nest register in use - reduce number of inreg parameters!");
7187 case CallingConv::X86_FastCall:
7188 case CallingConv::Fast:
7189 // Pass 'nest' parameter in EAX.
7190 // Must be kept in sync with X86CallingConv.td
7195 SDValue OutChains[4];
7198 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7199 DAG.getConstant(10, MVT::i32));
7200 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
7202 // This is storing the opcode for MOV32ri.
7203 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
7204 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
7205 OutChains[0] = DAG.getStore(Root, dl,
7206 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
7207 Trmp, TrmpAddr, 0, false, false, 0);
7209 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7210 DAG.getConstant(1, MVT::i32));
7211 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1,
7214 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
7215 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7216 DAG.getConstant(5, MVT::i32));
7217 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
7218 TrmpAddr, 5, false, false, 1);
7220 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7221 DAG.getConstant(6, MVT::i32));
7222 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6,
7226 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
7227 return DAG.getMergeValues(Ops, 2, dl);
7231 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
7233 The rounding mode is in bits 11:10 of FPSR, and has the following
7240 FLT_ROUNDS, on the other hand, expects the following:
7247 To perform the conversion, we do:
7248 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
7251 MachineFunction &MF = DAG.getMachineFunction();
7252 const TargetMachine &TM = MF.getTarget();
7253 const TargetFrameInfo &TFI = *TM.getFrameInfo();
7254 unsigned StackAlignment = TFI.getStackAlignment();
7255 EVT VT = Op.getValueType();
7256 DebugLoc dl = Op.getDebugLoc();
7258 // Save FP Control Word to stack slot
7259 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
7260 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7262 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
7263 DAG.getEntryNode(), StackSlot);
7265 // Load FP Control Word from stack slot
7266 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0,
7269 // Transform as necessary
7271 DAG.getNode(ISD::SRL, dl, MVT::i16,
7272 DAG.getNode(ISD::AND, dl, MVT::i16,
7273 CWD, DAG.getConstant(0x800, MVT::i16)),
7274 DAG.getConstant(11, MVT::i8));
7276 DAG.getNode(ISD::SRL, dl, MVT::i16,
7277 DAG.getNode(ISD::AND, dl, MVT::i16,
7278 CWD, DAG.getConstant(0x400, MVT::i16)),
7279 DAG.getConstant(9, MVT::i8));
7282 DAG.getNode(ISD::AND, dl, MVT::i16,
7283 DAG.getNode(ISD::ADD, dl, MVT::i16,
7284 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
7285 DAG.getConstant(1, MVT::i16)),
7286 DAG.getConstant(3, MVT::i16));
7289 return DAG.getNode((VT.getSizeInBits() < 16 ?
7290 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7293 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
7294 EVT VT = Op.getValueType();
7296 unsigned NumBits = VT.getSizeInBits();
7297 DebugLoc dl = Op.getDebugLoc();
7299 Op = Op.getOperand(0);
7300 if (VT == MVT::i8) {
7301 // Zero extend to i32 since there is not an i8 bsr.
7303 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7306 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
7307 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7308 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
7310 // If src is zero (i.e. bsr sets ZF), returns NumBits.
7313 DAG.getConstant(NumBits+NumBits-1, OpVT),
7314 DAG.getConstant(X86::COND_E, MVT::i8),
7317 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7319 // Finally xor with NumBits-1.
7320 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
7323 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7327 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
7328 EVT VT = Op.getValueType();
7330 unsigned NumBits = VT.getSizeInBits();
7331 DebugLoc dl = Op.getDebugLoc();
7333 Op = Op.getOperand(0);
7334 if (VT == MVT::i8) {
7336 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7339 // Issue a bsf (scan bits forward) which also sets EFLAGS.
7340 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7341 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
7343 // If src is zero (i.e. bsf sets ZF), returns NumBits.
7346 DAG.getConstant(NumBits, OpVT),
7347 DAG.getConstant(X86::COND_E, MVT::i8),
7350 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7353 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7357 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
7358 EVT VT = Op.getValueType();
7359 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
7360 DebugLoc dl = Op.getDebugLoc();
7362 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
7363 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
7364 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
7365 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
7366 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
7368 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
7369 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
7370 // return AloBlo + AloBhi + AhiBlo;
7372 SDValue A = Op.getOperand(0);
7373 SDValue B = Op.getOperand(1);
7375 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7376 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7377 A, DAG.getConstant(32, MVT::i32));
7378 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7379 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7380 B, DAG.getConstant(32, MVT::i32));
7381 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7382 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7384 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7385 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7387 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7388 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7390 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7391 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7392 AloBhi, DAG.getConstant(32, MVT::i32));
7393 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7394 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7395 AhiBlo, DAG.getConstant(32, MVT::i32));
7396 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
7397 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
7402 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
7403 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
7404 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
7405 // looks for this combo and may remove the "setcc" instruction if the "setcc"
7406 // has only one use.
7407 SDNode *N = Op.getNode();
7408 SDValue LHS = N->getOperand(0);
7409 SDValue RHS = N->getOperand(1);
7410 unsigned BaseOp = 0;
7412 DebugLoc dl = Op.getDebugLoc();
7414 switch (Op.getOpcode()) {
7415 default: llvm_unreachable("Unknown ovf instruction!");
7417 // A subtract of one will be selected as a INC. Note that INC doesn't
7418 // set CF, so we can't do this for UADDO.
7419 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7420 if (C->getAPIntValue() == 1) {
7421 BaseOp = X86ISD::INC;
7425 BaseOp = X86ISD::ADD;
7429 BaseOp = X86ISD::ADD;
7433 // A subtract of one will be selected as a DEC. Note that DEC doesn't
7434 // set CF, so we can't do this for USUBO.
7435 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7436 if (C->getAPIntValue() == 1) {
7437 BaseOp = X86ISD::DEC;
7441 BaseOp = X86ISD::SUB;
7445 BaseOp = X86ISD::SUB;
7449 BaseOp = X86ISD::SMUL;
7453 BaseOp = X86ISD::UMUL;
7458 // Also sets EFLAGS.
7459 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
7460 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
7463 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
7464 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
7466 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
7470 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
7471 EVT T = Op.getValueType();
7472 DebugLoc dl = Op.getDebugLoc();
7475 switch(T.getSimpleVT().SimpleTy) {
7477 assert(false && "Invalid value type!");
7478 case MVT::i8: Reg = X86::AL; size = 1; break;
7479 case MVT::i16: Reg = X86::AX; size = 2; break;
7480 case MVT::i32: Reg = X86::EAX; size = 4; break;
7482 assert(Subtarget->is64Bit() && "Node not type legal!");
7483 Reg = X86::RAX; size = 8;
7486 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
7487 Op.getOperand(2), SDValue());
7488 SDValue Ops[] = { cpIn.getValue(0),
7491 DAG.getTargetConstant(size, MVT::i8),
7493 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7494 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
7496 DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
7500 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
7501 SelectionDAG &DAG) {
7502 assert(Subtarget->is64Bit() && "Result not type legalized?");
7503 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7504 SDValue TheChain = Op.getOperand(0);
7505 DebugLoc dl = Op.getDebugLoc();
7506 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7507 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
7508 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
7510 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
7511 DAG.getConstant(32, MVT::i8));
7513 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
7516 return DAG.getMergeValues(Ops, 2, dl);
7519 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
7520 SDNode *Node = Op.getNode();
7521 DebugLoc dl = Node->getDebugLoc();
7522 EVT T = Node->getValueType(0);
7523 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
7524 DAG.getConstant(0, T), Node->getOperand(2));
7525 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
7526 cast<AtomicSDNode>(Node)->getMemoryVT(),
7527 Node->getOperand(0),
7528 Node->getOperand(1), negOp,
7529 cast<AtomicSDNode>(Node)->getSrcValue(),
7530 cast<AtomicSDNode>(Node)->getAlignment());
7533 /// LowerOperation - Provide custom lowering hooks for some operations.
7535 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
7536 switch (Op.getOpcode()) {
7537 default: llvm_unreachable("Should not custom lower this!");
7538 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
7539 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
7540 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
7541 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
7542 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7543 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7544 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7545 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
7546 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
7547 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
7548 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7549 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
7550 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
7551 case ISD::SHL_PARTS:
7552 case ISD::SRA_PARTS:
7553 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
7554 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
7555 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
7556 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
7557 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
7558 case ISD::FABS: return LowerFABS(Op, DAG);
7559 case ISD::FNEG: return LowerFNEG(Op, DAG);
7560 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
7561 case ISD::SETCC: return LowerSETCC(Op, DAG);
7562 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
7563 case ISD::SELECT: return LowerSELECT(Op, DAG);
7564 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
7565 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
7566 case ISD::VASTART: return LowerVASTART(Op, DAG);
7567 case ISD::VAARG: return LowerVAARG(Op, DAG);
7568 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
7569 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7570 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
7571 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
7572 case ISD::FRAME_TO_ARGS_OFFSET:
7573 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
7574 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
7575 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
7576 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
7577 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
7578 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
7579 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
7580 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
7586 case ISD::UMULO: return LowerXALUO(Op, DAG);
7587 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
7591 void X86TargetLowering::
7592 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
7593 SelectionDAG &DAG, unsigned NewOp) {
7594 EVT T = Node->getValueType(0);
7595 DebugLoc dl = Node->getDebugLoc();
7596 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
7598 SDValue Chain = Node->getOperand(0);
7599 SDValue In1 = Node->getOperand(1);
7600 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7601 Node->getOperand(2), DAG.getIntPtrConstant(0));
7602 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7603 Node->getOperand(2), DAG.getIntPtrConstant(1));
7604 SDValue Ops[] = { Chain, In1, In2L, In2H };
7605 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7607 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
7608 cast<MemSDNode>(Node)->getMemOperand());
7609 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7610 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7611 Results.push_back(Result.getValue(2));
7614 /// ReplaceNodeResults - Replace a node with an illegal result type
7615 /// with a new node built out of custom code.
7616 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7617 SmallVectorImpl<SDValue>&Results,
7618 SelectionDAG &DAG) {
7619 DebugLoc dl = N->getDebugLoc();
7620 switch (N->getOpcode()) {
7622 assert(false && "Do not know how to custom type legalize this operation!");
7624 case ISD::FP_TO_SINT: {
7625 std::pair<SDValue,SDValue> Vals =
7626 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
7627 SDValue FIST = Vals.first, StackSlot = Vals.second;
7628 if (FIST.getNode() != 0) {
7629 EVT VT = N->getValueType(0);
7630 // Return a load from the stack slot.
7631 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0,
7636 case ISD::READCYCLECOUNTER: {
7637 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7638 SDValue TheChain = N->getOperand(0);
7639 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7640 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7642 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7644 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7645 SDValue Ops[] = { eax, edx };
7646 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7647 Results.push_back(edx.getValue(1));
7650 case ISD::ATOMIC_CMP_SWAP: {
7651 EVT T = N->getValueType(0);
7652 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7653 SDValue cpInL, cpInH;
7654 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7655 DAG.getConstant(0, MVT::i32));
7656 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7657 DAG.getConstant(1, MVT::i32));
7658 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7659 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7661 SDValue swapInL, swapInH;
7662 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7663 DAG.getConstant(0, MVT::i32));
7664 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7665 DAG.getConstant(1, MVT::i32));
7666 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7668 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7669 swapInL.getValue(1));
7670 SDValue Ops[] = { swapInH.getValue(0),
7672 swapInH.getValue(1) };
7673 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7674 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7675 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7676 MVT::i32, Result.getValue(1));
7677 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7678 MVT::i32, cpOutL.getValue(2));
7679 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7680 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7681 Results.push_back(cpOutH.getValue(1));
7684 case ISD::ATOMIC_LOAD_ADD:
7685 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7687 case ISD::ATOMIC_LOAD_AND:
7688 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7690 case ISD::ATOMIC_LOAD_NAND:
7691 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7693 case ISD::ATOMIC_LOAD_OR:
7694 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7696 case ISD::ATOMIC_LOAD_SUB:
7697 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7699 case ISD::ATOMIC_LOAD_XOR:
7700 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7702 case ISD::ATOMIC_SWAP:
7703 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7708 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7710 default: return NULL;
7711 case X86ISD::BSF: return "X86ISD::BSF";
7712 case X86ISD::BSR: return "X86ISD::BSR";
7713 case X86ISD::SHLD: return "X86ISD::SHLD";
7714 case X86ISD::SHRD: return "X86ISD::SHRD";
7715 case X86ISD::FAND: return "X86ISD::FAND";
7716 case X86ISD::FOR: return "X86ISD::FOR";
7717 case X86ISD::FXOR: return "X86ISD::FXOR";
7718 case X86ISD::FSRL: return "X86ISD::FSRL";
7719 case X86ISD::FILD: return "X86ISD::FILD";
7720 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
7721 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7722 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7723 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7724 case X86ISD::FLD: return "X86ISD::FLD";
7725 case X86ISD::FST: return "X86ISD::FST";
7726 case X86ISD::CALL: return "X86ISD::CALL";
7727 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
7728 case X86ISD::BT: return "X86ISD::BT";
7729 case X86ISD::CMP: return "X86ISD::CMP";
7730 case X86ISD::COMI: return "X86ISD::COMI";
7731 case X86ISD::UCOMI: return "X86ISD::UCOMI";
7732 case X86ISD::SETCC: return "X86ISD::SETCC";
7733 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
7734 case X86ISD::CMOV: return "X86ISD::CMOV";
7735 case X86ISD::BRCOND: return "X86ISD::BRCOND";
7736 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
7737 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
7738 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
7739 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
7740 case X86ISD::Wrapper: return "X86ISD::Wrapper";
7741 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
7742 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
7743 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
7744 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
7745 case X86ISD::PINSRB: return "X86ISD::PINSRB";
7746 case X86ISD::PINSRW: return "X86ISD::PINSRW";
7747 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
7748 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
7749 case X86ISD::FMAX: return "X86ISD::FMAX";
7750 case X86ISD::FMIN: return "X86ISD::FMIN";
7751 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
7752 case X86ISD::FRCP: return "X86ISD::FRCP";
7753 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
7754 case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7755 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
7756 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
7757 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
7758 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
7759 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
7760 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
7761 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
7762 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
7763 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
7764 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
7765 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
7766 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
7767 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
7768 case X86ISD::VSHL: return "X86ISD::VSHL";
7769 case X86ISD::VSRL: return "X86ISD::VSRL";
7770 case X86ISD::CMPPD: return "X86ISD::CMPPD";
7771 case X86ISD::CMPPS: return "X86ISD::CMPPS";
7772 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
7773 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
7774 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
7775 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
7776 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
7777 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
7778 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
7779 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
7780 case X86ISD::ADD: return "X86ISD::ADD";
7781 case X86ISD::SUB: return "X86ISD::SUB";
7782 case X86ISD::SMUL: return "X86ISD::SMUL";
7783 case X86ISD::UMUL: return "X86ISD::UMUL";
7784 case X86ISD::INC: return "X86ISD::INC";
7785 case X86ISD::DEC: return "X86ISD::DEC";
7786 case X86ISD::OR: return "X86ISD::OR";
7787 case X86ISD::XOR: return "X86ISD::XOR";
7788 case X86ISD::AND: return "X86ISD::AND";
7789 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
7790 case X86ISD::PTEST: return "X86ISD::PTEST";
7791 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
7792 case X86ISD::MINGW_ALLOCA: return "X86ISD::MINGW_ALLOCA";
7796 // isLegalAddressingMode - Return true if the addressing mode represented
7797 // by AM is legal for this target, for a load/store of the specified type.
7798 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7799 const Type *Ty) const {
7800 // X86 supports extremely general addressing modes.
7801 CodeModel::Model M = getTargetMachine().getCodeModel();
7803 // X86 allows a sign-extended 32-bit immediate field as a displacement.
7804 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
7809 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7811 // If a reference to this global requires an extra load, we can't fold it.
7812 if (isGlobalStubReference(GVFlags))
7815 // If BaseGV requires a register for the PIC base, we cannot also have a
7816 // BaseReg specified.
7817 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
7820 // If lower 4G is not available, then we must use rip-relative addressing.
7821 if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
7831 // These scales always work.
7836 // These scales are formed with basereg+scalereg. Only accept if there is
7841 default: // Other stuff never works.
7849 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7850 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7852 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7853 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7854 if (NumBits1 <= NumBits2)
7859 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7860 if (!VT1.isInteger() || !VT2.isInteger())
7862 unsigned NumBits1 = VT1.getSizeInBits();
7863 unsigned NumBits2 = VT2.getSizeInBits();
7864 if (NumBits1 <= NumBits2)
7869 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7870 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7871 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
7874 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7875 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7876 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7879 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
7880 // i16 instructions are longer (0x66 prefix) and potentially slower.
7881 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7884 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7885 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7886 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7887 /// are assumed to be legal.
7889 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
7891 // Only do shuffles on 128-bit vector types for now.
7892 if (VT.getSizeInBits() == 64)
7895 // FIXME: pshufb, blends, shifts.
7896 return (VT.getVectorNumElements() == 2 ||
7897 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7898 isMOVLMask(M, VT) ||
7899 isSHUFPMask(M, VT) ||
7900 isPSHUFDMask(M, VT) ||
7901 isPSHUFHWMask(M, VT) ||
7902 isPSHUFLWMask(M, VT) ||
7903 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
7904 isUNPCKLMask(M, VT) ||
7905 isUNPCKHMask(M, VT) ||
7906 isUNPCKL_v_undef_Mask(M, VT) ||
7907 isUNPCKH_v_undef_Mask(M, VT));
7911 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
7913 unsigned NumElts = VT.getVectorNumElements();
7914 // FIXME: This collection of masks seems suspect.
7917 if (NumElts == 4 && VT.getSizeInBits() == 128) {
7918 return (isMOVLMask(Mask, VT) ||
7919 isCommutedMOVLMask(Mask, VT, true) ||
7920 isSHUFPMask(Mask, VT) ||
7921 isCommutedSHUFPMask(Mask, VT));
7926 //===----------------------------------------------------------------------===//
7927 // X86 Scheduler Hooks
7928 //===----------------------------------------------------------------------===//
7930 // private utility function
7932 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7933 MachineBasicBlock *MBB,
7941 TargetRegisterClass *RC,
7942 bool invSrc) const {
7943 // For the atomic bitwise operator, we generate
7946 // ld t1 = [bitinstr.addr]
7947 // op t2 = t1, [bitinstr.val]
7949 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7951 // fallthrough -->nextMBB
7952 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7953 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7954 MachineFunction::iterator MBBIter = MBB;
7957 /// First build the CFG
7958 MachineFunction *F = MBB->getParent();
7959 MachineBasicBlock *thisMBB = MBB;
7960 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7961 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7962 F->insert(MBBIter, newMBB);
7963 F->insert(MBBIter, nextMBB);
7965 // Move all successors to thisMBB to nextMBB
7966 nextMBB->transferSuccessors(thisMBB);
7968 // Update thisMBB to fall through to newMBB
7969 thisMBB->addSuccessor(newMBB);
7971 // newMBB jumps to itself and fall through to nextMBB
7972 newMBB->addSuccessor(nextMBB);
7973 newMBB->addSuccessor(newMBB);
7975 // Insert instructions into newMBB based on incoming instruction
7976 assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7977 "unexpected number of operands");
7978 DebugLoc dl = bInstr->getDebugLoc();
7979 MachineOperand& destOper = bInstr->getOperand(0);
7980 MachineOperand* argOpers[2 + X86AddrNumOperands];
7981 int numArgs = bInstr->getNumOperands() - 1;
7982 for (int i=0; i < numArgs; ++i)
7983 argOpers[i] = &bInstr->getOperand(i+1);
7985 // x86 address has 4 operands: base, index, scale, and displacement
7986 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7987 int valArgIndx = lastAddrIndx + 1;
7989 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7990 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7991 for (int i=0; i <= lastAddrIndx; ++i)
7992 (*MIB).addOperand(*argOpers[i]);
7994 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7996 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
8001 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8002 assert((argOpers[valArgIndx]->isReg() ||
8003 argOpers[valArgIndx]->isImm()) &&
8005 if (argOpers[valArgIndx]->isReg())
8006 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
8008 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
8010 (*MIB).addOperand(*argOpers[valArgIndx]);
8012 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
8015 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
8016 for (int i=0; i <= lastAddrIndx; ++i)
8017 (*MIB).addOperand(*argOpers[i]);
8019 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8020 (*MIB).setMemRefs(bInstr->memoperands_begin(),
8021 bInstr->memoperands_end());
8023 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
8027 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8029 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
8033 // private utility function: 64 bit atomics on 32 bit host.
8035 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
8036 MachineBasicBlock *MBB,
8041 bool invSrc) const {
8042 // For the atomic bitwise operator, we generate
8043 // thisMBB (instructions are in pairs, except cmpxchg8b)
8044 // ld t1,t2 = [bitinstr.addr]
8046 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
8047 // op t5, t6 <- out1, out2, [bitinstr.val]
8048 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
8049 // mov ECX, EBX <- t5, t6
8050 // mov EAX, EDX <- t1, t2
8051 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
8052 // mov t3, t4 <- EAX, EDX
8054 // result in out1, out2
8055 // fallthrough -->nextMBB
8057 const TargetRegisterClass *RC = X86::GR32RegisterClass;
8058 const unsigned LoadOpc = X86::MOV32rm;
8059 const unsigned copyOpc = X86::MOV32rr;
8060 const unsigned NotOpc = X86::NOT32r;
8061 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8062 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8063 MachineFunction::iterator MBBIter = MBB;
8066 /// First build the CFG
8067 MachineFunction *F = MBB->getParent();
8068 MachineBasicBlock *thisMBB = MBB;
8069 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8070 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8071 F->insert(MBBIter, newMBB);
8072 F->insert(MBBIter, nextMBB);
8074 // Move all successors to thisMBB to nextMBB
8075 nextMBB->transferSuccessors(thisMBB);
8077 // Update thisMBB to fall through to newMBB
8078 thisMBB->addSuccessor(newMBB);
8080 // newMBB jumps to itself and fall through to nextMBB
8081 newMBB->addSuccessor(nextMBB);
8082 newMBB->addSuccessor(newMBB);
8084 DebugLoc dl = bInstr->getDebugLoc();
8085 // Insert instructions into newMBB based on incoming instruction
8086 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
8087 assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
8088 "unexpected number of operands");
8089 MachineOperand& dest1Oper = bInstr->getOperand(0);
8090 MachineOperand& dest2Oper = bInstr->getOperand(1);
8091 MachineOperand* argOpers[2 + X86AddrNumOperands];
8092 for (int i=0; i < 2 + X86AddrNumOperands; ++i)
8093 argOpers[i] = &bInstr->getOperand(i+2);
8095 // x86 address has 5 operands: base, index, scale, displacement, and segment.
8096 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8098 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
8099 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
8100 for (int i=0; i <= lastAddrIndx; ++i)
8101 (*MIB).addOperand(*argOpers[i]);
8102 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8103 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
8104 // add 4 to displacement.
8105 for (int i=0; i <= lastAddrIndx-2; ++i)
8106 (*MIB).addOperand(*argOpers[i]);
8107 MachineOperand newOp3 = *(argOpers[3]);
8109 newOp3.setImm(newOp3.getImm()+4);
8111 newOp3.setOffset(newOp3.getOffset()+4);
8112 (*MIB).addOperand(newOp3);
8113 (*MIB).addOperand(*argOpers[lastAddrIndx]);
8115 // t3/4 are defined later, at the bottom of the loop
8116 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
8117 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
8118 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
8119 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
8120 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
8121 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
8123 // The subsequent operations should be using the destination registers of
8124 //the PHI instructions.
8126 t1 = F->getRegInfo().createVirtualRegister(RC);
8127 t2 = F->getRegInfo().createVirtualRegister(RC);
8128 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
8129 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
8131 t1 = dest1Oper.getReg();
8132 t2 = dest2Oper.getReg();
8135 int valArgIndx = lastAddrIndx + 1;
8136 assert((argOpers[valArgIndx]->isReg() ||
8137 argOpers[valArgIndx]->isImm()) &&
8139 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
8140 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
8141 if (argOpers[valArgIndx]->isReg())
8142 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
8144 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
8145 if (regOpcL != X86::MOV32rr)
8147 (*MIB).addOperand(*argOpers[valArgIndx]);
8148 assert(argOpers[valArgIndx + 1]->isReg() ==
8149 argOpers[valArgIndx]->isReg());
8150 assert(argOpers[valArgIndx + 1]->isImm() ==
8151 argOpers[valArgIndx]->isImm());
8152 if (argOpers[valArgIndx + 1]->isReg())
8153 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
8155 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
8156 if (regOpcH != X86::MOV32rr)
8158 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
8160 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
8162 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
8165 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
8167 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
8170 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
8171 for (int i=0; i <= lastAddrIndx; ++i)
8172 (*MIB).addOperand(*argOpers[i]);
8174 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8175 (*MIB).setMemRefs(bInstr->memoperands_begin(),
8176 bInstr->memoperands_end());
8178 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
8179 MIB.addReg(X86::EAX);
8180 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
8181 MIB.addReg(X86::EDX);
8184 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8186 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
8190 // private utility function
8192 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
8193 MachineBasicBlock *MBB,
8194 unsigned cmovOpc) const {
8195 // For the atomic min/max operator, we generate
8198 // ld t1 = [min/max.addr]
8199 // mov t2 = [min/max.val]
8201 // cmov[cond] t2 = t1
8203 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
8205 // fallthrough -->nextMBB
8207 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8208 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8209 MachineFunction::iterator MBBIter = MBB;
8212 /// First build the CFG
8213 MachineFunction *F = MBB->getParent();
8214 MachineBasicBlock *thisMBB = MBB;
8215 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8216 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8217 F->insert(MBBIter, newMBB);
8218 F->insert(MBBIter, nextMBB);
8220 // Move all successors of thisMBB to nextMBB
8221 nextMBB->transferSuccessors(thisMBB);
8223 // Update thisMBB to fall through to newMBB
8224 thisMBB->addSuccessor(newMBB);
8226 // newMBB jumps to newMBB and fall through to nextMBB
8227 newMBB->addSuccessor(nextMBB);
8228 newMBB->addSuccessor(newMBB);
8230 DebugLoc dl = mInstr->getDebugLoc();
8231 // Insert instructions into newMBB based on incoming instruction
8232 assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
8233 "unexpected number of operands");
8234 MachineOperand& destOper = mInstr->getOperand(0);
8235 MachineOperand* argOpers[2 + X86AddrNumOperands];
8236 int numArgs = mInstr->getNumOperands() - 1;
8237 for (int i=0; i < numArgs; ++i)
8238 argOpers[i] = &mInstr->getOperand(i+1);
8240 // x86 address has 4 operands: base, index, scale, and displacement
8241 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8242 int valArgIndx = lastAddrIndx + 1;
8244 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8245 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
8246 for (int i=0; i <= lastAddrIndx; ++i)
8247 (*MIB).addOperand(*argOpers[i]);
8249 // We only support register and immediate values
8250 assert((argOpers[valArgIndx]->isReg() ||
8251 argOpers[valArgIndx]->isImm()) &&
8254 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8255 if (argOpers[valArgIndx]->isReg())
8256 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8258 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8259 (*MIB).addOperand(*argOpers[valArgIndx]);
8261 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
8264 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
8269 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8270 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
8274 // Cmp and exchange if none has modified the memory location
8275 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
8276 for (int i=0; i <= lastAddrIndx; ++i)
8277 (*MIB).addOperand(*argOpers[i]);
8279 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8280 (*MIB).setMemRefs(mInstr->memoperands_begin(),
8281 mInstr->memoperands_end());
8283 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
8284 MIB.addReg(X86::EAX);
8287 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8289 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
8293 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
8294 // all of this code can be replaced with that in the .td file.
8296 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
8297 unsigned numArgs, bool memArg) const {
8299 MachineFunction *F = BB->getParent();
8300 DebugLoc dl = MI->getDebugLoc();
8301 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8305 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
8307 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
8309 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
8311 for (unsigned i = 0; i < numArgs; ++i) {
8312 MachineOperand &Op = MI->getOperand(i+1);
8314 if (!(Op.isReg() && Op.isImplicit()))
8318 BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
8321 F->DeleteMachineInstr(MI);
8327 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
8329 MachineBasicBlock *MBB) const {
8330 // Emit code to save XMM registers to the stack. The ABI says that the
8331 // number of registers to save is given in %al, so it's theoretically
8332 // possible to do an indirect jump trick to avoid saving all of them,
8333 // however this code takes a simpler approach and just executes all
8334 // of the stores if %al is non-zero. It's less code, and it's probably
8335 // easier on the hardware branch predictor, and stores aren't all that
8336 // expensive anyway.
8338 // Create the new basic blocks. One block contains all the XMM stores,
8339 // and one block is the final destination regardless of whether any
8340 // stores were performed.
8341 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8342 MachineFunction *F = MBB->getParent();
8343 MachineFunction::iterator MBBIter = MBB;
8345 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
8346 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
8347 F->insert(MBBIter, XMMSaveMBB);
8348 F->insert(MBBIter, EndMBB);
8351 // Move any original successors of MBB to the end block.
8352 EndMBB->transferSuccessors(MBB);
8353 // The original block will now fall through to the XMM save block.
8354 MBB->addSuccessor(XMMSaveMBB);
8355 // The XMMSaveMBB will fall through to the end block.
8356 XMMSaveMBB->addSuccessor(EndMBB);
8358 // Now add the instructions.
8359 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8360 DebugLoc DL = MI->getDebugLoc();
8362 unsigned CountReg = MI->getOperand(0).getReg();
8363 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
8364 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
8366 if (!Subtarget->isTargetWin64()) {
8367 // If %al is 0, branch around the XMM save block.
8368 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
8369 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
8370 MBB->addSuccessor(EndMBB);
8373 // In the XMM save block, save all the XMM argument registers.
8374 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
8375 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
8376 MachineMemOperand *MMO =
8377 F->getMachineMemOperand(
8378 PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
8379 MachineMemOperand::MOStore, Offset,
8380 /*Size=*/16, /*Align=*/16);
8381 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
8382 .addFrameIndex(RegSaveFrameIndex)
8383 .addImm(/*Scale=*/1)
8384 .addReg(/*IndexReg=*/0)
8385 .addImm(/*Disp=*/Offset)
8386 .addReg(/*Segment=*/0)
8387 .addReg(MI->getOperand(i).getReg())
8388 .addMemOperand(MMO);
8391 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8397 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
8398 MachineBasicBlock *BB,
8399 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8400 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8401 DebugLoc DL = MI->getDebugLoc();
8403 // To "insert" a SELECT_CC instruction, we actually have to insert the
8404 // diamond control-flow pattern. The incoming instruction knows the
8405 // destination vreg to set, the condition code register to branch on, the
8406 // true/false values to select between, and a branch opcode to use.
8407 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8408 MachineFunction::iterator It = BB;
8414 // cmpTY ccX, r1, r2
8416 // fallthrough --> copy0MBB
8417 MachineBasicBlock *thisMBB = BB;
8418 MachineFunction *F = BB->getParent();
8419 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8420 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8422 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
8423 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
8424 F->insert(It, copy0MBB);
8425 F->insert(It, sinkMBB);
8426 // Update machine-CFG edges by first adding all successors of the current
8427 // block to the new block which will contain the Phi node for the select.
8428 // Also inform sdisel of the edge changes.
8429 for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
8430 E = BB->succ_end(); I != E; ++I) {
8431 EM->insert(std::make_pair(*I, sinkMBB));
8432 sinkMBB->addSuccessor(*I);
8434 // Next, remove all successors of the current block, and add the true
8435 // and fallthrough blocks as its successors.
8436 while (!BB->succ_empty())
8437 BB->removeSuccessor(BB->succ_begin());
8438 // Add the true and fallthrough blocks as its successors.
8439 BB->addSuccessor(copy0MBB);
8440 BB->addSuccessor(sinkMBB);
8443 // %FalseValue = ...
8444 // # fallthrough to sinkMBB
8447 // Update machine-CFG edges
8448 BB->addSuccessor(sinkMBB);
8451 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8454 BuildMI(BB, DL, TII->get(X86::PHI), MI->getOperand(0).getReg())
8455 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8456 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8458 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8463 X86TargetLowering::EmitLoweredMingwAlloca(MachineInstr *MI,
8464 MachineBasicBlock *BB,
8465 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8466 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8467 DebugLoc DL = MI->getDebugLoc();
8468 MachineFunction *F = BB->getParent();
8470 // The lowering is pretty easy: we're just emitting the call to _alloca. The
8471 // non-trivial part is impdef of ESP.
8472 // FIXME: The code should be tweaked as soon as we'll try to do codegen for
8475 BuildMI(BB, DL, TII->get(X86::CALLpcrel32))
8476 .addExternalSymbol("_alloca")
8477 .addReg(X86::EAX, RegState::Implicit)
8478 .addReg(X86::ESP, RegState::Implicit)
8479 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
8480 .addReg(X86::ESP, RegState::Define | RegState::Implicit);
8482 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8487 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8488 MachineBasicBlock *BB,
8489 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8490 switch (MI->getOpcode()) {
8491 default: assert(false && "Unexpected instr type to insert");
8492 case X86::MINGW_ALLOCA:
8493 return EmitLoweredMingwAlloca(MI, BB, EM);
8495 case X86::CMOV_V1I64:
8496 case X86::CMOV_FR32:
8497 case X86::CMOV_FR64:
8498 case X86::CMOV_V4F32:
8499 case X86::CMOV_V2F64:
8500 case X86::CMOV_V2I64:
8501 return EmitLoweredSelect(MI, BB, EM);
8503 case X86::FP32_TO_INT16_IN_MEM:
8504 case X86::FP32_TO_INT32_IN_MEM:
8505 case X86::FP32_TO_INT64_IN_MEM:
8506 case X86::FP64_TO_INT16_IN_MEM:
8507 case X86::FP64_TO_INT32_IN_MEM:
8508 case X86::FP64_TO_INT64_IN_MEM:
8509 case X86::FP80_TO_INT16_IN_MEM:
8510 case X86::FP80_TO_INT32_IN_MEM:
8511 case X86::FP80_TO_INT64_IN_MEM: {
8512 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8513 DebugLoc DL = MI->getDebugLoc();
8515 // Change the floating point control register to use "round towards zero"
8516 // mode when truncating to an integer value.
8517 MachineFunction *F = BB->getParent();
8518 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
8519 addFrameReference(BuildMI(BB, DL, TII->get(X86::FNSTCW16m)), CWFrameIdx);
8521 // Load the old value of the high byte of the control word...
8523 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
8524 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16rm), OldCW),
8527 // Set the high part to be round to zero...
8528 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
8531 // Reload the modified control word now...
8532 addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8534 // Restore the memory image of control word to original value
8535 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
8538 // Get the X86 opcode to use.
8540 switch (MI->getOpcode()) {
8541 default: llvm_unreachable("illegal opcode!");
8542 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
8543 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
8544 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
8545 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
8546 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
8547 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
8548 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
8549 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
8550 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
8554 MachineOperand &Op = MI->getOperand(0);
8556 AM.BaseType = X86AddressMode::RegBase;
8557 AM.Base.Reg = Op.getReg();
8559 AM.BaseType = X86AddressMode::FrameIndexBase;
8560 AM.Base.FrameIndex = Op.getIndex();
8562 Op = MI->getOperand(1);
8564 AM.Scale = Op.getImm();
8565 Op = MI->getOperand(2);
8567 AM.IndexReg = Op.getImm();
8568 Op = MI->getOperand(3);
8569 if (Op.isGlobal()) {
8570 AM.GV = Op.getGlobal();
8572 AM.Disp = Op.getImm();
8574 addFullAddress(BuildMI(BB, DL, TII->get(Opc)), AM)
8575 .addReg(MI->getOperand(X86AddrNumOperands).getReg());
8577 // Reload the original control word now.
8578 addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8580 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8583 // DBG_VALUE. Only the frame index case is done here.
8584 case X86::DBG_VALUE: {
8585 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8586 DebugLoc DL = MI->getDebugLoc();
8588 MachineFunction *F = BB->getParent();
8589 AM.BaseType = X86AddressMode::FrameIndexBase;
8590 AM.Base.FrameIndex = MI->getOperand(0).getImm();
8591 addFullAddress(BuildMI(BB, DL, TII->get(X86::DBG_VALUE)), AM).
8592 addImm(MI->getOperand(1).getImm()).
8593 addMetadata(MI->getOperand(2).getMetadata());
8594 F->DeleteMachineInstr(MI); // Remove pseudo.
8598 // String/text processing lowering.
8599 case X86::PCMPISTRM128REG:
8600 return EmitPCMP(MI, BB, 3, false /* in-mem */);
8601 case X86::PCMPISTRM128MEM:
8602 return EmitPCMP(MI, BB, 3, true /* in-mem */);
8603 case X86::PCMPESTRM128REG:
8604 return EmitPCMP(MI, BB, 5, false /* in mem */);
8605 case X86::PCMPESTRM128MEM:
8606 return EmitPCMP(MI, BB, 5, true /* in mem */);
8609 case X86::ATOMAND32:
8610 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8611 X86::AND32ri, X86::MOV32rm,
8612 X86::LCMPXCHG32, X86::MOV32rr,
8613 X86::NOT32r, X86::EAX,
8614 X86::GR32RegisterClass);
8616 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
8617 X86::OR32ri, X86::MOV32rm,
8618 X86::LCMPXCHG32, X86::MOV32rr,
8619 X86::NOT32r, X86::EAX,
8620 X86::GR32RegisterClass);
8621 case X86::ATOMXOR32:
8622 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
8623 X86::XOR32ri, X86::MOV32rm,
8624 X86::LCMPXCHG32, X86::MOV32rr,
8625 X86::NOT32r, X86::EAX,
8626 X86::GR32RegisterClass);
8627 case X86::ATOMNAND32:
8628 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8629 X86::AND32ri, X86::MOV32rm,
8630 X86::LCMPXCHG32, X86::MOV32rr,
8631 X86::NOT32r, X86::EAX,
8632 X86::GR32RegisterClass, true);
8633 case X86::ATOMMIN32:
8634 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
8635 case X86::ATOMMAX32:
8636 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
8637 case X86::ATOMUMIN32:
8638 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
8639 case X86::ATOMUMAX32:
8640 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
8642 case X86::ATOMAND16:
8643 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8644 X86::AND16ri, X86::MOV16rm,
8645 X86::LCMPXCHG16, X86::MOV16rr,
8646 X86::NOT16r, X86::AX,
8647 X86::GR16RegisterClass);
8649 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
8650 X86::OR16ri, X86::MOV16rm,
8651 X86::LCMPXCHG16, X86::MOV16rr,
8652 X86::NOT16r, X86::AX,
8653 X86::GR16RegisterClass);
8654 case X86::ATOMXOR16:
8655 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
8656 X86::XOR16ri, X86::MOV16rm,
8657 X86::LCMPXCHG16, X86::MOV16rr,
8658 X86::NOT16r, X86::AX,
8659 X86::GR16RegisterClass);
8660 case X86::ATOMNAND16:
8661 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8662 X86::AND16ri, X86::MOV16rm,
8663 X86::LCMPXCHG16, X86::MOV16rr,
8664 X86::NOT16r, X86::AX,
8665 X86::GR16RegisterClass, true);
8666 case X86::ATOMMIN16:
8667 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
8668 case X86::ATOMMAX16:
8669 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
8670 case X86::ATOMUMIN16:
8671 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
8672 case X86::ATOMUMAX16:
8673 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
8676 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8677 X86::AND8ri, X86::MOV8rm,
8678 X86::LCMPXCHG8, X86::MOV8rr,
8679 X86::NOT8r, X86::AL,
8680 X86::GR8RegisterClass);
8682 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
8683 X86::OR8ri, X86::MOV8rm,
8684 X86::LCMPXCHG8, X86::MOV8rr,
8685 X86::NOT8r, X86::AL,
8686 X86::GR8RegisterClass);
8688 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
8689 X86::XOR8ri, X86::MOV8rm,
8690 X86::LCMPXCHG8, X86::MOV8rr,
8691 X86::NOT8r, X86::AL,
8692 X86::GR8RegisterClass);
8693 case X86::ATOMNAND8:
8694 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8695 X86::AND8ri, X86::MOV8rm,
8696 X86::LCMPXCHG8, X86::MOV8rr,
8697 X86::NOT8r, X86::AL,
8698 X86::GR8RegisterClass, true);
8699 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
8700 // This group is for 64-bit host.
8701 case X86::ATOMAND64:
8702 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8703 X86::AND64ri32, X86::MOV64rm,
8704 X86::LCMPXCHG64, X86::MOV64rr,
8705 X86::NOT64r, X86::RAX,
8706 X86::GR64RegisterClass);
8708 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
8709 X86::OR64ri32, X86::MOV64rm,
8710 X86::LCMPXCHG64, X86::MOV64rr,
8711 X86::NOT64r, X86::RAX,
8712 X86::GR64RegisterClass);
8713 case X86::ATOMXOR64:
8714 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
8715 X86::XOR64ri32, X86::MOV64rm,
8716 X86::LCMPXCHG64, X86::MOV64rr,
8717 X86::NOT64r, X86::RAX,
8718 X86::GR64RegisterClass);
8719 case X86::ATOMNAND64:
8720 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8721 X86::AND64ri32, X86::MOV64rm,
8722 X86::LCMPXCHG64, X86::MOV64rr,
8723 X86::NOT64r, X86::RAX,
8724 X86::GR64RegisterClass, true);
8725 case X86::ATOMMIN64:
8726 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
8727 case X86::ATOMMAX64:
8728 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
8729 case X86::ATOMUMIN64:
8730 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
8731 case X86::ATOMUMAX64:
8732 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
8734 // This group does 64-bit operations on a 32-bit host.
8735 case X86::ATOMAND6432:
8736 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8737 X86::AND32rr, X86::AND32rr,
8738 X86::AND32ri, X86::AND32ri,
8740 case X86::ATOMOR6432:
8741 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8742 X86::OR32rr, X86::OR32rr,
8743 X86::OR32ri, X86::OR32ri,
8745 case X86::ATOMXOR6432:
8746 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8747 X86::XOR32rr, X86::XOR32rr,
8748 X86::XOR32ri, X86::XOR32ri,
8750 case X86::ATOMNAND6432:
8751 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8752 X86::AND32rr, X86::AND32rr,
8753 X86::AND32ri, X86::AND32ri,
8755 case X86::ATOMADD6432:
8756 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8757 X86::ADD32rr, X86::ADC32rr,
8758 X86::ADD32ri, X86::ADC32ri,
8760 case X86::ATOMSUB6432:
8761 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8762 X86::SUB32rr, X86::SBB32rr,
8763 X86::SUB32ri, X86::SBB32ri,
8765 case X86::ATOMSWAP6432:
8766 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8767 X86::MOV32rr, X86::MOV32rr,
8768 X86::MOV32ri, X86::MOV32ri,
8770 case X86::VASTART_SAVE_XMM_REGS:
8771 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
8775 //===----------------------------------------------------------------------===//
8776 // X86 Optimization Hooks
8777 //===----------------------------------------------------------------------===//
8779 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8783 const SelectionDAG &DAG,
8784 unsigned Depth) const {
8785 unsigned Opc = Op.getOpcode();
8786 assert((Opc >= ISD::BUILTIN_OP_END ||
8787 Opc == ISD::INTRINSIC_WO_CHAIN ||
8788 Opc == ISD::INTRINSIC_W_CHAIN ||
8789 Opc == ISD::INTRINSIC_VOID) &&
8790 "Should use MaskedValueIsZero if you don't know whether Op"
8791 " is a target node!");
8793 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
8805 // These nodes' second result is a boolean.
8806 if (Op.getResNo() == 0)
8810 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
8811 Mask.getBitWidth() - 1);
8816 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
8817 /// node is a GlobalAddress + offset.
8818 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
8819 GlobalValue* &GA, int64_t &Offset) const{
8820 if (N->getOpcode() == X86ISD::Wrapper) {
8821 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
8822 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
8823 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
8827 return TargetLowering::isGAPlusOffset(N, GA, Offset);
8830 static bool EltsFromConsecutiveLoads(ShuffleVectorSDNode *N, unsigned NumElems,
8831 EVT EltVT, LoadSDNode *&LDBase,
8832 unsigned &LastLoadedElt,
8833 SelectionDAG &DAG, MachineFrameInfo *MFI,
8834 const TargetLowering &TLI) {
8836 LastLoadedElt = -1U;
8837 for (unsigned i = 0; i < NumElems; ++i) {
8838 if (N->getMaskElt(i) < 0) {
8844 SDValue Elt = DAG.getShuffleScalarElt(N, i);
8845 if (!Elt.getNode() ||
8846 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
8849 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
8851 LDBase = cast<LoadSDNode>(Elt.getNode());
8855 if (Elt.getOpcode() == ISD::UNDEF)
8858 LoadSDNode *LD = cast<LoadSDNode>(Elt);
8859 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
8866 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8867 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8868 /// if the load addresses are consecutive, non-overlapping, and in the right
8869 /// order. In the case of v2i64, it will see if it can rewrite the
8870 /// shuffle to be an appropriate build vector so it can take advantage of
8871 // performBuildVectorCombine.
8872 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8873 const TargetLowering &TLI) {
8874 DebugLoc dl = N->getDebugLoc();
8875 EVT VT = N->getValueType(0);
8876 EVT EltVT = VT.getVectorElementType();
8877 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8878 unsigned NumElems = VT.getVectorNumElements();
8880 if (VT.getSizeInBits() != 128)
8883 // Try to combine a vector_shuffle into a 128-bit load.
8884 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8885 LoadSDNode *LD = NULL;
8886 unsigned LastLoadedElt;
8887 if (!EltsFromConsecutiveLoads(SVN, NumElems, EltVT, LD, LastLoadedElt, DAG,
8891 if (LastLoadedElt == NumElems - 1) {
8892 if (DAG.InferPtrAlignment(LD->getBasePtr()) >= 16)
8893 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8894 LD->getSrcValue(), LD->getSrcValueOffset(),
8895 LD->isVolatile(), LD->isNonTemporal(), 0);
8896 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8897 LD->getSrcValue(), LD->getSrcValueOffset(),
8898 LD->isVolatile(), LD->isNonTemporal(),
8899 LD->getAlignment());
8900 } else if (NumElems == 4 && LastLoadedElt == 1) {
8901 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
8902 SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
8903 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
8904 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
8909 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
8910 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
8911 const X86Subtarget *Subtarget) {
8912 DebugLoc DL = N->getDebugLoc();
8913 SDValue Cond = N->getOperand(0);
8914 // Get the LHS/RHS of the select.
8915 SDValue LHS = N->getOperand(1);
8916 SDValue RHS = N->getOperand(2);
8918 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
8919 // instructions match the semantics of the common C idiom x<y?x:y but not
8920 // x<=y?x:y, because of how they handle negative zero (which can be
8921 // ignored in unsafe-math mode).
8922 if (Subtarget->hasSSE2() &&
8923 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
8924 Cond.getOpcode() == ISD::SETCC) {
8925 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
8927 unsigned Opcode = 0;
8928 // Check for x CC y ? x : y.
8929 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
8930 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
8934 // Converting this to a min would handle NaNs incorrectly, and swapping
8935 // the operands would cause it to handle comparisons between positive
8936 // and negative zero incorrectly.
8937 if (!FiniteOnlyFPMath() &&
8938 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
8939 if (!UnsafeFPMath &&
8940 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8942 std::swap(LHS, RHS);
8944 Opcode = X86ISD::FMIN;
8947 // Converting this to a min would handle comparisons between positive
8948 // and negative zero incorrectly.
8949 if (!UnsafeFPMath &&
8950 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
8952 Opcode = X86ISD::FMIN;
8955 // Converting this to a min would handle both negative zeros and NaNs
8956 // incorrectly, but we can swap the operands to fix both.
8957 std::swap(LHS, RHS);
8961 Opcode = X86ISD::FMIN;
8965 // Converting this to a max would handle comparisons between positive
8966 // and negative zero incorrectly.
8967 if (!UnsafeFPMath &&
8968 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
8970 Opcode = X86ISD::FMAX;
8973 // Converting this to a max would handle NaNs incorrectly, and swapping
8974 // the operands would cause it to handle comparisons between positive
8975 // and negative zero incorrectly.
8976 if (!FiniteOnlyFPMath() &&
8977 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
8978 if (!UnsafeFPMath &&
8979 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8981 std::swap(LHS, RHS);
8983 Opcode = X86ISD::FMAX;
8986 // Converting this to a max would handle both negative zeros and NaNs
8987 // incorrectly, but we can swap the operands to fix both.
8988 std::swap(LHS, RHS);
8992 Opcode = X86ISD::FMAX;
8995 // Check for x CC y ? y : x -- a min/max with reversed arms.
8996 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
8997 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
9001 // Converting this to a min would handle comparisons between positive
9002 // and negative zero incorrectly, and swapping the operands would
9003 // cause it to handle NaNs incorrectly.
9004 if (!UnsafeFPMath &&
9005 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
9006 if (!FiniteOnlyFPMath() &&
9007 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9009 std::swap(LHS, RHS);
9011 Opcode = X86ISD::FMIN;
9014 // Converting this to a min would handle NaNs incorrectly.
9015 if (!UnsafeFPMath &&
9016 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9018 Opcode = X86ISD::FMIN;
9021 // Converting this to a min would handle both negative zeros and NaNs
9022 // incorrectly, but we can swap the operands to fix both.
9023 std::swap(LHS, RHS);
9027 Opcode = X86ISD::FMIN;
9031 // Converting this to a max would handle NaNs incorrectly.
9032 if (!FiniteOnlyFPMath() &&
9033 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9035 Opcode = X86ISD::FMAX;
9038 // Converting this to a max would handle comparisons between positive
9039 // and negative zero incorrectly, and swapping the operands would
9040 // cause it to handle NaNs incorrectly.
9041 if (!UnsafeFPMath &&
9042 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
9043 if (!FiniteOnlyFPMath() &&
9044 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9046 std::swap(LHS, RHS);
9048 Opcode = X86ISD::FMAX;
9051 // Converting this to a max would handle both negative zeros and NaNs
9052 // incorrectly, but we can swap the operands to fix both.
9053 std::swap(LHS, RHS);
9057 Opcode = X86ISD::FMAX;
9063 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
9066 // If this is a select between two integer constants, try to do some
9068 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
9069 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
9070 // Don't do this for crazy integer types.
9071 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
9072 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
9073 // so that TrueC (the true value) is larger than FalseC.
9074 bool NeedsCondInvert = false;
9076 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
9077 // Efficiently invertible.
9078 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
9079 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
9080 isa<ConstantSDNode>(Cond.getOperand(1))))) {
9081 NeedsCondInvert = true;
9082 std::swap(TrueC, FalseC);
9085 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
9086 if (FalseC->getAPIntValue() == 0 &&
9087 TrueC->getAPIntValue().isPowerOf2()) {
9088 if (NeedsCondInvert) // Invert the condition if needed.
9089 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9090 DAG.getConstant(1, Cond.getValueType()));
9092 // Zero extend the condition if needed.
9093 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
9095 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9096 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
9097 DAG.getConstant(ShAmt, MVT::i8));
9100 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
9101 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9102 if (NeedsCondInvert) // Invert the condition if needed.
9103 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9104 DAG.getConstant(1, Cond.getValueType()));
9106 // Zero extend the condition if needed.
9107 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9108 FalseC->getValueType(0), Cond);
9109 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9110 SDValue(FalseC, 0));
9113 // Optimize cases that will turn into an LEA instruction. This requires
9114 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9115 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9116 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9117 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9119 bool isFastMultiplier = false;
9121 switch ((unsigned char)Diff) {
9123 case 1: // result = add base, cond
9124 case 2: // result = lea base( , cond*2)
9125 case 3: // result = lea base(cond, cond*2)
9126 case 4: // result = lea base( , cond*4)
9127 case 5: // result = lea base(cond, cond*4)
9128 case 8: // result = lea base( , cond*8)
9129 case 9: // result = lea base(cond, cond*8)
9130 isFastMultiplier = true;
9135 if (isFastMultiplier) {
9136 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9137 if (NeedsCondInvert) // Invert the condition if needed.
9138 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9139 DAG.getConstant(1, Cond.getValueType()));
9141 // Zero extend the condition if needed.
9142 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9144 // Scale the condition by the difference.
9146 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9147 DAG.getConstant(Diff, Cond.getValueType()));
9149 // Add the base if non-zero.
9150 if (FalseC->getAPIntValue() != 0)
9151 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9152 SDValue(FalseC, 0));
9162 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
9163 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
9164 TargetLowering::DAGCombinerInfo &DCI) {
9165 DebugLoc DL = N->getDebugLoc();
9167 // If the flag operand isn't dead, don't touch this CMOV.
9168 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
9171 // If this is a select between two integer constants, try to do some
9172 // optimizations. Note that the operands are ordered the opposite of SELECT
9174 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
9175 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9176 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
9177 // larger than FalseC (the false value).
9178 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
9180 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
9181 CC = X86::GetOppositeBranchCondition(CC);
9182 std::swap(TrueC, FalseC);
9185 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
9186 // This is efficient for any integer data type (including i8/i16) and
9188 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
9189 SDValue Cond = N->getOperand(3);
9190 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9191 DAG.getConstant(CC, MVT::i8), Cond);
9193 // Zero extend the condition if needed.
9194 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
9196 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9197 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
9198 DAG.getConstant(ShAmt, MVT::i8));
9199 if (N->getNumValues() == 2) // Dead flag value?
9200 return DCI.CombineTo(N, Cond, SDValue());
9204 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
9205 // for any integer data type, including i8/i16.
9206 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9207 SDValue Cond = N->getOperand(3);
9208 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9209 DAG.getConstant(CC, MVT::i8), Cond);
9211 // Zero extend the condition if needed.
9212 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9213 FalseC->getValueType(0), Cond);
9214 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9215 SDValue(FalseC, 0));
9217 if (N->getNumValues() == 2) // Dead flag value?
9218 return DCI.CombineTo(N, Cond, SDValue());
9222 // Optimize cases that will turn into an LEA instruction. This requires
9223 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9224 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9225 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9226 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9228 bool isFastMultiplier = false;
9230 switch ((unsigned char)Diff) {
9232 case 1: // result = add base, cond
9233 case 2: // result = lea base( , cond*2)
9234 case 3: // result = lea base(cond, cond*2)
9235 case 4: // result = lea base( , cond*4)
9236 case 5: // result = lea base(cond, cond*4)
9237 case 8: // result = lea base( , cond*8)
9238 case 9: // result = lea base(cond, cond*8)
9239 isFastMultiplier = true;
9244 if (isFastMultiplier) {
9245 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9246 SDValue Cond = N->getOperand(3);
9247 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9248 DAG.getConstant(CC, MVT::i8), Cond);
9249 // Zero extend the condition if needed.
9250 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9252 // Scale the condition by the difference.
9254 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9255 DAG.getConstant(Diff, Cond.getValueType()));
9257 // Add the base if non-zero.
9258 if (FalseC->getAPIntValue() != 0)
9259 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9260 SDValue(FalseC, 0));
9261 if (N->getNumValues() == 2) // Dead flag value?
9262 return DCI.CombineTo(N, Cond, SDValue());
9272 /// PerformMulCombine - Optimize a single multiply with constant into two
9273 /// in order to implement it with two cheaper instructions, e.g.
9274 /// LEA + SHL, LEA + LEA.
9275 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
9276 TargetLowering::DAGCombinerInfo &DCI) {
9277 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9280 EVT VT = N->getValueType(0);
9284 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9287 uint64_t MulAmt = C->getZExtValue();
9288 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
9291 uint64_t MulAmt1 = 0;
9292 uint64_t MulAmt2 = 0;
9293 if ((MulAmt % 9) == 0) {
9295 MulAmt2 = MulAmt / 9;
9296 } else if ((MulAmt % 5) == 0) {
9298 MulAmt2 = MulAmt / 5;
9299 } else if ((MulAmt % 3) == 0) {
9301 MulAmt2 = MulAmt / 3;
9304 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
9305 DebugLoc DL = N->getDebugLoc();
9307 if (isPowerOf2_64(MulAmt2) &&
9308 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
9309 // If second multiplifer is pow2, issue it first. We want the multiply by
9310 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
9312 std::swap(MulAmt1, MulAmt2);
9315 if (isPowerOf2_64(MulAmt1))
9316 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
9317 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
9319 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
9320 DAG.getConstant(MulAmt1, VT));
9322 if (isPowerOf2_64(MulAmt2))
9323 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
9324 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
9326 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
9327 DAG.getConstant(MulAmt2, VT));
9329 // Do not add new nodes to DAG combiner worklist.
9330 DCI.CombineTo(N, NewMul, false);
9335 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
9336 SDValue N0 = N->getOperand(0);
9337 SDValue N1 = N->getOperand(1);
9338 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9339 EVT VT = N0.getValueType();
9341 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
9342 // since the result of setcc_c is all zero's or all ones.
9343 if (N1C && N0.getOpcode() == ISD::AND &&
9344 N0.getOperand(1).getOpcode() == ISD::Constant) {
9345 SDValue N00 = N0.getOperand(0);
9346 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
9347 ((N00.getOpcode() == ISD::ANY_EXTEND ||
9348 N00.getOpcode() == ISD::ZERO_EXTEND) &&
9349 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
9350 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
9351 APInt ShAmt = N1C->getAPIntValue();
9352 Mask = Mask.shl(ShAmt);
9354 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
9355 N00, DAG.getConstant(Mask, VT));
9362 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
9364 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
9365 const X86Subtarget *Subtarget) {
9366 EVT VT = N->getValueType(0);
9367 if (!VT.isVector() && VT.isInteger() &&
9368 N->getOpcode() == ISD::SHL)
9369 return PerformSHLCombine(N, DAG);
9371 // On X86 with SSE2 support, we can transform this to a vector shift if
9372 // all elements are shifted by the same amount. We can't do this in legalize
9373 // because the a constant vector is typically transformed to a constant pool
9374 // so we have no knowledge of the shift amount.
9375 if (!Subtarget->hasSSE2())
9378 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
9381 SDValue ShAmtOp = N->getOperand(1);
9382 EVT EltVT = VT.getVectorElementType();
9383 DebugLoc DL = N->getDebugLoc();
9384 SDValue BaseShAmt = SDValue();
9385 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
9386 unsigned NumElts = VT.getVectorNumElements();
9388 for (; i != NumElts; ++i) {
9389 SDValue Arg = ShAmtOp.getOperand(i);
9390 if (Arg.getOpcode() == ISD::UNDEF) continue;
9394 for (; i != NumElts; ++i) {
9395 SDValue Arg = ShAmtOp.getOperand(i);
9396 if (Arg.getOpcode() == ISD::UNDEF) continue;
9397 if (Arg != BaseShAmt) {
9401 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
9402 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
9403 SDValue InVec = ShAmtOp.getOperand(0);
9404 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
9405 unsigned NumElts = InVec.getValueType().getVectorNumElements();
9407 for (; i != NumElts; ++i) {
9408 SDValue Arg = InVec.getOperand(i);
9409 if (Arg.getOpcode() == ISD::UNDEF) continue;
9413 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
9414 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
9415 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
9416 if (C->getZExtValue() == SplatIdx)
9417 BaseShAmt = InVec.getOperand(1);
9420 if (BaseShAmt.getNode() == 0)
9421 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
9422 DAG.getIntPtrConstant(0));
9426 // The shift amount is an i32.
9427 if (EltVT.bitsGT(MVT::i32))
9428 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
9429 else if (EltVT.bitsLT(MVT::i32))
9430 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
9432 // The shift amount is identical so we can do a vector shift.
9433 SDValue ValOp = N->getOperand(0);
9434 switch (N->getOpcode()) {
9436 llvm_unreachable("Unknown shift opcode!");
9439 if (VT == MVT::v2i64)
9440 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9441 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9443 if (VT == MVT::v4i32)
9444 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9445 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9447 if (VT == MVT::v8i16)
9448 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9449 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9453 if (VT == MVT::v4i32)
9454 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9455 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9457 if (VT == MVT::v8i16)
9458 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9459 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9463 if (VT == MVT::v2i64)
9464 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9465 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9467 if (VT == MVT::v4i32)
9468 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9469 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9471 if (VT == MVT::v8i16)
9472 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9473 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9480 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
9481 const X86Subtarget *Subtarget) {
9482 EVT VT = N->getValueType(0);
9483 if (VT != MVT::i64 || !Subtarget->is64Bit())
9486 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
9487 SDValue N0 = N->getOperand(0);
9488 SDValue N1 = N->getOperand(1);
9489 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
9491 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
9494 SDValue ShAmt0 = N0.getOperand(1);
9495 if (ShAmt0.getValueType() != MVT::i8)
9497 SDValue ShAmt1 = N1.getOperand(1);
9498 if (ShAmt1.getValueType() != MVT::i8)
9500 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
9501 ShAmt0 = ShAmt0.getOperand(0);
9502 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
9503 ShAmt1 = ShAmt1.getOperand(0);
9505 DebugLoc DL = N->getDebugLoc();
9506 unsigned Opc = X86ISD::SHLD;
9507 SDValue Op0 = N0.getOperand(0);
9508 SDValue Op1 = N1.getOperand(0);
9509 if (ShAmt0.getOpcode() == ISD::SUB) {
9511 std::swap(Op0, Op1);
9512 std::swap(ShAmt0, ShAmt1);
9515 if (ShAmt1.getOpcode() == ISD::SUB) {
9516 SDValue Sum = ShAmt1.getOperand(0);
9517 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
9518 if (SumC->getSExtValue() == 64 &&
9519 ShAmt1.getOperand(1) == ShAmt0)
9520 return DAG.getNode(Opc, DL, VT,
9522 DAG.getNode(ISD::TRUNCATE, DL,
9525 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
9526 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
9528 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == 64)
9529 return DAG.getNode(Opc, DL, VT,
9530 N0.getOperand(0), N1.getOperand(0),
9531 DAG.getNode(ISD::TRUNCATE, DL,
9538 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
9539 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
9540 const X86Subtarget *Subtarget) {
9541 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
9542 // the FP state in cases where an emms may be missing.
9543 // A preferable solution to the general problem is to figure out the right
9544 // places to insert EMMS. This qualifies as a quick hack.
9546 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
9547 StoreSDNode *St = cast<StoreSDNode>(N);
9548 EVT VT = St->getValue().getValueType();
9549 if (VT.getSizeInBits() != 64)
9552 const Function *F = DAG.getMachineFunction().getFunction();
9553 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
9554 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
9555 && Subtarget->hasSSE2();
9556 if ((VT.isVector() ||
9557 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
9558 isa<LoadSDNode>(St->getValue()) &&
9559 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
9560 St->getChain().hasOneUse() && !St->isVolatile()) {
9561 SDNode* LdVal = St->getValue().getNode();
9563 int TokenFactorIndex = -1;
9564 SmallVector<SDValue, 8> Ops;
9565 SDNode* ChainVal = St->getChain().getNode();
9566 // Must be a store of a load. We currently handle two cases: the load
9567 // is a direct child, and it's under an intervening TokenFactor. It is
9568 // possible to dig deeper under nested TokenFactors.
9569 if (ChainVal == LdVal)
9570 Ld = cast<LoadSDNode>(St->getChain());
9571 else if (St->getValue().hasOneUse() &&
9572 ChainVal->getOpcode() == ISD::TokenFactor) {
9573 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
9574 if (ChainVal->getOperand(i).getNode() == LdVal) {
9575 TokenFactorIndex = i;
9576 Ld = cast<LoadSDNode>(St->getValue());
9578 Ops.push_back(ChainVal->getOperand(i));
9582 if (!Ld || !ISD::isNormalLoad(Ld))
9585 // If this is not the MMX case, i.e. we are just turning i64 load/store
9586 // into f64 load/store, avoid the transformation if there are multiple
9587 // uses of the loaded value.
9588 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
9591 DebugLoc LdDL = Ld->getDebugLoc();
9592 DebugLoc StDL = N->getDebugLoc();
9593 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
9594 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
9596 if (Subtarget->is64Bit() || F64IsLegal) {
9597 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
9598 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
9599 Ld->getBasePtr(), Ld->getSrcValue(),
9600 Ld->getSrcValueOffset(), Ld->isVolatile(),
9601 Ld->isNonTemporal(), Ld->getAlignment());
9602 SDValue NewChain = NewLd.getValue(1);
9603 if (TokenFactorIndex != -1) {
9604 Ops.push_back(NewChain);
9605 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9608 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
9609 St->getSrcValue(), St->getSrcValueOffset(),
9610 St->isVolatile(), St->isNonTemporal(),
9611 St->getAlignment());
9614 // Otherwise, lower to two pairs of 32-bit loads / stores.
9615 SDValue LoAddr = Ld->getBasePtr();
9616 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
9617 DAG.getConstant(4, MVT::i32));
9619 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
9620 Ld->getSrcValue(), Ld->getSrcValueOffset(),
9621 Ld->isVolatile(), Ld->isNonTemporal(),
9622 Ld->getAlignment());
9623 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
9624 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
9625 Ld->isVolatile(), Ld->isNonTemporal(),
9626 MinAlign(Ld->getAlignment(), 4));
9628 SDValue NewChain = LoLd.getValue(1);
9629 if (TokenFactorIndex != -1) {
9630 Ops.push_back(LoLd);
9631 Ops.push_back(HiLd);
9632 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9636 LoAddr = St->getBasePtr();
9637 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
9638 DAG.getConstant(4, MVT::i32));
9640 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
9641 St->getSrcValue(), St->getSrcValueOffset(),
9642 St->isVolatile(), St->isNonTemporal(),
9643 St->getAlignment());
9644 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
9646 St->getSrcValueOffset() + 4,
9648 St->isNonTemporal(),
9649 MinAlign(St->getAlignment(), 4));
9650 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
9655 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
9656 /// X86ISD::FXOR nodes.
9657 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
9658 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
9659 // F[X]OR(0.0, x) -> x
9660 // F[X]OR(x, 0.0) -> x
9661 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9662 if (C->getValueAPF().isPosZero())
9663 return N->getOperand(1);
9664 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9665 if (C->getValueAPF().isPosZero())
9666 return N->getOperand(0);
9670 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
9671 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
9672 // FAND(0.0, x) -> 0.0
9673 // FAND(x, 0.0) -> 0.0
9674 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9675 if (C->getValueAPF().isPosZero())
9676 return N->getOperand(0);
9677 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9678 if (C->getValueAPF().isPosZero())
9679 return N->getOperand(1);
9683 static SDValue PerformBTCombine(SDNode *N,
9685 TargetLowering::DAGCombinerInfo &DCI) {
9686 // BT ignores high bits in the bit index operand.
9687 SDValue Op1 = N->getOperand(1);
9688 if (Op1.hasOneUse()) {
9689 unsigned BitWidth = Op1.getValueSizeInBits();
9690 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
9691 APInt KnownZero, KnownOne;
9692 TargetLowering::TargetLoweringOpt TLO(DAG);
9693 TargetLowering &TLI = DAG.getTargetLoweringInfo();
9694 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
9695 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
9696 DCI.CommitTargetLoweringOpt(TLO);
9701 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
9702 SDValue Op = N->getOperand(0);
9703 if (Op.getOpcode() == ISD::BIT_CONVERT)
9704 Op = Op.getOperand(0);
9705 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
9706 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
9707 VT.getVectorElementType().getSizeInBits() ==
9708 OpVT.getVectorElementType().getSizeInBits()) {
9709 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
9714 // On X86 and X86-64, atomic operations are lowered to locked instructions.
9715 // Locked instructions, in turn, have implicit fence semantics (all memory
9716 // operations are flushed before issuing the locked instruction, and the
9717 // are not buffered), so we can fold away the common pattern of
9718 // fence-atomic-fence.
9719 static SDValue PerformMEMBARRIERCombine(SDNode* N, SelectionDAG &DAG) {
9720 SDValue atomic = N->getOperand(0);
9721 switch (atomic.getOpcode()) {
9722 case ISD::ATOMIC_CMP_SWAP:
9723 case ISD::ATOMIC_SWAP:
9724 case ISD::ATOMIC_LOAD_ADD:
9725 case ISD::ATOMIC_LOAD_SUB:
9726 case ISD::ATOMIC_LOAD_AND:
9727 case ISD::ATOMIC_LOAD_OR:
9728 case ISD::ATOMIC_LOAD_XOR:
9729 case ISD::ATOMIC_LOAD_NAND:
9730 case ISD::ATOMIC_LOAD_MIN:
9731 case ISD::ATOMIC_LOAD_MAX:
9732 case ISD::ATOMIC_LOAD_UMIN:
9733 case ISD::ATOMIC_LOAD_UMAX:
9739 SDValue fence = atomic.getOperand(0);
9740 if (fence.getOpcode() != ISD::MEMBARRIER)
9743 switch (atomic.getOpcode()) {
9744 case ISD::ATOMIC_CMP_SWAP:
9745 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9746 atomic.getOperand(1), atomic.getOperand(2),
9747 atomic.getOperand(3));
9748 case ISD::ATOMIC_SWAP:
9749 case ISD::ATOMIC_LOAD_ADD:
9750 case ISD::ATOMIC_LOAD_SUB:
9751 case ISD::ATOMIC_LOAD_AND:
9752 case ISD::ATOMIC_LOAD_OR:
9753 case ISD::ATOMIC_LOAD_XOR:
9754 case ISD::ATOMIC_LOAD_NAND:
9755 case ISD::ATOMIC_LOAD_MIN:
9756 case ISD::ATOMIC_LOAD_MAX:
9757 case ISD::ATOMIC_LOAD_UMIN:
9758 case ISD::ATOMIC_LOAD_UMAX:
9759 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9760 atomic.getOperand(1), atomic.getOperand(2));
9766 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
9767 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
9768 // (and (i32 x86isd::setcc_carry), 1)
9769 // This eliminates the zext. This transformation is necessary because
9770 // ISD::SETCC is always legalized to i8.
9771 DebugLoc dl = N->getDebugLoc();
9772 SDValue N0 = N->getOperand(0);
9773 EVT VT = N->getValueType(0);
9774 if (N0.getOpcode() == ISD::AND &&
9776 N0.getOperand(0).hasOneUse()) {
9777 SDValue N00 = N0.getOperand(0);
9778 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
9780 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9781 if (!C || C->getZExtValue() != 1)
9783 return DAG.getNode(ISD::AND, dl, VT,
9784 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
9785 N00.getOperand(0), N00.getOperand(1)),
9786 DAG.getConstant(1, VT));
9792 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
9793 DAGCombinerInfo &DCI) const {
9794 SelectionDAG &DAG = DCI.DAG;
9795 switch (N->getOpcode()) {
9797 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
9798 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
9799 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
9800 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
9803 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
9804 case ISD::OR: return PerformOrCombine(N, DAG, Subtarget);
9805 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
9807 case X86ISD::FOR: return PerformFORCombine(N, DAG);
9808 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
9809 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
9810 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
9811 case ISD::MEMBARRIER: return PerformMEMBARRIERCombine(N, DAG);
9812 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
9818 //===----------------------------------------------------------------------===//
9819 // X86 Inline Assembly Support
9820 //===----------------------------------------------------------------------===//
9822 static bool LowerToBSwap(CallInst *CI) {
9823 // FIXME: this should verify that we are targetting a 486 or better. If not,
9824 // we will turn this bswap into something that will be lowered to logical ops
9825 // instead of emitting the bswap asm. For now, we don't support 486 or lower
9826 // so don't worry about this.
9828 // Verify this is a simple bswap.
9829 if (CI->getNumOperands() != 2 ||
9830 CI->getType() != CI->getOperand(1)->getType() ||
9831 !CI->getType()->isIntegerTy())
9834 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9835 if (!Ty || Ty->getBitWidth() % 16 != 0)
9838 // Okay, we can do this xform, do so now.
9839 const Type *Tys[] = { Ty };
9840 Module *M = CI->getParent()->getParent()->getParent();
9841 Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
9843 Value *Op = CI->getOperand(1);
9844 Op = CallInst::Create(Int, Op, CI->getName(), CI);
9846 CI->replaceAllUsesWith(Op);
9847 CI->eraseFromParent();
9851 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
9852 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9853 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
9855 std::string AsmStr = IA->getAsmString();
9857 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
9858 SmallVector<StringRef, 4> AsmPieces;
9859 SplitString(AsmStr, AsmPieces, "\n"); // ; as separator?
9861 switch (AsmPieces.size()) {
9862 default: return false;
9864 AsmStr = AsmPieces[0];
9866 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
9869 if (AsmPieces.size() == 2 &&
9870 (AsmPieces[0] == "bswap" ||
9871 AsmPieces[0] == "bswapq" ||
9872 AsmPieces[0] == "bswapl") &&
9873 (AsmPieces[1] == "$0" ||
9874 AsmPieces[1] == "${0:q}")) {
9875 // No need to check constraints, nothing other than the equivalent of
9876 // "=r,0" would be valid here.
9877 return LowerToBSwap(CI);
9879 // rorw $$8, ${0:w} --> llvm.bswap.i16
9880 if (CI->getType()->isIntegerTy(16) &&
9881 AsmPieces.size() == 3 &&
9882 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
9883 AsmPieces[1] == "$$8," &&
9884 AsmPieces[2] == "${0:w}" &&
9885 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
9887 const std::string &Constraints = IA->getConstraintString();
9888 SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
9889 std::sort(AsmPieces.begin(), AsmPieces.end());
9890 if (AsmPieces.size() == 4 &&
9891 AsmPieces[0] == "~{cc}" &&
9892 AsmPieces[1] == "~{dirflag}" &&
9893 AsmPieces[2] == "~{flags}" &&
9894 AsmPieces[3] == "~{fpsr}") {
9895 return LowerToBSwap(CI);
9900 if (CI->getType()->isIntegerTy(64) &&
9901 Constraints.size() >= 2 &&
9902 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
9903 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
9904 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
9905 SmallVector<StringRef, 4> Words;
9906 SplitString(AsmPieces[0], Words, " \t");
9907 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
9909 SplitString(AsmPieces[1], Words, " \t");
9910 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
9912 SplitString(AsmPieces[2], Words, " \t,");
9913 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
9914 Words[2] == "%edx") {
9915 return LowerToBSwap(CI);
9927 /// getConstraintType - Given a constraint letter, return the type of
9928 /// constraint it is for this target.
9929 X86TargetLowering::ConstraintType
9930 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
9931 if (Constraint.size() == 1) {
9932 switch (Constraint[0]) {
9944 return C_RegisterClass;
9952 return TargetLowering::getConstraintType(Constraint);
9955 /// LowerXConstraint - try to replace an X constraint, which matches anything,
9956 /// with another that has more specific requirements based on the type of the
9957 /// corresponding operand.
9958 const char *X86TargetLowering::
9959 LowerXConstraint(EVT ConstraintVT) const {
9960 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
9961 // 'f' like normal targets.
9962 if (ConstraintVT.isFloatingPoint()) {
9963 if (Subtarget->hasSSE2())
9965 if (Subtarget->hasSSE1())
9969 return TargetLowering::LowerXConstraint(ConstraintVT);
9972 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9973 /// vector. If it is invalid, don't add anything to Ops.
9974 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9977 std::vector<SDValue>&Ops,
9978 SelectionDAG &DAG) const {
9979 SDValue Result(0, 0);
9981 switch (Constraint) {
9984 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9985 if (C->getZExtValue() <= 31) {
9986 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9992 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9993 if (C->getZExtValue() <= 63) {
9994 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10000 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10001 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
10002 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10008 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10009 if (C->getZExtValue() <= 255) {
10010 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10016 // 32-bit signed value
10017 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10018 const ConstantInt *CI = C->getConstantIntValue();
10019 if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10020 C->getSExtValue())) {
10021 // Widen to 64 bits here to get it sign extended.
10022 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
10025 // FIXME gcc accepts some relocatable values here too, but only in certain
10026 // memory models; it's complicated.
10031 // 32-bit unsigned value
10032 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10033 const ConstantInt *CI = C->getConstantIntValue();
10034 if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10035 C->getZExtValue())) {
10036 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10040 // FIXME gcc accepts some relocatable values here too, but only in certain
10041 // memory models; it's complicated.
10045 // Literal immediates are always ok.
10046 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
10047 // Widen to 64 bits here to get it sign extended.
10048 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
10052 // If we are in non-pic codegen mode, we allow the address of a global (with
10053 // an optional displacement) to be used with 'i'.
10054 GlobalAddressSDNode *GA = 0;
10055 int64_t Offset = 0;
10057 // Match either (GA), (GA+C), (GA+C1+C2), etc.
10059 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
10060 Offset += GA->getOffset();
10062 } else if (Op.getOpcode() == ISD::ADD) {
10063 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10064 Offset += C->getZExtValue();
10065 Op = Op.getOperand(0);
10068 } else if (Op.getOpcode() == ISD::SUB) {
10069 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10070 Offset += -C->getZExtValue();
10071 Op = Op.getOperand(0);
10076 // Otherwise, this isn't something we can handle, reject it.
10080 GlobalValue *GV = GA->getGlobal();
10081 // If we require an extra load to get this address, as in PIC mode, we
10082 // can't accept it.
10083 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
10084 getTargetMachine())))
10088 Op = LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
10090 Op = DAG.getTargetGlobalAddress(GV, GA->getValueType(0), Offset);
10096 if (Result.getNode()) {
10097 Ops.push_back(Result);
10100 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
10104 std::vector<unsigned> X86TargetLowering::
10105 getRegClassForInlineAsmConstraint(const std::string &Constraint,
10107 if (Constraint.size() == 1) {
10108 // FIXME: not handling fp-stack yet!
10109 switch (Constraint[0]) { // GCC X86 Constraint Letters
10110 default: break; // Unknown constraint letter
10111 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
10112 if (Subtarget->is64Bit()) {
10113 if (VT == MVT::i32)
10114 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
10115 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
10116 X86::R10D,X86::R11D,X86::R12D,
10117 X86::R13D,X86::R14D,X86::R15D,
10118 X86::EBP, X86::ESP, 0);
10119 else if (VT == MVT::i16)
10120 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
10121 X86::SI, X86::DI, X86::R8W,X86::R9W,
10122 X86::R10W,X86::R11W,X86::R12W,
10123 X86::R13W,X86::R14W,X86::R15W,
10124 X86::BP, X86::SP, 0);
10125 else if (VT == MVT::i8)
10126 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
10127 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
10128 X86::R10B,X86::R11B,X86::R12B,
10129 X86::R13B,X86::R14B,X86::R15B,
10130 X86::BPL, X86::SPL, 0);
10132 else if (VT == MVT::i64)
10133 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
10134 X86::RSI, X86::RDI, X86::R8, X86::R9,
10135 X86::R10, X86::R11, X86::R12,
10136 X86::R13, X86::R14, X86::R15,
10137 X86::RBP, X86::RSP, 0);
10141 // 32-bit fallthrough
10142 case 'Q': // Q_REGS
10143 if (VT == MVT::i32)
10144 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
10145 else if (VT == MVT::i16)
10146 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
10147 else if (VT == MVT::i8)
10148 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
10149 else if (VT == MVT::i64)
10150 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
10155 return std::vector<unsigned>();
10158 std::pair<unsigned, const TargetRegisterClass*>
10159 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10161 // First, see if this is a constraint that directly corresponds to an LLVM
10163 if (Constraint.size() == 1) {
10164 // GCC Constraint Letters
10165 switch (Constraint[0]) {
10167 case 'r': // GENERAL_REGS
10168 case 'l': // INDEX_REGS
10170 return std::make_pair(0U, X86::GR8RegisterClass);
10171 if (VT == MVT::i16)
10172 return std::make_pair(0U, X86::GR16RegisterClass);
10173 if (VT == MVT::i32 || !Subtarget->is64Bit())
10174 return std::make_pair(0U, X86::GR32RegisterClass);
10175 return std::make_pair(0U, X86::GR64RegisterClass);
10176 case 'R': // LEGACY_REGS
10178 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
10179 if (VT == MVT::i16)
10180 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
10181 if (VT == MVT::i32 || !Subtarget->is64Bit())
10182 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
10183 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
10184 case 'f': // FP Stack registers.
10185 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
10186 // value to the correct fpstack register class.
10187 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
10188 return std::make_pair(0U, X86::RFP32RegisterClass);
10189 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
10190 return std::make_pair(0U, X86::RFP64RegisterClass);
10191 return std::make_pair(0U, X86::RFP80RegisterClass);
10192 case 'y': // MMX_REGS if MMX allowed.
10193 if (!Subtarget->hasMMX()) break;
10194 return std::make_pair(0U, X86::VR64RegisterClass);
10195 case 'Y': // SSE_REGS if SSE2 allowed
10196 if (!Subtarget->hasSSE2()) break;
10198 case 'x': // SSE_REGS if SSE1 allowed
10199 if (!Subtarget->hasSSE1()) break;
10201 switch (VT.getSimpleVT().SimpleTy) {
10203 // Scalar SSE types.
10206 return std::make_pair(0U, X86::FR32RegisterClass);
10209 return std::make_pair(0U, X86::FR64RegisterClass);
10217 return std::make_pair(0U, X86::VR128RegisterClass);
10223 // Use the default implementation in TargetLowering to convert the register
10224 // constraint into a member of a register class.
10225 std::pair<unsigned, const TargetRegisterClass*> Res;
10226 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10228 // Not found as a standard register?
10229 if (Res.second == 0) {
10230 // Map st(0) -> st(7) -> ST0
10231 if (Constraint.size() == 7 && Constraint[0] == '{' &&
10232 tolower(Constraint[1]) == 's' &&
10233 tolower(Constraint[2]) == 't' &&
10234 Constraint[3] == '(' &&
10235 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
10236 Constraint[5] == ')' &&
10237 Constraint[6] == '}') {
10239 Res.first = X86::ST0+Constraint[4]-'0';
10240 Res.second = X86::RFP80RegisterClass;
10244 // GCC allows "st(0)" to be called just plain "st".
10245 if (StringRef("{st}").equals_lower(Constraint)) {
10246 Res.first = X86::ST0;
10247 Res.second = X86::RFP80RegisterClass;
10252 if (StringRef("{flags}").equals_lower(Constraint)) {
10253 Res.first = X86::EFLAGS;
10254 Res.second = X86::CCRRegisterClass;
10258 // 'A' means EAX + EDX.
10259 if (Constraint == "A") {
10260 Res.first = X86::EAX;
10261 Res.second = X86::GR32_ADRegisterClass;
10267 // Otherwise, check to see if this is a register class of the wrong value
10268 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
10269 // turn into {ax},{dx}.
10270 if (Res.second->hasType(VT))
10271 return Res; // Correct type already, nothing to do.
10273 // All of the single-register GCC register classes map their values onto
10274 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
10275 // really want an 8-bit or 32-bit register, map to the appropriate register
10276 // class and return the appropriate register.
10277 if (Res.second == X86::GR16RegisterClass) {
10278 if (VT == MVT::i8) {
10279 unsigned DestReg = 0;
10280 switch (Res.first) {
10282 case X86::AX: DestReg = X86::AL; break;
10283 case X86::DX: DestReg = X86::DL; break;
10284 case X86::CX: DestReg = X86::CL; break;
10285 case X86::BX: DestReg = X86::BL; break;
10288 Res.first = DestReg;
10289 Res.second = X86::GR8RegisterClass;
10291 } else if (VT == MVT::i32) {
10292 unsigned DestReg = 0;
10293 switch (Res.first) {
10295 case X86::AX: DestReg = X86::EAX; break;
10296 case X86::DX: DestReg = X86::EDX; break;
10297 case X86::CX: DestReg = X86::ECX; break;
10298 case X86::BX: DestReg = X86::EBX; break;
10299 case X86::SI: DestReg = X86::ESI; break;
10300 case X86::DI: DestReg = X86::EDI; break;
10301 case X86::BP: DestReg = X86::EBP; break;
10302 case X86::SP: DestReg = X86::ESP; break;
10305 Res.first = DestReg;
10306 Res.second = X86::GR32RegisterClass;
10308 } else if (VT == MVT::i64) {
10309 unsigned DestReg = 0;
10310 switch (Res.first) {
10312 case X86::AX: DestReg = X86::RAX; break;
10313 case X86::DX: DestReg = X86::RDX; break;
10314 case X86::CX: DestReg = X86::RCX; break;
10315 case X86::BX: DestReg = X86::RBX; break;
10316 case X86::SI: DestReg = X86::RSI; break;
10317 case X86::DI: DestReg = X86::RDI; break;
10318 case X86::BP: DestReg = X86::RBP; break;
10319 case X86::SP: DestReg = X86::RSP; break;
10322 Res.first = DestReg;
10323 Res.second = X86::GR64RegisterClass;
10326 } else if (Res.second == X86::FR32RegisterClass ||
10327 Res.second == X86::FR64RegisterClass ||
10328 Res.second == X86::VR128RegisterClass) {
10329 // Handle references to XMM physical registers that got mapped into the
10330 // wrong class. This can happen with constraints like {xmm0} where the
10331 // target independent register mapper will just pick the first match it can
10332 // find, ignoring the required type.
10333 if (VT == MVT::f32)
10334 Res.second = X86::FR32RegisterClass;
10335 else if (VT == MVT::f64)
10336 Res.second = X86::FR64RegisterClass;
10337 else if (X86::VR128RegisterClass->hasType(VT))
10338 Res.second = X86::VR128RegisterClass;