1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "x86-isel"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/GlobalAlias.h"
25 #include "llvm/GlobalVariable.h"
26 #include "llvm/Function.h"
27 #include "llvm/Instructions.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/LLVMContext.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/PseudoSourceValue.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/MC/MCContext.h"
39 #include "llvm/MC/MCExpr.h"
40 #include "llvm/MC/MCSymbol.h"
41 #include "llvm/ADT/BitVector.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/ADT/VectorExtras.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/Dwarf.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Support/raw_ostream.h"
53 using namespace dwarf;
55 STATISTIC(NumTailCalls, "Number of tail calls");
58 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
60 // Disable16Bit - 16-bit operations typically have a larger encoding than
61 // corresponding 32-bit instructions, and 16-bit code is slow on some
62 // processors. This is an experimental flag to disable 16-bit operations
63 // (which forces them to be Legalized to 32-bit operations).
65 Disable16Bit("disable-16bit", cl::Hidden,
66 cl::desc("Disable use of 16-bit instructions"));
68 // Forward declarations.
69 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
72 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
73 switch (TM.getSubtarget<X86Subtarget>().TargetType) {
74 default: llvm_unreachable("unknown subtarget type");
75 case X86Subtarget::isDarwin:
76 if (TM.getSubtarget<X86Subtarget>().is64Bit())
77 return new X8664_MachoTargetObjectFile();
78 return new TargetLoweringObjectFileMachO();
79 case X86Subtarget::isELF:
80 if (TM.getSubtarget<X86Subtarget>().is64Bit())
81 return new X8664_ELFTargetObjectFile(TM);
82 return new X8632_ELFTargetObjectFile(TM);
83 case X86Subtarget::isMingw:
84 case X86Subtarget::isCygwin:
85 case X86Subtarget::isWindows:
86 return new TargetLoweringObjectFileCOFF();
90 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
91 : TargetLowering(TM, createTLOF(TM)) {
92 Subtarget = &TM.getSubtarget<X86Subtarget>();
93 X86ScalarSSEf64 = Subtarget->hasSSE2();
94 X86ScalarSSEf32 = Subtarget->hasSSE1();
95 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
97 RegInfo = TM.getRegisterInfo();
100 // Set up the TargetLowering object.
102 // X86 is weird, it always uses i8 for shift amounts and setcc results.
103 setShiftAmountType(MVT::i8);
104 setBooleanContents(ZeroOrOneBooleanContent);
105 setSchedulingPreference(SchedulingForRegPressure);
106 setStackPointerRegisterToSaveRestore(X86StackPtr);
108 if (Subtarget->isTargetDarwin()) {
109 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
110 setUseUnderscoreSetJmp(false);
111 setUseUnderscoreLongJmp(false);
112 } else if (Subtarget->isTargetMingw()) {
113 // MS runtime is weird: it exports _setjmp, but longjmp!
114 setUseUnderscoreSetJmp(true);
115 setUseUnderscoreLongJmp(false);
117 setUseUnderscoreSetJmp(true);
118 setUseUnderscoreLongJmp(true);
121 // Set up the register classes.
122 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
124 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
125 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
126 if (Subtarget->is64Bit())
127 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
129 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
131 // We don't accept any truncstore of integer registers.
132 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
134 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
135 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
137 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
138 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
139 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
141 // SETOEQ and SETUNE require checking two conditions.
142 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
143 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
144 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
145 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
146 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
147 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
149 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
151 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
152 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
153 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
155 if (Subtarget->is64Bit()) {
156 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
157 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
158 } else if (!UseSoftFloat) {
159 if (X86ScalarSSEf64) {
160 // We have an impenetrably clever algorithm for ui64->double only.
161 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
163 // We have an algorithm for SSE2, and we turn this into a 64-bit
164 // FILD for other targets.
165 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
168 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
170 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
171 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
174 // SSE has no i16 to fp conversion, only i32
175 if (X86ScalarSSEf32) {
176 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
177 // f32 and f64 cases are Legal, f80 case is not
178 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
180 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
181 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
184 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
185 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
188 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
189 // are Legal, f80 is custom lowered.
190 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
191 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
193 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
195 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
196 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
198 if (X86ScalarSSEf32) {
199 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
200 // f32 and f64 cases are Legal, f80 case is not
201 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
203 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
204 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
207 // Handle FP_TO_UINT by promoting the destination to a larger signed
209 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
210 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
211 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
213 if (Subtarget->is64Bit()) {
214 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
215 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
216 } else if (!UseSoftFloat) {
217 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
218 // Expand FP_TO_UINT into a select.
219 // FIXME: We would like to use a Custom expander here eventually to do
220 // the optimal thing for SSE vs. the default expansion in the legalizer.
221 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
223 // With SSE3 we can use fisttpll to convert to a signed i64; without
224 // SSE, we're stuck with a fistpll.
225 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
228 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
229 if (!X86ScalarSSEf64) {
230 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
231 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
234 // Scalar integer divide and remainder are lowered to use operations that
235 // produce two results, to match the available instructions. This exposes
236 // the two-result form to trivial CSE, which is able to combine x/y and x%y
237 // into a single instruction.
239 // Scalar integer multiply-high is also lowered to use two-result
240 // operations, to match the available instructions. However, plain multiply
241 // (low) operations are left as Legal, as there are single-result
242 // instructions for this in x86. Using the two-result multiply instructions
243 // when both high and low results are needed must be arranged by dagcombine.
244 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
245 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
246 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
247 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
248 setOperationAction(ISD::SREM , MVT::i8 , Expand);
249 setOperationAction(ISD::UREM , MVT::i8 , Expand);
250 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
251 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
252 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
253 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
254 setOperationAction(ISD::SREM , MVT::i16 , Expand);
255 setOperationAction(ISD::UREM , MVT::i16 , Expand);
256 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
257 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
258 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
259 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
260 setOperationAction(ISD::SREM , MVT::i32 , Expand);
261 setOperationAction(ISD::UREM , MVT::i32 , Expand);
262 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
263 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
264 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
265 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
266 setOperationAction(ISD::SREM , MVT::i64 , Expand);
267 setOperationAction(ISD::UREM , MVT::i64 , Expand);
269 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
270 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
271 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
272 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
273 if (Subtarget->is64Bit())
274 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
275 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
276 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
277 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
278 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
279 setOperationAction(ISD::FREM , MVT::f32 , Expand);
280 setOperationAction(ISD::FREM , MVT::f64 , Expand);
281 setOperationAction(ISD::FREM , MVT::f80 , Expand);
282 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
284 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
285 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
286 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
287 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
289 setOperationAction(ISD::CTTZ , MVT::i16 , Expand);
290 setOperationAction(ISD::CTLZ , MVT::i16 , Expand);
292 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
293 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
295 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
296 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
297 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
298 if (Subtarget->is64Bit()) {
299 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
300 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
301 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
304 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
305 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
307 // These should be promoted to a larger select which is supported.
308 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
309 // X86 wants to expand cmov itself.
310 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
312 setOperationAction(ISD::SELECT , MVT::i16 , Expand);
314 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
315 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
316 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
317 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
318 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
319 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
321 setOperationAction(ISD::SETCC , MVT::i16 , Expand);
323 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
324 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
325 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
326 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
327 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
328 if (Subtarget->is64Bit()) {
329 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
330 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
332 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
335 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
336 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
337 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
338 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
339 if (Subtarget->is64Bit())
340 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
341 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
342 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
343 if (Subtarget->is64Bit()) {
344 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
345 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
346 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
347 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
348 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
350 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
351 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
352 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
353 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
354 if (Subtarget->is64Bit()) {
355 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
356 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
357 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
360 if (Subtarget->hasSSE1())
361 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
363 if (!Subtarget->hasSSE2())
364 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
366 // Expand certain atomics
367 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
368 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
369 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
370 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
372 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
373 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
374 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
375 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
377 if (!Subtarget->is64Bit()) {
378 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
379 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
380 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
381 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
382 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
383 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
384 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
387 // FIXME - use subtarget debug flags
388 if (!Subtarget->isTargetDarwin() &&
389 !Subtarget->isTargetELF() &&
390 !Subtarget->isTargetCygMing()) {
391 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
394 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
395 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
396 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
397 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
398 if (Subtarget->is64Bit()) {
399 setExceptionPointerRegister(X86::RAX);
400 setExceptionSelectorRegister(X86::RDX);
402 setExceptionPointerRegister(X86::EAX);
403 setExceptionSelectorRegister(X86::EDX);
405 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
406 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
408 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
410 setOperationAction(ISD::TRAP, MVT::Other, Legal);
412 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
413 setOperationAction(ISD::VASTART , MVT::Other, Custom);
414 setOperationAction(ISD::VAEND , MVT::Other, Expand);
415 if (Subtarget->is64Bit()) {
416 setOperationAction(ISD::VAARG , MVT::Other, Custom);
417 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
419 setOperationAction(ISD::VAARG , MVT::Other, Expand);
420 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
423 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
424 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
425 if (Subtarget->is64Bit())
426 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
427 if (Subtarget->isTargetCygMing())
428 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
430 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
432 if (!UseSoftFloat && X86ScalarSSEf64) {
433 // f32 and f64 use SSE.
434 // Set up the FP register classes.
435 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
436 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
438 // Use ANDPD to simulate FABS.
439 setOperationAction(ISD::FABS , MVT::f64, Custom);
440 setOperationAction(ISD::FABS , MVT::f32, Custom);
442 // Use XORP to simulate FNEG.
443 setOperationAction(ISD::FNEG , MVT::f64, Custom);
444 setOperationAction(ISD::FNEG , MVT::f32, Custom);
446 // Use ANDPD and ORPD to simulate FCOPYSIGN.
447 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
448 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
450 // We don't support sin/cos/fmod
451 setOperationAction(ISD::FSIN , MVT::f64, Expand);
452 setOperationAction(ISD::FCOS , MVT::f64, Expand);
453 setOperationAction(ISD::FSIN , MVT::f32, Expand);
454 setOperationAction(ISD::FCOS , MVT::f32, Expand);
456 // Expand FP immediates into loads from the stack, except for the special
458 addLegalFPImmediate(APFloat(+0.0)); // xorpd
459 addLegalFPImmediate(APFloat(+0.0f)); // xorps
460 } else if (!UseSoftFloat && X86ScalarSSEf32) {
461 // Use SSE for f32, x87 for f64.
462 // Set up the FP register classes.
463 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
464 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
466 // Use ANDPS to simulate FABS.
467 setOperationAction(ISD::FABS , MVT::f32, Custom);
469 // Use XORP to simulate FNEG.
470 setOperationAction(ISD::FNEG , MVT::f32, Custom);
472 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
474 // Use ANDPS and ORPS to simulate FCOPYSIGN.
475 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
476 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
478 // We don't support sin/cos/fmod
479 setOperationAction(ISD::FSIN , MVT::f32, Expand);
480 setOperationAction(ISD::FCOS , MVT::f32, Expand);
482 // Special cases we handle for FP constants.
483 addLegalFPImmediate(APFloat(+0.0f)); // xorps
484 addLegalFPImmediate(APFloat(+0.0)); // FLD0
485 addLegalFPImmediate(APFloat(+1.0)); // FLD1
486 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
487 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
490 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
491 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
493 } else if (!UseSoftFloat) {
494 // f32 and f64 in x87.
495 // Set up the FP register classes.
496 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
497 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
499 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
500 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
501 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
502 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
505 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
506 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
508 addLegalFPImmediate(APFloat(+0.0)); // FLD0
509 addLegalFPImmediate(APFloat(+1.0)); // FLD1
510 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
511 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
512 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
513 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
514 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
515 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
518 // Long double always uses X87.
520 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
521 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
522 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
525 APFloat TmpFlt(+0.0);
526 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
528 addLegalFPImmediate(TmpFlt); // FLD0
530 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
531 APFloat TmpFlt2(+1.0);
532 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
534 addLegalFPImmediate(TmpFlt2); // FLD1
535 TmpFlt2.changeSign();
536 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
540 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
541 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
545 // Always use a library call for pow.
546 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
547 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
548 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
550 setOperationAction(ISD::FLOG, MVT::f80, Expand);
551 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
552 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
553 setOperationAction(ISD::FEXP, MVT::f80, Expand);
554 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
556 // First set operation action for all vector types to either promote
557 // (for widening) or expand (for scalarization). Then we will selectively
558 // turn on ones that can be effectively codegen'd.
559 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
560 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
561 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
562 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
563 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
564 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
565 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
566 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
567 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
568 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
569 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
570 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
571 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
572 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
573 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
574 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
575 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
576 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
577 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
578 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
579 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
580 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
581 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
582 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
583 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
584 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
585 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
586 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
587 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
588 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
589 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
590 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
591 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
592 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
593 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
594 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
595 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
596 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
597 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
598 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
599 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
600 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
601 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
602 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
603 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
604 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
605 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
606 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
607 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
608 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
609 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
610 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
611 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
612 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
613 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
614 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
615 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
616 setTruncStoreAction((MVT::SimpleValueType)VT,
617 (MVT::SimpleValueType)InnerVT, Expand);
618 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
619 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
620 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
623 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
624 // with -msoft-float, disable use of MMX as well.
625 if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
626 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
627 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
628 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
629 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
630 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
632 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
633 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
634 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
635 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
637 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
638 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
639 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
640 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
642 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
643 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
645 setOperationAction(ISD::AND, MVT::v8i8, Promote);
646 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
647 setOperationAction(ISD::AND, MVT::v4i16, Promote);
648 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
649 setOperationAction(ISD::AND, MVT::v2i32, Promote);
650 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
651 setOperationAction(ISD::AND, MVT::v1i64, Legal);
653 setOperationAction(ISD::OR, MVT::v8i8, Promote);
654 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
655 setOperationAction(ISD::OR, MVT::v4i16, Promote);
656 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
657 setOperationAction(ISD::OR, MVT::v2i32, Promote);
658 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
659 setOperationAction(ISD::OR, MVT::v1i64, Legal);
661 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
662 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
663 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
664 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
665 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
666 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
667 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
669 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
670 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
671 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
672 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
673 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
674 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
675 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
676 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
677 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
679 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
680 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
681 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
682 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
683 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
685 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
686 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
687 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
688 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
690 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
691 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
692 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
693 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
695 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
697 setOperationAction(ISD::SELECT, MVT::v8i8, Promote);
698 setOperationAction(ISD::SELECT, MVT::v4i16, Promote);
699 setOperationAction(ISD::SELECT, MVT::v2i32, Promote);
700 setOperationAction(ISD::SELECT, MVT::v1i64, Custom);
701 setOperationAction(ISD::VSETCC, MVT::v8i8, Custom);
702 setOperationAction(ISD::VSETCC, MVT::v4i16, Custom);
703 setOperationAction(ISD::VSETCC, MVT::v2i32, Custom);
706 if (!UseSoftFloat && Subtarget->hasSSE1()) {
707 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
709 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
710 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
711 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
712 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
713 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
714 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
715 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
716 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
717 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
718 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
719 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
720 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
723 if (!UseSoftFloat && Subtarget->hasSSE2()) {
724 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
726 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
727 // registers cannot be used even for integer operations.
728 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
729 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
730 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
731 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
733 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
734 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
735 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
736 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
737 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
738 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
739 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
740 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
741 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
742 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
743 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
744 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
745 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
746 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
747 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
748 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
750 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
751 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
752 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
753 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
755 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
756 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
757 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
758 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
759 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
761 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
762 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
763 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
764 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
765 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
767 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
768 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
769 EVT VT = (MVT::SimpleValueType)i;
770 // Do not attempt to custom lower non-power-of-2 vectors
771 if (!isPowerOf2_32(VT.getVectorNumElements()))
773 // Do not attempt to custom lower non-128-bit vectors
774 if (!VT.is128BitVector())
776 setOperationAction(ISD::BUILD_VECTOR,
777 VT.getSimpleVT().SimpleTy, Custom);
778 setOperationAction(ISD::VECTOR_SHUFFLE,
779 VT.getSimpleVT().SimpleTy, Custom);
780 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
781 VT.getSimpleVT().SimpleTy, Custom);
784 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
785 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
786 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
787 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
788 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
789 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
791 if (Subtarget->is64Bit()) {
792 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
793 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
796 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
797 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
798 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
801 // Do not attempt to promote non-128-bit vectors
802 if (!VT.is128BitVector()) {
806 setOperationAction(ISD::AND, SVT, Promote);
807 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
808 setOperationAction(ISD::OR, SVT, Promote);
809 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
810 setOperationAction(ISD::XOR, SVT, Promote);
811 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
812 setOperationAction(ISD::LOAD, SVT, Promote);
813 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
814 setOperationAction(ISD::SELECT, SVT, Promote);
815 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
818 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
820 // Custom lower v2i64 and v2f64 selects.
821 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
822 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
823 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
824 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
826 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
827 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
828 if (!DisableMMX && Subtarget->hasMMX()) {
829 setOperationAction(ISD::FP_TO_SINT, MVT::v2i32, Custom);
830 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
834 if (Subtarget->hasSSE41()) {
835 // FIXME: Do we need to handle scalar-to-vector here?
836 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
838 // i8 and i16 vectors are custom , because the source register and source
839 // source memory operand types are not the same width. f32 vectors are
840 // custom since the immediate controlling the insert encodes additional
842 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
843 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
844 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
845 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
847 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
848 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
849 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
850 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
852 if (Subtarget->is64Bit()) {
853 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
854 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
858 if (Subtarget->hasSSE42()) {
859 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
862 if (!UseSoftFloat && Subtarget->hasAVX()) {
863 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
864 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
865 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
866 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
868 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
869 setOperationAction(ISD::LOAD, MVT::v8i32, Legal);
870 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
871 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
872 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
873 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
874 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
875 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
876 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
877 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
878 //setOperationAction(ISD::BUILD_VECTOR, MVT::v8f32, Custom);
879 //setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Custom);
880 //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
881 //setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
882 //setOperationAction(ISD::VSETCC, MVT::v8f32, Custom);
884 // Operations to consider commented out -v16i16 v32i8
885 //setOperationAction(ISD::ADD, MVT::v16i16, Legal);
886 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
887 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
888 //setOperationAction(ISD::SUB, MVT::v32i8, Legal);
889 //setOperationAction(ISD::SUB, MVT::v16i16, Legal);
890 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
891 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
892 //setOperationAction(ISD::MUL, MVT::v16i16, Legal);
893 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
894 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
895 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
896 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
897 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
898 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
900 setOperationAction(ISD::VSETCC, MVT::v4f64, Custom);
901 // setOperationAction(ISD::VSETCC, MVT::v32i8, Custom);
902 // setOperationAction(ISD::VSETCC, MVT::v16i16, Custom);
903 setOperationAction(ISD::VSETCC, MVT::v8i32, Custom);
905 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v32i8, Custom);
906 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i16, Custom);
907 // setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i16, Custom);
908 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i32, Custom);
909 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8f32, Custom);
911 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
912 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i64, Custom);
913 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f64, Custom);
914 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i64, Custom);
915 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f64, Custom);
916 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
919 // Not sure we want to do this since there are no 256-bit integer
922 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
923 // This includes 256-bit vectors
924 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
925 EVT VT = (MVT::SimpleValueType)i;
927 // Do not attempt to custom lower non-power-of-2 vectors
928 if (!isPowerOf2_32(VT.getVectorNumElements()))
931 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
932 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
933 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
936 if (Subtarget->is64Bit()) {
937 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i64, Custom);
938 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
943 // Not sure we want to do this since there are no 256-bit integer
946 // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
947 // Including 256-bit vectors
948 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
949 EVT VT = (MVT::SimpleValueType)i;
951 if (!VT.is256BitVector()) {
954 setOperationAction(ISD::AND, VT, Promote);
955 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
956 setOperationAction(ISD::OR, VT, Promote);
957 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
958 setOperationAction(ISD::XOR, VT, Promote);
959 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
960 setOperationAction(ISD::LOAD, VT, Promote);
961 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
962 setOperationAction(ISD::SELECT, VT, Promote);
963 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
966 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
970 // We want to custom lower some of our intrinsics.
971 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
973 // Add/Sub/Mul with overflow operations are custom lowered.
974 setOperationAction(ISD::SADDO, MVT::i32, Custom);
975 setOperationAction(ISD::SADDO, MVT::i64, Custom);
976 setOperationAction(ISD::UADDO, MVT::i32, Custom);
977 setOperationAction(ISD::UADDO, MVT::i64, Custom);
978 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
979 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
980 setOperationAction(ISD::USUBO, MVT::i32, Custom);
981 setOperationAction(ISD::USUBO, MVT::i64, Custom);
982 setOperationAction(ISD::SMULO, MVT::i32, Custom);
983 setOperationAction(ISD::SMULO, MVT::i64, Custom);
985 if (!Subtarget->is64Bit()) {
986 // These libcalls are not available in 32-bit.
987 setLibcallName(RTLIB::SHL_I128, 0);
988 setLibcallName(RTLIB::SRL_I128, 0);
989 setLibcallName(RTLIB::SRA_I128, 0);
992 // We have target-specific dag combine patterns for the following nodes:
993 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
994 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
995 setTargetDAGCombine(ISD::BUILD_VECTOR);
996 setTargetDAGCombine(ISD::SELECT);
997 setTargetDAGCombine(ISD::SHL);
998 setTargetDAGCombine(ISD::SRA);
999 setTargetDAGCombine(ISD::SRL);
1000 setTargetDAGCombine(ISD::OR);
1001 setTargetDAGCombine(ISD::STORE);
1002 setTargetDAGCombine(ISD::MEMBARRIER);
1003 setTargetDAGCombine(ISD::ZERO_EXTEND);
1004 if (Subtarget->is64Bit())
1005 setTargetDAGCombine(ISD::MUL);
1007 computeRegisterProperties();
1009 // FIXME: These should be based on subtarget info. Plus, the values should
1010 // be smaller when we are in optimizing for size mode.
1011 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1012 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1013 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
1014 setPrefLoopAlignment(16);
1015 benefitFromCodePlacementOpt = true;
1019 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1024 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1025 /// the desired ByVal argument alignment.
1026 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1029 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1030 if (VTy->getBitWidth() == 128)
1032 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1033 unsigned EltAlign = 0;
1034 getMaxByValAlign(ATy->getElementType(), EltAlign);
1035 if (EltAlign > MaxAlign)
1036 MaxAlign = EltAlign;
1037 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1038 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1039 unsigned EltAlign = 0;
1040 getMaxByValAlign(STy->getElementType(i), EltAlign);
1041 if (EltAlign > MaxAlign)
1042 MaxAlign = EltAlign;
1050 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1051 /// function arguments in the caller parameter area. For X86, aggregates
1052 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1053 /// are at 4-byte boundaries.
1054 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1055 if (Subtarget->is64Bit()) {
1056 // Max of 8 and alignment of type.
1057 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1064 if (Subtarget->hasSSE1())
1065 getMaxByValAlign(Ty, Align);
1069 /// getOptimalMemOpType - Returns the target specific optimal type for load
1070 /// and store operations as a result of memset, memcpy, and memmove lowering.
1071 /// If DstAlign is zero that means it's safe to destination alignment can
1072 /// satisfy any constraint. Similarly if SrcAlign is zero it means there
1073 /// isn't a need to check it against alignment requirement, probably because
1074 /// the source does not need to be loaded. If 'NonScalarIntSafe' is true, that
1075 /// means it's safe to return a non-scalar-integer type, e.g. constant string
1076 /// source or loaded from memory. It returns EVT::Other if SelectionDAG should
1077 /// be responsible for determining it.
1079 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1080 unsigned DstAlign, unsigned SrcAlign,
1081 bool NonScalarIntSafe,
1082 SelectionDAG &DAG) const {
1083 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1084 // linux. This is because the stack realignment code can't handle certain
1085 // cases like PR2962. This should be removed when PR2962 is fixed.
1086 const Function *F = DAG.getMachineFunction().getFunction();
1087 if (NonScalarIntSafe &&
1088 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1090 (Subtarget->isUnalignedMemAccessFast() ||
1091 ((DstAlign == 0 || DstAlign >= 16) &&
1092 (SrcAlign == 0 || SrcAlign >= 16))) &&
1093 Subtarget->getStackAlignment() >= 16) {
1094 if (Subtarget->hasSSE2())
1096 if (Subtarget->hasSSE1())
1098 } else if (Size >= 8 &&
1099 !Subtarget->is64Bit() &&
1100 Subtarget->getStackAlignment() >= 8 &&
1101 Subtarget->hasSSE2())
1104 if (Subtarget->is64Bit() && Size >= 8)
1109 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1110 /// current function. The returned value is a member of the
1111 /// MachineJumpTableInfo::JTEntryKind enum.
1112 unsigned X86TargetLowering::getJumpTableEncoding() const {
1113 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1115 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1116 Subtarget->isPICStyleGOT())
1117 return MachineJumpTableInfo::EK_Custom32;
1119 // Otherwise, use the normal jump table encoding heuristics.
1120 return TargetLowering::getJumpTableEncoding();
1123 /// getPICBaseSymbol - Return the X86-32 PIC base.
1125 X86TargetLowering::getPICBaseSymbol(const MachineFunction *MF,
1126 MCContext &Ctx) const {
1127 const MCAsmInfo &MAI = *getTargetMachine().getMCAsmInfo();
1128 return Ctx.GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix())+
1129 Twine(MF->getFunctionNumber())+"$pb");
1134 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1135 const MachineBasicBlock *MBB,
1136 unsigned uid,MCContext &Ctx) const{
1137 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1138 Subtarget->isPICStyleGOT());
1139 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1141 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1142 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1145 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1147 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1148 SelectionDAG &DAG) const {
1149 if (!Subtarget->is64Bit())
1150 // This doesn't have DebugLoc associated with it, but is not really the
1151 // same as a Register.
1152 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1156 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1157 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1159 const MCExpr *X86TargetLowering::
1160 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1161 MCContext &Ctx) const {
1162 // X86-64 uses RIP relative addressing based on the jump table label.
1163 if (Subtarget->isPICStyleRIPRel())
1164 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1166 // Otherwise, the reference is relative to the PIC base.
1167 return MCSymbolRefExpr::Create(getPICBaseSymbol(MF, Ctx), Ctx);
1170 /// getFunctionAlignment - Return the Log2 alignment of this function.
1171 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1172 return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1175 //===----------------------------------------------------------------------===//
1176 // Return Value Calling Convention Implementation
1177 //===----------------------------------------------------------------------===//
1179 #include "X86GenCallingConv.inc"
1182 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1183 const SmallVectorImpl<EVT> &OutTys,
1184 const SmallVectorImpl<ISD::ArgFlagsTy> &ArgsFlags,
1185 SelectionDAG &DAG) {
1186 SmallVector<CCValAssign, 16> RVLocs;
1187 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1188 RVLocs, *DAG.getContext());
1189 return CCInfo.CheckReturn(OutTys, ArgsFlags, RetCC_X86);
1193 X86TargetLowering::LowerReturn(SDValue Chain,
1194 CallingConv::ID CallConv, bool isVarArg,
1195 const SmallVectorImpl<ISD::OutputArg> &Outs,
1196 DebugLoc dl, SelectionDAG &DAG) {
1198 SmallVector<CCValAssign, 16> RVLocs;
1199 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1200 RVLocs, *DAG.getContext());
1201 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1203 // Add the regs to the liveout set for the function.
1204 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1205 for (unsigned i = 0; i != RVLocs.size(); ++i)
1206 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1207 MRI.addLiveOut(RVLocs[i].getLocReg());
1211 SmallVector<SDValue, 6> RetOps;
1212 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1213 // Operand #1 = Bytes To Pop
1214 RetOps.push_back(DAG.getTargetConstant(getBytesToPopOnReturn(), MVT::i16));
1216 // Copy the result values into the output registers.
1217 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1218 CCValAssign &VA = RVLocs[i];
1219 assert(VA.isRegLoc() && "Can only return in registers!");
1220 SDValue ValToCopy = Outs[i].Val;
1222 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1223 // the RET instruction and handled by the FP Stackifier.
1224 if (VA.getLocReg() == X86::ST0 ||
1225 VA.getLocReg() == X86::ST1) {
1226 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1227 // change the value to the FP stack register class.
1228 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1229 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1230 RetOps.push_back(ValToCopy);
1231 // Don't emit a copytoreg.
1235 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1236 // which is returned in RAX / RDX.
1237 if (Subtarget->is64Bit()) {
1238 EVT ValVT = ValToCopy.getValueType();
1239 if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1240 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1241 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1242 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1246 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1247 Flag = Chain.getValue(1);
1250 // The x86-64 ABI for returning structs by value requires that we copy
1251 // the sret argument into %rax for the return. We saved the argument into
1252 // a virtual register in the entry block, so now we copy the value out
1254 if (Subtarget->is64Bit() &&
1255 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1256 MachineFunction &MF = DAG.getMachineFunction();
1257 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1258 unsigned Reg = FuncInfo->getSRetReturnReg();
1260 Reg = MRI.createVirtualRegister(getRegClassFor(MVT::i64));
1261 FuncInfo->setSRetReturnReg(Reg);
1263 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1265 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1266 Flag = Chain.getValue(1);
1268 // RAX now acts like a return value.
1269 MRI.addLiveOut(X86::RAX);
1272 RetOps[0] = Chain; // Update chain.
1274 // Add the flag if we have it.
1276 RetOps.push_back(Flag);
1278 return DAG.getNode(X86ISD::RET_FLAG, dl,
1279 MVT::Other, &RetOps[0], RetOps.size());
1282 /// LowerCallResult - Lower the result values of a call into the
1283 /// appropriate copies out of appropriate physical registers.
1286 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1287 CallingConv::ID CallConv, bool isVarArg,
1288 const SmallVectorImpl<ISD::InputArg> &Ins,
1289 DebugLoc dl, SelectionDAG &DAG,
1290 SmallVectorImpl<SDValue> &InVals) {
1292 // Assign locations to each value returned by this call.
1293 SmallVector<CCValAssign, 16> RVLocs;
1294 bool Is64Bit = Subtarget->is64Bit();
1295 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1296 RVLocs, *DAG.getContext());
1297 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1299 // Copy all of the result registers out of their specified physreg.
1300 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1301 CCValAssign &VA = RVLocs[i];
1302 EVT CopyVT = VA.getValVT();
1304 // If this is x86-64, and we disabled SSE, we can't return FP values
1305 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1306 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1307 llvm_report_error("SSE register return with SSE disabled");
1310 // If this is a call to a function that returns an fp value on the floating
1311 // point stack, but where we prefer to use the value in xmm registers, copy
1312 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1313 if ((VA.getLocReg() == X86::ST0 ||
1314 VA.getLocReg() == X86::ST1) &&
1315 isScalarFPTypeInSSEReg(VA.getValVT())) {
1320 if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1321 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1322 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1323 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1324 MVT::v2i64, InFlag).getValue(1);
1325 Val = Chain.getValue(0);
1326 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1327 Val, DAG.getConstant(0, MVT::i64));
1329 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1330 MVT::i64, InFlag).getValue(1);
1331 Val = Chain.getValue(0);
1333 Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1335 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1336 CopyVT, InFlag).getValue(1);
1337 Val = Chain.getValue(0);
1339 InFlag = Chain.getValue(2);
1341 if (CopyVT != VA.getValVT()) {
1342 // Round the F80 the right size, which also moves to the appropriate xmm
1344 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1345 // This truncation won't change the value.
1346 DAG.getIntPtrConstant(1));
1349 InVals.push_back(Val);
1356 //===----------------------------------------------------------------------===//
1357 // C & StdCall & Fast Calling Convention implementation
1358 //===----------------------------------------------------------------------===//
1359 // StdCall calling convention seems to be standard for many Windows' API
1360 // routines and around. It differs from C calling convention just a little:
1361 // callee should clean up the stack, not caller. Symbols should be also
1362 // decorated in some fancy way :) It doesn't support any vector arguments.
1363 // For info on fast calling convention see Fast Calling Convention (tail call)
1364 // implementation LowerX86_32FastCCCallTo.
1366 /// CallIsStructReturn - Determines whether a call uses struct return
1368 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1372 return Outs[0].Flags.isSRet();
1375 /// ArgsAreStructReturn - Determines whether a function uses struct
1376 /// return semantics.
1378 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1382 return Ins[0].Flags.isSRet();
1385 /// IsCalleePop - Determines whether the callee is required to pop its
1386 /// own arguments. Callee pop is necessary to support tail calls.
1387 bool X86TargetLowering::IsCalleePop(bool IsVarArg, CallingConv::ID CallingConv){
1391 switch (CallingConv) {
1394 case CallingConv::X86_StdCall:
1395 return !Subtarget->is64Bit();
1396 case CallingConv::X86_FastCall:
1397 return !Subtarget->is64Bit();
1398 case CallingConv::Fast:
1399 return GuaranteedTailCallOpt;
1400 case CallingConv::GHC:
1401 return GuaranteedTailCallOpt;
1405 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1406 /// given CallingConvention value.
1407 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1408 if (Subtarget->is64Bit()) {
1409 if (CC == CallingConv::GHC)
1410 return CC_X86_64_GHC;
1411 else if (Subtarget->isTargetWin64())
1412 return CC_X86_Win64_C;
1417 if (CC == CallingConv::X86_FastCall)
1418 return CC_X86_32_FastCall;
1419 else if (CC == CallingConv::Fast)
1420 return CC_X86_32_FastCC;
1421 else if (CC == CallingConv::GHC)
1422 return CC_X86_32_GHC;
1427 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1428 /// by "Src" to address "Dst" with size and alignment information specified by
1429 /// the specific parameter attribute. The copy will be passed as a byval
1430 /// function parameter.
1432 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1433 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1435 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1436 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1437 /*isVolatile*/false, /*AlwaysInline=*/true,
1441 /// IsTailCallConvention - Return true if the calling convention is one that
1442 /// supports tail call optimization.
1443 static bool IsTailCallConvention(CallingConv::ID CC) {
1444 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1447 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1448 /// a tailcall target by changing its ABI.
1449 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1450 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1454 X86TargetLowering::LowerMemArgument(SDValue Chain,
1455 CallingConv::ID CallConv,
1456 const SmallVectorImpl<ISD::InputArg> &Ins,
1457 DebugLoc dl, SelectionDAG &DAG,
1458 const CCValAssign &VA,
1459 MachineFrameInfo *MFI,
1461 // Create the nodes corresponding to a load from this parameter slot.
1462 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1463 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1464 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1467 // If value is passed by pointer we have address passed instead of the value
1469 if (VA.getLocInfo() == CCValAssign::Indirect)
1470 ValVT = VA.getLocVT();
1472 ValVT = VA.getValVT();
1474 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1475 // changed with more analysis.
1476 // In case of tail call optimization mark all arguments mutable. Since they
1477 // could be overwritten by lowering of arguments in case of a tail call.
1478 if (Flags.isByVal()) {
1479 int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1480 VA.getLocMemOffset(), isImmutable, false);
1481 return DAG.getFrameIndex(FI, getPointerTy());
1483 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1484 VA.getLocMemOffset(), isImmutable, false);
1485 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1486 return DAG.getLoad(ValVT, dl, Chain, FIN,
1487 PseudoSourceValue::getFixedStack(FI), 0,
1493 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1494 CallingConv::ID CallConv,
1496 const SmallVectorImpl<ISD::InputArg> &Ins,
1499 SmallVectorImpl<SDValue> &InVals) {
1500 MachineFunction &MF = DAG.getMachineFunction();
1501 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1503 const Function* Fn = MF.getFunction();
1504 if (Fn->hasExternalLinkage() &&
1505 Subtarget->isTargetCygMing() &&
1506 Fn->getName() == "main")
1507 FuncInfo->setForceFramePointer(true);
1509 MachineFrameInfo *MFI = MF.getFrameInfo();
1510 bool Is64Bit = Subtarget->is64Bit();
1511 bool IsWin64 = Subtarget->isTargetWin64();
1513 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1514 "Var args not supported with calling convention fastcc or ghc");
1516 // Assign locations to all of the incoming arguments.
1517 SmallVector<CCValAssign, 16> ArgLocs;
1518 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1519 ArgLocs, *DAG.getContext());
1520 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1522 unsigned LastVal = ~0U;
1524 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1525 CCValAssign &VA = ArgLocs[i];
1526 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1528 assert(VA.getValNo() != LastVal &&
1529 "Don't support value assigned to multiple locs yet");
1530 LastVal = VA.getValNo();
1532 if (VA.isRegLoc()) {
1533 EVT RegVT = VA.getLocVT();
1534 TargetRegisterClass *RC = NULL;
1535 if (RegVT == MVT::i32)
1536 RC = X86::GR32RegisterClass;
1537 else if (Is64Bit && RegVT == MVT::i64)
1538 RC = X86::GR64RegisterClass;
1539 else if (RegVT == MVT::f32)
1540 RC = X86::FR32RegisterClass;
1541 else if (RegVT == MVT::f64)
1542 RC = X86::FR64RegisterClass;
1543 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1544 RC = X86::VR128RegisterClass;
1545 else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1546 RC = X86::VR64RegisterClass;
1548 llvm_unreachable("Unknown argument type!");
1550 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1551 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1553 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1554 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1556 if (VA.getLocInfo() == CCValAssign::SExt)
1557 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1558 DAG.getValueType(VA.getValVT()));
1559 else if (VA.getLocInfo() == CCValAssign::ZExt)
1560 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1561 DAG.getValueType(VA.getValVT()));
1562 else if (VA.getLocInfo() == CCValAssign::BCvt)
1563 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1565 if (VA.isExtInLoc()) {
1566 // Handle MMX values passed in XMM regs.
1567 if (RegVT.isVector()) {
1568 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1569 ArgValue, DAG.getConstant(0, MVT::i64));
1570 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1572 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1575 assert(VA.isMemLoc());
1576 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1579 // If value is passed via pointer - do a load.
1580 if (VA.getLocInfo() == CCValAssign::Indirect)
1581 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0,
1584 InVals.push_back(ArgValue);
1587 // The x86-64 ABI for returning structs by value requires that we copy
1588 // the sret argument into %rax for the return. Save the argument into
1589 // a virtual register so that we can access it from the return points.
1590 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1591 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1592 unsigned Reg = FuncInfo->getSRetReturnReg();
1594 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1595 FuncInfo->setSRetReturnReg(Reg);
1597 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1598 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1601 unsigned StackSize = CCInfo.getNextStackOffset();
1602 // Align stack specially for tail calls.
1603 if (FuncIsMadeTailCallSafe(CallConv))
1604 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1606 // If the function takes variable number of arguments, make a frame index for
1607 // the start of the first vararg value... for expansion of llvm.va_start.
1609 if (Is64Bit || CallConv != CallingConv::X86_FastCall) {
1610 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize, true, false);
1613 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1615 // FIXME: We should really autogenerate these arrays
1616 static const unsigned GPR64ArgRegsWin64[] = {
1617 X86::RCX, X86::RDX, X86::R8, X86::R9
1619 static const unsigned XMMArgRegsWin64[] = {
1620 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1622 static const unsigned GPR64ArgRegs64Bit[] = {
1623 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1625 static const unsigned XMMArgRegs64Bit[] = {
1626 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1627 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1629 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1632 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1633 GPR64ArgRegs = GPR64ArgRegsWin64;
1634 XMMArgRegs = XMMArgRegsWin64;
1636 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1637 GPR64ArgRegs = GPR64ArgRegs64Bit;
1638 XMMArgRegs = XMMArgRegs64Bit;
1640 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1642 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1645 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1646 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1647 "SSE register cannot be used when SSE is disabled!");
1648 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1649 "SSE register cannot be used when SSE is disabled!");
1650 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1651 // Kernel mode asks for SSE to be disabled, so don't push them
1653 TotalNumXMMRegs = 0;
1655 // For X86-64, if there are vararg parameters that are passed via
1656 // registers, then we must store them to their spots on the stack so they
1657 // may be loaded by deferencing the result of va_next.
1658 VarArgsGPOffset = NumIntRegs * 8;
1659 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1660 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1661 TotalNumXMMRegs * 16, 16,
1664 // Store the integer parameter registers.
1665 SmallVector<SDValue, 8> MemOps;
1666 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1667 unsigned Offset = VarArgsGPOffset;
1668 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1669 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1670 DAG.getIntPtrConstant(Offset));
1671 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1672 X86::GR64RegisterClass);
1673 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1675 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1676 PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
1677 Offset, false, false, 0);
1678 MemOps.push_back(Store);
1682 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1683 // Now store the XMM (fp + vector) parameter registers.
1684 SmallVector<SDValue, 11> SaveXMMOps;
1685 SaveXMMOps.push_back(Chain);
1687 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1688 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1689 SaveXMMOps.push_back(ALVal);
1691 SaveXMMOps.push_back(DAG.getIntPtrConstant(RegSaveFrameIndex));
1692 SaveXMMOps.push_back(DAG.getIntPtrConstant(VarArgsFPOffset));
1694 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1695 unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1696 X86::VR128RegisterClass);
1697 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1698 SaveXMMOps.push_back(Val);
1700 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1702 &SaveXMMOps[0], SaveXMMOps.size()));
1705 if (!MemOps.empty())
1706 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1707 &MemOps[0], MemOps.size());
1711 // Some CCs need callee pop.
1712 if (IsCalleePop(isVarArg, CallConv)) {
1713 BytesToPopOnReturn = StackSize; // Callee pops everything.
1715 BytesToPopOnReturn = 0; // Callee pops nothing.
1716 // If this is an sret function, the return should pop the hidden pointer.
1717 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1718 BytesToPopOnReturn = 4;
1722 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1723 if (CallConv == CallingConv::X86_FastCall)
1724 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1727 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1733 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1734 SDValue StackPtr, SDValue Arg,
1735 DebugLoc dl, SelectionDAG &DAG,
1736 const CCValAssign &VA,
1737 ISD::ArgFlagsTy Flags) {
1738 const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1739 unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1740 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1741 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1742 if (Flags.isByVal()) {
1743 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1745 return DAG.getStore(Chain, dl, Arg, PtrOff,
1746 PseudoSourceValue::getStack(), LocMemOffset,
1750 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1751 /// optimization is performed and it is required.
1753 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1754 SDValue &OutRetAddr, SDValue Chain,
1755 bool IsTailCall, bool Is64Bit,
1756 int FPDiff, DebugLoc dl) {
1757 // Adjust the Return address stack slot.
1758 EVT VT = getPointerTy();
1759 OutRetAddr = getReturnAddressFrameIndex(DAG);
1761 // Load the "old" Return address.
1762 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0, false, false, 0);
1763 return SDValue(OutRetAddr.getNode(), 1);
1766 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1767 /// optimization is performed and it is required (FPDiff!=0).
1769 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1770 SDValue Chain, SDValue RetAddrFrIdx,
1771 bool Is64Bit, int FPDiff, DebugLoc dl) {
1772 // Store the return address to the appropriate stack slot.
1773 if (!FPDiff) return Chain;
1774 // Calculate the new stack slot for the return address.
1775 int SlotSize = Is64Bit ? 8 : 4;
1776 int NewReturnAddrFI =
1777 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false, false);
1778 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1779 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1780 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1781 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0,
1787 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1788 CallingConv::ID CallConv, bool isVarArg,
1790 const SmallVectorImpl<ISD::OutputArg> &Outs,
1791 const SmallVectorImpl<ISD::InputArg> &Ins,
1792 DebugLoc dl, SelectionDAG &DAG,
1793 SmallVectorImpl<SDValue> &InVals) {
1794 MachineFunction &MF = DAG.getMachineFunction();
1795 bool Is64Bit = Subtarget->is64Bit();
1796 bool IsStructRet = CallIsStructReturn(Outs);
1797 bool IsSibcall = false;
1800 // Check if it's really possible to do a tail call.
1801 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1802 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1805 // Sibcalls are automatically detected tailcalls which do not require
1807 if (!GuaranteedTailCallOpt && isTailCall)
1814 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1815 "Var args not supported with calling convention fastcc or ghc");
1817 // Analyze operands of the call, assigning locations to each operand.
1818 SmallVector<CCValAssign, 16> ArgLocs;
1819 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1820 ArgLocs, *DAG.getContext());
1821 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1823 // Get a count of how many bytes are to be pushed on the stack.
1824 unsigned NumBytes = CCInfo.getNextStackOffset();
1826 // This is a sibcall. The memory operands are available in caller's
1827 // own caller's stack.
1829 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1830 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1833 if (isTailCall && !IsSibcall) {
1834 // Lower arguments at fp - stackoffset + fpdiff.
1835 unsigned NumBytesCallerPushed =
1836 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1837 FPDiff = NumBytesCallerPushed - NumBytes;
1839 // Set the delta of movement of the returnaddr stackslot.
1840 // But only set if delta is greater than previous delta.
1841 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1842 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1846 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1848 SDValue RetAddrFrIdx;
1849 // Load return adress for tail calls.
1850 if (isTailCall && FPDiff)
1851 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1852 Is64Bit, FPDiff, dl);
1854 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1855 SmallVector<SDValue, 8> MemOpChains;
1858 // Walk the register/memloc assignments, inserting copies/loads. In the case
1859 // of tail call optimization arguments are handle later.
1860 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1861 CCValAssign &VA = ArgLocs[i];
1862 EVT RegVT = VA.getLocVT();
1863 SDValue Arg = Outs[i].Val;
1864 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1865 bool isByVal = Flags.isByVal();
1867 // Promote the value if needed.
1868 switch (VA.getLocInfo()) {
1869 default: llvm_unreachable("Unknown loc info!");
1870 case CCValAssign::Full: break;
1871 case CCValAssign::SExt:
1872 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1874 case CCValAssign::ZExt:
1875 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1877 case CCValAssign::AExt:
1878 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1879 // Special case: passing MMX values in XMM registers.
1880 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1881 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1882 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1884 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1886 case CCValAssign::BCvt:
1887 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1889 case CCValAssign::Indirect: {
1890 // Store the argument.
1891 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1892 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1893 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1894 PseudoSourceValue::getFixedStack(FI), 0,
1901 if (VA.isRegLoc()) {
1902 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1903 } else if (!IsSibcall && (!isTailCall || isByVal)) {
1904 assert(VA.isMemLoc());
1905 if (StackPtr.getNode() == 0)
1906 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1907 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1908 dl, DAG, VA, Flags));
1912 if (!MemOpChains.empty())
1913 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1914 &MemOpChains[0], MemOpChains.size());
1916 // Build a sequence of copy-to-reg nodes chained together with token chain
1917 // and flag operands which copy the outgoing args into registers.
1919 // Tail call byval lowering might overwrite argument registers so in case of
1920 // tail call optimization the copies to registers are lowered later.
1922 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1923 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1924 RegsToPass[i].second, InFlag);
1925 InFlag = Chain.getValue(1);
1928 if (Subtarget->isPICStyleGOT()) {
1929 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1932 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1933 DAG.getNode(X86ISD::GlobalBaseReg,
1934 DebugLoc(), getPointerTy()),
1936 InFlag = Chain.getValue(1);
1938 // If we are tail calling and generating PIC/GOT style code load the
1939 // address of the callee into ECX. The value in ecx is used as target of
1940 // the tail jump. This is done to circumvent the ebx/callee-saved problem
1941 // for tail calls on PIC/GOT architectures. Normally we would just put the
1942 // address of GOT into ebx and then call target@PLT. But for tail calls
1943 // ebx would be restored (since ebx is callee saved) before jumping to the
1946 // Note: The actual moving to ECX is done further down.
1947 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1948 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1949 !G->getGlobal()->hasProtectedVisibility())
1950 Callee = LowerGlobalAddress(Callee, DAG);
1951 else if (isa<ExternalSymbolSDNode>(Callee))
1952 Callee = LowerExternalSymbol(Callee, DAG);
1956 if (Is64Bit && isVarArg) {
1957 // From AMD64 ABI document:
1958 // For calls that may call functions that use varargs or stdargs
1959 // (prototype-less calls or calls to functions containing ellipsis (...) in
1960 // the declaration) %al is used as hidden argument to specify the number
1961 // of SSE registers used. The contents of %al do not need to match exactly
1962 // the number of registers, but must be an ubound on the number of SSE
1963 // registers used and is in the range 0 - 8 inclusive.
1965 // FIXME: Verify this on Win64
1966 // Count the number of XMM registers allocated.
1967 static const unsigned XMMArgRegs[] = {
1968 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1969 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1971 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1972 assert((Subtarget->hasSSE1() || !NumXMMRegs)
1973 && "SSE registers cannot be used when SSE is disabled");
1975 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1976 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1977 InFlag = Chain.getValue(1);
1981 // For tail calls lower the arguments to the 'real' stack slot.
1983 // Force all the incoming stack arguments to be loaded from the stack
1984 // before any new outgoing arguments are stored to the stack, because the
1985 // outgoing stack slots may alias the incoming argument stack slots, and
1986 // the alias isn't otherwise explicit. This is slightly more conservative
1987 // than necessary, because it means that each store effectively depends
1988 // on every argument instead of just those arguments it would clobber.
1989 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
1991 SmallVector<SDValue, 8> MemOpChains2;
1994 // Do not flag preceeding copytoreg stuff together with the following stuff.
1996 if (GuaranteedTailCallOpt) {
1997 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1998 CCValAssign &VA = ArgLocs[i];
2001 assert(VA.isMemLoc());
2002 SDValue Arg = Outs[i].Val;
2003 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2004 // Create frame index.
2005 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2006 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2007 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true, false);
2008 FIN = DAG.getFrameIndex(FI, getPointerTy());
2010 if (Flags.isByVal()) {
2011 // Copy relative to framepointer.
2012 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2013 if (StackPtr.getNode() == 0)
2014 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2016 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2018 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2022 // Store relative to framepointer.
2023 MemOpChains2.push_back(
2024 DAG.getStore(ArgChain, dl, Arg, FIN,
2025 PseudoSourceValue::getFixedStack(FI), 0,
2031 if (!MemOpChains2.empty())
2032 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2033 &MemOpChains2[0], MemOpChains2.size());
2035 // Copy arguments to their registers.
2036 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2037 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2038 RegsToPass[i].second, InFlag);
2039 InFlag = Chain.getValue(1);
2043 // Store the return address to the appropriate stack slot.
2044 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2048 bool WasGlobalOrExternal = false;
2049 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2050 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2051 // In the 64-bit large code model, we have to make all calls
2052 // through a register, since the call instruction's 32-bit
2053 // pc-relative offset may not be large enough to hold the whole
2055 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2056 WasGlobalOrExternal = true;
2057 // If the callee is a GlobalAddress node (quite common, every direct call
2058 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2061 // We should use extra load for direct calls to dllimported functions in
2063 GlobalValue *GV = G->getGlobal();
2064 if (!GV->hasDLLImportLinkage()) {
2065 unsigned char OpFlags = 0;
2067 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2068 // external symbols most go through the PLT in PIC mode. If the symbol
2069 // has hidden or protected visibility, or if it is static or local, then
2070 // we don't need to use the PLT - we can directly call it.
2071 if (Subtarget->isTargetELF() &&
2072 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2073 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2074 OpFlags = X86II::MO_PLT;
2075 } else if (Subtarget->isPICStyleStubAny() &&
2076 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2077 Subtarget->getDarwinVers() < 9) {
2078 // PC-relative references to external symbols should go through $stub,
2079 // unless we're building with the leopard linker or later, which
2080 // automatically synthesizes these stubs.
2081 OpFlags = X86II::MO_DARWIN_STUB;
2084 Callee = DAG.getTargetGlobalAddress(GV, getPointerTy(),
2085 G->getOffset(), OpFlags);
2087 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2088 WasGlobalOrExternal = true;
2089 unsigned char OpFlags = 0;
2091 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2092 // symbols should go through the PLT.
2093 if (Subtarget->isTargetELF() &&
2094 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2095 OpFlags = X86II::MO_PLT;
2096 } else if (Subtarget->isPICStyleStubAny() &&
2097 Subtarget->getDarwinVers() < 9) {
2098 // PC-relative references to external symbols should go through $stub,
2099 // unless we're building with the leopard linker or later, which
2100 // automatically synthesizes these stubs.
2101 OpFlags = X86II::MO_DARWIN_STUB;
2104 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2108 // Returns a chain & a flag for retval copy to use.
2109 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2110 SmallVector<SDValue, 8> Ops;
2112 if (!IsSibcall && isTailCall) {
2113 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2114 DAG.getIntPtrConstant(0, true), InFlag);
2115 InFlag = Chain.getValue(1);
2118 Ops.push_back(Chain);
2119 Ops.push_back(Callee);
2122 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2124 // Add argument registers to the end of the list so that they are known live
2126 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2127 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2128 RegsToPass[i].second.getValueType()));
2130 // Add an implicit use GOT pointer in EBX.
2131 if (!isTailCall && Subtarget->isPICStyleGOT())
2132 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2134 // Add an implicit use of AL for x86 vararg functions.
2135 if (Is64Bit && isVarArg)
2136 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2138 if (InFlag.getNode())
2139 Ops.push_back(InFlag);
2142 // If this is the first return lowered for this function, add the regs
2143 // to the liveout set for the function.
2144 if (MF.getRegInfo().liveout_empty()) {
2145 SmallVector<CCValAssign, 16> RVLocs;
2146 CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
2148 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2149 for (unsigned i = 0; i != RVLocs.size(); ++i)
2150 if (RVLocs[i].isRegLoc())
2151 MF.getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2153 return DAG.getNode(X86ISD::TC_RETURN, dl,
2154 NodeTys, &Ops[0], Ops.size());
2157 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2158 InFlag = Chain.getValue(1);
2160 // Create the CALLSEQ_END node.
2161 unsigned NumBytesForCalleeToPush;
2162 if (IsCalleePop(isVarArg, CallConv))
2163 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2164 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2165 // If this is a call to a struct-return function, the callee
2166 // pops the hidden struct pointer, so we have to push it back.
2167 // This is common for Darwin/X86, Linux & Mingw32 targets.
2168 NumBytesForCalleeToPush = 4;
2170 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2172 // Returns a flag for retval copy to use.
2174 Chain = DAG.getCALLSEQ_END(Chain,
2175 DAG.getIntPtrConstant(NumBytes, true),
2176 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2179 InFlag = Chain.getValue(1);
2182 // Handle result values, copying them out of physregs into vregs that we
2184 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2185 Ins, dl, DAG, InVals);
2189 //===----------------------------------------------------------------------===//
2190 // Fast Calling Convention (tail call) implementation
2191 //===----------------------------------------------------------------------===//
2193 // Like std call, callee cleans arguments, convention except that ECX is
2194 // reserved for storing the tail called function address. Only 2 registers are
2195 // free for argument passing (inreg). Tail call optimization is performed
2197 // * tailcallopt is enabled
2198 // * caller/callee are fastcc
2199 // On X86_64 architecture with GOT-style position independent code only local
2200 // (within module) calls are supported at the moment.
2201 // To keep the stack aligned according to platform abi the function
2202 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2203 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2204 // If a tail called function callee has more arguments than the caller the
2205 // caller needs to make sure that there is room to move the RETADDR to. This is
2206 // achieved by reserving an area the size of the argument delta right after the
2207 // original REtADDR, but before the saved framepointer or the spilled registers
2208 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2220 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2221 /// for a 16 byte align requirement.
2222 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2223 SelectionDAG& DAG) {
2224 MachineFunction &MF = DAG.getMachineFunction();
2225 const TargetMachine &TM = MF.getTarget();
2226 const TargetFrameInfo &TFI = *TM.getFrameInfo();
2227 unsigned StackAlignment = TFI.getStackAlignment();
2228 uint64_t AlignMask = StackAlignment - 1;
2229 int64_t Offset = StackSize;
2230 uint64_t SlotSize = TD->getPointerSize();
2231 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2232 // Number smaller than 12 so just add the difference.
2233 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2235 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2236 Offset = ((~AlignMask) & Offset) + StackAlignment +
2237 (StackAlignment-SlotSize);
2242 /// MatchingStackOffset - Return true if the given stack call argument is
2243 /// already available in the same position (relatively) of the caller's
2244 /// incoming argument stack.
2246 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2247 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2248 const X86InstrInfo *TII) {
2249 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2251 if (Arg.getOpcode() == ISD::CopyFromReg) {
2252 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2253 if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2255 MachineInstr *Def = MRI->getVRegDef(VR);
2258 if (!Flags.isByVal()) {
2259 if (!TII->isLoadFromStackSlot(Def, FI))
2262 unsigned Opcode = Def->getOpcode();
2263 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2264 Def->getOperand(1).isFI()) {
2265 FI = Def->getOperand(1).getIndex();
2266 Bytes = Flags.getByValSize();
2270 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2271 if (Flags.isByVal())
2272 // ByVal argument is passed in as a pointer but it's now being
2273 // dereferenced. e.g.
2274 // define @foo(%struct.X* %A) {
2275 // tail call @bar(%struct.X* byval %A)
2278 SDValue Ptr = Ld->getBasePtr();
2279 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2282 FI = FINode->getIndex();
2286 assert(FI != INT_MAX);
2287 if (!MFI->isFixedObjectIndex(FI))
2289 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2292 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2293 /// for tail call optimization. Targets which want to do tail call
2294 /// optimization should implement this function.
2296 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2297 CallingConv::ID CalleeCC,
2299 bool isCalleeStructRet,
2300 bool isCallerStructRet,
2301 const SmallVectorImpl<ISD::OutputArg> &Outs,
2302 const SmallVectorImpl<ISD::InputArg> &Ins,
2303 SelectionDAG& DAG) const {
2304 if (!IsTailCallConvention(CalleeCC) &&
2305 CalleeCC != CallingConv::C)
2308 // If -tailcallopt is specified, make fastcc functions tail-callable.
2309 const MachineFunction &MF = DAG.getMachineFunction();
2310 const Function *CallerF = DAG.getMachineFunction().getFunction();
2311 if (GuaranteedTailCallOpt) {
2312 if (IsTailCallConvention(CalleeCC) &&
2313 CallerF->getCallingConv() == CalleeCC)
2318 // Look for obvious safe cases to perform tail call optimization that does not
2319 // requite ABI changes. This is what gcc calls sibcall.
2321 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2322 // emit a special epilogue.
2323 if (RegInfo->needsStackRealignment(MF))
2326 // Do not sibcall optimize vararg calls unless the call site is not passing any
2328 if (isVarArg && !Outs.empty())
2331 // Also avoid sibcall optimization if either caller or callee uses struct
2332 // return semantics.
2333 if (isCalleeStructRet || isCallerStructRet)
2336 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2337 // Therefore if it's not used by the call it is not safe to optimize this into
2339 bool Unused = false;
2340 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2347 SmallVector<CCValAssign, 16> RVLocs;
2348 CCState CCInfo(CalleeCC, false, getTargetMachine(),
2349 RVLocs, *DAG.getContext());
2350 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2351 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2352 CCValAssign &VA = RVLocs[i];
2353 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2358 // If the callee takes no arguments then go on to check the results of the
2360 if (!Outs.empty()) {
2361 // Check if stack adjustment is needed. For now, do not do this if any
2362 // argument is passed on the stack.
2363 SmallVector<CCValAssign, 16> ArgLocs;
2364 CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2365 ArgLocs, *DAG.getContext());
2366 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
2367 if (CCInfo.getNextStackOffset()) {
2368 MachineFunction &MF = DAG.getMachineFunction();
2369 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2371 if (Subtarget->isTargetWin64())
2372 // Win64 ABI has additional complications.
2375 // Check if the arguments are already laid out in the right way as
2376 // the caller's fixed stack objects.
2377 MachineFrameInfo *MFI = MF.getFrameInfo();
2378 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2379 const X86InstrInfo *TII =
2380 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2381 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2382 CCValAssign &VA = ArgLocs[i];
2383 EVT RegVT = VA.getLocVT();
2384 SDValue Arg = Outs[i].Val;
2385 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2386 if (VA.getLocInfo() == CCValAssign::Indirect)
2388 if (!VA.isRegLoc()) {
2389 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2401 X86TargetLowering::createFastISel(MachineFunction &mf,
2402 DenseMap<const Value *, unsigned> &vm,
2403 DenseMap<const BasicBlock*, MachineBasicBlock*> &bm,
2404 DenseMap<const AllocaInst *, int> &am
2406 , SmallSet<Instruction*, 8> &cil
2409 return X86::createFastISel(mf, vm, bm, am
2417 //===----------------------------------------------------------------------===//
2418 // Other Lowering Hooks
2419 //===----------------------------------------------------------------------===//
2422 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2423 MachineFunction &MF = DAG.getMachineFunction();
2424 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2425 int ReturnAddrIndex = FuncInfo->getRAIndex();
2427 if (ReturnAddrIndex == 0) {
2428 // Set up a frame object for the return address.
2429 uint64_t SlotSize = TD->getPointerSize();
2430 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2432 FuncInfo->setRAIndex(ReturnAddrIndex);
2435 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2439 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2440 bool hasSymbolicDisplacement) {
2441 // Offset should fit into 32 bit immediate field.
2442 if (!isInt<32>(Offset))
2445 // If we don't have a symbolic displacement - we don't have any extra
2447 if (!hasSymbolicDisplacement)
2450 // FIXME: Some tweaks might be needed for medium code model.
2451 if (M != CodeModel::Small && M != CodeModel::Kernel)
2454 // For small code model we assume that latest object is 16MB before end of 31
2455 // bits boundary. We may also accept pretty large negative constants knowing
2456 // that all objects are in the positive half of address space.
2457 if (M == CodeModel::Small && Offset < 16*1024*1024)
2460 // For kernel code model we know that all object resist in the negative half
2461 // of 32bits address space. We may not accept negative offsets, since they may
2462 // be just off and we may accept pretty large positive ones.
2463 if (M == CodeModel::Kernel && Offset > 0)
2469 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2470 /// specific condition code, returning the condition code and the LHS/RHS of the
2471 /// comparison to make.
2472 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2473 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2475 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2476 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2477 // X > -1 -> X == 0, jump !sign.
2478 RHS = DAG.getConstant(0, RHS.getValueType());
2479 return X86::COND_NS;
2480 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2481 // X < 0 -> X == 0, jump on sign.
2483 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2485 RHS = DAG.getConstant(0, RHS.getValueType());
2486 return X86::COND_LE;
2490 switch (SetCCOpcode) {
2491 default: llvm_unreachable("Invalid integer condition!");
2492 case ISD::SETEQ: return X86::COND_E;
2493 case ISD::SETGT: return X86::COND_G;
2494 case ISD::SETGE: return X86::COND_GE;
2495 case ISD::SETLT: return X86::COND_L;
2496 case ISD::SETLE: return X86::COND_LE;
2497 case ISD::SETNE: return X86::COND_NE;
2498 case ISD::SETULT: return X86::COND_B;
2499 case ISD::SETUGT: return X86::COND_A;
2500 case ISD::SETULE: return X86::COND_BE;
2501 case ISD::SETUGE: return X86::COND_AE;
2505 // First determine if it is required or is profitable to flip the operands.
2507 // If LHS is a foldable load, but RHS is not, flip the condition.
2508 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2509 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2510 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2511 std::swap(LHS, RHS);
2514 switch (SetCCOpcode) {
2520 std::swap(LHS, RHS);
2524 // On a floating point condition, the flags are set as follows:
2526 // 0 | 0 | 0 | X > Y
2527 // 0 | 0 | 1 | X < Y
2528 // 1 | 0 | 0 | X == Y
2529 // 1 | 1 | 1 | unordered
2530 switch (SetCCOpcode) {
2531 default: llvm_unreachable("Condcode should be pre-legalized away");
2533 case ISD::SETEQ: return X86::COND_E;
2534 case ISD::SETOLT: // flipped
2536 case ISD::SETGT: return X86::COND_A;
2537 case ISD::SETOLE: // flipped
2539 case ISD::SETGE: return X86::COND_AE;
2540 case ISD::SETUGT: // flipped
2542 case ISD::SETLT: return X86::COND_B;
2543 case ISD::SETUGE: // flipped
2545 case ISD::SETLE: return X86::COND_BE;
2547 case ISD::SETNE: return X86::COND_NE;
2548 case ISD::SETUO: return X86::COND_P;
2549 case ISD::SETO: return X86::COND_NP;
2551 case ISD::SETUNE: return X86::COND_INVALID;
2555 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2556 /// code. Current x86 isa includes the following FP cmov instructions:
2557 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2558 static bool hasFPCMov(unsigned X86CC) {
2574 /// isFPImmLegal - Returns true if the target can instruction select the
2575 /// specified FP immediate natively. If false, the legalizer will
2576 /// materialize the FP immediate as a load from a constant pool.
2577 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2578 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2579 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2585 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2586 /// the specified range (L, H].
2587 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2588 return (Val < 0) || (Val >= Low && Val < Hi);
2591 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2592 /// specified value.
2593 static bool isUndefOrEqual(int Val, int CmpVal) {
2594 if (Val < 0 || Val == CmpVal)
2599 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2600 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2601 /// the second operand.
2602 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2603 if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2604 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2605 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2606 return (Mask[0] < 2 && Mask[1] < 2);
2610 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2611 SmallVector<int, 8> M;
2613 return ::isPSHUFDMask(M, N->getValueType(0));
2616 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2617 /// is suitable for input to PSHUFHW.
2618 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2619 if (VT != MVT::v8i16)
2622 // Lower quadword copied in order or undef.
2623 for (int i = 0; i != 4; ++i)
2624 if (Mask[i] >= 0 && Mask[i] != i)
2627 // Upper quadword shuffled.
2628 for (int i = 4; i != 8; ++i)
2629 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2635 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2636 SmallVector<int, 8> M;
2638 return ::isPSHUFHWMask(M, N->getValueType(0));
2641 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2642 /// is suitable for input to PSHUFLW.
2643 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2644 if (VT != MVT::v8i16)
2647 // Upper quadword copied in order.
2648 for (int i = 4; i != 8; ++i)
2649 if (Mask[i] >= 0 && Mask[i] != i)
2652 // Lower quadword shuffled.
2653 for (int i = 0; i != 4; ++i)
2660 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2661 SmallVector<int, 8> M;
2663 return ::isPSHUFLWMask(M, N->getValueType(0));
2666 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2667 /// is suitable for input to PALIGNR.
2668 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2670 int i, e = VT.getVectorNumElements();
2672 // Do not handle v2i64 / v2f64 shuffles with palignr.
2673 if (e < 4 || !hasSSSE3)
2676 for (i = 0; i != e; ++i)
2680 // All undef, not a palignr.
2684 // Determine if it's ok to perform a palignr with only the LHS, since we
2685 // don't have access to the actual shuffle elements to see if RHS is undef.
2686 bool Unary = Mask[i] < (int)e;
2687 bool NeedsUnary = false;
2689 int s = Mask[i] - i;
2691 // Check the rest of the elements to see if they are consecutive.
2692 for (++i; i != e; ++i) {
2697 Unary = Unary && (m < (int)e);
2698 NeedsUnary = NeedsUnary || (m < s);
2700 if (NeedsUnary && !Unary)
2702 if (Unary && m != ((s+i) & (e-1)))
2704 if (!Unary && m != (s+i))
2710 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2711 SmallVector<int, 8> M;
2713 return ::isPALIGNRMask(M, N->getValueType(0), true);
2716 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2717 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2718 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2719 int NumElems = VT.getVectorNumElements();
2720 if (NumElems != 2 && NumElems != 4)
2723 int Half = NumElems / 2;
2724 for (int i = 0; i < Half; ++i)
2725 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2727 for (int i = Half; i < NumElems; ++i)
2728 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2734 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2735 SmallVector<int, 8> M;
2737 return ::isSHUFPMask(M, N->getValueType(0));
2740 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2741 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2742 /// half elements to come from vector 1 (which would equal the dest.) and
2743 /// the upper half to come from vector 2.
2744 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2745 int NumElems = VT.getVectorNumElements();
2747 if (NumElems != 2 && NumElems != 4)
2750 int Half = NumElems / 2;
2751 for (int i = 0; i < Half; ++i)
2752 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2754 for (int i = Half; i < NumElems; ++i)
2755 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2760 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2761 SmallVector<int, 8> M;
2763 return isCommutedSHUFPMask(M, N->getValueType(0));
2766 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2767 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2768 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2769 if (N->getValueType(0).getVectorNumElements() != 4)
2772 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2773 return isUndefOrEqual(N->getMaskElt(0), 6) &&
2774 isUndefOrEqual(N->getMaskElt(1), 7) &&
2775 isUndefOrEqual(N->getMaskElt(2), 2) &&
2776 isUndefOrEqual(N->getMaskElt(3), 3);
2779 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2780 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2782 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2783 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2788 return isUndefOrEqual(N->getMaskElt(0), 2) &&
2789 isUndefOrEqual(N->getMaskElt(1), 3) &&
2790 isUndefOrEqual(N->getMaskElt(2), 2) &&
2791 isUndefOrEqual(N->getMaskElt(3), 3);
2794 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2795 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2796 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2797 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2799 if (NumElems != 2 && NumElems != 4)
2802 for (unsigned i = 0; i < NumElems/2; ++i)
2803 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2806 for (unsigned i = NumElems/2; i < NumElems; ++i)
2807 if (!isUndefOrEqual(N->getMaskElt(i), i))
2813 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
2814 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
2815 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
2816 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2818 if (NumElems != 2 && NumElems != 4)
2821 for (unsigned i = 0; i < NumElems/2; ++i)
2822 if (!isUndefOrEqual(N->getMaskElt(i), i))
2825 for (unsigned i = 0; i < NumElems/2; ++i)
2826 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2832 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2833 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2834 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2835 bool V2IsSplat = false) {
2836 int NumElts = VT.getVectorNumElements();
2837 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2840 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2842 int BitI1 = Mask[i+1];
2843 if (!isUndefOrEqual(BitI, j))
2846 if (!isUndefOrEqual(BitI1, NumElts))
2849 if (!isUndefOrEqual(BitI1, j + NumElts))
2856 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2857 SmallVector<int, 8> M;
2859 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2862 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2863 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2864 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
2865 bool V2IsSplat = false) {
2866 int NumElts = VT.getVectorNumElements();
2867 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2870 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2872 int BitI1 = Mask[i+1];
2873 if (!isUndefOrEqual(BitI, j + NumElts/2))
2876 if (isUndefOrEqual(BitI1, NumElts))
2879 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2886 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2887 SmallVector<int, 8> M;
2889 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2892 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2893 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2895 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2896 int NumElems = VT.getVectorNumElements();
2897 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2900 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2902 int BitI1 = Mask[i+1];
2903 if (!isUndefOrEqual(BitI, j))
2905 if (!isUndefOrEqual(BitI1, j))
2911 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2912 SmallVector<int, 8> M;
2914 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2917 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2918 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2920 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2921 int NumElems = VT.getVectorNumElements();
2922 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2925 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2927 int BitI1 = Mask[i+1];
2928 if (!isUndefOrEqual(BitI, j))
2930 if (!isUndefOrEqual(BitI1, j))
2936 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2937 SmallVector<int, 8> M;
2939 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2942 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2943 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2944 /// MOVSD, and MOVD, i.e. setting the lowest element.
2945 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2946 if (VT.getVectorElementType().getSizeInBits() < 32)
2949 int NumElts = VT.getVectorNumElements();
2951 if (!isUndefOrEqual(Mask[0], NumElts))
2954 for (int i = 1; i < NumElts; ++i)
2955 if (!isUndefOrEqual(Mask[i], i))
2961 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2962 SmallVector<int, 8> M;
2964 return ::isMOVLMask(M, N->getValueType(0));
2967 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2968 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2969 /// element of vector 2 and the other elements to come from vector 1 in order.
2970 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2971 bool V2IsSplat = false, bool V2IsUndef = false) {
2972 int NumOps = VT.getVectorNumElements();
2973 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2976 if (!isUndefOrEqual(Mask[0], 0))
2979 for (int i = 1; i < NumOps; ++i)
2980 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
2981 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
2982 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
2988 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
2989 bool V2IsUndef = false) {
2990 SmallVector<int, 8> M;
2992 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
2995 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2996 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2997 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
2998 if (N->getValueType(0).getVectorNumElements() != 4)
3001 // Expect 1, 1, 3, 3
3002 for (unsigned i = 0; i < 2; ++i) {
3003 int Elt = N->getMaskElt(i);
3004 if (Elt >= 0 && Elt != 1)
3009 for (unsigned i = 2; i < 4; ++i) {
3010 int Elt = N->getMaskElt(i);
3011 if (Elt >= 0 && Elt != 3)
3016 // Don't use movshdup if it can be done with a shufps.
3017 // FIXME: verify that matching u, u, 3, 3 is what we want.
3021 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3022 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3023 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3024 if (N->getValueType(0).getVectorNumElements() != 4)
3027 // Expect 0, 0, 2, 2
3028 for (unsigned i = 0; i < 2; ++i)
3029 if (N->getMaskElt(i) > 0)
3033 for (unsigned i = 2; i < 4; ++i) {
3034 int Elt = N->getMaskElt(i);
3035 if (Elt >= 0 && Elt != 2)
3040 // Don't use movsldup if it can be done with a shufps.
3044 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3045 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3046 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3047 int e = N->getValueType(0).getVectorNumElements() / 2;
3049 for (int i = 0; i < e; ++i)
3050 if (!isUndefOrEqual(N->getMaskElt(i), i))
3052 for (int i = 0; i < e; ++i)
3053 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3058 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3059 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3060 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3061 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3062 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3064 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3066 for (int i = 0; i < NumOperands; ++i) {
3067 int Val = SVOp->getMaskElt(NumOperands-i-1);
3068 if (Val < 0) Val = 0;
3069 if (Val >= NumOperands) Val -= NumOperands;
3071 if (i != NumOperands - 1)
3077 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3078 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3079 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3080 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3082 // 8 nodes, but we only care about the last 4.
3083 for (unsigned i = 7; i >= 4; --i) {
3084 int Val = SVOp->getMaskElt(i);
3093 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3094 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3095 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3096 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3098 // 8 nodes, but we only care about the first 4.
3099 for (int i = 3; i >= 0; --i) {
3100 int Val = SVOp->getMaskElt(i);
3109 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3110 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3111 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3112 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3113 EVT VVT = N->getValueType(0);
3114 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3118 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3119 Val = SVOp->getMaskElt(i);
3123 return (Val - i) * EltSize;
3126 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3128 bool X86::isZeroNode(SDValue Elt) {
3129 return ((isa<ConstantSDNode>(Elt) &&
3130 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
3131 (isa<ConstantFPSDNode>(Elt) &&
3132 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3135 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3136 /// their permute mask.
3137 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3138 SelectionDAG &DAG) {
3139 EVT VT = SVOp->getValueType(0);
3140 unsigned NumElems = VT.getVectorNumElements();
3141 SmallVector<int, 8> MaskVec;
3143 for (unsigned i = 0; i != NumElems; ++i) {
3144 int idx = SVOp->getMaskElt(i);
3146 MaskVec.push_back(idx);
3147 else if (idx < (int)NumElems)
3148 MaskVec.push_back(idx + NumElems);
3150 MaskVec.push_back(idx - NumElems);
3152 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3153 SVOp->getOperand(0), &MaskVec[0]);
3156 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3157 /// the two vector operands have swapped position.
3158 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3159 unsigned NumElems = VT.getVectorNumElements();
3160 for (unsigned i = 0; i != NumElems; ++i) {
3164 else if (idx < (int)NumElems)
3165 Mask[i] = idx + NumElems;
3167 Mask[i] = idx - NumElems;
3171 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3172 /// match movhlps. The lower half elements should come from upper half of
3173 /// V1 (and in order), and the upper half elements should come from the upper
3174 /// half of V2 (and in order).
3175 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3176 if (Op->getValueType(0).getVectorNumElements() != 4)
3178 for (unsigned i = 0, e = 2; i != e; ++i)
3179 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3181 for (unsigned i = 2; i != 4; ++i)
3182 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3187 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3188 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3190 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3191 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3193 N = N->getOperand(0).getNode();
3194 if (!ISD::isNON_EXTLoad(N))
3197 *LD = cast<LoadSDNode>(N);
3201 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3202 /// match movlp{s|d}. The lower half elements should come from lower half of
3203 /// V1 (and in order), and the upper half elements should come from the upper
3204 /// half of V2 (and in order). And since V1 will become the source of the
3205 /// MOVLP, it must be either a vector load or a scalar load to vector.
3206 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3207 ShuffleVectorSDNode *Op) {
3208 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3210 // Is V2 is a vector load, don't do this transformation. We will try to use
3211 // load folding shufps op.
3212 if (ISD::isNON_EXTLoad(V2))
3215 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3217 if (NumElems != 2 && NumElems != 4)
3219 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3220 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3222 for (unsigned i = NumElems/2; i != NumElems; ++i)
3223 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3228 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3230 static bool isSplatVector(SDNode *N) {
3231 if (N->getOpcode() != ISD::BUILD_VECTOR)
3234 SDValue SplatValue = N->getOperand(0);
3235 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3236 if (N->getOperand(i) != SplatValue)
3241 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3242 /// to an zero vector.
3243 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3244 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3245 SDValue V1 = N->getOperand(0);
3246 SDValue V2 = N->getOperand(1);
3247 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3248 for (unsigned i = 0; i != NumElems; ++i) {
3249 int Idx = N->getMaskElt(i);
3250 if (Idx >= (int)NumElems) {
3251 unsigned Opc = V2.getOpcode();
3252 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3254 if (Opc != ISD::BUILD_VECTOR ||
3255 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3257 } else if (Idx >= 0) {
3258 unsigned Opc = V1.getOpcode();
3259 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3261 if (Opc != ISD::BUILD_VECTOR ||
3262 !X86::isZeroNode(V1.getOperand(Idx)))
3269 /// getZeroVector - Returns a vector of specified type with all zero elements.
3271 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3273 assert(VT.isVector() && "Expected a vector type");
3275 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3276 // type. This ensures they get CSE'd.
3278 if (VT.getSizeInBits() == 64) { // MMX
3279 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3280 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3281 } else if (HasSSE2) { // SSE2
3282 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3283 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3285 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3286 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3288 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3291 /// getOnesVector - Returns a vector of specified type with all bits set.
3293 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3294 assert(VT.isVector() && "Expected a vector type");
3296 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3297 // type. This ensures they get CSE'd.
3298 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3300 if (VT.getSizeInBits() == 64) // MMX
3301 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3303 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3304 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3308 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3309 /// that point to V2 points to its first element.
3310 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3311 EVT VT = SVOp->getValueType(0);
3312 unsigned NumElems = VT.getVectorNumElements();
3314 bool Changed = false;
3315 SmallVector<int, 8> MaskVec;
3316 SVOp->getMask(MaskVec);
3318 for (unsigned i = 0; i != NumElems; ++i) {
3319 if (MaskVec[i] > (int)NumElems) {
3320 MaskVec[i] = NumElems;
3325 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3326 SVOp->getOperand(1), &MaskVec[0]);
3327 return SDValue(SVOp, 0);
3330 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3331 /// operation of specified width.
3332 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3334 unsigned NumElems = VT.getVectorNumElements();
3335 SmallVector<int, 8> Mask;
3336 Mask.push_back(NumElems);
3337 for (unsigned i = 1; i != NumElems; ++i)
3339 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3342 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3343 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3345 unsigned NumElems = VT.getVectorNumElements();
3346 SmallVector<int, 8> Mask;
3347 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3349 Mask.push_back(i + NumElems);
3351 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3354 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3355 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3357 unsigned NumElems = VT.getVectorNumElements();
3358 unsigned Half = NumElems/2;
3359 SmallVector<int, 8> Mask;
3360 for (unsigned i = 0; i != Half; ++i) {
3361 Mask.push_back(i + Half);
3362 Mask.push_back(i + NumElems + Half);
3364 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3367 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3368 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3370 if (SV->getValueType(0).getVectorNumElements() <= 4)
3371 return SDValue(SV, 0);
3373 EVT PVT = MVT::v4f32;
3374 EVT VT = SV->getValueType(0);
3375 DebugLoc dl = SV->getDebugLoc();
3376 SDValue V1 = SV->getOperand(0);
3377 int NumElems = VT.getVectorNumElements();
3378 int EltNo = SV->getSplatIndex();
3380 // unpack elements to the correct location
3381 while (NumElems > 4) {
3382 if (EltNo < NumElems/2) {
3383 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3385 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3386 EltNo -= NumElems/2;
3391 // Perform the splat.
3392 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3393 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3394 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3395 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3398 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3399 /// vector of zero or undef vector. This produces a shuffle where the low
3400 /// element of V2 is swizzled into the zero/undef vector, landing at element
3401 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3402 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3403 bool isZero, bool HasSSE2,
3404 SelectionDAG &DAG) {
3405 EVT VT = V2.getValueType();
3407 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3408 unsigned NumElems = VT.getVectorNumElements();
3409 SmallVector<int, 16> MaskVec;
3410 for (unsigned i = 0; i != NumElems; ++i)
3411 // If this is the insertion idx, put the low elt of V2 here.
3412 MaskVec.push_back(i == Idx ? NumElems : i);
3413 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3416 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3417 /// a shuffle that is zero.
3419 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3420 bool Low, SelectionDAG &DAG) {
3421 unsigned NumZeros = 0;
3422 for (int i = 0; i < NumElems; ++i) {
3423 unsigned Index = Low ? i : NumElems-i-1;
3424 int Idx = SVOp->getMaskElt(Index);
3429 SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3430 if (Elt.getNode() && X86::isZeroNode(Elt))
3438 /// isVectorShift - Returns true if the shuffle can be implemented as a
3439 /// logical left or right shift of a vector.
3440 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3441 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3442 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3443 int NumElems = SVOp->getValueType(0).getVectorNumElements();
3446 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3449 NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3453 bool SeenV1 = false;
3454 bool SeenV2 = false;
3455 for (int i = NumZeros; i < NumElems; ++i) {
3456 int Val = isLeft ? (i - NumZeros) : i;
3457 int Idx = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3469 if (SeenV1 && SeenV2)
3472 ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3478 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3480 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3481 unsigned NumNonZero, unsigned NumZero,
3482 SelectionDAG &DAG, TargetLowering &TLI) {
3486 DebugLoc dl = Op.getDebugLoc();
3489 for (unsigned i = 0; i < 16; ++i) {
3490 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3491 if (ThisIsNonZero && First) {
3493 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3495 V = DAG.getUNDEF(MVT::v8i16);
3500 SDValue ThisElt(0, 0), LastElt(0, 0);
3501 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3502 if (LastIsNonZero) {
3503 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3504 MVT::i16, Op.getOperand(i-1));
3506 if (ThisIsNonZero) {
3507 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3508 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3509 ThisElt, DAG.getConstant(8, MVT::i8));
3511 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3515 if (ThisElt.getNode())
3516 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3517 DAG.getIntPtrConstant(i/2));
3521 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3524 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3526 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3527 unsigned NumNonZero, unsigned NumZero,
3528 SelectionDAG &DAG, TargetLowering &TLI) {
3532 DebugLoc dl = Op.getDebugLoc();
3535 for (unsigned i = 0; i < 8; ++i) {
3536 bool isNonZero = (NonZeros & (1 << i)) != 0;
3540 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3542 V = DAG.getUNDEF(MVT::v8i16);
3545 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3546 MVT::v8i16, V, Op.getOperand(i),
3547 DAG.getIntPtrConstant(i));
3554 /// getVShift - Return a vector logical shift node.
3556 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3557 unsigned NumBits, SelectionDAG &DAG,
3558 const TargetLowering &TLI, DebugLoc dl) {
3559 bool isMMX = VT.getSizeInBits() == 64;
3560 EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3561 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3562 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3563 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3564 DAG.getNode(Opc, dl, ShVT, SrcOp,
3565 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3569 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3570 SelectionDAG &DAG) {
3572 // Check if the scalar load can be widened into a vector load. And if
3573 // the address is "base + cst" see if the cst can be "absorbed" into
3574 // the shuffle mask.
3575 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3576 SDValue Ptr = LD->getBasePtr();
3577 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3579 EVT PVT = LD->getValueType(0);
3580 if (PVT != MVT::i32 && PVT != MVT::f32)
3585 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3586 FI = FINode->getIndex();
3588 } else if (Ptr.getOpcode() == ISD::ADD &&
3589 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
3590 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
3591 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
3592 Offset = Ptr.getConstantOperandVal(1);
3593 Ptr = Ptr.getOperand(0);
3598 SDValue Chain = LD->getChain();
3599 // Make sure the stack object alignment is at least 16.
3600 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3601 if (DAG.InferPtrAlignment(Ptr) < 16) {
3602 if (MFI->isFixedObjectIndex(FI)) {
3603 // Can't change the alignment. FIXME: It's possible to compute
3604 // the exact stack offset and reference FI + adjust offset instead.
3605 // If someone *really* cares about this. That's the way to implement it.
3608 MFI->setObjectAlignment(FI, 16);
3612 // (Offset % 16) must be multiple of 4. Then address is then
3613 // Ptr + (Offset & ~15).
3616 if ((Offset % 16) & 3)
3618 int64_t StartOffset = Offset & ~15;
3620 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
3621 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
3623 int EltNo = (Offset - StartOffset) >> 2;
3624 int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
3625 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
3626 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,LD->getSrcValue(),0,
3628 // Canonicalize it to a v4i32 shuffle.
3629 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
3630 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3631 DAG.getVectorShuffle(MVT::v4i32, dl, V1,
3632 DAG.getUNDEF(MVT::v4i32), &Mask[0]));
3638 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
3639 /// vector of type 'VT', see if the elements can be replaced by a single large
3640 /// load which has the same value as a build_vector whose operands are 'elts'.
3642 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
3644 /// FIXME: we'd also like to handle the case where the last elements are zero
3645 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
3646 /// There's even a handy isZeroNode for that purpose.
3647 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
3648 DebugLoc &dl, SelectionDAG &DAG) {
3649 EVT EltVT = VT.getVectorElementType();
3650 unsigned NumElems = Elts.size();
3652 LoadSDNode *LDBase = NULL;
3653 unsigned LastLoadedElt = -1U;
3655 // For each element in the initializer, see if we've found a load or an undef.
3656 // If we don't find an initial load element, or later load elements are
3657 // non-consecutive, bail out.
3658 for (unsigned i = 0; i < NumElems; ++i) {
3659 SDValue Elt = Elts[i];
3661 if (!Elt.getNode() ||
3662 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
3665 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
3667 LDBase = cast<LoadSDNode>(Elt.getNode());
3671 if (Elt.getOpcode() == ISD::UNDEF)
3674 LoadSDNode *LD = cast<LoadSDNode>(Elt);
3675 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
3680 // If we have found an entire vector of loads and undefs, then return a large
3681 // load of the entire vector width starting at the base pointer. If we found
3682 // consecutive loads for the low half, generate a vzext_load node.
3683 if (LastLoadedElt == NumElems - 1) {
3684 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
3685 return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3686 LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3687 LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
3688 return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3689 LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3690 LDBase->isVolatile(), LDBase->isNonTemporal(),
3691 LDBase->getAlignment());
3692 } else if (NumElems == 4 && LastLoadedElt == 1) {
3693 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
3694 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
3695 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
3696 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
3702 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3703 DebugLoc dl = Op.getDebugLoc();
3704 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3705 if (ISD::isBuildVectorAllZeros(Op.getNode())
3706 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3707 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3708 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3709 // eliminated on x86-32 hosts.
3710 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3713 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3714 return getOnesVector(Op.getValueType(), DAG, dl);
3715 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3718 EVT VT = Op.getValueType();
3719 EVT ExtVT = VT.getVectorElementType();
3720 unsigned EVTBits = ExtVT.getSizeInBits();
3722 unsigned NumElems = Op.getNumOperands();
3723 unsigned NumZero = 0;
3724 unsigned NumNonZero = 0;
3725 unsigned NonZeros = 0;
3726 bool IsAllConstants = true;
3727 SmallSet<SDValue, 8> Values;
3728 for (unsigned i = 0; i < NumElems; ++i) {
3729 SDValue Elt = Op.getOperand(i);
3730 if (Elt.getOpcode() == ISD::UNDEF)
3733 if (Elt.getOpcode() != ISD::Constant &&
3734 Elt.getOpcode() != ISD::ConstantFP)
3735 IsAllConstants = false;
3736 if (X86::isZeroNode(Elt))
3739 NonZeros |= (1 << i);
3744 if (NumNonZero == 0) {
3745 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3746 return DAG.getUNDEF(VT);
3749 // Special case for single non-zero, non-undef, element.
3750 if (NumNonZero == 1) {
3751 unsigned Idx = CountTrailingZeros_32(NonZeros);
3752 SDValue Item = Op.getOperand(Idx);
3754 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3755 // the value are obviously zero, truncate the value to i32 and do the
3756 // insertion that way. Only do this if the value is non-constant or if the
3757 // value is a constant being inserted into element 0. It is cheaper to do
3758 // a constant pool load than it is to do a movd + shuffle.
3759 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3760 (!IsAllConstants || Idx == 0)) {
3761 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3762 // Handle MMX and SSE both.
3763 EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3764 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3766 // Truncate the value (which may itself be a constant) to i32, and
3767 // convert it to a vector with movd (S2V+shuffle to zero extend).
3768 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3769 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3770 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3771 Subtarget->hasSSE2(), DAG);
3773 // Now we have our 32-bit value zero extended in the low element of
3774 // a vector. If Idx != 0, swizzle it into place.
3776 SmallVector<int, 4> Mask;
3777 Mask.push_back(Idx);
3778 for (unsigned i = 1; i != VecElts; ++i)
3780 Item = DAG.getVectorShuffle(VecVT, dl, Item,
3781 DAG.getUNDEF(Item.getValueType()),
3784 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3788 // If we have a constant or non-constant insertion into the low element of
3789 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3790 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3791 // depending on what the source datatype is.
3794 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3795 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3796 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3797 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3798 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3799 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3801 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3802 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3803 EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3804 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3805 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3806 Subtarget->hasSSE2(), DAG);
3807 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3811 // Is it a vector logical left shift?
3812 if (NumElems == 2 && Idx == 1 &&
3813 X86::isZeroNode(Op.getOperand(0)) &&
3814 !X86::isZeroNode(Op.getOperand(1))) {
3815 unsigned NumBits = VT.getSizeInBits();
3816 return getVShift(true, VT,
3817 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3818 VT, Op.getOperand(1)),
3819 NumBits/2, DAG, *this, dl);
3822 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3825 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3826 // is a non-constant being inserted into an element other than the low one,
3827 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3828 // movd/movss) to move this into the low element, then shuffle it into
3830 if (EVTBits == 32) {
3831 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3833 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3834 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3835 Subtarget->hasSSE2(), DAG);
3836 SmallVector<int, 8> MaskVec;
3837 for (unsigned i = 0; i < NumElems; i++)
3838 MaskVec.push_back(i == Idx ? 0 : 1);
3839 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3843 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3844 if (Values.size() == 1) {
3845 if (EVTBits == 32) {
3846 // Instead of a shuffle like this:
3847 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
3848 // Check if it's possible to issue this instead.
3849 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
3850 unsigned Idx = CountTrailingZeros_32(NonZeros);
3851 SDValue Item = Op.getOperand(Idx);
3852 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
3853 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
3858 // A vector full of immediates; various special cases are already
3859 // handled, so this is best done with a single constant-pool load.
3863 // Let legalizer expand 2-wide build_vectors.
3864 if (EVTBits == 64) {
3865 if (NumNonZero == 1) {
3866 // One half is zero or undef.
3867 unsigned Idx = CountTrailingZeros_32(NonZeros);
3868 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3869 Op.getOperand(Idx));
3870 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3871 Subtarget->hasSSE2(), DAG);
3876 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3877 if (EVTBits == 8 && NumElems == 16) {
3878 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3880 if (V.getNode()) return V;
3883 if (EVTBits == 16 && NumElems == 8) {
3884 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3886 if (V.getNode()) return V;
3889 // If element VT is == 32 bits, turn it into a number of shuffles.
3890 SmallVector<SDValue, 8> V;
3892 if (NumElems == 4 && NumZero > 0) {
3893 for (unsigned i = 0; i < 4; ++i) {
3894 bool isZero = !(NonZeros & (1 << i));
3896 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3898 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3901 for (unsigned i = 0; i < 2; ++i) {
3902 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3905 V[i] = V[i*2]; // Must be a zero vector.
3908 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3911 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3914 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3919 SmallVector<int, 8> MaskVec;
3920 bool Reverse = (NonZeros & 0x3) == 2;
3921 for (unsigned i = 0; i < 2; ++i)
3922 MaskVec.push_back(Reverse ? 1-i : i);
3923 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3924 for (unsigned i = 0; i < 2; ++i)
3925 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3926 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3929 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
3930 // Check for a build vector of consecutive loads.
3931 for (unsigned i = 0; i < NumElems; ++i)
3932 V[i] = Op.getOperand(i);
3934 // Check for elements which are consecutive loads.
3935 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
3939 // For SSE 4.1, use inserts into undef.
3940 if (getSubtarget()->hasSSE41()) {
3941 V[0] = DAG.getUNDEF(VT);
3942 for (unsigned i = 0; i < NumElems; ++i)
3943 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3944 V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3945 Op.getOperand(i), DAG.getIntPtrConstant(i));
3949 // Otherwise, expand into a number of unpckl*
3951 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3952 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3953 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3954 for (unsigned i = 0; i < NumElems; ++i)
3955 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3957 while (NumElems != 0) {
3958 for (unsigned i = 0; i < NumElems; ++i)
3959 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3968 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
3969 // We support concatenate two MMX registers and place them in a MMX
3970 // register. This is better than doing a stack convert.
3971 DebugLoc dl = Op.getDebugLoc();
3972 EVT ResVT = Op.getValueType();
3973 assert(Op.getNumOperands() == 2);
3974 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
3975 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
3977 SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
3978 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
3979 InVec = Op.getOperand(1);
3980 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
3981 unsigned NumElts = ResVT.getVectorNumElements();
3982 VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
3983 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
3984 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
3986 InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
3987 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
3988 Mask[0] = 0; Mask[1] = 2;
3989 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
3991 return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
3994 // v8i16 shuffles - Prefer shuffles in the following order:
3995 // 1. [all] pshuflw, pshufhw, optional move
3996 // 2. [ssse3] 1 x pshufb
3997 // 3. [ssse3] 2 x pshufb + 1 x por
3998 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4000 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
4001 SelectionDAG &DAG, X86TargetLowering &TLI) {
4002 SDValue V1 = SVOp->getOperand(0);
4003 SDValue V2 = SVOp->getOperand(1);
4004 DebugLoc dl = SVOp->getDebugLoc();
4005 SmallVector<int, 8> MaskVals;
4007 // Determine if more than 1 of the words in each of the low and high quadwords
4008 // of the result come from the same quadword of one of the two inputs. Undef
4009 // mask values count as coming from any quadword, for better codegen.
4010 SmallVector<unsigned, 4> LoQuad(4);
4011 SmallVector<unsigned, 4> HiQuad(4);
4012 BitVector InputQuads(4);
4013 for (unsigned i = 0; i < 8; ++i) {
4014 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4015 int EltIdx = SVOp->getMaskElt(i);
4016 MaskVals.push_back(EltIdx);
4025 InputQuads.set(EltIdx / 4);
4028 int BestLoQuad = -1;
4029 unsigned MaxQuad = 1;
4030 for (unsigned i = 0; i < 4; ++i) {
4031 if (LoQuad[i] > MaxQuad) {
4033 MaxQuad = LoQuad[i];
4037 int BestHiQuad = -1;
4039 for (unsigned i = 0; i < 4; ++i) {
4040 if (HiQuad[i] > MaxQuad) {
4042 MaxQuad = HiQuad[i];
4046 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4047 // of the two input vectors, shuffle them into one input vector so only a
4048 // single pshufb instruction is necessary. If There are more than 2 input
4049 // quads, disable the next transformation since it does not help SSSE3.
4050 bool V1Used = InputQuads[0] || InputQuads[1];
4051 bool V2Used = InputQuads[2] || InputQuads[3];
4052 if (TLI.getSubtarget()->hasSSSE3()) {
4053 if (InputQuads.count() == 2 && V1Used && V2Used) {
4054 BestLoQuad = InputQuads.find_first();
4055 BestHiQuad = InputQuads.find_next(BestLoQuad);
4057 if (InputQuads.count() > 2) {
4063 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4064 // the shuffle mask. If a quad is scored as -1, that means that it contains
4065 // words from all 4 input quadwords.
4067 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4068 SmallVector<int, 8> MaskV;
4069 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4070 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4071 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4072 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
4073 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
4074 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
4076 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4077 // source words for the shuffle, to aid later transformations.
4078 bool AllWordsInNewV = true;
4079 bool InOrder[2] = { true, true };
4080 for (unsigned i = 0; i != 8; ++i) {
4081 int idx = MaskVals[i];
4083 InOrder[i/4] = false;
4084 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4086 AllWordsInNewV = false;
4090 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4091 if (AllWordsInNewV) {
4092 for (int i = 0; i != 8; ++i) {
4093 int idx = MaskVals[i];
4096 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4097 if ((idx != i) && idx < 4)
4099 if ((idx != i) && idx > 3)
4108 // If we've eliminated the use of V2, and the new mask is a pshuflw or
4109 // pshufhw, that's as cheap as it gets. Return the new shuffle.
4110 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4111 return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4112 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4116 // If we have SSSE3, and all words of the result are from 1 input vector,
4117 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
4118 // is present, fall back to case 4.
4119 if (TLI.getSubtarget()->hasSSSE3()) {
4120 SmallVector<SDValue,16> pshufbMask;
4122 // If we have elements from both input vectors, set the high bit of the
4123 // shuffle mask element to zero out elements that come from V2 in the V1
4124 // mask, and elements that come from V1 in the V2 mask, so that the two
4125 // results can be OR'd together.
4126 bool TwoInputs = V1Used && V2Used;
4127 for (unsigned i = 0; i != 8; ++i) {
4128 int EltIdx = MaskVals[i] * 2;
4129 if (TwoInputs && (EltIdx >= 16)) {
4130 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4131 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4134 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4135 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4137 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
4138 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4139 DAG.getNode(ISD::BUILD_VECTOR, dl,
4140 MVT::v16i8, &pshufbMask[0], 16));
4142 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4144 // Calculate the shuffle mask for the second input, shuffle it, and
4145 // OR it with the first shuffled input.
4147 for (unsigned i = 0; i != 8; ++i) {
4148 int EltIdx = MaskVals[i] * 2;
4150 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4151 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4154 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4155 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4157 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
4158 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4159 DAG.getNode(ISD::BUILD_VECTOR, dl,
4160 MVT::v16i8, &pshufbMask[0], 16));
4161 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4162 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4165 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4166 // and update MaskVals with new element order.
4167 BitVector InOrder(8);
4168 if (BestLoQuad >= 0) {
4169 SmallVector<int, 8> MaskV;
4170 for (int i = 0; i != 4; ++i) {
4171 int idx = MaskVals[i];
4173 MaskV.push_back(-1);
4175 } else if ((idx / 4) == BestLoQuad) {
4176 MaskV.push_back(idx & 3);
4179 MaskV.push_back(-1);
4182 for (unsigned i = 4; i != 8; ++i)
4184 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4188 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4189 // and update MaskVals with the new element order.
4190 if (BestHiQuad >= 0) {
4191 SmallVector<int, 8> MaskV;
4192 for (unsigned i = 0; i != 4; ++i)
4194 for (unsigned i = 4; i != 8; ++i) {
4195 int idx = MaskVals[i];
4197 MaskV.push_back(-1);
4199 } else if ((idx / 4) == BestHiQuad) {
4200 MaskV.push_back((idx & 3) + 4);
4203 MaskV.push_back(-1);
4206 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4210 // In case BestHi & BestLo were both -1, which means each quadword has a word
4211 // from each of the four input quadwords, calculate the InOrder bitvector now
4212 // before falling through to the insert/extract cleanup.
4213 if (BestLoQuad == -1 && BestHiQuad == -1) {
4215 for (int i = 0; i != 8; ++i)
4216 if (MaskVals[i] < 0 || MaskVals[i] == i)
4220 // The other elements are put in the right place using pextrw and pinsrw.
4221 for (unsigned i = 0; i != 8; ++i) {
4224 int EltIdx = MaskVals[i];
4227 SDValue ExtOp = (EltIdx < 8)
4228 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4229 DAG.getIntPtrConstant(EltIdx))
4230 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4231 DAG.getIntPtrConstant(EltIdx - 8));
4232 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4233 DAG.getIntPtrConstant(i));
4238 // v16i8 shuffles - Prefer shuffles in the following order:
4239 // 1. [ssse3] 1 x pshufb
4240 // 2. [ssse3] 2 x pshufb + 1 x por
4241 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
4243 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4244 SelectionDAG &DAG, X86TargetLowering &TLI) {
4245 SDValue V1 = SVOp->getOperand(0);
4246 SDValue V2 = SVOp->getOperand(1);
4247 DebugLoc dl = SVOp->getDebugLoc();
4248 SmallVector<int, 16> MaskVals;
4249 SVOp->getMask(MaskVals);
4251 // If we have SSSE3, case 1 is generated when all result bytes come from
4252 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
4253 // present, fall back to case 3.
4254 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4257 for (unsigned i = 0; i < 16; ++i) {
4258 int EltIdx = MaskVals[i];
4267 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4268 if (TLI.getSubtarget()->hasSSSE3()) {
4269 SmallVector<SDValue,16> pshufbMask;
4271 // If all result elements are from one input vector, then only translate
4272 // undef mask values to 0x80 (zero out result) in the pshufb mask.
4274 // Otherwise, we have elements from both input vectors, and must zero out
4275 // elements that come from V2 in the first mask, and V1 in the second mask
4276 // so that we can OR them together.
4277 bool TwoInputs = !(V1Only || V2Only);
4278 for (unsigned i = 0; i != 16; ++i) {
4279 int EltIdx = MaskVals[i];
4280 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4281 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4284 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4286 // If all the elements are from V2, assign it to V1 and return after
4287 // building the first pshufb.
4290 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4291 DAG.getNode(ISD::BUILD_VECTOR, dl,
4292 MVT::v16i8, &pshufbMask[0], 16));
4296 // Calculate the shuffle mask for the second input, shuffle it, and
4297 // OR it with the first shuffled input.
4299 for (unsigned i = 0; i != 16; ++i) {
4300 int EltIdx = MaskVals[i];
4302 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4305 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4307 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4308 DAG.getNode(ISD::BUILD_VECTOR, dl,
4309 MVT::v16i8, &pshufbMask[0], 16));
4310 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4313 // No SSSE3 - Calculate in place words and then fix all out of place words
4314 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
4315 // the 16 different words that comprise the two doublequadword input vectors.
4316 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4317 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4318 SDValue NewV = V2Only ? V2 : V1;
4319 for (int i = 0; i != 8; ++i) {
4320 int Elt0 = MaskVals[i*2];
4321 int Elt1 = MaskVals[i*2+1];
4323 // This word of the result is all undef, skip it.
4324 if (Elt0 < 0 && Elt1 < 0)
4327 // This word of the result is already in the correct place, skip it.
4328 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4330 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4333 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4334 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4337 // If Elt0 and Elt1 are defined, are consecutive, and can be load
4338 // using a single extract together, load it and store it.
4339 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4340 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4341 DAG.getIntPtrConstant(Elt1 / 2));
4342 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4343 DAG.getIntPtrConstant(i));
4347 // If Elt1 is defined, extract it from the appropriate source. If the
4348 // source byte is not also odd, shift the extracted word left 8 bits
4349 // otherwise clear the bottom 8 bits if we need to do an or.
4351 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4352 DAG.getIntPtrConstant(Elt1 / 2));
4353 if ((Elt1 & 1) == 0)
4354 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4355 DAG.getConstant(8, TLI.getShiftAmountTy()));
4357 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4358 DAG.getConstant(0xFF00, MVT::i16));
4360 // If Elt0 is defined, extract it from the appropriate source. If the
4361 // source byte is not also even, shift the extracted word right 8 bits. If
4362 // Elt1 was also defined, OR the extracted values together before
4363 // inserting them in the result.
4365 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4366 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4367 if ((Elt0 & 1) != 0)
4368 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4369 DAG.getConstant(8, TLI.getShiftAmountTy()));
4371 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4372 DAG.getConstant(0x00FF, MVT::i16));
4373 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4376 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4377 DAG.getIntPtrConstant(i));
4379 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4382 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4383 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
4384 /// done when every pair / quad of shuffle mask elements point to elements in
4385 /// the right sequence. e.g.
4386 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
4388 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4390 TargetLowering &TLI, DebugLoc dl) {
4391 EVT VT = SVOp->getValueType(0);
4392 SDValue V1 = SVOp->getOperand(0);
4393 SDValue V2 = SVOp->getOperand(1);
4394 unsigned NumElems = VT.getVectorNumElements();
4395 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4396 EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
4397 EVT MaskEltVT = MaskVT.getVectorElementType();
4399 switch (VT.getSimpleVT().SimpleTy) {
4400 default: assert(false && "Unexpected!");
4401 case MVT::v4f32: NewVT = MVT::v2f64; break;
4402 case MVT::v4i32: NewVT = MVT::v2i64; break;
4403 case MVT::v8i16: NewVT = MVT::v4i32; break;
4404 case MVT::v16i8: NewVT = MVT::v4i32; break;
4407 if (NewWidth == 2) {
4413 int Scale = NumElems / NewWidth;
4414 SmallVector<int, 8> MaskVec;
4415 for (unsigned i = 0; i < NumElems; i += Scale) {
4417 for (int j = 0; j < Scale; ++j) {
4418 int EltIdx = SVOp->getMaskElt(i+j);
4422 StartIdx = EltIdx - (EltIdx % Scale);
4423 if (EltIdx != StartIdx + j)
4427 MaskVec.push_back(-1);
4429 MaskVec.push_back(StartIdx / Scale);
4432 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4433 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4434 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4437 /// getVZextMovL - Return a zero-extending vector move low node.
4439 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4440 SDValue SrcOp, SelectionDAG &DAG,
4441 const X86Subtarget *Subtarget, DebugLoc dl) {
4442 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4443 LoadSDNode *LD = NULL;
4444 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4445 LD = dyn_cast<LoadSDNode>(SrcOp);
4447 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4449 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4450 if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4451 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4452 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4453 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4455 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4456 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4457 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4458 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4466 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4467 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4468 DAG.getNode(ISD::BIT_CONVERT, dl,
4472 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4475 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4476 SDValue V1 = SVOp->getOperand(0);
4477 SDValue V2 = SVOp->getOperand(1);
4478 DebugLoc dl = SVOp->getDebugLoc();
4479 EVT VT = SVOp->getValueType(0);
4481 SmallVector<std::pair<int, int>, 8> Locs;
4483 SmallVector<int, 8> Mask1(4U, -1);
4484 SmallVector<int, 8> PermMask;
4485 SVOp->getMask(PermMask);
4489 for (unsigned i = 0; i != 4; ++i) {
4490 int Idx = PermMask[i];
4492 Locs[i] = std::make_pair(-1, -1);
4494 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4496 Locs[i] = std::make_pair(0, NumLo);
4500 Locs[i] = std::make_pair(1, NumHi);
4502 Mask1[2+NumHi] = Idx;
4508 if (NumLo <= 2 && NumHi <= 2) {
4509 // If no more than two elements come from either vector. This can be
4510 // implemented with two shuffles. First shuffle gather the elements.
4511 // The second shuffle, which takes the first shuffle as both of its
4512 // vector operands, put the elements into the right order.
4513 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4515 SmallVector<int, 8> Mask2(4U, -1);
4517 for (unsigned i = 0; i != 4; ++i) {
4518 if (Locs[i].first == -1)
4521 unsigned Idx = (i < 2) ? 0 : 4;
4522 Idx += Locs[i].first * 2 + Locs[i].second;
4527 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4528 } else if (NumLo == 3 || NumHi == 3) {
4529 // Otherwise, we must have three elements from one vector, call it X, and
4530 // one element from the other, call it Y. First, use a shufps to build an
4531 // intermediate vector with the one element from Y and the element from X
4532 // that will be in the same half in the final destination (the indexes don't
4533 // matter). Then, use a shufps to build the final vector, taking the half
4534 // containing the element from Y from the intermediate, and the other half
4537 // Normalize it so the 3 elements come from V1.
4538 CommuteVectorShuffleMask(PermMask, VT);
4542 // Find the element from V2.
4544 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4545 int Val = PermMask[HiIndex];
4552 Mask1[0] = PermMask[HiIndex];
4554 Mask1[2] = PermMask[HiIndex^1];
4556 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4559 Mask1[0] = PermMask[0];
4560 Mask1[1] = PermMask[1];
4561 Mask1[2] = HiIndex & 1 ? 6 : 4;
4562 Mask1[3] = HiIndex & 1 ? 4 : 6;
4563 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4565 Mask1[0] = HiIndex & 1 ? 2 : 0;
4566 Mask1[1] = HiIndex & 1 ? 0 : 2;
4567 Mask1[2] = PermMask[2];
4568 Mask1[3] = PermMask[3];
4573 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4577 // Break it into (shuffle shuffle_hi, shuffle_lo).
4579 SmallVector<int,8> LoMask(4U, -1);
4580 SmallVector<int,8> HiMask(4U, -1);
4582 SmallVector<int,8> *MaskPtr = &LoMask;
4583 unsigned MaskIdx = 0;
4586 for (unsigned i = 0; i != 4; ++i) {
4593 int Idx = PermMask[i];
4595 Locs[i] = std::make_pair(-1, -1);
4596 } else if (Idx < 4) {
4597 Locs[i] = std::make_pair(MaskIdx, LoIdx);
4598 (*MaskPtr)[LoIdx] = Idx;
4601 Locs[i] = std::make_pair(MaskIdx, HiIdx);
4602 (*MaskPtr)[HiIdx] = Idx;
4607 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4608 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4609 SmallVector<int, 8> MaskOps;
4610 for (unsigned i = 0; i != 4; ++i) {
4611 if (Locs[i].first == -1) {
4612 MaskOps.push_back(-1);
4614 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4615 MaskOps.push_back(Idx);
4618 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4622 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4623 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4624 SDValue V1 = Op.getOperand(0);
4625 SDValue V2 = Op.getOperand(1);
4626 EVT VT = Op.getValueType();
4627 DebugLoc dl = Op.getDebugLoc();
4628 unsigned NumElems = VT.getVectorNumElements();
4629 bool isMMX = VT.getSizeInBits() == 64;
4630 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4631 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4632 bool V1IsSplat = false;
4633 bool V2IsSplat = false;
4635 if (isZeroShuffle(SVOp))
4636 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4638 // Promote splats to v4f32.
4639 if (SVOp->isSplat()) {
4640 if (isMMX || NumElems < 4)
4642 return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4645 // If the shuffle can be profitably rewritten as a narrower shuffle, then
4647 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4648 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4649 if (NewOp.getNode())
4650 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4651 LowerVECTOR_SHUFFLE(NewOp, DAG));
4652 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4653 // FIXME: Figure out a cleaner way to do this.
4654 // Try to make use of movq to zero out the top part.
4655 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4656 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4657 if (NewOp.getNode()) {
4658 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4659 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4660 DAG, Subtarget, dl);
4662 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4663 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4664 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4665 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4666 DAG, Subtarget, dl);
4670 if (X86::isPSHUFDMask(SVOp))
4673 // Check if this can be converted into a logical shift.
4674 bool isLeft = false;
4677 bool isShift = getSubtarget()->hasSSE2() &&
4678 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4679 if (isShift && ShVal.hasOneUse()) {
4680 // If the shifted value has multiple uses, it may be cheaper to use
4681 // v_set0 + movlhps or movhlps, etc.
4682 EVT EltVT = VT.getVectorElementType();
4683 ShAmt *= EltVT.getSizeInBits();
4684 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4687 if (X86::isMOVLMask(SVOp)) {
4690 if (ISD::isBuildVectorAllZeros(V1.getNode()))
4691 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4696 // FIXME: fold these into legal mask.
4697 if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4698 X86::isMOVSLDUPMask(SVOp) ||
4699 X86::isMOVHLPSMask(SVOp) ||
4700 X86::isMOVLHPSMask(SVOp) ||
4701 X86::isMOVLPMask(SVOp)))
4704 if (ShouldXformToMOVHLPS(SVOp) ||
4705 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4706 return CommuteVectorShuffle(SVOp, DAG);
4709 // No better options. Use a vshl / vsrl.
4710 EVT EltVT = VT.getVectorElementType();
4711 ShAmt *= EltVT.getSizeInBits();
4712 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4715 bool Commuted = false;
4716 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4717 // 1,1,1,1 -> v8i16 though.
4718 V1IsSplat = isSplatVector(V1.getNode());
4719 V2IsSplat = isSplatVector(V2.getNode());
4721 // Canonicalize the splat or undef, if present, to be on the RHS.
4722 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4723 Op = CommuteVectorShuffle(SVOp, DAG);
4724 SVOp = cast<ShuffleVectorSDNode>(Op);
4725 V1 = SVOp->getOperand(0);
4726 V2 = SVOp->getOperand(1);
4727 std::swap(V1IsSplat, V2IsSplat);
4728 std::swap(V1IsUndef, V2IsUndef);
4732 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4733 // Shuffling low element of v1 into undef, just return v1.
4736 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4737 // the instruction selector will not match, so get a canonical MOVL with
4738 // swapped operands to undo the commute.
4739 return getMOVL(DAG, dl, VT, V2, V1);
4742 if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4743 X86::isUNPCKH_v_undef_Mask(SVOp) ||
4744 X86::isUNPCKLMask(SVOp) ||
4745 X86::isUNPCKHMask(SVOp))
4749 // Normalize mask so all entries that point to V2 points to its first
4750 // element then try to match unpck{h|l} again. If match, return a
4751 // new vector_shuffle with the corrected mask.
4752 SDValue NewMask = NormalizeMask(SVOp, DAG);
4753 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4754 if (NSVOp != SVOp) {
4755 if (X86::isUNPCKLMask(NSVOp, true)) {
4757 } else if (X86::isUNPCKHMask(NSVOp, true)) {
4764 // Commute is back and try unpck* again.
4765 // FIXME: this seems wrong.
4766 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4767 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4768 if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4769 X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4770 X86::isUNPCKLMask(NewSVOp) ||
4771 X86::isUNPCKHMask(NewSVOp))
4775 // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4777 // Normalize the node to match x86 shuffle ops if needed
4778 if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4779 return CommuteVectorShuffle(SVOp, DAG);
4781 // Check for legal shuffle and return?
4782 SmallVector<int, 16> PermMask;
4783 SVOp->getMask(PermMask);
4784 if (isShuffleMaskLegal(PermMask, VT))
4787 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4788 if (VT == MVT::v8i16) {
4789 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4790 if (NewOp.getNode())
4794 if (VT == MVT::v16i8) {
4795 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4796 if (NewOp.getNode())
4800 // Handle all 4 wide cases with a number of shuffles except for MMX.
4801 if (NumElems == 4 && !isMMX)
4802 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4808 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4809 SelectionDAG &DAG) {
4810 EVT VT = Op.getValueType();
4811 DebugLoc dl = Op.getDebugLoc();
4812 if (VT.getSizeInBits() == 8) {
4813 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4814 Op.getOperand(0), Op.getOperand(1));
4815 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4816 DAG.getValueType(VT));
4817 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4818 } else if (VT.getSizeInBits() == 16) {
4819 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4820 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4822 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4823 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4824 DAG.getNode(ISD::BIT_CONVERT, dl,
4828 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4829 Op.getOperand(0), Op.getOperand(1));
4830 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4831 DAG.getValueType(VT));
4832 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4833 } else if (VT == MVT::f32) {
4834 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4835 // the result back to FR32 register. It's only worth matching if the
4836 // result has a single use which is a store or a bitcast to i32. And in
4837 // the case of a store, it's not worth it if the index is a constant 0,
4838 // because a MOVSSmr can be used instead, which is smaller and faster.
4839 if (!Op.hasOneUse())
4841 SDNode *User = *Op.getNode()->use_begin();
4842 if ((User->getOpcode() != ISD::STORE ||
4843 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4844 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4845 (User->getOpcode() != ISD::BIT_CONVERT ||
4846 User->getValueType(0) != MVT::i32))
4848 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4849 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4852 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4853 } else if (VT == MVT::i32) {
4854 // ExtractPS works with constant index.
4855 if (isa<ConstantSDNode>(Op.getOperand(1)))
4863 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4864 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4867 if (Subtarget->hasSSE41()) {
4868 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4873 EVT VT = Op.getValueType();
4874 DebugLoc dl = Op.getDebugLoc();
4875 // TODO: handle v16i8.
4876 if (VT.getSizeInBits() == 16) {
4877 SDValue Vec = Op.getOperand(0);
4878 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4880 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4881 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4882 DAG.getNode(ISD::BIT_CONVERT, dl,
4885 // Transform it so it match pextrw which produces a 32-bit result.
4886 EVT EltVT = MVT::i32;
4887 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
4888 Op.getOperand(0), Op.getOperand(1));
4889 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
4890 DAG.getValueType(VT));
4891 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4892 } else if (VT.getSizeInBits() == 32) {
4893 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4897 // SHUFPS the element to the lowest double word, then movss.
4898 int Mask[4] = { Idx, -1, -1, -1 };
4899 EVT VVT = Op.getOperand(0).getValueType();
4900 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4901 DAG.getUNDEF(VVT), Mask);
4902 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4903 DAG.getIntPtrConstant(0));
4904 } else if (VT.getSizeInBits() == 64) {
4905 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4906 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4907 // to match extract_elt for f64.
4908 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4912 // UNPCKHPD the element to the lowest double word, then movsd.
4913 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4914 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4915 int Mask[2] = { 1, -1 };
4916 EVT VVT = Op.getOperand(0).getValueType();
4917 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4918 DAG.getUNDEF(VVT), Mask);
4919 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4920 DAG.getIntPtrConstant(0));
4927 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4928 EVT VT = Op.getValueType();
4929 EVT EltVT = VT.getVectorElementType();
4930 DebugLoc dl = Op.getDebugLoc();
4932 SDValue N0 = Op.getOperand(0);
4933 SDValue N1 = Op.getOperand(1);
4934 SDValue N2 = Op.getOperand(2);
4936 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
4937 isa<ConstantSDNode>(N2)) {
4939 if (VT == MVT::v8i16)
4940 Opc = X86ISD::PINSRW;
4941 else if (VT == MVT::v4i16)
4942 Opc = X86ISD::MMX_PINSRW;
4943 else if (VT == MVT::v16i8)
4944 Opc = X86ISD::PINSRB;
4946 Opc = X86ISD::PINSRB;
4948 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4950 if (N1.getValueType() != MVT::i32)
4951 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4952 if (N2.getValueType() != MVT::i32)
4953 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4954 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4955 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4956 // Bits [7:6] of the constant are the source select. This will always be
4957 // zero here. The DAG Combiner may combine an extract_elt index into these
4958 // bits. For example (insert (extract, 3), 2) could be matched by putting
4959 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4960 // Bits [5:4] of the constant are the destination select. This is the
4961 // value of the incoming immediate.
4962 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4963 // combine either bitwise AND or insert of float 0.0 to set these bits.
4964 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4965 // Create this as a scalar to vector..
4966 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
4967 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4968 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
4969 // PINSR* works with constant index.
4976 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4977 EVT VT = Op.getValueType();
4978 EVT EltVT = VT.getVectorElementType();
4980 if (Subtarget->hasSSE41())
4981 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4983 if (EltVT == MVT::i8)
4986 DebugLoc dl = Op.getDebugLoc();
4987 SDValue N0 = Op.getOperand(0);
4988 SDValue N1 = Op.getOperand(1);
4989 SDValue N2 = Op.getOperand(2);
4991 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
4992 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4993 // as its second argument.
4994 if (N1.getValueType() != MVT::i32)
4995 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4996 if (N2.getValueType() != MVT::i32)
4997 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4998 return DAG.getNode(VT == MVT::v8i16 ? X86ISD::PINSRW : X86ISD::MMX_PINSRW,
4999 dl, VT, N0, N1, N2);
5005 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
5006 DebugLoc dl = Op.getDebugLoc();
5007 if (Op.getValueType() == MVT::v2f32)
5008 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
5009 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
5010 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
5011 Op.getOperand(0))));
5013 if (Op.getValueType() == MVT::v1i64 && Op.getOperand(0).getValueType() == MVT::i64)
5014 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5016 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5017 EVT VT = MVT::v2i32;
5018 switch (Op.getValueType().getSimpleVT().SimpleTy) {
5025 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
5026 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
5029 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5030 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5031 // one of the above mentioned nodes. It has to be wrapped because otherwise
5032 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5033 // be used to form addressing mode. These wrapped nodes will be selected
5036 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
5037 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5039 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5041 unsigned char OpFlag = 0;
5042 unsigned WrapperKind = X86ISD::Wrapper;
5043 CodeModel::Model M = getTargetMachine().getCodeModel();
5045 if (Subtarget->isPICStyleRIPRel() &&
5046 (M == CodeModel::Small || M == CodeModel::Kernel))
5047 WrapperKind = X86ISD::WrapperRIP;
5048 else if (Subtarget->isPICStyleGOT())
5049 OpFlag = X86II::MO_GOTOFF;
5050 else if (Subtarget->isPICStyleStubPIC())
5051 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5053 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5055 CP->getOffset(), OpFlag);
5056 DebugLoc DL = CP->getDebugLoc();
5057 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5058 // With PIC, the address is actually $g + Offset.
5060 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5061 DAG.getNode(X86ISD::GlobalBaseReg,
5062 DebugLoc(), getPointerTy()),
5069 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
5070 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5072 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5074 unsigned char OpFlag = 0;
5075 unsigned WrapperKind = X86ISD::Wrapper;
5076 CodeModel::Model M = getTargetMachine().getCodeModel();
5078 if (Subtarget->isPICStyleRIPRel() &&
5079 (M == CodeModel::Small || M == CodeModel::Kernel))
5080 WrapperKind = X86ISD::WrapperRIP;
5081 else if (Subtarget->isPICStyleGOT())
5082 OpFlag = X86II::MO_GOTOFF;
5083 else if (Subtarget->isPICStyleStubPIC())
5084 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5086 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5088 DebugLoc DL = JT->getDebugLoc();
5089 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5091 // With PIC, the address is actually $g + Offset.
5093 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5094 DAG.getNode(X86ISD::GlobalBaseReg,
5095 DebugLoc(), getPointerTy()),
5103 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
5104 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5106 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5108 unsigned char OpFlag = 0;
5109 unsigned WrapperKind = X86ISD::Wrapper;
5110 CodeModel::Model M = getTargetMachine().getCodeModel();
5112 if (Subtarget->isPICStyleRIPRel() &&
5113 (M == CodeModel::Small || M == CodeModel::Kernel))
5114 WrapperKind = X86ISD::WrapperRIP;
5115 else if (Subtarget->isPICStyleGOT())
5116 OpFlag = X86II::MO_GOTOFF;
5117 else if (Subtarget->isPICStyleStubPIC())
5118 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5120 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5122 DebugLoc DL = Op.getDebugLoc();
5123 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5126 // With PIC, the address is actually $g + Offset.
5127 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
5128 !Subtarget->is64Bit()) {
5129 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5130 DAG.getNode(X86ISD::GlobalBaseReg,
5131 DebugLoc(), getPointerTy()),
5139 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) {
5140 // Create the TargetBlockAddressAddress node.
5141 unsigned char OpFlags =
5142 Subtarget->ClassifyBlockAddressReference();
5143 CodeModel::Model M = getTargetMachine().getCodeModel();
5144 BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5145 DebugLoc dl = Op.getDebugLoc();
5146 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5147 /*isTarget=*/true, OpFlags);
5149 if (Subtarget->isPICStyleRIPRel() &&
5150 (M == CodeModel::Small || M == CodeModel::Kernel))
5151 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5153 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5155 // With PIC, the address is actually $g + Offset.
5156 if (isGlobalRelativeToPICBase(OpFlags)) {
5157 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5158 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5166 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
5168 SelectionDAG &DAG) const {
5169 // Create the TargetGlobalAddress node, folding in the constant
5170 // offset if it is legal.
5171 unsigned char OpFlags =
5172 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5173 CodeModel::Model M = getTargetMachine().getCodeModel();
5175 if (OpFlags == X86II::MO_NO_FLAG &&
5176 X86::isOffsetSuitableForCodeModel(Offset, M)) {
5177 // A direct static reference to a global.
5178 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
5181 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
5184 if (Subtarget->isPICStyleRIPRel() &&
5185 (M == CodeModel::Small || M == CodeModel::Kernel))
5186 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5188 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5190 // With PIC, the address is actually $g + Offset.
5191 if (isGlobalRelativeToPICBase(OpFlags)) {
5192 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5193 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5197 // For globals that require a load from a stub to get the address, emit the
5199 if (isGlobalStubReference(OpFlags))
5200 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
5201 PseudoSourceValue::getGOT(), 0, false, false, 0);
5203 // If there was a non-zero offset that we didn't fold, create an explicit
5206 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
5207 DAG.getConstant(Offset, getPointerTy()));
5213 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
5214 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
5215 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
5216 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
5220 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
5221 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
5222 unsigned char OperandFlags) {
5223 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5224 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5225 DebugLoc dl = GA->getDebugLoc();
5226 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
5227 GA->getValueType(0),
5231 SDValue Ops[] = { Chain, TGA, *InFlag };
5232 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
5234 SDValue Ops[] = { Chain, TGA };
5235 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
5238 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
5239 MFI->setHasCalls(true);
5241 SDValue Flag = Chain.getValue(1);
5242 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
5245 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
5247 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5250 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
5251 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
5252 DAG.getNode(X86ISD::GlobalBaseReg,
5253 DebugLoc(), PtrVT), InFlag);
5254 InFlag = Chain.getValue(1);
5256 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
5259 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
5261 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5263 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
5264 X86::RAX, X86II::MO_TLSGD);
5267 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
5268 // "local exec" model.
5269 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5270 const EVT PtrVT, TLSModel::Model model,
5272 DebugLoc dl = GA->getDebugLoc();
5273 // Get the Thread Pointer
5274 SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
5276 DAG.getRegister(is64Bit? X86::FS : X86::GS,
5279 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
5280 NULL, 0, false, false, 0);
5282 unsigned char OperandFlags = 0;
5283 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
5285 unsigned WrapperKind = X86ISD::Wrapper;
5286 if (model == TLSModel::LocalExec) {
5287 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
5288 } else if (is64Bit) {
5289 assert(model == TLSModel::InitialExec);
5290 OperandFlags = X86II::MO_GOTTPOFF;
5291 WrapperKind = X86ISD::WrapperRIP;
5293 assert(model == TLSModel::InitialExec);
5294 OperandFlags = X86II::MO_INDNTPOFF;
5297 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
5299 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
5300 GA->getOffset(), OperandFlags);
5301 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
5303 if (model == TLSModel::InitialExec)
5304 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
5305 PseudoSourceValue::getGOT(), 0, false, false, 0);
5307 // The address of the thread local variable is the add of the thread
5308 // pointer with the offset of the variable.
5309 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
5313 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
5314 // TODO: implement the "local dynamic" model
5315 // TODO: implement the "initial exec"model for pic executables
5316 assert(Subtarget->isTargetELF() &&
5317 "TLS not implemented for non-ELF targets");
5318 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5319 const GlobalValue *GV = GA->getGlobal();
5321 // If GV is an alias then use the aliasee for determining
5322 // thread-localness.
5323 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
5324 GV = GA->resolveAliasedGlobal(false);
5326 TLSModel::Model model = getTLSModel(GV,
5327 getTargetMachine().getRelocationModel());
5330 case TLSModel::GeneralDynamic:
5331 case TLSModel::LocalDynamic: // not implemented
5332 if (Subtarget->is64Bit())
5333 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
5334 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
5336 case TLSModel::InitialExec:
5337 case TLSModel::LocalExec:
5338 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
5339 Subtarget->is64Bit());
5342 llvm_unreachable("Unreachable");
5347 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
5348 /// take a 2 x i32 value to shift plus a shift amount.
5349 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
5350 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5351 EVT VT = Op.getValueType();
5352 unsigned VTBits = VT.getSizeInBits();
5353 DebugLoc dl = Op.getDebugLoc();
5354 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
5355 SDValue ShOpLo = Op.getOperand(0);
5356 SDValue ShOpHi = Op.getOperand(1);
5357 SDValue ShAmt = Op.getOperand(2);
5358 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
5359 DAG.getConstant(VTBits - 1, MVT::i8))
5360 : DAG.getConstant(0, VT);
5363 if (Op.getOpcode() == ISD::SHL_PARTS) {
5364 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
5365 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5367 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
5368 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
5371 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
5372 DAG.getConstant(VTBits, MVT::i8));
5373 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
5374 AndNode, DAG.getConstant(0, MVT::i8));
5377 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5378 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
5379 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
5381 if (Op.getOpcode() == ISD::SHL_PARTS) {
5382 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5383 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5385 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5386 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5389 SDValue Ops[2] = { Lo, Hi };
5390 return DAG.getMergeValues(Ops, 2, dl);
5393 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5394 EVT SrcVT = Op.getOperand(0).getValueType();
5396 if (SrcVT.isVector()) {
5397 if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
5403 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
5404 "Unknown SINT_TO_FP to lower!");
5406 // These are really Legal; return the operand so the caller accepts it as
5408 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
5410 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
5411 Subtarget->is64Bit()) {
5415 DebugLoc dl = Op.getDebugLoc();
5416 unsigned Size = SrcVT.getSizeInBits()/8;
5417 MachineFunction &MF = DAG.getMachineFunction();
5418 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
5419 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5420 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5422 PseudoSourceValue::getFixedStack(SSFI), 0,
5424 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
5427 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
5429 SelectionDAG &DAG) {
5431 DebugLoc dl = Op.getDebugLoc();
5433 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
5435 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
5437 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
5438 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
5439 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
5440 Tys, Ops, array_lengthof(Ops));
5443 Chain = Result.getValue(1);
5444 SDValue InFlag = Result.getValue(2);
5446 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5447 // shouldn't be necessary except that RFP cannot be live across
5448 // multiple blocks. When stackifier is fixed, they can be uncoupled.
5449 MachineFunction &MF = DAG.getMachineFunction();
5450 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5451 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5452 Tys = DAG.getVTList(MVT::Other);
5454 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
5456 Chain = DAG.getNode(X86ISD::FST, dl, Tys, Ops, array_lengthof(Ops));
5457 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5458 PseudoSourceValue::getFixedStack(SSFI), 0,
5465 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5466 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
5467 // This algorithm is not obvious. Here it is in C code, more or less:
5469 double uint64_to_double( uint32_t hi, uint32_t lo ) {
5470 static const __m128i exp = { 0x4330000045300000ULL, 0 };
5471 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5473 // Copy ints to xmm registers.
5474 __m128i xh = _mm_cvtsi32_si128( hi );
5475 __m128i xl = _mm_cvtsi32_si128( lo );
5477 // Combine into low half of a single xmm register.
5478 __m128i x = _mm_unpacklo_epi32( xh, xl );
5482 // Merge in appropriate exponents to give the integer bits the right
5484 x = _mm_unpacklo_epi32( x, exp );
5486 // Subtract away the biases to deal with the IEEE-754 double precision
5488 d = _mm_sub_pd( (__m128d) x, bias );
5490 // All conversions up to here are exact. The correctly rounded result is
5491 // calculated using the current rounding mode using the following
5493 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5494 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
5495 // store doesn't really need to be here (except
5496 // maybe to zero the other double)
5501 DebugLoc dl = Op.getDebugLoc();
5502 LLVMContext *Context = DAG.getContext();
5504 // Build some magic constants.
5505 std::vector<Constant*> CV0;
5506 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
5507 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
5508 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5509 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5510 Constant *C0 = ConstantVector::get(CV0);
5511 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5513 std::vector<Constant*> CV1;
5515 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
5517 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
5518 Constant *C1 = ConstantVector::get(CV1);
5519 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5521 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5522 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5524 DAG.getIntPtrConstant(1)));
5525 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5526 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5528 DAG.getIntPtrConstant(0)));
5529 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
5530 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5531 PseudoSourceValue::getConstantPool(), 0,
5533 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
5534 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5535 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5536 PseudoSourceValue::getConstantPool(), 0,
5538 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5540 // Add the halves; easiest way is to swap them into another reg first.
5541 int ShufMask[2] = { 1, -1 };
5542 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
5543 DAG.getUNDEF(MVT::v2f64), ShufMask);
5544 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5545 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5546 DAG.getIntPtrConstant(0));
5549 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5550 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
5551 DebugLoc dl = Op.getDebugLoc();
5552 // FP constant to bias correct the final result.
5553 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5556 // Load the 32-bit value into an XMM register.
5557 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5558 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5560 DAG.getIntPtrConstant(0)));
5562 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5563 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5564 DAG.getIntPtrConstant(0));
5566 // Or the load with the bias.
5567 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5568 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5569 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5571 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5572 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5573 MVT::v2f64, Bias)));
5574 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5575 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5576 DAG.getIntPtrConstant(0));
5578 // Subtract the bias.
5579 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5581 // Handle final rounding.
5582 EVT DestVT = Op.getValueType();
5584 if (DestVT.bitsLT(MVT::f64)) {
5585 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5586 DAG.getIntPtrConstant(0));
5587 } else if (DestVT.bitsGT(MVT::f64)) {
5588 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5591 // Handle final rounding.
5595 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5596 SDValue N0 = Op.getOperand(0);
5597 DebugLoc dl = Op.getDebugLoc();
5599 // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
5600 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5601 // the optimization here.
5602 if (DAG.SignBitIsZero(N0))
5603 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5605 EVT SrcVT = N0.getValueType();
5606 if (SrcVT == MVT::i64) {
5607 // We only handle SSE2 f64 target here; caller can expand the rest.
5608 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
5611 return LowerUINT_TO_FP_i64(Op, DAG);
5612 } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
5613 return LowerUINT_TO_FP_i32(Op, DAG);
5616 assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
5618 // Make a 64-bit buffer, and use it to build an FILD.
5619 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5620 SDValue WordOff = DAG.getConstant(4, getPointerTy());
5621 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5622 getPointerTy(), StackSlot, WordOff);
5623 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5624 StackSlot, NULL, 0, false, false, 0);
5625 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5626 OffsetSlot, NULL, 0, false, false, 0);
5627 return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5630 std::pair<SDValue,SDValue> X86TargetLowering::
5631 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) {
5632 DebugLoc dl = Op.getDebugLoc();
5634 EVT DstTy = Op.getValueType();
5637 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5641 assert(DstTy.getSimpleVT() <= MVT::i64 &&
5642 DstTy.getSimpleVT() >= MVT::i16 &&
5643 "Unknown FP_TO_SINT to lower!");
5645 // These are really Legal.
5646 if (DstTy == MVT::i32 &&
5647 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5648 return std::make_pair(SDValue(), SDValue());
5649 if (Subtarget->is64Bit() &&
5650 DstTy == MVT::i64 &&
5651 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5652 return std::make_pair(SDValue(), SDValue());
5654 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5656 MachineFunction &MF = DAG.getMachineFunction();
5657 unsigned MemSize = DstTy.getSizeInBits()/8;
5658 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5659 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5662 switch (DstTy.getSimpleVT().SimpleTy) {
5663 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5664 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5665 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5666 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5669 SDValue Chain = DAG.getEntryNode();
5670 SDValue Value = Op.getOperand(0);
5671 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5672 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5673 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5674 PseudoSourceValue::getFixedStack(SSFI), 0,
5676 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5678 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5680 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5681 Chain = Value.getValue(1);
5682 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5683 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5686 // Build the FP_TO_INT*_IN_MEM
5687 SDValue Ops[] = { Chain, Value, StackSlot };
5688 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5690 return std::make_pair(FIST, StackSlot);
5693 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
5694 if (Op.getValueType().isVector()) {
5695 if (Op.getValueType() == MVT::v2i32 &&
5696 Op.getOperand(0).getValueType() == MVT::v2f64) {
5702 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5703 SDValue FIST = Vals.first, StackSlot = Vals.second;
5704 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5705 if (FIST.getNode() == 0) return Op;
5708 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5709 FIST, StackSlot, NULL, 0, false, false, 0);
5712 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG) {
5713 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5714 SDValue FIST = Vals.first, StackSlot = Vals.second;
5715 assert(FIST.getNode() && "Unexpected failure");
5718 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5719 FIST, StackSlot, NULL, 0, false, false, 0);
5722 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
5723 LLVMContext *Context = DAG.getContext();
5724 DebugLoc dl = Op.getDebugLoc();
5725 EVT VT = Op.getValueType();
5728 EltVT = VT.getVectorElementType();
5729 std::vector<Constant*> CV;
5730 if (EltVT == MVT::f64) {
5731 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5735 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5741 Constant *C = ConstantVector::get(CV);
5742 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5743 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5744 PseudoSourceValue::getConstantPool(), 0,
5746 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5749 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
5750 LLVMContext *Context = DAG.getContext();
5751 DebugLoc dl = Op.getDebugLoc();
5752 EVT VT = Op.getValueType();
5755 EltVT = VT.getVectorElementType();
5756 std::vector<Constant*> CV;
5757 if (EltVT == MVT::f64) {
5758 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5762 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5768 Constant *C = ConstantVector::get(CV);
5769 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5770 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5771 PseudoSourceValue::getConstantPool(), 0,
5773 if (VT.isVector()) {
5774 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5775 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5776 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5778 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5780 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5784 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5785 LLVMContext *Context = DAG.getContext();
5786 SDValue Op0 = Op.getOperand(0);
5787 SDValue Op1 = Op.getOperand(1);
5788 DebugLoc dl = Op.getDebugLoc();
5789 EVT VT = Op.getValueType();
5790 EVT SrcVT = Op1.getValueType();
5792 // If second operand is smaller, extend it first.
5793 if (SrcVT.bitsLT(VT)) {
5794 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5797 // And if it is bigger, shrink it first.
5798 if (SrcVT.bitsGT(VT)) {
5799 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5803 // At this point the operands and the result should have the same
5804 // type, and that won't be f80 since that is not custom lowered.
5806 // First get the sign bit of second operand.
5807 std::vector<Constant*> CV;
5808 if (SrcVT == MVT::f64) {
5809 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
5810 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5812 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
5813 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5814 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5815 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5817 Constant *C = ConstantVector::get(CV);
5818 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5819 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5820 PseudoSourceValue::getConstantPool(), 0,
5822 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5824 // Shift sign bit right or left if the two operands have different types.
5825 if (SrcVT.bitsGT(VT)) {
5826 // Op0 is MVT::f32, Op1 is MVT::f64.
5827 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5828 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5829 DAG.getConstant(32, MVT::i32));
5830 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5831 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5832 DAG.getIntPtrConstant(0));
5835 // Clear first operand sign bit.
5837 if (VT == MVT::f64) {
5838 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
5839 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5841 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
5842 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5843 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5844 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5846 C = ConstantVector::get(CV);
5847 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5848 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5849 PseudoSourceValue::getConstantPool(), 0,
5851 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5853 // Or the value with the sign bit.
5854 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5857 /// Emit nodes that will be selected as "test Op0,Op0", or something
5859 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5860 SelectionDAG &DAG) {
5861 DebugLoc dl = Op.getDebugLoc();
5863 // CF and OF aren't always set the way we want. Determine which
5864 // of these we need.
5865 bool NeedCF = false;
5866 bool NeedOF = false;
5868 case X86::COND_A: case X86::COND_AE:
5869 case X86::COND_B: case X86::COND_BE:
5872 case X86::COND_G: case X86::COND_GE:
5873 case X86::COND_L: case X86::COND_LE:
5874 case X86::COND_O: case X86::COND_NO:
5880 // See if we can use the EFLAGS value from the operand instead of
5881 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5882 // we prove that the arithmetic won't overflow, we can't use OF or CF.
5883 if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5884 unsigned Opcode = 0;
5885 unsigned NumOperands = 0;
5886 switch (Op.getNode()->getOpcode()) {
5888 // Due to an isel shortcoming, be conservative if this add is likely to
5889 // be selected as part of a load-modify-store instruction. When the root
5890 // node in a match is a store, isel doesn't know how to remap non-chain
5891 // non-flag uses of other nodes in the match, such as the ADD in this
5892 // case. This leads to the ADD being left around and reselected, with
5893 // the result being two adds in the output.
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 if (ConstantSDNode *C =
5899 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5900 // An add of one will be selected as an INC.
5901 if (C->getAPIntValue() == 1) {
5902 Opcode = X86ISD::INC;
5906 // An add of negative one (subtract of one) will be selected as a DEC.
5907 if (C->getAPIntValue().isAllOnesValue()) {
5908 Opcode = X86ISD::DEC;
5913 // Otherwise use a regular EFLAGS-setting add.
5914 Opcode = X86ISD::ADD;
5918 // If the primary and result isn't used, don't bother using X86ISD::AND,
5919 // because a TEST instruction will be better.
5920 bool NonFlagUse = false;
5921 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5922 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
5924 unsigned UOpNo = UI.getOperandNo();
5925 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
5926 // Look pass truncate.
5927 UOpNo = User->use_begin().getOperandNo();
5928 User = *User->use_begin();
5930 if (User->getOpcode() != ISD::BRCOND &&
5931 User->getOpcode() != ISD::SETCC &&
5932 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
5944 // Due to the ISEL shortcoming noted above, be conservative if this op is
5945 // likely to be selected as part of a load-modify-store instruction.
5946 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5947 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5948 if (UI->getOpcode() == ISD::STORE)
5950 // Otherwise use a regular EFLAGS-setting instruction.
5951 switch (Op.getNode()->getOpcode()) {
5952 case ISD::SUB: Opcode = X86ISD::SUB; break;
5953 case ISD::OR: Opcode = X86ISD::OR; break;
5954 case ISD::XOR: Opcode = X86ISD::XOR; break;
5955 case ISD::AND: Opcode = X86ISD::AND; break;
5956 default: llvm_unreachable("unexpected operator!");
5967 return SDValue(Op.getNode(), 1);
5973 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
5974 SmallVector<SDValue, 4> Ops;
5975 for (unsigned i = 0; i != NumOperands; ++i)
5976 Ops.push_back(Op.getOperand(i));
5977 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
5978 DAG.ReplaceAllUsesWith(Op, New);
5979 return SDValue(New.getNode(), 1);
5983 // Otherwise just emit a CMP with 0, which is the TEST pattern.
5984 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5985 DAG.getConstant(0, Op.getValueType()));
5988 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
5990 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5991 SelectionDAG &DAG) {
5992 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5993 if (C->getAPIntValue() == 0)
5994 return EmitTest(Op0, X86CC, DAG);
5996 DebugLoc dl = Op0.getDebugLoc();
5997 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
6000 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
6001 /// if it's possible.
6002 static SDValue LowerToBT(SDValue And, ISD::CondCode CC,
6003 DebugLoc dl, SelectionDAG &DAG) {
6004 SDValue Op0 = And.getOperand(0);
6005 SDValue Op1 = And.getOperand(1);
6006 if (Op0.getOpcode() == ISD::TRUNCATE)
6007 Op0 = Op0.getOperand(0);
6008 if (Op1.getOpcode() == ISD::TRUNCATE)
6009 Op1 = Op1.getOperand(0);
6012 if (Op1.getOpcode() == ISD::SHL) {
6013 if (ConstantSDNode *And10C = dyn_cast<ConstantSDNode>(Op1.getOperand(0)))
6014 if (And10C->getZExtValue() == 1) {
6016 RHS = Op1.getOperand(1);
6018 } else if (Op0.getOpcode() == ISD::SHL) {
6019 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
6020 if (And00C->getZExtValue() == 1) {
6022 RHS = Op0.getOperand(1);
6024 } else if (Op1.getOpcode() == ISD::Constant) {
6025 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
6026 SDValue AndLHS = Op0;
6027 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
6028 LHS = AndLHS.getOperand(0);
6029 RHS = AndLHS.getOperand(1);
6033 if (LHS.getNode()) {
6034 // If LHS is i8, promote it to i16 with any_extend. There is no i8 BT
6035 // instruction. Since the shift amount is in-range-or-undefined, we know
6036 // that doing a bittest on the i16 value is ok. We extend to i32 because
6037 // the encoding for the i16 version is larger than the i32 version.
6038 if (LHS.getValueType() == MVT::i8)
6039 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
6041 // If the operand types disagree, extend the shift amount to match. Since
6042 // BT ignores high bits (like shifts) we can use anyextend.
6043 if (LHS.getValueType() != RHS.getValueType())
6044 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
6046 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
6047 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
6048 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6049 DAG.getConstant(Cond, MVT::i8), BT);
6055 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
6056 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
6057 SDValue Op0 = Op.getOperand(0);
6058 SDValue Op1 = Op.getOperand(1);
6059 DebugLoc dl = Op.getDebugLoc();
6060 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6062 // Optimize to BT if possible.
6063 // Lower (X & (1 << N)) == 0 to BT(X, N).
6064 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
6065 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
6066 if (Op0.getOpcode() == ISD::AND &&
6068 Op1.getOpcode() == ISD::Constant &&
6069 cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
6070 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6071 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
6072 if (NewSetCC.getNode())
6076 // Look for "(setcc) == / != 1" to avoid unncessary setcc.
6077 if (Op0.getOpcode() == X86ISD::SETCC &&
6078 Op1.getOpcode() == ISD::Constant &&
6079 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
6080 cast<ConstantSDNode>(Op1)->isNullValue()) &&
6081 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6082 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
6083 bool Invert = (CC == ISD::SETNE) ^
6084 cast<ConstantSDNode>(Op1)->isNullValue();
6086 CCode = X86::GetOppositeBranchCondition(CCode);
6087 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6088 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
6091 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
6092 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
6093 if (X86CC == X86::COND_INVALID)
6096 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
6098 // Use sbb x, x to materialize carry bit into a GPR.
6099 if (X86CC == X86::COND_B)
6100 return DAG.getNode(ISD::AND, dl, MVT::i8,
6101 DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
6102 DAG.getConstant(X86CC, MVT::i8), Cond),
6103 DAG.getConstant(1, MVT::i8));
6105 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6106 DAG.getConstant(X86CC, MVT::i8), Cond);
6109 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
6111 SDValue Op0 = Op.getOperand(0);
6112 SDValue Op1 = Op.getOperand(1);
6113 SDValue CC = Op.getOperand(2);
6114 EVT VT = Op.getValueType();
6115 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6116 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
6117 DebugLoc dl = Op.getDebugLoc();
6121 EVT VT0 = Op0.getValueType();
6122 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
6123 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
6126 switch (SetCCOpcode) {
6129 case ISD::SETEQ: SSECC = 0; break;
6131 case ISD::SETGT: Swap = true; // Fallthrough
6133 case ISD::SETOLT: SSECC = 1; break;
6135 case ISD::SETGE: Swap = true; // Fallthrough
6137 case ISD::SETOLE: SSECC = 2; break;
6138 case ISD::SETUO: SSECC = 3; break;
6140 case ISD::SETNE: SSECC = 4; break;
6141 case ISD::SETULE: Swap = true;
6142 case ISD::SETUGE: SSECC = 5; break;
6143 case ISD::SETULT: Swap = true;
6144 case ISD::SETUGT: SSECC = 6; break;
6145 case ISD::SETO: SSECC = 7; break;
6148 std::swap(Op0, Op1);
6150 // In the two special cases we can't handle, emit two comparisons.
6152 if (SetCCOpcode == ISD::SETUEQ) {
6154 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
6155 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
6156 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
6158 else if (SetCCOpcode == ISD::SETONE) {
6160 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
6161 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
6162 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
6164 llvm_unreachable("Illegal FP comparison");
6166 // Handle all other FP comparisons here.
6167 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
6170 // We are handling one of the integer comparisons here. Since SSE only has
6171 // GT and EQ comparisons for integer, swapping operands and multiple
6172 // operations may be required for some comparisons.
6173 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
6174 bool Swap = false, Invert = false, FlipSigns = false;
6176 switch (VT.getSimpleVT().SimpleTy) {
6179 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
6181 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
6183 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
6184 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
6187 switch (SetCCOpcode) {
6189 case ISD::SETNE: Invert = true;
6190 case ISD::SETEQ: Opc = EQOpc; break;
6191 case ISD::SETLT: Swap = true;
6192 case ISD::SETGT: Opc = GTOpc; break;
6193 case ISD::SETGE: Swap = true;
6194 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
6195 case ISD::SETULT: Swap = true;
6196 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
6197 case ISD::SETUGE: Swap = true;
6198 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
6201 std::swap(Op0, Op1);
6203 // Since SSE has no unsigned integer comparisons, we need to flip the sign
6204 // bits of the inputs before performing those operations.
6206 EVT EltVT = VT.getVectorElementType();
6207 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
6209 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
6210 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
6212 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
6213 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
6216 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
6218 // If the logical-not of the result is required, perform that now.
6220 Result = DAG.getNOT(dl, Result, VT);
6225 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
6226 static bool isX86LogicalCmp(SDValue Op) {
6227 unsigned Opc = Op.getNode()->getOpcode();
6228 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
6230 if (Op.getResNo() == 1 &&
6231 (Opc == X86ISD::ADD ||
6232 Opc == X86ISD::SUB ||
6233 Opc == X86ISD::SMUL ||
6234 Opc == X86ISD::UMUL ||
6235 Opc == X86ISD::INC ||
6236 Opc == X86ISD::DEC ||
6237 Opc == X86ISD::OR ||
6238 Opc == X86ISD::XOR ||
6239 Opc == X86ISD::AND))
6245 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
6246 bool addTest = true;
6247 SDValue Cond = Op.getOperand(0);
6248 DebugLoc dl = Op.getDebugLoc();
6251 if (Cond.getOpcode() == ISD::SETCC) {
6252 SDValue NewCond = LowerSETCC(Cond, DAG);
6253 if (NewCond.getNode())
6257 // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
6258 SDValue Op1 = Op.getOperand(1);
6259 SDValue Op2 = Op.getOperand(2);
6260 if (Cond.getOpcode() == X86ISD::SETCC &&
6261 cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
6262 SDValue Cmp = Cond.getOperand(1);
6263 if (Cmp.getOpcode() == X86ISD::CMP) {
6264 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
6265 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
6266 ConstantSDNode *RHSC =
6267 dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
6268 if (N1C && N1C->isAllOnesValue() &&
6269 N2C && N2C->isNullValue() &&
6270 RHSC && RHSC->isNullValue()) {
6271 SDValue CmpOp0 = Cmp.getOperand(0);
6272 Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6273 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
6274 return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
6275 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
6280 // Look pass (and (setcc_carry (cmp ...)), 1).
6281 if (Cond.getOpcode() == ISD::AND &&
6282 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6283 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6284 if (C && C->getAPIntValue() == 1)
6285 Cond = Cond.getOperand(0);
6288 // If condition flag is set by a X86ISD::CMP, then use it as the condition
6289 // setting operand in place of the X86ISD::SETCC.
6290 if (Cond.getOpcode() == X86ISD::SETCC ||
6291 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6292 CC = Cond.getOperand(0);
6294 SDValue Cmp = Cond.getOperand(1);
6295 unsigned Opc = Cmp.getOpcode();
6296 EVT VT = Op.getValueType();
6298 bool IllegalFPCMov = false;
6299 if (VT.isFloatingPoint() && !VT.isVector() &&
6300 !isScalarFPTypeInSSEReg(VT)) // FPStack?
6301 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
6303 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
6304 Opc == X86ISD::BT) { // FIXME
6311 // Look pass the truncate.
6312 if (Cond.getOpcode() == ISD::TRUNCATE)
6313 Cond = Cond.getOperand(0);
6315 // We know the result of AND is compared against zero. Try to match
6317 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
6318 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6319 if (NewSetCC.getNode()) {
6320 CC = NewSetCC.getOperand(0);
6321 Cond = NewSetCC.getOperand(1);
6328 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6329 Cond = EmitTest(Cond, X86::COND_NE, DAG);
6332 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
6333 // condition is true.
6334 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
6335 SDValue Ops[] = { Op2, Op1, CC, Cond };
6336 return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
6339 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
6340 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
6341 // from the AND / OR.
6342 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
6343 Opc = Op.getOpcode();
6344 if (Opc != ISD::OR && Opc != ISD::AND)
6346 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6347 Op.getOperand(0).hasOneUse() &&
6348 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
6349 Op.getOperand(1).hasOneUse());
6352 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
6353 // 1 and that the SETCC node has a single use.
6354 static bool isXor1OfSetCC(SDValue Op) {
6355 if (Op.getOpcode() != ISD::XOR)
6357 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6358 if (N1C && N1C->getAPIntValue() == 1) {
6359 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6360 Op.getOperand(0).hasOneUse();
6365 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
6366 bool addTest = true;
6367 SDValue Chain = Op.getOperand(0);
6368 SDValue Cond = Op.getOperand(1);
6369 SDValue Dest = Op.getOperand(2);
6370 DebugLoc dl = Op.getDebugLoc();
6373 if (Cond.getOpcode() == ISD::SETCC) {
6374 SDValue NewCond = LowerSETCC(Cond, DAG);
6375 if (NewCond.getNode())
6379 // FIXME: LowerXALUO doesn't handle these!!
6380 else if (Cond.getOpcode() == X86ISD::ADD ||
6381 Cond.getOpcode() == X86ISD::SUB ||
6382 Cond.getOpcode() == X86ISD::SMUL ||
6383 Cond.getOpcode() == X86ISD::UMUL)
6384 Cond = LowerXALUO(Cond, DAG);
6387 // Look pass (and (setcc_carry (cmp ...)), 1).
6388 if (Cond.getOpcode() == ISD::AND &&
6389 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6390 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6391 if (C && C->getAPIntValue() == 1)
6392 Cond = Cond.getOperand(0);
6395 // If condition flag is set by a X86ISD::CMP, then use it as the condition
6396 // setting operand in place of the X86ISD::SETCC.
6397 if (Cond.getOpcode() == X86ISD::SETCC ||
6398 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6399 CC = Cond.getOperand(0);
6401 SDValue Cmp = Cond.getOperand(1);
6402 unsigned Opc = Cmp.getOpcode();
6403 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
6404 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
6408 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
6412 // These can only come from an arithmetic instruction with overflow,
6413 // e.g. SADDO, UADDO.
6414 Cond = Cond.getNode()->getOperand(1);
6421 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
6422 SDValue Cmp = Cond.getOperand(0).getOperand(1);
6423 if (CondOpc == ISD::OR) {
6424 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
6425 // two branches instead of an explicit OR instruction with a
6427 if (Cmp == Cond.getOperand(1).getOperand(1) &&
6428 isX86LogicalCmp(Cmp)) {
6429 CC = Cond.getOperand(0).getOperand(0);
6430 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6431 Chain, Dest, CC, Cmp);
6432 CC = Cond.getOperand(1).getOperand(0);
6436 } else { // ISD::AND
6437 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
6438 // two branches instead of an explicit AND instruction with a
6439 // separate test. However, we only do this if this block doesn't
6440 // have a fall-through edge, because this requires an explicit
6441 // jmp when the condition is false.
6442 if (Cmp == Cond.getOperand(1).getOperand(1) &&
6443 isX86LogicalCmp(Cmp) &&
6444 Op.getNode()->hasOneUse()) {
6445 X86::CondCode CCode =
6446 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6447 CCode = X86::GetOppositeBranchCondition(CCode);
6448 CC = DAG.getConstant(CCode, MVT::i8);
6449 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
6450 // Look for an unconditional branch following this conditional branch.
6451 // We need this because we need to reverse the successors in order
6452 // to implement FCMP_OEQ.
6453 if (User.getOpcode() == ISD::BR) {
6454 SDValue FalseBB = User.getOperand(1);
6456 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
6457 assert(NewBR == User);
6460 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6461 Chain, Dest, CC, Cmp);
6462 X86::CondCode CCode =
6463 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
6464 CCode = X86::GetOppositeBranchCondition(CCode);
6465 CC = DAG.getConstant(CCode, MVT::i8);
6471 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
6472 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
6473 // It should be transformed during dag combiner except when the condition
6474 // is set by a arithmetics with overflow node.
6475 X86::CondCode CCode =
6476 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6477 CCode = X86::GetOppositeBranchCondition(CCode);
6478 CC = DAG.getConstant(CCode, MVT::i8);
6479 Cond = Cond.getOperand(0).getOperand(1);
6485 // Look pass the truncate.
6486 if (Cond.getOpcode() == ISD::TRUNCATE)
6487 Cond = Cond.getOperand(0);
6489 // We know the result of AND is compared against zero. Try to match
6491 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
6492 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6493 if (NewSetCC.getNode()) {
6494 CC = NewSetCC.getOperand(0);
6495 Cond = NewSetCC.getOperand(1);
6502 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6503 Cond = EmitTest(Cond, X86::COND_NE, DAG);
6505 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6506 Chain, Dest, CC, Cond);
6510 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
6511 // Calls to _alloca is needed to probe the stack when allocating more than 4k
6512 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
6513 // that the guard pages used by the OS virtual memory manager are allocated in
6514 // correct sequence.
6516 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6517 SelectionDAG &DAG) {
6518 assert(Subtarget->isTargetCygMing() &&
6519 "This should be used only on Cygwin/Mingw targets");
6520 DebugLoc dl = Op.getDebugLoc();
6523 SDValue Chain = Op.getOperand(0);
6524 SDValue Size = Op.getOperand(1);
6525 // FIXME: Ensure alignment here
6529 EVT IntPtr = getPointerTy();
6530 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
6532 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
6533 Flag = Chain.getValue(1);
6535 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6537 Chain = DAG.getNode(X86ISD::MINGW_ALLOCA, dl, NodeTys, Chain, Flag);
6538 Flag = Chain.getValue(1);
6540 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
6542 SDValue Ops1[2] = { Chain.getValue(0), Chain };
6543 return DAG.getMergeValues(Ops1, 2, dl);
6547 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
6549 SDValue Dst, SDValue Src,
6550 SDValue Size, unsigned Align,
6553 uint64_t DstSVOff) {
6554 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6556 // If not DWORD aligned or size is more than the threshold, call the library.
6557 // The libc version is likely to be faster for these cases. It can use the
6558 // address value and run time information about the CPU.
6559 if ((Align & 3) != 0 ||
6561 ConstantSize->getZExtValue() >
6562 getSubtarget()->getMaxInlineSizeThreshold()) {
6563 SDValue InFlag(0, 0);
6565 // Check to see if there is a specialized entry-point for memory zeroing.
6566 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
6568 if (const char *bzeroEntry = V &&
6569 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
6570 EVT IntPtr = getPointerTy();
6571 const Type *IntPtrTy = TD->getIntPtrType(*DAG.getContext());
6572 TargetLowering::ArgListTy Args;
6573 TargetLowering::ArgListEntry Entry;
6575 Entry.Ty = IntPtrTy;
6576 Args.push_back(Entry);
6578 Args.push_back(Entry);
6579 std::pair<SDValue,SDValue> CallResult =
6580 LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()),
6581 false, false, false, false,
6582 0, CallingConv::C, false, /*isReturnValueUsed=*/false,
6583 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl);
6584 return CallResult.second;
6587 // Otherwise have the target-independent code call memset.
6591 uint64_t SizeVal = ConstantSize->getZExtValue();
6592 SDValue InFlag(0, 0);
6595 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
6596 unsigned BytesLeft = 0;
6597 bool TwoRepStos = false;
6600 uint64_t Val = ValC->getZExtValue() & 255;
6602 // If the value is a constant, then we can potentially use larger sets.
6603 switch (Align & 3) {
6604 case 2: // WORD aligned
6607 Val = (Val << 8) | Val;
6609 case 0: // DWORD aligned
6612 Val = (Val << 8) | Val;
6613 Val = (Val << 16) | Val;
6614 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
6617 Val = (Val << 32) | Val;
6620 default: // Byte aligned
6623 Count = DAG.getIntPtrConstant(SizeVal);
6627 if (AVT.bitsGT(MVT::i8)) {
6628 unsigned UBytes = AVT.getSizeInBits() / 8;
6629 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
6630 BytesLeft = SizeVal % UBytes;
6633 Chain = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
6635 InFlag = Chain.getValue(1);
6638 Count = DAG.getIntPtrConstant(SizeVal);
6639 Chain = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
6640 InFlag = Chain.getValue(1);
6643 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6646 InFlag = Chain.getValue(1);
6647 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6650 InFlag = Chain.getValue(1);
6652 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6653 SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6654 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6657 InFlag = Chain.getValue(1);
6659 EVT CVT = Count.getValueType();
6660 SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
6661 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
6662 Chain = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
6665 InFlag = Chain.getValue(1);
6666 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6667 SDValue Ops[] = { Chain, DAG.getValueType(MVT::i8), InFlag };
6668 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, Ops, array_lengthof(Ops));
6669 } else if (BytesLeft) {
6670 // Handle the last 1 - 7 bytes.
6671 unsigned Offset = SizeVal - BytesLeft;
6672 EVT AddrVT = Dst.getValueType();
6673 EVT SizeVT = Size.getValueType();
6675 Chain = DAG.getMemset(Chain, dl,
6676 DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
6677 DAG.getConstant(Offset, AddrVT)),
6679 DAG.getConstant(BytesLeft, SizeVT),
6680 Align, isVolatile, DstSV, DstSVOff + Offset);
6683 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
6688 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
6689 SDValue Chain, SDValue Dst, SDValue Src,
6690 SDValue Size, unsigned Align,
6691 bool isVolatile, bool AlwaysInline,
6692 const Value *DstSV, uint64_t DstSVOff,
6693 const Value *SrcSV, uint64_t SrcSVOff) {
6694 // This requires the copy size to be a constant, preferrably
6695 // within a subtarget-specific limit.
6696 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6699 uint64_t SizeVal = ConstantSize->getZExtValue();
6700 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
6703 /// If not DWORD aligned, call the library.
6704 if ((Align & 3) != 0)
6709 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
6712 unsigned UBytes = AVT.getSizeInBits() / 8;
6713 unsigned CountVal = SizeVal / UBytes;
6714 SDValue Count = DAG.getIntPtrConstant(CountVal);
6715 unsigned BytesLeft = SizeVal % UBytes;
6717 SDValue InFlag(0, 0);
6718 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6721 InFlag = Chain.getValue(1);
6722 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6725 InFlag = Chain.getValue(1);
6726 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
6729 InFlag = Chain.getValue(1);
6731 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6732 SDValue Ops[] = { Chain, DAG.getValueType(AVT), InFlag };
6733 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, Ops,
6734 array_lengthof(Ops));
6736 SmallVector<SDValue, 4> Results;
6737 Results.push_back(RepMovs);
6739 // Handle the last 1 - 7 bytes.
6740 unsigned Offset = SizeVal - BytesLeft;
6741 EVT DstVT = Dst.getValueType();
6742 EVT SrcVT = Src.getValueType();
6743 EVT SizeVT = Size.getValueType();
6744 Results.push_back(DAG.getMemcpy(Chain, dl,
6745 DAG.getNode(ISD::ADD, dl, DstVT, Dst,
6746 DAG.getConstant(Offset, DstVT)),
6747 DAG.getNode(ISD::ADD, dl, SrcVT, Src,
6748 DAG.getConstant(Offset, SrcVT)),
6749 DAG.getConstant(BytesLeft, SizeVT),
6750 Align, isVolatile, AlwaysInline,
6751 DstSV, DstSVOff + Offset,
6752 SrcSV, SrcSVOff + Offset));
6755 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6756 &Results[0], Results.size());
6759 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
6760 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6761 DebugLoc dl = Op.getDebugLoc();
6763 if (!Subtarget->is64Bit()) {
6764 // vastart just stores the address of the VarArgsFrameIndex slot into the
6765 // memory location argument.
6766 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6767 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0,
6772 // gp_offset (0 - 6 * 8)
6773 // fp_offset (48 - 48 + 8 * 16)
6774 // overflow_arg_area (point to parameters coming in memory).
6776 SmallVector<SDValue, 8> MemOps;
6777 SDValue FIN = Op.getOperand(1);
6779 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6780 DAG.getConstant(VarArgsGPOffset, MVT::i32),
6781 FIN, SV, 0, false, false, 0);
6782 MemOps.push_back(Store);
6785 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6786 FIN, DAG.getIntPtrConstant(4));
6787 Store = DAG.getStore(Op.getOperand(0), dl,
6788 DAG.getConstant(VarArgsFPOffset, MVT::i32),
6789 FIN, SV, 0, false, false, 0);
6790 MemOps.push_back(Store);
6792 // Store ptr to overflow_arg_area
6793 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6794 FIN, DAG.getIntPtrConstant(4));
6795 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6796 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0,
6798 MemOps.push_back(Store);
6800 // Store ptr to reg_save_area.
6801 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6802 FIN, DAG.getIntPtrConstant(8));
6803 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
6804 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0,
6806 MemOps.push_back(Store);
6807 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6808 &MemOps[0], MemOps.size());
6811 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
6812 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6813 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6814 SDValue Chain = Op.getOperand(0);
6815 SDValue SrcPtr = Op.getOperand(1);
6816 SDValue SrcSV = Op.getOperand(2);
6818 llvm_report_error("VAArgInst is not yet implemented for x86-64!");
6822 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
6823 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6824 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6825 SDValue Chain = Op.getOperand(0);
6826 SDValue DstPtr = Op.getOperand(1);
6827 SDValue SrcPtr = Op.getOperand(2);
6828 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6829 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6830 DebugLoc dl = Op.getDebugLoc();
6832 return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6833 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
6834 false, DstSV, 0, SrcSV, 0);
6838 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
6839 DebugLoc dl = Op.getDebugLoc();
6840 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6842 default: return SDValue(); // Don't custom lower most intrinsics.
6843 // Comparison intrinsics.
6844 case Intrinsic::x86_sse_comieq_ss:
6845 case Intrinsic::x86_sse_comilt_ss:
6846 case Intrinsic::x86_sse_comile_ss:
6847 case Intrinsic::x86_sse_comigt_ss:
6848 case Intrinsic::x86_sse_comige_ss:
6849 case Intrinsic::x86_sse_comineq_ss:
6850 case Intrinsic::x86_sse_ucomieq_ss:
6851 case Intrinsic::x86_sse_ucomilt_ss:
6852 case Intrinsic::x86_sse_ucomile_ss:
6853 case Intrinsic::x86_sse_ucomigt_ss:
6854 case Intrinsic::x86_sse_ucomige_ss:
6855 case Intrinsic::x86_sse_ucomineq_ss:
6856 case Intrinsic::x86_sse2_comieq_sd:
6857 case Intrinsic::x86_sse2_comilt_sd:
6858 case Intrinsic::x86_sse2_comile_sd:
6859 case Intrinsic::x86_sse2_comigt_sd:
6860 case Intrinsic::x86_sse2_comige_sd:
6861 case Intrinsic::x86_sse2_comineq_sd:
6862 case Intrinsic::x86_sse2_ucomieq_sd:
6863 case Intrinsic::x86_sse2_ucomilt_sd:
6864 case Intrinsic::x86_sse2_ucomile_sd:
6865 case Intrinsic::x86_sse2_ucomigt_sd:
6866 case Intrinsic::x86_sse2_ucomige_sd:
6867 case Intrinsic::x86_sse2_ucomineq_sd: {
6869 ISD::CondCode CC = ISD::SETCC_INVALID;
6872 case Intrinsic::x86_sse_comieq_ss:
6873 case Intrinsic::x86_sse2_comieq_sd:
6877 case Intrinsic::x86_sse_comilt_ss:
6878 case Intrinsic::x86_sse2_comilt_sd:
6882 case Intrinsic::x86_sse_comile_ss:
6883 case Intrinsic::x86_sse2_comile_sd:
6887 case Intrinsic::x86_sse_comigt_ss:
6888 case Intrinsic::x86_sse2_comigt_sd:
6892 case Intrinsic::x86_sse_comige_ss:
6893 case Intrinsic::x86_sse2_comige_sd:
6897 case Intrinsic::x86_sse_comineq_ss:
6898 case Intrinsic::x86_sse2_comineq_sd:
6902 case Intrinsic::x86_sse_ucomieq_ss:
6903 case Intrinsic::x86_sse2_ucomieq_sd:
6904 Opc = X86ISD::UCOMI;
6907 case Intrinsic::x86_sse_ucomilt_ss:
6908 case Intrinsic::x86_sse2_ucomilt_sd:
6909 Opc = X86ISD::UCOMI;
6912 case Intrinsic::x86_sse_ucomile_ss:
6913 case Intrinsic::x86_sse2_ucomile_sd:
6914 Opc = X86ISD::UCOMI;
6917 case Intrinsic::x86_sse_ucomigt_ss:
6918 case Intrinsic::x86_sse2_ucomigt_sd:
6919 Opc = X86ISD::UCOMI;
6922 case Intrinsic::x86_sse_ucomige_ss:
6923 case Intrinsic::x86_sse2_ucomige_sd:
6924 Opc = X86ISD::UCOMI;
6927 case Intrinsic::x86_sse_ucomineq_ss:
6928 case Intrinsic::x86_sse2_ucomineq_sd:
6929 Opc = X86ISD::UCOMI;
6934 SDValue LHS = Op.getOperand(1);
6935 SDValue RHS = Op.getOperand(2);
6936 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6937 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
6938 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6939 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6940 DAG.getConstant(X86CC, MVT::i8), Cond);
6941 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6943 // ptest intrinsics. The intrinsic these come from are designed to return
6944 // an integer value, not just an instruction so lower it to the ptest
6945 // pattern and a setcc for the result.
6946 case Intrinsic::x86_sse41_ptestz:
6947 case Intrinsic::x86_sse41_ptestc:
6948 case Intrinsic::x86_sse41_ptestnzc:{
6951 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
6952 case Intrinsic::x86_sse41_ptestz:
6954 X86CC = X86::COND_E;
6956 case Intrinsic::x86_sse41_ptestc:
6958 X86CC = X86::COND_B;
6960 case Intrinsic::x86_sse41_ptestnzc:
6962 X86CC = X86::COND_A;
6966 SDValue LHS = Op.getOperand(1);
6967 SDValue RHS = Op.getOperand(2);
6968 SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
6969 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
6970 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
6971 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6974 // Fix vector shift instructions where the last operand is a non-immediate
6976 case Intrinsic::x86_sse2_pslli_w:
6977 case Intrinsic::x86_sse2_pslli_d:
6978 case Intrinsic::x86_sse2_pslli_q:
6979 case Intrinsic::x86_sse2_psrli_w:
6980 case Intrinsic::x86_sse2_psrli_d:
6981 case Intrinsic::x86_sse2_psrli_q:
6982 case Intrinsic::x86_sse2_psrai_w:
6983 case Intrinsic::x86_sse2_psrai_d:
6984 case Intrinsic::x86_mmx_pslli_w:
6985 case Intrinsic::x86_mmx_pslli_d:
6986 case Intrinsic::x86_mmx_pslli_q:
6987 case Intrinsic::x86_mmx_psrli_w:
6988 case Intrinsic::x86_mmx_psrli_d:
6989 case Intrinsic::x86_mmx_psrli_q:
6990 case Intrinsic::x86_mmx_psrai_w:
6991 case Intrinsic::x86_mmx_psrai_d: {
6992 SDValue ShAmt = Op.getOperand(2);
6993 if (isa<ConstantSDNode>(ShAmt))
6996 unsigned NewIntNo = 0;
6997 EVT ShAmtVT = MVT::v4i32;
6999 case Intrinsic::x86_sse2_pslli_w:
7000 NewIntNo = Intrinsic::x86_sse2_psll_w;
7002 case Intrinsic::x86_sse2_pslli_d:
7003 NewIntNo = Intrinsic::x86_sse2_psll_d;
7005 case Intrinsic::x86_sse2_pslli_q:
7006 NewIntNo = Intrinsic::x86_sse2_psll_q;
7008 case Intrinsic::x86_sse2_psrli_w:
7009 NewIntNo = Intrinsic::x86_sse2_psrl_w;
7011 case Intrinsic::x86_sse2_psrli_d:
7012 NewIntNo = Intrinsic::x86_sse2_psrl_d;
7014 case Intrinsic::x86_sse2_psrli_q:
7015 NewIntNo = Intrinsic::x86_sse2_psrl_q;
7017 case Intrinsic::x86_sse2_psrai_w:
7018 NewIntNo = Intrinsic::x86_sse2_psra_w;
7020 case Intrinsic::x86_sse2_psrai_d:
7021 NewIntNo = Intrinsic::x86_sse2_psra_d;
7024 ShAmtVT = MVT::v2i32;
7026 case Intrinsic::x86_mmx_pslli_w:
7027 NewIntNo = Intrinsic::x86_mmx_psll_w;
7029 case Intrinsic::x86_mmx_pslli_d:
7030 NewIntNo = Intrinsic::x86_mmx_psll_d;
7032 case Intrinsic::x86_mmx_pslli_q:
7033 NewIntNo = Intrinsic::x86_mmx_psll_q;
7035 case Intrinsic::x86_mmx_psrli_w:
7036 NewIntNo = Intrinsic::x86_mmx_psrl_w;
7038 case Intrinsic::x86_mmx_psrli_d:
7039 NewIntNo = Intrinsic::x86_mmx_psrl_d;
7041 case Intrinsic::x86_mmx_psrli_q:
7042 NewIntNo = Intrinsic::x86_mmx_psrl_q;
7044 case Intrinsic::x86_mmx_psrai_w:
7045 NewIntNo = Intrinsic::x86_mmx_psra_w;
7047 case Intrinsic::x86_mmx_psrai_d:
7048 NewIntNo = Intrinsic::x86_mmx_psra_d;
7050 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7056 // The vector shift intrinsics with scalars uses 32b shift amounts but
7057 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
7061 ShOps[1] = DAG.getConstant(0, MVT::i32);
7062 if (ShAmtVT == MVT::v4i32) {
7063 ShOps[2] = DAG.getUNDEF(MVT::i32);
7064 ShOps[3] = DAG.getUNDEF(MVT::i32);
7065 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
7067 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
7070 EVT VT = Op.getValueType();
7071 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
7072 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7073 DAG.getConstant(NewIntNo, MVT::i32),
7074 Op.getOperand(1), ShAmt);
7079 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
7080 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7081 DebugLoc dl = Op.getDebugLoc();
7084 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7086 DAG.getConstant(TD->getPointerSize(),
7087 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
7088 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7089 DAG.getNode(ISD::ADD, dl, getPointerTy(),
7091 NULL, 0, false, false, 0);
7094 // Just load the return address.
7095 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
7096 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7097 RetAddrFI, NULL, 0, false, false, 0);
7100 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
7101 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7102 MFI->setFrameAddressIsTaken(true);
7103 EVT VT = Op.getValueType();
7104 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
7105 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7106 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
7107 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
7109 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0,
7114 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
7115 SelectionDAG &DAG) {
7116 return DAG.getIntPtrConstant(2*TD->getPointerSize());
7119 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
7121 MachineFunction &MF = DAG.getMachineFunction();
7122 SDValue Chain = Op.getOperand(0);
7123 SDValue Offset = Op.getOperand(1);
7124 SDValue Handler = Op.getOperand(2);
7125 DebugLoc dl = Op.getDebugLoc();
7127 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
7129 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
7131 SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
7132 DAG.getIntPtrConstant(-TD->getPointerSize()));
7133 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
7134 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0, false, false, 0);
7135 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
7136 MF.getRegInfo().addLiveOut(StoreAddrReg);
7138 return DAG.getNode(X86ISD::EH_RETURN, dl,
7140 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
7143 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
7144 SelectionDAG &DAG) {
7145 SDValue Root = Op.getOperand(0);
7146 SDValue Trmp = Op.getOperand(1); // trampoline
7147 SDValue FPtr = Op.getOperand(2); // nested function
7148 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
7149 DebugLoc dl = Op.getDebugLoc();
7151 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7153 if (Subtarget->is64Bit()) {
7154 SDValue OutChains[6];
7156 // Large code-model.
7157 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
7158 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
7160 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
7161 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
7163 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
7165 // Load the pointer to the nested function into R11.
7166 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
7167 SDValue Addr = Trmp;
7168 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7169 Addr, TrmpAddr, 0, false, false, 0);
7171 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7172 DAG.getConstant(2, MVT::i64));
7173 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2,
7176 // Load the 'nest' parameter value into R10.
7177 // R10 is specified in X86CallingConv.td
7178 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
7179 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7180 DAG.getConstant(10, MVT::i64));
7181 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7182 Addr, TrmpAddr, 10, false, false, 0);
7184 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7185 DAG.getConstant(12, MVT::i64));
7186 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12,
7189 // Jump to the nested function.
7190 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
7191 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7192 DAG.getConstant(20, MVT::i64));
7193 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7194 Addr, TrmpAddr, 20, false, false, 0);
7196 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
7197 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7198 DAG.getConstant(22, MVT::i64));
7199 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
7200 TrmpAddr, 22, false, false, 0);
7203 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
7204 return DAG.getMergeValues(Ops, 2, dl);
7206 const Function *Func =
7207 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
7208 CallingConv::ID CC = Func->getCallingConv();
7213 llvm_unreachable("Unsupported calling convention");
7214 case CallingConv::C:
7215 case CallingConv::X86_StdCall: {
7216 // Pass 'nest' parameter in ECX.
7217 // Must be kept in sync with X86CallingConv.td
7220 // Check that ECX wasn't needed by an 'inreg' parameter.
7221 const FunctionType *FTy = Func->getFunctionType();
7222 const AttrListPtr &Attrs = Func->getAttributes();
7224 if (!Attrs.isEmpty() && !Func->isVarArg()) {
7225 unsigned InRegCount = 0;
7228 for (FunctionType::param_iterator I = FTy->param_begin(),
7229 E = FTy->param_end(); I != E; ++I, ++Idx)
7230 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
7231 // FIXME: should only count parameters that are lowered to integers.
7232 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
7234 if (InRegCount > 2) {
7235 llvm_report_error("Nest register in use - reduce number of inreg parameters!");
7240 case CallingConv::X86_FastCall:
7241 case CallingConv::Fast:
7242 // Pass 'nest' parameter in EAX.
7243 // Must be kept in sync with X86CallingConv.td
7248 SDValue OutChains[4];
7251 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7252 DAG.getConstant(10, MVT::i32));
7253 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
7255 // This is storing the opcode for MOV32ri.
7256 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
7257 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
7258 OutChains[0] = DAG.getStore(Root, dl,
7259 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
7260 Trmp, TrmpAddr, 0, false, false, 0);
7262 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7263 DAG.getConstant(1, MVT::i32));
7264 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1,
7267 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
7268 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7269 DAG.getConstant(5, MVT::i32));
7270 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
7271 TrmpAddr, 5, false, false, 1);
7273 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7274 DAG.getConstant(6, MVT::i32));
7275 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6,
7279 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
7280 return DAG.getMergeValues(Ops, 2, dl);
7284 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
7286 The rounding mode is in bits 11:10 of FPSR, and has the following
7293 FLT_ROUNDS, on the other hand, expects the following:
7300 To perform the conversion, we do:
7301 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
7304 MachineFunction &MF = DAG.getMachineFunction();
7305 const TargetMachine &TM = MF.getTarget();
7306 const TargetFrameInfo &TFI = *TM.getFrameInfo();
7307 unsigned StackAlignment = TFI.getStackAlignment();
7308 EVT VT = Op.getValueType();
7309 DebugLoc dl = Op.getDebugLoc();
7311 // Save FP Control Word to stack slot
7312 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
7313 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7315 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
7316 DAG.getEntryNode(), StackSlot);
7318 // Load FP Control Word from stack slot
7319 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0,
7322 // Transform as necessary
7324 DAG.getNode(ISD::SRL, dl, MVT::i16,
7325 DAG.getNode(ISD::AND, dl, MVT::i16,
7326 CWD, DAG.getConstant(0x800, MVT::i16)),
7327 DAG.getConstant(11, MVT::i8));
7329 DAG.getNode(ISD::SRL, dl, MVT::i16,
7330 DAG.getNode(ISD::AND, dl, MVT::i16,
7331 CWD, DAG.getConstant(0x400, MVT::i16)),
7332 DAG.getConstant(9, MVT::i8));
7335 DAG.getNode(ISD::AND, dl, MVT::i16,
7336 DAG.getNode(ISD::ADD, dl, MVT::i16,
7337 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
7338 DAG.getConstant(1, MVT::i16)),
7339 DAG.getConstant(3, MVT::i16));
7342 return DAG.getNode((VT.getSizeInBits() < 16 ?
7343 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7346 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
7347 EVT VT = Op.getValueType();
7349 unsigned NumBits = VT.getSizeInBits();
7350 DebugLoc dl = Op.getDebugLoc();
7352 Op = Op.getOperand(0);
7353 if (VT == MVT::i8) {
7354 // Zero extend to i32 since there is not an i8 bsr.
7356 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7359 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
7360 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7361 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
7363 // If src is zero (i.e. bsr sets ZF), returns NumBits.
7366 DAG.getConstant(NumBits+NumBits-1, OpVT),
7367 DAG.getConstant(X86::COND_E, MVT::i8),
7370 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7372 // Finally xor with NumBits-1.
7373 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
7376 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7380 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
7381 EVT VT = Op.getValueType();
7383 unsigned NumBits = VT.getSizeInBits();
7384 DebugLoc dl = Op.getDebugLoc();
7386 Op = Op.getOperand(0);
7387 if (VT == MVT::i8) {
7389 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7392 // Issue a bsf (scan bits forward) which also sets EFLAGS.
7393 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7394 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
7396 // If src is zero (i.e. bsf sets ZF), returns NumBits.
7399 DAG.getConstant(NumBits, OpVT),
7400 DAG.getConstant(X86::COND_E, MVT::i8),
7403 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7406 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7410 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
7411 EVT VT = Op.getValueType();
7412 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
7413 DebugLoc dl = Op.getDebugLoc();
7415 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
7416 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
7417 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
7418 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
7419 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
7421 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
7422 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
7423 // return AloBlo + AloBhi + AhiBlo;
7425 SDValue A = Op.getOperand(0);
7426 SDValue B = Op.getOperand(1);
7428 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7429 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7430 A, DAG.getConstant(32, MVT::i32));
7431 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7432 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7433 B, DAG.getConstant(32, MVT::i32));
7434 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7435 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7437 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7438 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7440 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7441 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7443 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7444 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7445 AloBhi, DAG.getConstant(32, MVT::i32));
7446 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7447 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7448 AhiBlo, DAG.getConstant(32, MVT::i32));
7449 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
7450 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
7455 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
7456 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
7457 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
7458 // looks for this combo and may remove the "setcc" instruction if the "setcc"
7459 // has only one use.
7460 SDNode *N = Op.getNode();
7461 SDValue LHS = N->getOperand(0);
7462 SDValue RHS = N->getOperand(1);
7463 unsigned BaseOp = 0;
7465 DebugLoc dl = Op.getDebugLoc();
7467 switch (Op.getOpcode()) {
7468 default: llvm_unreachable("Unknown ovf instruction!");
7470 // A subtract of one will be selected as a INC. Note that INC doesn't
7471 // set CF, so we can't do this for UADDO.
7472 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7473 if (C->getAPIntValue() == 1) {
7474 BaseOp = X86ISD::INC;
7478 BaseOp = X86ISD::ADD;
7482 BaseOp = X86ISD::ADD;
7486 // A subtract of one will be selected as a DEC. Note that DEC doesn't
7487 // set CF, so we can't do this for USUBO.
7488 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7489 if (C->getAPIntValue() == 1) {
7490 BaseOp = X86ISD::DEC;
7494 BaseOp = X86ISD::SUB;
7498 BaseOp = X86ISD::SUB;
7502 BaseOp = X86ISD::SMUL;
7506 BaseOp = X86ISD::UMUL;
7511 // Also sets EFLAGS.
7512 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
7513 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
7516 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
7517 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
7519 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
7523 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
7524 EVT T = Op.getValueType();
7525 DebugLoc dl = Op.getDebugLoc();
7528 switch(T.getSimpleVT().SimpleTy) {
7530 assert(false && "Invalid value type!");
7531 case MVT::i8: Reg = X86::AL; size = 1; break;
7532 case MVT::i16: Reg = X86::AX; size = 2; break;
7533 case MVT::i32: Reg = X86::EAX; size = 4; break;
7535 assert(Subtarget->is64Bit() && "Node not type legal!");
7536 Reg = X86::RAX; size = 8;
7539 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
7540 Op.getOperand(2), SDValue());
7541 SDValue Ops[] = { cpIn.getValue(0),
7544 DAG.getTargetConstant(size, MVT::i8),
7546 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7547 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
7549 DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
7553 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
7554 SelectionDAG &DAG) {
7555 assert(Subtarget->is64Bit() && "Result not type legalized?");
7556 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7557 SDValue TheChain = Op.getOperand(0);
7558 DebugLoc dl = Op.getDebugLoc();
7559 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7560 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
7561 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
7563 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
7564 DAG.getConstant(32, MVT::i8));
7566 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
7569 return DAG.getMergeValues(Ops, 2, dl);
7572 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
7573 SDNode *Node = Op.getNode();
7574 DebugLoc dl = Node->getDebugLoc();
7575 EVT T = Node->getValueType(0);
7576 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
7577 DAG.getConstant(0, T), Node->getOperand(2));
7578 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
7579 cast<AtomicSDNode>(Node)->getMemoryVT(),
7580 Node->getOperand(0),
7581 Node->getOperand(1), negOp,
7582 cast<AtomicSDNode>(Node)->getSrcValue(),
7583 cast<AtomicSDNode>(Node)->getAlignment());
7586 /// LowerOperation - Provide custom lowering hooks for some operations.
7588 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
7589 switch (Op.getOpcode()) {
7590 default: llvm_unreachable("Should not custom lower this!");
7591 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
7592 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
7593 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
7594 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
7595 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7596 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7597 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7598 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
7599 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
7600 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
7601 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7602 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
7603 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
7604 case ISD::SHL_PARTS:
7605 case ISD::SRA_PARTS:
7606 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
7607 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
7608 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
7609 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
7610 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
7611 case ISD::FABS: return LowerFABS(Op, DAG);
7612 case ISD::FNEG: return LowerFNEG(Op, DAG);
7613 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
7614 case ISD::SETCC: return LowerSETCC(Op, DAG);
7615 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
7616 case ISD::SELECT: return LowerSELECT(Op, DAG);
7617 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
7618 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
7619 case ISD::VASTART: return LowerVASTART(Op, DAG);
7620 case ISD::VAARG: return LowerVAARG(Op, DAG);
7621 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
7622 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7623 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
7624 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
7625 case ISD::FRAME_TO_ARGS_OFFSET:
7626 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
7627 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
7628 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
7629 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
7630 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
7631 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
7632 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
7633 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
7639 case ISD::UMULO: return LowerXALUO(Op, DAG);
7640 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
7644 void X86TargetLowering::
7645 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
7646 SelectionDAG &DAG, unsigned NewOp) {
7647 EVT T = Node->getValueType(0);
7648 DebugLoc dl = Node->getDebugLoc();
7649 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
7651 SDValue Chain = Node->getOperand(0);
7652 SDValue In1 = Node->getOperand(1);
7653 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7654 Node->getOperand(2), DAG.getIntPtrConstant(0));
7655 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7656 Node->getOperand(2), DAG.getIntPtrConstant(1));
7657 SDValue Ops[] = { Chain, In1, In2L, In2H };
7658 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7660 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
7661 cast<MemSDNode>(Node)->getMemOperand());
7662 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7663 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7664 Results.push_back(Result.getValue(2));
7667 /// ReplaceNodeResults - Replace a node with an illegal result type
7668 /// with a new node built out of custom code.
7669 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7670 SmallVectorImpl<SDValue>&Results,
7671 SelectionDAG &DAG) {
7672 DebugLoc dl = N->getDebugLoc();
7673 switch (N->getOpcode()) {
7675 assert(false && "Do not know how to custom type legalize this operation!");
7677 case ISD::FP_TO_SINT: {
7678 std::pair<SDValue,SDValue> Vals =
7679 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
7680 SDValue FIST = Vals.first, StackSlot = Vals.second;
7681 if (FIST.getNode() != 0) {
7682 EVT VT = N->getValueType(0);
7683 // Return a load from the stack slot.
7684 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0,
7689 case ISD::READCYCLECOUNTER: {
7690 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7691 SDValue TheChain = N->getOperand(0);
7692 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7693 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7695 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7697 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7698 SDValue Ops[] = { eax, edx };
7699 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7700 Results.push_back(edx.getValue(1));
7703 case ISD::ATOMIC_CMP_SWAP: {
7704 EVT T = N->getValueType(0);
7705 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7706 SDValue cpInL, cpInH;
7707 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7708 DAG.getConstant(0, MVT::i32));
7709 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7710 DAG.getConstant(1, MVT::i32));
7711 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7712 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7714 SDValue swapInL, swapInH;
7715 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7716 DAG.getConstant(0, MVT::i32));
7717 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7718 DAG.getConstant(1, MVT::i32));
7719 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7721 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7722 swapInL.getValue(1));
7723 SDValue Ops[] = { swapInH.getValue(0),
7725 swapInH.getValue(1) };
7726 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7727 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7728 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7729 MVT::i32, Result.getValue(1));
7730 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7731 MVT::i32, cpOutL.getValue(2));
7732 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7733 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7734 Results.push_back(cpOutH.getValue(1));
7737 case ISD::ATOMIC_LOAD_ADD:
7738 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7740 case ISD::ATOMIC_LOAD_AND:
7741 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7743 case ISD::ATOMIC_LOAD_NAND:
7744 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7746 case ISD::ATOMIC_LOAD_OR:
7747 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7749 case ISD::ATOMIC_LOAD_SUB:
7750 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7752 case ISD::ATOMIC_LOAD_XOR:
7753 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7755 case ISD::ATOMIC_SWAP:
7756 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7761 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7763 default: return NULL;
7764 case X86ISD::BSF: return "X86ISD::BSF";
7765 case X86ISD::BSR: return "X86ISD::BSR";
7766 case X86ISD::SHLD: return "X86ISD::SHLD";
7767 case X86ISD::SHRD: return "X86ISD::SHRD";
7768 case X86ISD::FAND: return "X86ISD::FAND";
7769 case X86ISD::FOR: return "X86ISD::FOR";
7770 case X86ISD::FXOR: return "X86ISD::FXOR";
7771 case X86ISD::FSRL: return "X86ISD::FSRL";
7772 case X86ISD::FILD: return "X86ISD::FILD";
7773 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
7774 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7775 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7776 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7777 case X86ISD::FLD: return "X86ISD::FLD";
7778 case X86ISD::FST: return "X86ISD::FST";
7779 case X86ISD::CALL: return "X86ISD::CALL";
7780 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
7781 case X86ISD::BT: return "X86ISD::BT";
7782 case X86ISD::CMP: return "X86ISD::CMP";
7783 case X86ISD::COMI: return "X86ISD::COMI";
7784 case X86ISD::UCOMI: return "X86ISD::UCOMI";
7785 case X86ISD::SETCC: return "X86ISD::SETCC";
7786 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
7787 case X86ISD::CMOV: return "X86ISD::CMOV";
7788 case X86ISD::BRCOND: return "X86ISD::BRCOND";
7789 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
7790 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
7791 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
7792 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
7793 case X86ISD::Wrapper: return "X86ISD::Wrapper";
7794 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
7795 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
7796 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
7797 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
7798 case X86ISD::PINSRB: return "X86ISD::PINSRB";
7799 case X86ISD::PINSRW: return "X86ISD::PINSRW";
7800 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
7801 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
7802 case X86ISD::FMAX: return "X86ISD::FMAX";
7803 case X86ISD::FMIN: return "X86ISD::FMIN";
7804 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
7805 case X86ISD::FRCP: return "X86ISD::FRCP";
7806 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
7807 case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7808 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
7809 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
7810 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
7811 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
7812 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
7813 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
7814 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
7815 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
7816 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
7817 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
7818 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
7819 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
7820 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
7821 case X86ISD::VSHL: return "X86ISD::VSHL";
7822 case X86ISD::VSRL: return "X86ISD::VSRL";
7823 case X86ISD::CMPPD: return "X86ISD::CMPPD";
7824 case X86ISD::CMPPS: return "X86ISD::CMPPS";
7825 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
7826 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
7827 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
7828 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
7829 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
7830 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
7831 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
7832 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
7833 case X86ISD::ADD: return "X86ISD::ADD";
7834 case X86ISD::SUB: return "X86ISD::SUB";
7835 case X86ISD::SMUL: return "X86ISD::SMUL";
7836 case X86ISD::UMUL: return "X86ISD::UMUL";
7837 case X86ISD::INC: return "X86ISD::INC";
7838 case X86ISD::DEC: return "X86ISD::DEC";
7839 case X86ISD::OR: return "X86ISD::OR";
7840 case X86ISD::XOR: return "X86ISD::XOR";
7841 case X86ISD::AND: return "X86ISD::AND";
7842 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
7843 case X86ISD::PTEST: return "X86ISD::PTEST";
7844 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
7845 case X86ISD::MINGW_ALLOCA: return "X86ISD::MINGW_ALLOCA";
7849 // isLegalAddressingMode - Return true if the addressing mode represented
7850 // by AM is legal for this target, for a load/store of the specified type.
7851 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7852 const Type *Ty) const {
7853 // X86 supports extremely general addressing modes.
7854 CodeModel::Model M = getTargetMachine().getCodeModel();
7856 // X86 allows a sign-extended 32-bit immediate field as a displacement.
7857 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
7862 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7864 // If a reference to this global requires an extra load, we can't fold it.
7865 if (isGlobalStubReference(GVFlags))
7868 // If BaseGV requires a register for the PIC base, we cannot also have a
7869 // BaseReg specified.
7870 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
7873 // If lower 4G is not available, then we must use rip-relative addressing.
7874 if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
7884 // These scales always work.
7889 // These scales are formed with basereg+scalereg. Only accept if there is
7894 default: // Other stuff never works.
7902 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7903 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7905 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7906 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7907 if (NumBits1 <= NumBits2)
7912 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7913 if (!VT1.isInteger() || !VT2.isInteger())
7915 unsigned NumBits1 = VT1.getSizeInBits();
7916 unsigned NumBits2 = VT2.getSizeInBits();
7917 if (NumBits1 <= NumBits2)
7922 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7923 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7924 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
7927 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7928 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7929 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7932 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
7933 // i16 instructions are longer (0x66 prefix) and potentially slower.
7934 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7937 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7938 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7939 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7940 /// are assumed to be legal.
7942 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
7944 // Only do shuffles on 128-bit vector types for now.
7945 if (VT.getSizeInBits() == 64)
7948 // FIXME: pshufb, blends, shifts.
7949 return (VT.getVectorNumElements() == 2 ||
7950 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7951 isMOVLMask(M, VT) ||
7952 isSHUFPMask(M, VT) ||
7953 isPSHUFDMask(M, VT) ||
7954 isPSHUFHWMask(M, VT) ||
7955 isPSHUFLWMask(M, VT) ||
7956 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
7957 isUNPCKLMask(M, VT) ||
7958 isUNPCKHMask(M, VT) ||
7959 isUNPCKL_v_undef_Mask(M, VT) ||
7960 isUNPCKH_v_undef_Mask(M, VT));
7964 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
7966 unsigned NumElts = VT.getVectorNumElements();
7967 // FIXME: This collection of masks seems suspect.
7970 if (NumElts == 4 && VT.getSizeInBits() == 128) {
7971 return (isMOVLMask(Mask, VT) ||
7972 isCommutedMOVLMask(Mask, VT, true) ||
7973 isSHUFPMask(Mask, VT) ||
7974 isCommutedSHUFPMask(Mask, VT));
7979 //===----------------------------------------------------------------------===//
7980 // X86 Scheduler Hooks
7981 //===----------------------------------------------------------------------===//
7983 // private utility function
7985 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7986 MachineBasicBlock *MBB,
7994 TargetRegisterClass *RC,
7995 bool invSrc) const {
7996 // For the atomic bitwise operator, we generate
7999 // ld t1 = [bitinstr.addr]
8000 // op t2 = t1, [bitinstr.val]
8002 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
8004 // fallthrough -->nextMBB
8005 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8006 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8007 MachineFunction::iterator MBBIter = MBB;
8010 /// First build the CFG
8011 MachineFunction *F = MBB->getParent();
8012 MachineBasicBlock *thisMBB = MBB;
8013 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8014 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8015 F->insert(MBBIter, newMBB);
8016 F->insert(MBBIter, nextMBB);
8018 // Move all successors to thisMBB to nextMBB
8019 nextMBB->transferSuccessors(thisMBB);
8021 // Update thisMBB to fall through to newMBB
8022 thisMBB->addSuccessor(newMBB);
8024 // newMBB jumps to itself and fall through to nextMBB
8025 newMBB->addSuccessor(nextMBB);
8026 newMBB->addSuccessor(newMBB);
8028 // Insert instructions into newMBB based on incoming instruction
8029 assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
8030 "unexpected number of operands");
8031 DebugLoc dl = bInstr->getDebugLoc();
8032 MachineOperand& destOper = bInstr->getOperand(0);
8033 MachineOperand* argOpers[2 + X86AddrNumOperands];
8034 int numArgs = bInstr->getNumOperands() - 1;
8035 for (int i=0; i < numArgs; ++i)
8036 argOpers[i] = &bInstr->getOperand(i+1);
8038 // x86 address has 4 operands: base, index, scale, and displacement
8039 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8040 int valArgIndx = lastAddrIndx + 1;
8042 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
8043 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
8044 for (int i=0; i <= lastAddrIndx; ++i)
8045 (*MIB).addOperand(*argOpers[i]);
8047 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
8049 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
8054 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8055 assert((argOpers[valArgIndx]->isReg() ||
8056 argOpers[valArgIndx]->isImm()) &&
8058 if (argOpers[valArgIndx]->isReg())
8059 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
8061 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
8063 (*MIB).addOperand(*argOpers[valArgIndx]);
8065 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
8068 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
8069 for (int i=0; i <= lastAddrIndx; ++i)
8070 (*MIB).addOperand(*argOpers[i]);
8072 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8073 (*MIB).setMemRefs(bInstr->memoperands_begin(),
8074 bInstr->memoperands_end());
8076 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
8080 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8082 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
8086 // private utility function: 64 bit atomics on 32 bit host.
8088 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
8089 MachineBasicBlock *MBB,
8094 bool invSrc) const {
8095 // For the atomic bitwise operator, we generate
8096 // thisMBB (instructions are in pairs, except cmpxchg8b)
8097 // ld t1,t2 = [bitinstr.addr]
8099 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
8100 // op t5, t6 <- out1, out2, [bitinstr.val]
8101 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
8102 // mov ECX, EBX <- t5, t6
8103 // mov EAX, EDX <- t1, t2
8104 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
8105 // mov t3, t4 <- EAX, EDX
8107 // result in out1, out2
8108 // fallthrough -->nextMBB
8110 const TargetRegisterClass *RC = X86::GR32RegisterClass;
8111 const unsigned LoadOpc = X86::MOV32rm;
8112 const unsigned copyOpc = X86::MOV32rr;
8113 const unsigned NotOpc = X86::NOT32r;
8114 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8115 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8116 MachineFunction::iterator MBBIter = MBB;
8119 /// First build the CFG
8120 MachineFunction *F = MBB->getParent();
8121 MachineBasicBlock *thisMBB = MBB;
8122 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8123 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8124 F->insert(MBBIter, newMBB);
8125 F->insert(MBBIter, nextMBB);
8127 // Move all successors to thisMBB to nextMBB
8128 nextMBB->transferSuccessors(thisMBB);
8130 // Update thisMBB to fall through to newMBB
8131 thisMBB->addSuccessor(newMBB);
8133 // newMBB jumps to itself and fall through to nextMBB
8134 newMBB->addSuccessor(nextMBB);
8135 newMBB->addSuccessor(newMBB);
8137 DebugLoc dl = bInstr->getDebugLoc();
8138 // Insert instructions into newMBB based on incoming instruction
8139 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
8140 assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
8141 "unexpected number of operands");
8142 MachineOperand& dest1Oper = bInstr->getOperand(0);
8143 MachineOperand& dest2Oper = bInstr->getOperand(1);
8144 MachineOperand* argOpers[2 + X86AddrNumOperands];
8145 for (int i=0; i < 2 + X86AddrNumOperands; ++i)
8146 argOpers[i] = &bInstr->getOperand(i+2);
8148 // x86 address has 5 operands: base, index, scale, displacement, and segment.
8149 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8151 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
8152 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
8153 for (int i=0; i <= lastAddrIndx; ++i)
8154 (*MIB).addOperand(*argOpers[i]);
8155 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8156 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
8157 // add 4 to displacement.
8158 for (int i=0; i <= lastAddrIndx-2; ++i)
8159 (*MIB).addOperand(*argOpers[i]);
8160 MachineOperand newOp3 = *(argOpers[3]);
8162 newOp3.setImm(newOp3.getImm()+4);
8164 newOp3.setOffset(newOp3.getOffset()+4);
8165 (*MIB).addOperand(newOp3);
8166 (*MIB).addOperand(*argOpers[lastAddrIndx]);
8168 // t3/4 are defined later, at the bottom of the loop
8169 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
8170 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
8171 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
8172 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
8173 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
8174 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
8176 // The subsequent operations should be using the destination registers of
8177 //the PHI instructions.
8179 t1 = F->getRegInfo().createVirtualRegister(RC);
8180 t2 = F->getRegInfo().createVirtualRegister(RC);
8181 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
8182 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
8184 t1 = dest1Oper.getReg();
8185 t2 = dest2Oper.getReg();
8188 int valArgIndx = lastAddrIndx + 1;
8189 assert((argOpers[valArgIndx]->isReg() ||
8190 argOpers[valArgIndx]->isImm()) &&
8192 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
8193 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
8194 if (argOpers[valArgIndx]->isReg())
8195 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
8197 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
8198 if (regOpcL != X86::MOV32rr)
8200 (*MIB).addOperand(*argOpers[valArgIndx]);
8201 assert(argOpers[valArgIndx + 1]->isReg() ==
8202 argOpers[valArgIndx]->isReg());
8203 assert(argOpers[valArgIndx + 1]->isImm() ==
8204 argOpers[valArgIndx]->isImm());
8205 if (argOpers[valArgIndx + 1]->isReg())
8206 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
8208 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
8209 if (regOpcH != X86::MOV32rr)
8211 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
8213 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
8215 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
8218 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
8220 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
8223 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
8224 for (int i=0; i <= lastAddrIndx; ++i)
8225 (*MIB).addOperand(*argOpers[i]);
8227 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8228 (*MIB).setMemRefs(bInstr->memoperands_begin(),
8229 bInstr->memoperands_end());
8231 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
8232 MIB.addReg(X86::EAX);
8233 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
8234 MIB.addReg(X86::EDX);
8237 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8239 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
8243 // private utility function
8245 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
8246 MachineBasicBlock *MBB,
8247 unsigned cmovOpc) const {
8248 // For the atomic min/max operator, we generate
8251 // ld t1 = [min/max.addr]
8252 // mov t2 = [min/max.val]
8254 // cmov[cond] t2 = t1
8256 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
8258 // fallthrough -->nextMBB
8260 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8261 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8262 MachineFunction::iterator MBBIter = MBB;
8265 /// First build the CFG
8266 MachineFunction *F = MBB->getParent();
8267 MachineBasicBlock *thisMBB = MBB;
8268 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8269 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8270 F->insert(MBBIter, newMBB);
8271 F->insert(MBBIter, nextMBB);
8273 // Move all successors of thisMBB to nextMBB
8274 nextMBB->transferSuccessors(thisMBB);
8276 // Update thisMBB to fall through to newMBB
8277 thisMBB->addSuccessor(newMBB);
8279 // newMBB jumps to newMBB and fall through to nextMBB
8280 newMBB->addSuccessor(nextMBB);
8281 newMBB->addSuccessor(newMBB);
8283 DebugLoc dl = mInstr->getDebugLoc();
8284 // Insert instructions into newMBB based on incoming instruction
8285 assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
8286 "unexpected number of operands");
8287 MachineOperand& destOper = mInstr->getOperand(0);
8288 MachineOperand* argOpers[2 + X86AddrNumOperands];
8289 int numArgs = mInstr->getNumOperands() - 1;
8290 for (int i=0; i < numArgs; ++i)
8291 argOpers[i] = &mInstr->getOperand(i+1);
8293 // x86 address has 4 operands: base, index, scale, and displacement
8294 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8295 int valArgIndx = lastAddrIndx + 1;
8297 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8298 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
8299 for (int i=0; i <= lastAddrIndx; ++i)
8300 (*MIB).addOperand(*argOpers[i]);
8302 // We only support register and immediate values
8303 assert((argOpers[valArgIndx]->isReg() ||
8304 argOpers[valArgIndx]->isImm()) &&
8307 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8308 if (argOpers[valArgIndx]->isReg())
8309 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8311 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8312 (*MIB).addOperand(*argOpers[valArgIndx]);
8314 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
8317 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
8322 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8323 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
8327 // Cmp and exchange if none has modified the memory location
8328 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
8329 for (int i=0; i <= lastAddrIndx; ++i)
8330 (*MIB).addOperand(*argOpers[i]);
8332 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8333 (*MIB).setMemRefs(mInstr->memoperands_begin(),
8334 mInstr->memoperands_end());
8336 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
8337 MIB.addReg(X86::EAX);
8340 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8342 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
8346 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
8347 // all of this code can be replaced with that in the .td file.
8349 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
8350 unsigned numArgs, bool memArg) const {
8352 MachineFunction *F = BB->getParent();
8353 DebugLoc dl = MI->getDebugLoc();
8354 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8358 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
8360 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
8362 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
8364 for (unsigned i = 0; i < numArgs; ++i) {
8365 MachineOperand &Op = MI->getOperand(i+1);
8367 if (!(Op.isReg() && Op.isImplicit()))
8371 BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
8374 F->DeleteMachineInstr(MI);
8380 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
8382 MachineBasicBlock *MBB) const {
8383 // Emit code to save XMM registers to the stack. The ABI says that the
8384 // number of registers to save is given in %al, so it's theoretically
8385 // possible to do an indirect jump trick to avoid saving all of them,
8386 // however this code takes a simpler approach and just executes all
8387 // of the stores if %al is non-zero. It's less code, and it's probably
8388 // easier on the hardware branch predictor, and stores aren't all that
8389 // expensive anyway.
8391 // Create the new basic blocks. One block contains all the XMM stores,
8392 // and one block is the final destination regardless of whether any
8393 // stores were performed.
8394 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8395 MachineFunction *F = MBB->getParent();
8396 MachineFunction::iterator MBBIter = MBB;
8398 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
8399 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
8400 F->insert(MBBIter, XMMSaveMBB);
8401 F->insert(MBBIter, EndMBB);
8404 // Move any original successors of MBB to the end block.
8405 EndMBB->transferSuccessors(MBB);
8406 // The original block will now fall through to the XMM save block.
8407 MBB->addSuccessor(XMMSaveMBB);
8408 // The XMMSaveMBB will fall through to the end block.
8409 XMMSaveMBB->addSuccessor(EndMBB);
8411 // Now add the instructions.
8412 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8413 DebugLoc DL = MI->getDebugLoc();
8415 unsigned CountReg = MI->getOperand(0).getReg();
8416 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
8417 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
8419 if (!Subtarget->isTargetWin64()) {
8420 // If %al is 0, branch around the XMM save block.
8421 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
8422 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
8423 MBB->addSuccessor(EndMBB);
8426 // In the XMM save block, save all the XMM argument registers.
8427 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
8428 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
8429 MachineMemOperand *MMO =
8430 F->getMachineMemOperand(
8431 PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
8432 MachineMemOperand::MOStore, Offset,
8433 /*Size=*/16, /*Align=*/16);
8434 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
8435 .addFrameIndex(RegSaveFrameIndex)
8436 .addImm(/*Scale=*/1)
8437 .addReg(/*IndexReg=*/0)
8438 .addImm(/*Disp=*/Offset)
8439 .addReg(/*Segment=*/0)
8440 .addReg(MI->getOperand(i).getReg())
8441 .addMemOperand(MMO);
8444 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8450 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
8451 MachineBasicBlock *BB,
8452 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8453 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8454 DebugLoc DL = MI->getDebugLoc();
8456 // To "insert" a SELECT_CC instruction, we actually have to insert the
8457 // diamond control-flow pattern. The incoming instruction knows the
8458 // destination vreg to set, the condition code register to branch on, the
8459 // true/false values to select between, and a branch opcode to use.
8460 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8461 MachineFunction::iterator It = BB;
8467 // cmpTY ccX, r1, r2
8469 // fallthrough --> copy0MBB
8470 MachineBasicBlock *thisMBB = BB;
8471 MachineFunction *F = BB->getParent();
8472 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8473 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8475 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
8476 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
8477 F->insert(It, copy0MBB);
8478 F->insert(It, sinkMBB);
8479 // Update machine-CFG edges by first adding all successors of the current
8480 // block to the new block which will contain the Phi node for the select.
8481 // Also inform sdisel of the edge changes.
8482 for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
8483 E = BB->succ_end(); I != E; ++I) {
8484 EM->insert(std::make_pair(*I, sinkMBB));
8485 sinkMBB->addSuccessor(*I);
8487 // Next, remove all successors of the current block, and add the true
8488 // and fallthrough blocks as its successors.
8489 while (!BB->succ_empty())
8490 BB->removeSuccessor(BB->succ_begin());
8491 // Add the true and fallthrough blocks as its successors.
8492 BB->addSuccessor(copy0MBB);
8493 BB->addSuccessor(sinkMBB);
8496 // %FalseValue = ...
8497 // # fallthrough to sinkMBB
8500 // Update machine-CFG edges
8501 BB->addSuccessor(sinkMBB);
8504 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8507 BuildMI(BB, DL, TII->get(X86::PHI), MI->getOperand(0).getReg())
8508 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8509 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8511 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8516 X86TargetLowering::EmitLoweredMingwAlloca(MachineInstr *MI,
8517 MachineBasicBlock *BB,
8518 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8519 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8520 DebugLoc DL = MI->getDebugLoc();
8521 MachineFunction *F = BB->getParent();
8523 // The lowering is pretty easy: we're just emitting the call to _alloca. The
8524 // non-trivial part is impdef of ESP.
8525 // FIXME: The code should be tweaked as soon as we'll try to do codegen for
8528 BuildMI(BB, DL, TII->get(X86::CALLpcrel32))
8529 .addExternalSymbol("_alloca")
8530 .addReg(X86::EAX, RegState::Implicit)
8531 .addReg(X86::ESP, RegState::Implicit)
8532 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
8533 .addReg(X86::ESP, RegState::Define | RegState::Implicit);
8535 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8540 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8541 MachineBasicBlock *BB,
8542 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8543 switch (MI->getOpcode()) {
8544 default: assert(false && "Unexpected instr type to insert");
8545 case X86::MINGW_ALLOCA:
8546 return EmitLoweredMingwAlloca(MI, BB, EM);
8548 case X86::CMOV_V1I64:
8549 case X86::CMOV_FR32:
8550 case X86::CMOV_FR64:
8551 case X86::CMOV_V4F32:
8552 case X86::CMOV_V2F64:
8553 case X86::CMOV_V2I64:
8554 case X86::CMOV_GR16:
8555 case X86::CMOV_GR32:
8556 case X86::CMOV_RFP32:
8557 case X86::CMOV_RFP64:
8558 case X86::CMOV_RFP80:
8559 return EmitLoweredSelect(MI, BB, EM);
8561 case X86::FP32_TO_INT16_IN_MEM:
8562 case X86::FP32_TO_INT32_IN_MEM:
8563 case X86::FP32_TO_INT64_IN_MEM:
8564 case X86::FP64_TO_INT16_IN_MEM:
8565 case X86::FP64_TO_INT32_IN_MEM:
8566 case X86::FP64_TO_INT64_IN_MEM:
8567 case X86::FP80_TO_INT16_IN_MEM:
8568 case X86::FP80_TO_INT32_IN_MEM:
8569 case X86::FP80_TO_INT64_IN_MEM: {
8570 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8571 DebugLoc DL = MI->getDebugLoc();
8573 // Change the floating point control register to use "round towards zero"
8574 // mode when truncating to an integer value.
8575 MachineFunction *F = BB->getParent();
8576 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
8577 addFrameReference(BuildMI(BB, DL, TII->get(X86::FNSTCW16m)), CWFrameIdx);
8579 // Load the old value of the high byte of the control word...
8581 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
8582 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16rm), OldCW),
8585 // Set the high part to be round to zero...
8586 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
8589 // Reload the modified control word now...
8590 addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8592 // Restore the memory image of control word to original value
8593 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
8596 // Get the X86 opcode to use.
8598 switch (MI->getOpcode()) {
8599 default: llvm_unreachable("illegal opcode!");
8600 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
8601 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
8602 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
8603 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
8604 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
8605 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
8606 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
8607 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
8608 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
8612 MachineOperand &Op = MI->getOperand(0);
8614 AM.BaseType = X86AddressMode::RegBase;
8615 AM.Base.Reg = Op.getReg();
8617 AM.BaseType = X86AddressMode::FrameIndexBase;
8618 AM.Base.FrameIndex = Op.getIndex();
8620 Op = MI->getOperand(1);
8622 AM.Scale = Op.getImm();
8623 Op = MI->getOperand(2);
8625 AM.IndexReg = Op.getImm();
8626 Op = MI->getOperand(3);
8627 if (Op.isGlobal()) {
8628 AM.GV = Op.getGlobal();
8630 AM.Disp = Op.getImm();
8632 addFullAddress(BuildMI(BB, DL, TII->get(Opc)), AM)
8633 .addReg(MI->getOperand(X86AddrNumOperands).getReg());
8635 // Reload the original control word now.
8636 addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8638 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8641 // DBG_VALUE. Only the frame index case is done here.
8642 case X86::DBG_VALUE: {
8643 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8644 DebugLoc DL = MI->getDebugLoc();
8646 MachineFunction *F = BB->getParent();
8647 AM.BaseType = X86AddressMode::FrameIndexBase;
8648 AM.Base.FrameIndex = MI->getOperand(0).getImm();
8649 addFullAddress(BuildMI(BB, DL, TII->get(X86::DBG_VALUE)), AM).
8650 addImm(MI->getOperand(1).getImm()).
8651 addMetadata(MI->getOperand(2).getMetadata());
8652 F->DeleteMachineInstr(MI); // Remove pseudo.
8656 // String/text processing lowering.
8657 case X86::PCMPISTRM128REG:
8658 return EmitPCMP(MI, BB, 3, false /* in-mem */);
8659 case X86::PCMPISTRM128MEM:
8660 return EmitPCMP(MI, BB, 3, true /* in-mem */);
8661 case X86::PCMPESTRM128REG:
8662 return EmitPCMP(MI, BB, 5, false /* in mem */);
8663 case X86::PCMPESTRM128MEM:
8664 return EmitPCMP(MI, BB, 5, true /* in mem */);
8667 case X86::ATOMAND32:
8668 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8669 X86::AND32ri, X86::MOV32rm,
8670 X86::LCMPXCHG32, X86::MOV32rr,
8671 X86::NOT32r, X86::EAX,
8672 X86::GR32RegisterClass);
8674 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
8675 X86::OR32ri, X86::MOV32rm,
8676 X86::LCMPXCHG32, X86::MOV32rr,
8677 X86::NOT32r, X86::EAX,
8678 X86::GR32RegisterClass);
8679 case X86::ATOMXOR32:
8680 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
8681 X86::XOR32ri, X86::MOV32rm,
8682 X86::LCMPXCHG32, X86::MOV32rr,
8683 X86::NOT32r, X86::EAX,
8684 X86::GR32RegisterClass);
8685 case X86::ATOMNAND32:
8686 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8687 X86::AND32ri, X86::MOV32rm,
8688 X86::LCMPXCHG32, X86::MOV32rr,
8689 X86::NOT32r, X86::EAX,
8690 X86::GR32RegisterClass, true);
8691 case X86::ATOMMIN32:
8692 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
8693 case X86::ATOMMAX32:
8694 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
8695 case X86::ATOMUMIN32:
8696 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
8697 case X86::ATOMUMAX32:
8698 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
8700 case X86::ATOMAND16:
8701 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8702 X86::AND16ri, X86::MOV16rm,
8703 X86::LCMPXCHG16, X86::MOV16rr,
8704 X86::NOT16r, X86::AX,
8705 X86::GR16RegisterClass);
8707 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
8708 X86::OR16ri, X86::MOV16rm,
8709 X86::LCMPXCHG16, X86::MOV16rr,
8710 X86::NOT16r, X86::AX,
8711 X86::GR16RegisterClass);
8712 case X86::ATOMXOR16:
8713 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
8714 X86::XOR16ri, X86::MOV16rm,
8715 X86::LCMPXCHG16, X86::MOV16rr,
8716 X86::NOT16r, X86::AX,
8717 X86::GR16RegisterClass);
8718 case X86::ATOMNAND16:
8719 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8720 X86::AND16ri, X86::MOV16rm,
8721 X86::LCMPXCHG16, X86::MOV16rr,
8722 X86::NOT16r, X86::AX,
8723 X86::GR16RegisterClass, true);
8724 case X86::ATOMMIN16:
8725 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
8726 case X86::ATOMMAX16:
8727 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
8728 case X86::ATOMUMIN16:
8729 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
8730 case X86::ATOMUMAX16:
8731 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
8734 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8735 X86::AND8ri, X86::MOV8rm,
8736 X86::LCMPXCHG8, X86::MOV8rr,
8737 X86::NOT8r, X86::AL,
8738 X86::GR8RegisterClass);
8740 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
8741 X86::OR8ri, X86::MOV8rm,
8742 X86::LCMPXCHG8, X86::MOV8rr,
8743 X86::NOT8r, X86::AL,
8744 X86::GR8RegisterClass);
8746 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
8747 X86::XOR8ri, X86::MOV8rm,
8748 X86::LCMPXCHG8, X86::MOV8rr,
8749 X86::NOT8r, X86::AL,
8750 X86::GR8RegisterClass);
8751 case X86::ATOMNAND8:
8752 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8753 X86::AND8ri, X86::MOV8rm,
8754 X86::LCMPXCHG8, X86::MOV8rr,
8755 X86::NOT8r, X86::AL,
8756 X86::GR8RegisterClass, true);
8757 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
8758 // This group is for 64-bit host.
8759 case X86::ATOMAND64:
8760 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8761 X86::AND64ri32, X86::MOV64rm,
8762 X86::LCMPXCHG64, X86::MOV64rr,
8763 X86::NOT64r, X86::RAX,
8764 X86::GR64RegisterClass);
8766 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
8767 X86::OR64ri32, X86::MOV64rm,
8768 X86::LCMPXCHG64, X86::MOV64rr,
8769 X86::NOT64r, X86::RAX,
8770 X86::GR64RegisterClass);
8771 case X86::ATOMXOR64:
8772 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
8773 X86::XOR64ri32, X86::MOV64rm,
8774 X86::LCMPXCHG64, X86::MOV64rr,
8775 X86::NOT64r, X86::RAX,
8776 X86::GR64RegisterClass);
8777 case X86::ATOMNAND64:
8778 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8779 X86::AND64ri32, X86::MOV64rm,
8780 X86::LCMPXCHG64, X86::MOV64rr,
8781 X86::NOT64r, X86::RAX,
8782 X86::GR64RegisterClass, true);
8783 case X86::ATOMMIN64:
8784 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
8785 case X86::ATOMMAX64:
8786 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
8787 case X86::ATOMUMIN64:
8788 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
8789 case X86::ATOMUMAX64:
8790 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
8792 // This group does 64-bit operations on a 32-bit host.
8793 case X86::ATOMAND6432:
8794 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8795 X86::AND32rr, X86::AND32rr,
8796 X86::AND32ri, X86::AND32ri,
8798 case X86::ATOMOR6432:
8799 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8800 X86::OR32rr, X86::OR32rr,
8801 X86::OR32ri, X86::OR32ri,
8803 case X86::ATOMXOR6432:
8804 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8805 X86::XOR32rr, X86::XOR32rr,
8806 X86::XOR32ri, X86::XOR32ri,
8808 case X86::ATOMNAND6432:
8809 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8810 X86::AND32rr, X86::AND32rr,
8811 X86::AND32ri, X86::AND32ri,
8813 case X86::ATOMADD6432:
8814 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8815 X86::ADD32rr, X86::ADC32rr,
8816 X86::ADD32ri, X86::ADC32ri,
8818 case X86::ATOMSUB6432:
8819 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8820 X86::SUB32rr, X86::SBB32rr,
8821 X86::SUB32ri, X86::SBB32ri,
8823 case X86::ATOMSWAP6432:
8824 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8825 X86::MOV32rr, X86::MOV32rr,
8826 X86::MOV32ri, X86::MOV32ri,
8828 case X86::VASTART_SAVE_XMM_REGS:
8829 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
8833 //===----------------------------------------------------------------------===//
8834 // X86 Optimization Hooks
8835 //===----------------------------------------------------------------------===//
8837 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8841 const SelectionDAG &DAG,
8842 unsigned Depth) const {
8843 unsigned Opc = Op.getOpcode();
8844 assert((Opc >= ISD::BUILTIN_OP_END ||
8845 Opc == ISD::INTRINSIC_WO_CHAIN ||
8846 Opc == ISD::INTRINSIC_W_CHAIN ||
8847 Opc == ISD::INTRINSIC_VOID) &&
8848 "Should use MaskedValueIsZero if you don't know whether Op"
8849 " is a target node!");
8851 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
8863 // These nodes' second result is a boolean.
8864 if (Op.getResNo() == 0)
8868 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
8869 Mask.getBitWidth() - 1);
8874 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
8875 /// node is a GlobalAddress + offset.
8876 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
8877 GlobalValue* &GA, int64_t &Offset) const{
8878 if (N->getOpcode() == X86ISD::Wrapper) {
8879 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
8880 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
8881 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
8885 return TargetLowering::isGAPlusOffset(N, GA, Offset);
8888 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8889 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8890 /// if the load addresses are consecutive, non-overlapping, and in the right
8892 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8893 const TargetLowering &TLI) {
8894 DebugLoc dl = N->getDebugLoc();
8895 EVT VT = N->getValueType(0);
8896 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8898 if (VT.getSizeInBits() != 128)
8901 SmallVector<SDValue, 16> Elts;
8902 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
8903 Elts.push_back(DAG.getShuffleScalarElt(SVN, i));
8905 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
8908 /// PerformShuffleCombine - Detect vector gather/scatter index generation
8909 /// and convert it from being a bunch of shuffles and extracts to a simple
8910 /// store and scalar loads to extract the elements.
8911 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
8912 const TargetLowering &TLI) {
8913 SDValue InputVector = N->getOperand(0);
8915 // Only operate on vectors of 4 elements, where the alternative shuffling
8916 // gets to be more expensive.
8917 if (InputVector.getValueType() != MVT::v4i32)
8920 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
8921 // single use which is a sign-extend or zero-extend, and all elements are
8923 SmallVector<SDNode *, 4> Uses;
8924 unsigned ExtractedElements = 0;
8925 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
8926 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
8927 if (UI.getUse().getResNo() != InputVector.getResNo())
8930 SDNode *Extract = *UI;
8931 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8934 if (Extract->getValueType(0) != MVT::i32)
8936 if (!Extract->hasOneUse())
8938 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
8939 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
8941 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
8944 // Record which element was extracted.
8945 ExtractedElements |=
8946 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
8948 Uses.push_back(Extract);
8951 // If not all the elements were used, this may not be worthwhile.
8952 if (ExtractedElements != 15)
8955 // Ok, we've now decided to do the transformation.
8956 DebugLoc dl = InputVector.getDebugLoc();
8958 // Store the value to a temporary stack slot.
8959 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
8960 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr, NULL, 0,
8963 // Replace each use (extract) with a load of the appropriate element.
8964 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
8965 UE = Uses.end(); UI != UE; ++UI) {
8966 SDNode *Extract = *UI;
8968 // Compute the element's address.
8969 SDValue Idx = Extract->getOperand(1);
8971 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
8972 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
8973 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
8975 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), OffsetVal, StackPtr);
8978 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch, ScalarAddr,
8979 NULL, 0, false, false, 0);
8981 // Replace the exact with the load.
8982 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
8985 // The replacement was made in place; don't return anything.
8989 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
8990 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
8991 const X86Subtarget *Subtarget) {
8992 DebugLoc DL = N->getDebugLoc();
8993 SDValue Cond = N->getOperand(0);
8994 // Get the LHS/RHS of the select.
8995 SDValue LHS = N->getOperand(1);
8996 SDValue RHS = N->getOperand(2);
8998 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
8999 // instructions match the semantics of the common C idiom x<y?x:y but not
9000 // x<=y?x:y, because of how they handle negative zero (which can be
9001 // ignored in unsafe-math mode).
9002 if (Subtarget->hasSSE2() &&
9003 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
9004 Cond.getOpcode() == ISD::SETCC) {
9005 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
9007 unsigned Opcode = 0;
9008 // Check for x CC y ? x : y.
9009 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
9010 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
9014 // Converting this to a min would handle NaNs incorrectly, and swapping
9015 // the operands would cause it to handle comparisons between positive
9016 // and negative zero incorrectly.
9017 if (!FiniteOnlyFPMath() &&
9018 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
9019 if (!UnsafeFPMath &&
9020 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9022 std::swap(LHS, RHS);
9024 Opcode = X86ISD::FMIN;
9027 // Converting this to a min would handle comparisons between positive
9028 // and negative zero incorrectly.
9029 if (!UnsafeFPMath &&
9030 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
9032 Opcode = X86ISD::FMIN;
9035 // Converting this to a min would handle both negative zeros and NaNs
9036 // incorrectly, but we can swap the operands to fix both.
9037 std::swap(LHS, RHS);
9041 Opcode = X86ISD::FMIN;
9045 // Converting this to a max would handle comparisons between positive
9046 // and negative zero incorrectly.
9047 if (!UnsafeFPMath &&
9048 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
9050 Opcode = X86ISD::FMAX;
9053 // Converting this to a max would handle NaNs incorrectly, and swapping
9054 // the operands would cause it to handle comparisons between positive
9055 // and negative zero incorrectly.
9056 if (!FiniteOnlyFPMath() &&
9057 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
9058 if (!UnsafeFPMath &&
9059 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9061 std::swap(LHS, RHS);
9063 Opcode = X86ISD::FMAX;
9066 // Converting this to a max would handle both negative zeros and NaNs
9067 // incorrectly, but we can swap the operands to fix both.
9068 std::swap(LHS, RHS);
9072 Opcode = X86ISD::FMAX;
9075 // Check for x CC y ? y : x -- a min/max with reversed arms.
9076 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
9077 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
9081 // Converting this to a min would handle comparisons between positive
9082 // and negative zero incorrectly, and swapping the operands would
9083 // cause it to handle NaNs incorrectly.
9084 if (!UnsafeFPMath &&
9085 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
9086 if (!FiniteOnlyFPMath() &&
9087 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9089 std::swap(LHS, RHS);
9091 Opcode = X86ISD::FMIN;
9094 // Converting this to a min would handle NaNs incorrectly.
9095 if (!UnsafeFPMath &&
9096 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9098 Opcode = X86ISD::FMIN;
9101 // Converting this to a min would handle both negative zeros and NaNs
9102 // incorrectly, but we can swap the operands to fix both.
9103 std::swap(LHS, RHS);
9107 Opcode = X86ISD::FMIN;
9111 // Converting this to a max would handle NaNs incorrectly.
9112 if (!FiniteOnlyFPMath() &&
9113 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9115 Opcode = X86ISD::FMAX;
9118 // Converting this to a max would handle comparisons between positive
9119 // and negative zero incorrectly, and swapping the operands would
9120 // cause it to handle NaNs incorrectly.
9121 if (!UnsafeFPMath &&
9122 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
9123 if (!FiniteOnlyFPMath() &&
9124 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9126 std::swap(LHS, RHS);
9128 Opcode = X86ISD::FMAX;
9131 // Converting this to a max would handle both negative zeros and NaNs
9132 // incorrectly, but we can swap the operands to fix both.
9133 std::swap(LHS, RHS);
9137 Opcode = X86ISD::FMAX;
9143 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
9146 // If this is a select between two integer constants, try to do some
9148 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
9149 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
9150 // Don't do this for crazy integer types.
9151 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
9152 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
9153 // so that TrueC (the true value) is larger than FalseC.
9154 bool NeedsCondInvert = false;
9156 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
9157 // Efficiently invertible.
9158 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
9159 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
9160 isa<ConstantSDNode>(Cond.getOperand(1))))) {
9161 NeedsCondInvert = true;
9162 std::swap(TrueC, FalseC);
9165 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
9166 if (FalseC->getAPIntValue() == 0 &&
9167 TrueC->getAPIntValue().isPowerOf2()) {
9168 if (NeedsCondInvert) // Invert the condition if needed.
9169 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9170 DAG.getConstant(1, Cond.getValueType()));
9172 // Zero extend the condition if needed.
9173 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
9175 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9176 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
9177 DAG.getConstant(ShAmt, MVT::i8));
9180 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
9181 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9182 if (NeedsCondInvert) // Invert the condition if needed.
9183 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9184 DAG.getConstant(1, Cond.getValueType()));
9186 // Zero extend the condition if needed.
9187 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9188 FalseC->getValueType(0), Cond);
9189 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9190 SDValue(FalseC, 0));
9193 // Optimize cases that will turn into an LEA instruction. This requires
9194 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9195 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9196 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9197 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9199 bool isFastMultiplier = false;
9201 switch ((unsigned char)Diff) {
9203 case 1: // result = add base, cond
9204 case 2: // result = lea base( , cond*2)
9205 case 3: // result = lea base(cond, cond*2)
9206 case 4: // result = lea base( , cond*4)
9207 case 5: // result = lea base(cond, cond*4)
9208 case 8: // result = lea base( , cond*8)
9209 case 9: // result = lea base(cond, cond*8)
9210 isFastMultiplier = true;
9215 if (isFastMultiplier) {
9216 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9217 if (NeedsCondInvert) // Invert the condition if needed.
9218 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9219 DAG.getConstant(1, Cond.getValueType()));
9221 // Zero extend the condition if needed.
9222 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9224 // Scale the condition by the difference.
9226 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9227 DAG.getConstant(Diff, Cond.getValueType()));
9229 // Add the base if non-zero.
9230 if (FalseC->getAPIntValue() != 0)
9231 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9232 SDValue(FalseC, 0));
9242 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
9243 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
9244 TargetLowering::DAGCombinerInfo &DCI) {
9245 DebugLoc DL = N->getDebugLoc();
9247 // If the flag operand isn't dead, don't touch this CMOV.
9248 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
9251 // If this is a select between two integer constants, try to do some
9252 // optimizations. Note that the operands are ordered the opposite of SELECT
9254 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
9255 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9256 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
9257 // larger than FalseC (the false value).
9258 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
9260 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
9261 CC = X86::GetOppositeBranchCondition(CC);
9262 std::swap(TrueC, FalseC);
9265 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
9266 // This is efficient for any integer data type (including i8/i16) and
9268 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
9269 SDValue Cond = N->getOperand(3);
9270 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9271 DAG.getConstant(CC, MVT::i8), Cond);
9273 // Zero extend the condition if needed.
9274 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
9276 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9277 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
9278 DAG.getConstant(ShAmt, MVT::i8));
9279 if (N->getNumValues() == 2) // Dead flag value?
9280 return DCI.CombineTo(N, Cond, SDValue());
9284 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
9285 // for any integer data type, including i8/i16.
9286 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9287 SDValue Cond = N->getOperand(3);
9288 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9289 DAG.getConstant(CC, MVT::i8), Cond);
9291 // Zero extend the condition if needed.
9292 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9293 FalseC->getValueType(0), Cond);
9294 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9295 SDValue(FalseC, 0));
9297 if (N->getNumValues() == 2) // Dead flag value?
9298 return DCI.CombineTo(N, Cond, SDValue());
9302 // Optimize cases that will turn into an LEA instruction. This requires
9303 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9304 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9305 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9306 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9308 bool isFastMultiplier = false;
9310 switch ((unsigned char)Diff) {
9312 case 1: // result = add base, cond
9313 case 2: // result = lea base( , cond*2)
9314 case 3: // result = lea base(cond, cond*2)
9315 case 4: // result = lea base( , cond*4)
9316 case 5: // result = lea base(cond, cond*4)
9317 case 8: // result = lea base( , cond*8)
9318 case 9: // result = lea base(cond, cond*8)
9319 isFastMultiplier = true;
9324 if (isFastMultiplier) {
9325 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9326 SDValue Cond = N->getOperand(3);
9327 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9328 DAG.getConstant(CC, MVT::i8), Cond);
9329 // Zero extend the condition if needed.
9330 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9332 // Scale the condition by the difference.
9334 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9335 DAG.getConstant(Diff, Cond.getValueType()));
9337 // Add the base if non-zero.
9338 if (FalseC->getAPIntValue() != 0)
9339 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9340 SDValue(FalseC, 0));
9341 if (N->getNumValues() == 2) // Dead flag value?
9342 return DCI.CombineTo(N, Cond, SDValue());
9352 /// PerformMulCombine - Optimize a single multiply with constant into two
9353 /// in order to implement it with two cheaper instructions, e.g.
9354 /// LEA + SHL, LEA + LEA.
9355 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
9356 TargetLowering::DAGCombinerInfo &DCI) {
9357 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9360 EVT VT = N->getValueType(0);
9364 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9367 uint64_t MulAmt = C->getZExtValue();
9368 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
9371 uint64_t MulAmt1 = 0;
9372 uint64_t MulAmt2 = 0;
9373 if ((MulAmt % 9) == 0) {
9375 MulAmt2 = MulAmt / 9;
9376 } else if ((MulAmt % 5) == 0) {
9378 MulAmt2 = MulAmt / 5;
9379 } else if ((MulAmt % 3) == 0) {
9381 MulAmt2 = MulAmt / 3;
9384 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
9385 DebugLoc DL = N->getDebugLoc();
9387 if (isPowerOf2_64(MulAmt2) &&
9388 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
9389 // If second multiplifer is pow2, issue it first. We want the multiply by
9390 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
9392 std::swap(MulAmt1, MulAmt2);
9395 if (isPowerOf2_64(MulAmt1))
9396 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
9397 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
9399 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
9400 DAG.getConstant(MulAmt1, VT));
9402 if (isPowerOf2_64(MulAmt2))
9403 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
9404 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
9406 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
9407 DAG.getConstant(MulAmt2, VT));
9409 // Do not add new nodes to DAG combiner worklist.
9410 DCI.CombineTo(N, NewMul, false);
9415 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
9416 SDValue N0 = N->getOperand(0);
9417 SDValue N1 = N->getOperand(1);
9418 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9419 EVT VT = N0.getValueType();
9421 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
9422 // since the result of setcc_c is all zero's or all ones.
9423 if (N1C && N0.getOpcode() == ISD::AND &&
9424 N0.getOperand(1).getOpcode() == ISD::Constant) {
9425 SDValue N00 = N0.getOperand(0);
9426 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
9427 ((N00.getOpcode() == ISD::ANY_EXTEND ||
9428 N00.getOpcode() == ISD::ZERO_EXTEND) &&
9429 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
9430 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
9431 APInt ShAmt = N1C->getAPIntValue();
9432 Mask = Mask.shl(ShAmt);
9434 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
9435 N00, DAG.getConstant(Mask, VT));
9442 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
9444 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
9445 const X86Subtarget *Subtarget) {
9446 EVT VT = N->getValueType(0);
9447 if (!VT.isVector() && VT.isInteger() &&
9448 N->getOpcode() == ISD::SHL)
9449 return PerformSHLCombine(N, DAG);
9451 // On X86 with SSE2 support, we can transform this to a vector shift if
9452 // all elements are shifted by the same amount. We can't do this in legalize
9453 // because the a constant vector is typically transformed to a constant pool
9454 // so we have no knowledge of the shift amount.
9455 if (!Subtarget->hasSSE2())
9458 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
9461 SDValue ShAmtOp = N->getOperand(1);
9462 EVT EltVT = VT.getVectorElementType();
9463 DebugLoc DL = N->getDebugLoc();
9464 SDValue BaseShAmt = SDValue();
9465 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
9466 unsigned NumElts = VT.getVectorNumElements();
9468 for (; i != NumElts; ++i) {
9469 SDValue Arg = ShAmtOp.getOperand(i);
9470 if (Arg.getOpcode() == ISD::UNDEF) continue;
9474 for (; i != NumElts; ++i) {
9475 SDValue Arg = ShAmtOp.getOperand(i);
9476 if (Arg.getOpcode() == ISD::UNDEF) continue;
9477 if (Arg != BaseShAmt) {
9481 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
9482 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
9483 SDValue InVec = ShAmtOp.getOperand(0);
9484 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
9485 unsigned NumElts = InVec.getValueType().getVectorNumElements();
9487 for (; i != NumElts; ++i) {
9488 SDValue Arg = InVec.getOperand(i);
9489 if (Arg.getOpcode() == ISD::UNDEF) continue;
9493 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
9494 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
9495 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
9496 if (C->getZExtValue() == SplatIdx)
9497 BaseShAmt = InVec.getOperand(1);
9500 if (BaseShAmt.getNode() == 0)
9501 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
9502 DAG.getIntPtrConstant(0));
9506 // The shift amount is an i32.
9507 if (EltVT.bitsGT(MVT::i32))
9508 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
9509 else if (EltVT.bitsLT(MVT::i32))
9510 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
9512 // The shift amount is identical so we can do a vector shift.
9513 SDValue ValOp = N->getOperand(0);
9514 switch (N->getOpcode()) {
9516 llvm_unreachable("Unknown shift opcode!");
9519 if (VT == MVT::v2i64)
9520 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9521 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9523 if (VT == MVT::v4i32)
9524 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9525 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9527 if (VT == MVT::v8i16)
9528 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9529 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9533 if (VT == MVT::v4i32)
9534 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9535 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9537 if (VT == MVT::v8i16)
9538 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9539 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9543 if (VT == MVT::v2i64)
9544 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9545 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9547 if (VT == MVT::v4i32)
9548 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9549 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9551 if (VT == MVT::v8i16)
9552 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9553 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9560 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
9561 const X86Subtarget *Subtarget) {
9562 EVT VT = N->getValueType(0);
9563 if (VT != MVT::i64 || !Subtarget->is64Bit())
9566 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
9567 SDValue N0 = N->getOperand(0);
9568 SDValue N1 = N->getOperand(1);
9569 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
9571 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
9574 SDValue ShAmt0 = N0.getOperand(1);
9575 if (ShAmt0.getValueType() != MVT::i8)
9577 SDValue ShAmt1 = N1.getOperand(1);
9578 if (ShAmt1.getValueType() != MVT::i8)
9580 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
9581 ShAmt0 = ShAmt0.getOperand(0);
9582 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
9583 ShAmt1 = ShAmt1.getOperand(0);
9585 DebugLoc DL = N->getDebugLoc();
9586 unsigned Opc = X86ISD::SHLD;
9587 SDValue Op0 = N0.getOperand(0);
9588 SDValue Op1 = N1.getOperand(0);
9589 if (ShAmt0.getOpcode() == ISD::SUB) {
9591 std::swap(Op0, Op1);
9592 std::swap(ShAmt0, ShAmt1);
9595 if (ShAmt1.getOpcode() == ISD::SUB) {
9596 SDValue Sum = ShAmt1.getOperand(0);
9597 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
9598 if (SumC->getSExtValue() == 64 &&
9599 ShAmt1.getOperand(1) == ShAmt0)
9600 return DAG.getNode(Opc, DL, VT,
9602 DAG.getNode(ISD::TRUNCATE, DL,
9605 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
9606 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
9608 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == 64)
9609 return DAG.getNode(Opc, DL, VT,
9610 N0.getOperand(0), N1.getOperand(0),
9611 DAG.getNode(ISD::TRUNCATE, DL,
9618 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
9619 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
9620 const X86Subtarget *Subtarget) {
9621 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
9622 // the FP state in cases where an emms may be missing.
9623 // A preferable solution to the general problem is to figure out the right
9624 // places to insert EMMS. This qualifies as a quick hack.
9626 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
9627 StoreSDNode *St = cast<StoreSDNode>(N);
9628 EVT VT = St->getValue().getValueType();
9629 if (VT.getSizeInBits() != 64)
9632 const Function *F = DAG.getMachineFunction().getFunction();
9633 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
9634 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
9635 && Subtarget->hasSSE2();
9636 if ((VT.isVector() ||
9637 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
9638 isa<LoadSDNode>(St->getValue()) &&
9639 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
9640 St->getChain().hasOneUse() && !St->isVolatile()) {
9641 SDNode* LdVal = St->getValue().getNode();
9643 int TokenFactorIndex = -1;
9644 SmallVector<SDValue, 8> Ops;
9645 SDNode* ChainVal = St->getChain().getNode();
9646 // Must be a store of a load. We currently handle two cases: the load
9647 // is a direct child, and it's under an intervening TokenFactor. It is
9648 // possible to dig deeper under nested TokenFactors.
9649 if (ChainVal == LdVal)
9650 Ld = cast<LoadSDNode>(St->getChain());
9651 else if (St->getValue().hasOneUse() &&
9652 ChainVal->getOpcode() == ISD::TokenFactor) {
9653 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
9654 if (ChainVal->getOperand(i).getNode() == LdVal) {
9655 TokenFactorIndex = i;
9656 Ld = cast<LoadSDNode>(St->getValue());
9658 Ops.push_back(ChainVal->getOperand(i));
9662 if (!Ld || !ISD::isNormalLoad(Ld))
9665 // If this is not the MMX case, i.e. we are just turning i64 load/store
9666 // into f64 load/store, avoid the transformation if there are multiple
9667 // uses of the loaded value.
9668 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
9671 DebugLoc LdDL = Ld->getDebugLoc();
9672 DebugLoc StDL = N->getDebugLoc();
9673 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
9674 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
9676 if (Subtarget->is64Bit() || F64IsLegal) {
9677 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
9678 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
9679 Ld->getBasePtr(), Ld->getSrcValue(),
9680 Ld->getSrcValueOffset(), Ld->isVolatile(),
9681 Ld->isNonTemporal(), Ld->getAlignment());
9682 SDValue NewChain = NewLd.getValue(1);
9683 if (TokenFactorIndex != -1) {
9684 Ops.push_back(NewChain);
9685 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9688 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
9689 St->getSrcValue(), St->getSrcValueOffset(),
9690 St->isVolatile(), St->isNonTemporal(),
9691 St->getAlignment());
9694 // Otherwise, lower to two pairs of 32-bit loads / stores.
9695 SDValue LoAddr = Ld->getBasePtr();
9696 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
9697 DAG.getConstant(4, MVT::i32));
9699 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
9700 Ld->getSrcValue(), Ld->getSrcValueOffset(),
9701 Ld->isVolatile(), Ld->isNonTemporal(),
9702 Ld->getAlignment());
9703 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
9704 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
9705 Ld->isVolatile(), Ld->isNonTemporal(),
9706 MinAlign(Ld->getAlignment(), 4));
9708 SDValue NewChain = LoLd.getValue(1);
9709 if (TokenFactorIndex != -1) {
9710 Ops.push_back(LoLd);
9711 Ops.push_back(HiLd);
9712 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9716 LoAddr = St->getBasePtr();
9717 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
9718 DAG.getConstant(4, MVT::i32));
9720 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
9721 St->getSrcValue(), St->getSrcValueOffset(),
9722 St->isVolatile(), St->isNonTemporal(),
9723 St->getAlignment());
9724 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
9726 St->getSrcValueOffset() + 4,
9728 St->isNonTemporal(),
9729 MinAlign(St->getAlignment(), 4));
9730 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
9735 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
9736 /// X86ISD::FXOR nodes.
9737 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
9738 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
9739 // F[X]OR(0.0, x) -> x
9740 // F[X]OR(x, 0.0) -> x
9741 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9742 if (C->getValueAPF().isPosZero())
9743 return N->getOperand(1);
9744 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9745 if (C->getValueAPF().isPosZero())
9746 return N->getOperand(0);
9750 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
9751 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
9752 // FAND(0.0, x) -> 0.0
9753 // FAND(x, 0.0) -> 0.0
9754 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9755 if (C->getValueAPF().isPosZero())
9756 return N->getOperand(0);
9757 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9758 if (C->getValueAPF().isPosZero())
9759 return N->getOperand(1);
9763 static SDValue PerformBTCombine(SDNode *N,
9765 TargetLowering::DAGCombinerInfo &DCI) {
9766 // BT ignores high bits in the bit index operand.
9767 SDValue Op1 = N->getOperand(1);
9768 if (Op1.hasOneUse()) {
9769 unsigned BitWidth = Op1.getValueSizeInBits();
9770 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
9771 APInt KnownZero, KnownOne;
9772 TargetLowering::TargetLoweringOpt TLO(DAG);
9773 TargetLowering &TLI = DAG.getTargetLoweringInfo();
9774 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
9775 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
9776 DCI.CommitTargetLoweringOpt(TLO);
9781 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
9782 SDValue Op = N->getOperand(0);
9783 if (Op.getOpcode() == ISD::BIT_CONVERT)
9784 Op = Op.getOperand(0);
9785 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
9786 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
9787 VT.getVectorElementType().getSizeInBits() ==
9788 OpVT.getVectorElementType().getSizeInBits()) {
9789 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
9794 // On X86 and X86-64, atomic operations are lowered to locked instructions.
9795 // Locked instructions, in turn, have implicit fence semantics (all memory
9796 // operations are flushed before issuing the locked instruction, and the
9797 // are not buffered), so we can fold away the common pattern of
9798 // fence-atomic-fence.
9799 static SDValue PerformMEMBARRIERCombine(SDNode* N, SelectionDAG &DAG) {
9800 SDValue atomic = N->getOperand(0);
9801 switch (atomic.getOpcode()) {
9802 case ISD::ATOMIC_CMP_SWAP:
9803 case ISD::ATOMIC_SWAP:
9804 case ISD::ATOMIC_LOAD_ADD:
9805 case ISD::ATOMIC_LOAD_SUB:
9806 case ISD::ATOMIC_LOAD_AND:
9807 case ISD::ATOMIC_LOAD_OR:
9808 case ISD::ATOMIC_LOAD_XOR:
9809 case ISD::ATOMIC_LOAD_NAND:
9810 case ISD::ATOMIC_LOAD_MIN:
9811 case ISD::ATOMIC_LOAD_MAX:
9812 case ISD::ATOMIC_LOAD_UMIN:
9813 case ISD::ATOMIC_LOAD_UMAX:
9819 SDValue fence = atomic.getOperand(0);
9820 if (fence.getOpcode() != ISD::MEMBARRIER)
9823 switch (atomic.getOpcode()) {
9824 case ISD::ATOMIC_CMP_SWAP:
9825 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9826 atomic.getOperand(1), atomic.getOperand(2),
9827 atomic.getOperand(3));
9828 case ISD::ATOMIC_SWAP:
9829 case ISD::ATOMIC_LOAD_ADD:
9830 case ISD::ATOMIC_LOAD_SUB:
9831 case ISD::ATOMIC_LOAD_AND:
9832 case ISD::ATOMIC_LOAD_OR:
9833 case ISD::ATOMIC_LOAD_XOR:
9834 case ISD::ATOMIC_LOAD_NAND:
9835 case ISD::ATOMIC_LOAD_MIN:
9836 case ISD::ATOMIC_LOAD_MAX:
9837 case ISD::ATOMIC_LOAD_UMIN:
9838 case ISD::ATOMIC_LOAD_UMAX:
9839 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9840 atomic.getOperand(1), atomic.getOperand(2));
9846 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
9847 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
9848 // (and (i32 x86isd::setcc_carry), 1)
9849 // This eliminates the zext. This transformation is necessary because
9850 // ISD::SETCC is always legalized to i8.
9851 DebugLoc dl = N->getDebugLoc();
9852 SDValue N0 = N->getOperand(0);
9853 EVT VT = N->getValueType(0);
9854 if (N0.getOpcode() == ISD::AND &&
9856 N0.getOperand(0).hasOneUse()) {
9857 SDValue N00 = N0.getOperand(0);
9858 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
9860 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9861 if (!C || C->getZExtValue() != 1)
9863 return DAG.getNode(ISD::AND, dl, VT,
9864 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
9865 N00.getOperand(0), N00.getOperand(1)),
9866 DAG.getConstant(1, VT));
9872 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
9873 DAGCombinerInfo &DCI) const {
9874 SelectionDAG &DAG = DCI.DAG;
9875 switch (N->getOpcode()) {
9877 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
9878 case ISD::EXTRACT_VECTOR_ELT:
9879 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
9880 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
9881 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
9882 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
9885 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
9886 case ISD::OR: return PerformOrCombine(N, DAG, Subtarget);
9887 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
9889 case X86ISD::FOR: return PerformFORCombine(N, DAG);
9890 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
9891 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
9892 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
9893 case ISD::MEMBARRIER: return PerformMEMBARRIERCombine(N, DAG);
9894 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
9900 //===----------------------------------------------------------------------===//
9901 // X86 Inline Assembly Support
9902 //===----------------------------------------------------------------------===//
9904 static bool LowerToBSwap(CallInst *CI) {
9905 // FIXME: this should verify that we are targetting a 486 or better. If not,
9906 // we will turn this bswap into something that will be lowered to logical ops
9907 // instead of emitting the bswap asm. For now, we don't support 486 or lower
9908 // so don't worry about this.
9910 // Verify this is a simple bswap.
9911 if (CI->getNumOperands() != 2 ||
9912 CI->getType() != CI->getOperand(1)->getType() ||
9913 !CI->getType()->isIntegerTy())
9916 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9917 if (!Ty || Ty->getBitWidth() % 16 != 0)
9920 // Okay, we can do this xform, do so now.
9921 const Type *Tys[] = { Ty };
9922 Module *M = CI->getParent()->getParent()->getParent();
9923 Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
9925 Value *Op = CI->getOperand(1);
9926 Op = CallInst::Create(Int, Op, CI->getName(), CI);
9928 CI->replaceAllUsesWith(Op);
9929 CI->eraseFromParent();
9933 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
9934 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9935 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
9937 std::string AsmStr = IA->getAsmString();
9939 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
9940 SmallVector<StringRef, 4> AsmPieces;
9941 SplitString(AsmStr, AsmPieces, "\n"); // ; as separator?
9943 switch (AsmPieces.size()) {
9944 default: return false;
9946 AsmStr = AsmPieces[0];
9948 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
9951 if (AsmPieces.size() == 2 &&
9952 (AsmPieces[0] == "bswap" ||
9953 AsmPieces[0] == "bswapq" ||
9954 AsmPieces[0] == "bswapl") &&
9955 (AsmPieces[1] == "$0" ||
9956 AsmPieces[1] == "${0:q}")) {
9957 // No need to check constraints, nothing other than the equivalent of
9958 // "=r,0" would be valid here.
9959 return LowerToBSwap(CI);
9961 // rorw $$8, ${0:w} --> llvm.bswap.i16
9962 if (CI->getType()->isIntegerTy(16) &&
9963 AsmPieces.size() == 3 &&
9964 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
9965 AsmPieces[1] == "$$8," &&
9966 AsmPieces[2] == "${0:w}" &&
9967 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
9969 const std::string &Constraints = IA->getConstraintString();
9970 SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
9971 std::sort(AsmPieces.begin(), AsmPieces.end());
9972 if (AsmPieces.size() == 4 &&
9973 AsmPieces[0] == "~{cc}" &&
9974 AsmPieces[1] == "~{dirflag}" &&
9975 AsmPieces[2] == "~{flags}" &&
9976 AsmPieces[3] == "~{fpsr}") {
9977 return LowerToBSwap(CI);
9982 if (CI->getType()->isIntegerTy(64) &&
9983 Constraints.size() >= 2 &&
9984 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
9985 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
9986 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
9987 SmallVector<StringRef, 4> Words;
9988 SplitString(AsmPieces[0], Words, " \t");
9989 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
9991 SplitString(AsmPieces[1], Words, " \t");
9992 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
9994 SplitString(AsmPieces[2], Words, " \t,");
9995 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
9996 Words[2] == "%edx") {
9997 return LowerToBSwap(CI);
10009 /// getConstraintType - Given a constraint letter, return the type of
10010 /// constraint it is for this target.
10011 X86TargetLowering::ConstraintType
10012 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
10013 if (Constraint.size() == 1) {
10014 switch (Constraint[0]) {
10026 return C_RegisterClass;
10034 return TargetLowering::getConstraintType(Constraint);
10037 /// LowerXConstraint - try to replace an X constraint, which matches anything,
10038 /// with another that has more specific requirements based on the type of the
10039 /// corresponding operand.
10040 const char *X86TargetLowering::
10041 LowerXConstraint(EVT ConstraintVT) const {
10042 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
10043 // 'f' like normal targets.
10044 if (ConstraintVT.isFloatingPoint()) {
10045 if (Subtarget->hasSSE2())
10047 if (Subtarget->hasSSE1())
10051 return TargetLowering::LowerXConstraint(ConstraintVT);
10054 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10055 /// vector. If it is invalid, don't add anything to Ops.
10056 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10059 std::vector<SDValue>&Ops,
10060 SelectionDAG &DAG) const {
10061 SDValue Result(0, 0);
10063 switch (Constraint) {
10066 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10067 if (C->getZExtValue() <= 31) {
10068 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10074 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10075 if (C->getZExtValue() <= 63) {
10076 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10082 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10083 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
10084 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10090 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10091 if (C->getZExtValue() <= 255) {
10092 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10098 // 32-bit signed value
10099 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10100 const ConstantInt *CI = C->getConstantIntValue();
10101 if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10102 C->getSExtValue())) {
10103 // Widen to 64 bits here to get it sign extended.
10104 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
10107 // FIXME gcc accepts some relocatable values here too, but only in certain
10108 // memory models; it's complicated.
10113 // 32-bit unsigned value
10114 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10115 const ConstantInt *CI = C->getConstantIntValue();
10116 if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10117 C->getZExtValue())) {
10118 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10122 // FIXME gcc accepts some relocatable values here too, but only in certain
10123 // memory models; it's complicated.
10127 // Literal immediates are always ok.
10128 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
10129 // Widen to 64 bits here to get it sign extended.
10130 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
10134 // If we are in non-pic codegen mode, we allow the address of a global (with
10135 // an optional displacement) to be used with 'i'.
10136 GlobalAddressSDNode *GA = 0;
10137 int64_t Offset = 0;
10139 // Match either (GA), (GA+C), (GA+C1+C2), etc.
10141 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
10142 Offset += GA->getOffset();
10144 } else if (Op.getOpcode() == ISD::ADD) {
10145 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10146 Offset += C->getZExtValue();
10147 Op = Op.getOperand(0);
10150 } else if (Op.getOpcode() == ISD::SUB) {
10151 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10152 Offset += -C->getZExtValue();
10153 Op = Op.getOperand(0);
10158 // Otherwise, this isn't something we can handle, reject it.
10162 GlobalValue *GV = GA->getGlobal();
10163 // If we require an extra load to get this address, as in PIC mode, we
10164 // can't accept it.
10165 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
10166 getTargetMachine())))
10170 Op = LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
10172 Op = DAG.getTargetGlobalAddress(GV, GA->getValueType(0), Offset);
10178 if (Result.getNode()) {
10179 Ops.push_back(Result);
10182 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
10186 std::vector<unsigned> X86TargetLowering::
10187 getRegClassForInlineAsmConstraint(const std::string &Constraint,
10189 if (Constraint.size() == 1) {
10190 // FIXME: not handling fp-stack yet!
10191 switch (Constraint[0]) { // GCC X86 Constraint Letters
10192 default: break; // Unknown constraint letter
10193 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
10194 if (Subtarget->is64Bit()) {
10195 if (VT == MVT::i32)
10196 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
10197 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
10198 X86::R10D,X86::R11D,X86::R12D,
10199 X86::R13D,X86::R14D,X86::R15D,
10200 X86::EBP, X86::ESP, 0);
10201 else if (VT == MVT::i16)
10202 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
10203 X86::SI, X86::DI, X86::R8W,X86::R9W,
10204 X86::R10W,X86::R11W,X86::R12W,
10205 X86::R13W,X86::R14W,X86::R15W,
10206 X86::BP, X86::SP, 0);
10207 else if (VT == MVT::i8)
10208 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
10209 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
10210 X86::R10B,X86::R11B,X86::R12B,
10211 X86::R13B,X86::R14B,X86::R15B,
10212 X86::BPL, X86::SPL, 0);
10214 else if (VT == MVT::i64)
10215 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
10216 X86::RSI, X86::RDI, X86::R8, X86::R9,
10217 X86::R10, X86::R11, X86::R12,
10218 X86::R13, X86::R14, X86::R15,
10219 X86::RBP, X86::RSP, 0);
10223 // 32-bit fallthrough
10224 case 'Q': // Q_REGS
10225 if (VT == MVT::i32)
10226 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
10227 else if (VT == MVT::i16)
10228 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
10229 else if (VT == MVT::i8)
10230 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
10231 else if (VT == MVT::i64)
10232 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
10237 return std::vector<unsigned>();
10240 std::pair<unsigned, const TargetRegisterClass*>
10241 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10243 // First, see if this is a constraint that directly corresponds to an LLVM
10245 if (Constraint.size() == 1) {
10246 // GCC Constraint Letters
10247 switch (Constraint[0]) {
10249 case 'r': // GENERAL_REGS
10250 case 'l': // INDEX_REGS
10252 return std::make_pair(0U, X86::GR8RegisterClass);
10253 if (VT == MVT::i16)
10254 return std::make_pair(0U, X86::GR16RegisterClass);
10255 if (VT == MVT::i32 || !Subtarget->is64Bit())
10256 return std::make_pair(0U, X86::GR32RegisterClass);
10257 return std::make_pair(0U, X86::GR64RegisterClass);
10258 case 'R': // LEGACY_REGS
10260 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
10261 if (VT == MVT::i16)
10262 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
10263 if (VT == MVT::i32 || !Subtarget->is64Bit())
10264 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
10265 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
10266 case 'f': // FP Stack registers.
10267 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
10268 // value to the correct fpstack register class.
10269 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
10270 return std::make_pair(0U, X86::RFP32RegisterClass);
10271 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
10272 return std::make_pair(0U, X86::RFP64RegisterClass);
10273 return std::make_pair(0U, X86::RFP80RegisterClass);
10274 case 'y': // MMX_REGS if MMX allowed.
10275 if (!Subtarget->hasMMX()) break;
10276 return std::make_pair(0U, X86::VR64RegisterClass);
10277 case 'Y': // SSE_REGS if SSE2 allowed
10278 if (!Subtarget->hasSSE2()) break;
10280 case 'x': // SSE_REGS if SSE1 allowed
10281 if (!Subtarget->hasSSE1()) break;
10283 switch (VT.getSimpleVT().SimpleTy) {
10285 // Scalar SSE types.
10288 return std::make_pair(0U, X86::FR32RegisterClass);
10291 return std::make_pair(0U, X86::FR64RegisterClass);
10299 return std::make_pair(0U, X86::VR128RegisterClass);
10305 // Use the default implementation in TargetLowering to convert the register
10306 // constraint into a member of a register class.
10307 std::pair<unsigned, const TargetRegisterClass*> Res;
10308 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10310 // Not found as a standard register?
10311 if (Res.second == 0) {
10312 // Map st(0) -> st(7) -> ST0
10313 if (Constraint.size() == 7 && Constraint[0] == '{' &&
10314 tolower(Constraint[1]) == 's' &&
10315 tolower(Constraint[2]) == 't' &&
10316 Constraint[3] == '(' &&
10317 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
10318 Constraint[5] == ')' &&
10319 Constraint[6] == '}') {
10321 Res.first = X86::ST0+Constraint[4]-'0';
10322 Res.second = X86::RFP80RegisterClass;
10326 // GCC allows "st(0)" to be called just plain "st".
10327 if (StringRef("{st}").equals_lower(Constraint)) {
10328 Res.first = X86::ST0;
10329 Res.second = X86::RFP80RegisterClass;
10334 if (StringRef("{flags}").equals_lower(Constraint)) {
10335 Res.first = X86::EFLAGS;
10336 Res.second = X86::CCRRegisterClass;
10340 // 'A' means EAX + EDX.
10341 if (Constraint == "A") {
10342 Res.first = X86::EAX;
10343 Res.second = X86::GR32_ADRegisterClass;
10349 // Otherwise, check to see if this is a register class of the wrong value
10350 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
10351 // turn into {ax},{dx}.
10352 if (Res.second->hasType(VT))
10353 return Res; // Correct type already, nothing to do.
10355 // All of the single-register GCC register classes map their values onto
10356 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
10357 // really want an 8-bit or 32-bit register, map to the appropriate register
10358 // class and return the appropriate register.
10359 if (Res.second == X86::GR16RegisterClass) {
10360 if (VT == MVT::i8) {
10361 unsigned DestReg = 0;
10362 switch (Res.first) {
10364 case X86::AX: DestReg = X86::AL; break;
10365 case X86::DX: DestReg = X86::DL; break;
10366 case X86::CX: DestReg = X86::CL; break;
10367 case X86::BX: DestReg = X86::BL; break;
10370 Res.first = DestReg;
10371 Res.second = X86::GR8RegisterClass;
10373 } else if (VT == MVT::i32) {
10374 unsigned DestReg = 0;
10375 switch (Res.first) {
10377 case X86::AX: DestReg = X86::EAX; break;
10378 case X86::DX: DestReg = X86::EDX; break;
10379 case X86::CX: DestReg = X86::ECX; break;
10380 case X86::BX: DestReg = X86::EBX; break;
10381 case X86::SI: DestReg = X86::ESI; break;
10382 case X86::DI: DestReg = X86::EDI; break;
10383 case X86::BP: DestReg = X86::EBP; break;
10384 case X86::SP: DestReg = X86::ESP; break;
10387 Res.first = DestReg;
10388 Res.second = X86::GR32RegisterClass;
10390 } else if (VT == MVT::i64) {
10391 unsigned DestReg = 0;
10392 switch (Res.first) {
10394 case X86::AX: DestReg = X86::RAX; break;
10395 case X86::DX: DestReg = X86::RDX; break;
10396 case X86::CX: DestReg = X86::RCX; break;
10397 case X86::BX: DestReg = X86::RBX; break;
10398 case X86::SI: DestReg = X86::RSI; break;
10399 case X86::DI: DestReg = X86::RDI; break;
10400 case X86::BP: DestReg = X86::RBP; break;
10401 case X86::SP: DestReg = X86::RSP; break;
10404 Res.first = DestReg;
10405 Res.second = X86::GR64RegisterClass;
10408 } else if (Res.second == X86::FR32RegisterClass ||
10409 Res.second == X86::FR64RegisterClass ||
10410 Res.second == X86::VR128RegisterClass) {
10411 // Handle references to XMM physical registers that got mapped into the
10412 // wrong class. This can happen with constraints like {xmm0} where the
10413 // target independent register mapper will just pick the first match it can
10414 // find, ignoring the required type.
10415 if (VT == MVT::f32)
10416 Res.second = X86::FR32RegisterClass;
10417 else if (VT == MVT::f64)
10418 Res.second = X86::FR64RegisterClass;
10419 else if (X86::VR128RegisterClass->hasType(VT))
10420 Res.second = X86::VR128RegisterClass;