1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
16 #include "X86InstrBuilder.h"
17 #include "X86ISelLowering.h"
18 #include "X86TargetMachine.h"
19 #include "llvm/CallingConv.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/GlobalAlias.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Function.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/ADT/BitVector.h"
27 #include "llvm/ADT/VectorExtras.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/PseudoSourceValue.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/ADT/SmallSet.h"
39 #include "llvm/ADT/StringExtras.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/raw_ostream.h"
45 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
47 // Forward declarations.
48 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
51 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
52 : TargetLowering(TM) {
53 Subtarget = &TM.getSubtarget<X86Subtarget>();
54 X86ScalarSSEf64 = Subtarget->hasSSE2();
55 X86ScalarSSEf32 = Subtarget->hasSSE1();
56 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
58 RegInfo = TM.getRegisterInfo();
61 // Set up the TargetLowering object.
63 // X86 is weird, it always uses i8 for shift amounts and setcc results.
64 setShiftAmountType(MVT::i8);
65 setBooleanContents(ZeroOrOneBooleanContent);
66 setSchedulingPreference(SchedulingForRegPressure);
67 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
68 setStackPointerRegisterToSaveRestore(X86StackPtr);
70 if (Subtarget->isTargetDarwin()) {
71 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
72 setUseUnderscoreSetJmp(false);
73 setUseUnderscoreLongJmp(false);
74 } else if (Subtarget->isTargetMingw()) {
75 // MS runtime is weird: it exports _setjmp, but longjmp!
76 setUseUnderscoreSetJmp(true);
77 setUseUnderscoreLongJmp(false);
79 setUseUnderscoreSetJmp(true);
80 setUseUnderscoreLongJmp(true);
83 // Set up the register classes.
84 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
85 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
86 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
87 if (Subtarget->is64Bit())
88 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
90 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
92 // We don't accept any truncstore of integer registers.
93 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
94 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
95 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
96 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
97 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
98 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
100 // SETOEQ and SETUNE require checking two conditions.
101 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
102 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
103 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
104 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
105 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
106 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
108 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
110 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
111 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
112 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
114 if (Subtarget->is64Bit()) {
115 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
116 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
117 } else if (!UseSoftFloat) {
118 if (X86ScalarSSEf64) {
119 // We have an impenetrably clever algorithm for ui64->double only.
120 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
122 // We have an algorithm for SSE2, and we turn this into a 64-bit
123 // FILD for other targets.
124 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
127 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
129 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
130 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
133 // SSE has no i16 to fp conversion, only i32
134 if (X86ScalarSSEf32) {
135 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
136 // f32 and f64 cases are Legal, f80 case is not
137 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
139 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
140 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
143 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
144 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
147 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
148 // are Legal, f80 is custom lowered.
149 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
150 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
152 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
154 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
155 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
157 if (X86ScalarSSEf32) {
158 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
159 // f32 and f64 cases are Legal, f80 case is not
160 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
162 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
163 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
166 // Handle FP_TO_UINT by promoting the destination to a larger signed
168 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
169 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
170 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
172 if (Subtarget->is64Bit()) {
173 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
174 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
175 } else if (!UseSoftFloat) {
176 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
177 // Expand FP_TO_UINT into a select.
178 // FIXME: We would like to use a Custom expander here eventually to do
179 // the optimal thing for SSE vs. the default expansion in the legalizer.
180 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
182 // With SSE3 we can use fisttpll to convert to a signed i64; without
183 // SSE, we're stuck with a fistpll.
184 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
187 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
188 if (!X86ScalarSSEf64) {
189 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
190 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
193 // Scalar integer divide and remainder are lowered to use operations that
194 // produce two results, to match the available instructions. This exposes
195 // the two-result form to trivial CSE, which is able to combine x/y and x%y
196 // into a single instruction.
198 // Scalar integer multiply-high is also lowered to use two-result
199 // operations, to match the available instructions. However, plain multiply
200 // (low) operations are left as Legal, as there are single-result
201 // instructions for this in x86. Using the two-result multiply instructions
202 // when both high and low results are needed must be arranged by dagcombine.
203 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
204 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
205 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
206 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
207 setOperationAction(ISD::SREM , MVT::i8 , Expand);
208 setOperationAction(ISD::UREM , MVT::i8 , Expand);
209 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
210 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
211 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
212 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
213 setOperationAction(ISD::SREM , MVT::i16 , Expand);
214 setOperationAction(ISD::UREM , MVT::i16 , Expand);
215 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
216 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
217 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
218 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
219 setOperationAction(ISD::SREM , MVT::i32 , Expand);
220 setOperationAction(ISD::UREM , MVT::i32 , Expand);
221 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
222 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
223 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
224 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
225 setOperationAction(ISD::SREM , MVT::i64 , Expand);
226 setOperationAction(ISD::UREM , MVT::i64 , Expand);
228 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
229 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
230 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
231 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
232 if (Subtarget->is64Bit())
233 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
234 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
235 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
236 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
237 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
238 setOperationAction(ISD::FREM , MVT::f32 , Expand);
239 setOperationAction(ISD::FREM , MVT::f64 , Expand);
240 setOperationAction(ISD::FREM , MVT::f80 , Expand);
241 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
243 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
244 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
245 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
246 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
247 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
248 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
249 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
250 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
251 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
252 if (Subtarget->is64Bit()) {
253 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
254 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
255 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
258 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
259 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
261 // These should be promoted to a larger select which is supported.
262 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
263 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
264 // X86 wants to expand cmov itself.
265 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
266 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
267 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
268 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
269 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
270 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
271 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
272 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
273 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
274 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
275 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
276 if (Subtarget->is64Bit()) {
277 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
278 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
280 // X86 ret instruction may pop stack.
281 setOperationAction(ISD::RET , MVT::Other, Custom);
282 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
285 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
286 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
287 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
288 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
289 if (Subtarget->is64Bit())
290 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
291 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
292 if (Subtarget->is64Bit()) {
293 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
294 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
295 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
296 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
298 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
299 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
300 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
301 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
302 if (Subtarget->is64Bit()) {
303 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
304 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
305 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
308 if (Subtarget->hasSSE1())
309 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
311 if (!Subtarget->hasSSE2())
312 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
314 // Expand certain atomics
315 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
316 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
317 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
318 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
320 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
321 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
322 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
323 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
325 if (!Subtarget->is64Bit()) {
326 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
327 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
328 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
329 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
330 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
331 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
332 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
335 // Use the default ISD::DBG_STOPPOINT, ISD::DECLARE expansion.
336 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
337 // FIXME - use subtarget debug flags
338 if (!Subtarget->isTargetDarwin() &&
339 !Subtarget->isTargetELF() &&
340 !Subtarget->isTargetCygMing()) {
341 setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
342 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
345 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
346 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
347 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
348 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
349 if (Subtarget->is64Bit()) {
350 setExceptionPointerRegister(X86::RAX);
351 setExceptionSelectorRegister(X86::RDX);
353 setExceptionPointerRegister(X86::EAX);
354 setExceptionSelectorRegister(X86::EDX);
356 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
357 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
359 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
361 setOperationAction(ISD::TRAP, MVT::Other, Legal);
363 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
364 setOperationAction(ISD::VASTART , MVT::Other, Custom);
365 setOperationAction(ISD::VAEND , MVT::Other, Expand);
366 if (Subtarget->is64Bit()) {
367 setOperationAction(ISD::VAARG , MVT::Other, Custom);
368 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
370 setOperationAction(ISD::VAARG , MVT::Other, Expand);
371 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
374 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
375 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
376 if (Subtarget->is64Bit())
377 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
378 if (Subtarget->isTargetCygMing())
379 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
381 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
383 if (!UseSoftFloat && X86ScalarSSEf64) {
384 // f32 and f64 use SSE.
385 // Set up the FP register classes.
386 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
387 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
389 // Use ANDPD to simulate FABS.
390 setOperationAction(ISD::FABS , MVT::f64, Custom);
391 setOperationAction(ISD::FABS , MVT::f32, Custom);
393 // Use XORP to simulate FNEG.
394 setOperationAction(ISD::FNEG , MVT::f64, Custom);
395 setOperationAction(ISD::FNEG , MVT::f32, Custom);
397 // Use ANDPD and ORPD to simulate FCOPYSIGN.
398 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
399 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
401 // We don't support sin/cos/fmod
402 setOperationAction(ISD::FSIN , MVT::f64, Expand);
403 setOperationAction(ISD::FCOS , MVT::f64, Expand);
404 setOperationAction(ISD::FSIN , MVT::f32, Expand);
405 setOperationAction(ISD::FCOS , MVT::f32, Expand);
407 // Expand FP immediates into loads from the stack, except for the special
409 addLegalFPImmediate(APFloat(+0.0)); // xorpd
410 addLegalFPImmediate(APFloat(+0.0f)); // xorps
411 } else if (!UseSoftFloat && X86ScalarSSEf32) {
412 // Use SSE for f32, x87 for f64.
413 // Set up the FP register classes.
414 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
415 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
417 // Use ANDPS to simulate FABS.
418 setOperationAction(ISD::FABS , MVT::f32, Custom);
420 // Use XORP to simulate FNEG.
421 setOperationAction(ISD::FNEG , MVT::f32, Custom);
423 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
425 // Use ANDPS and ORPS to simulate FCOPYSIGN.
426 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
427 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
429 // We don't support sin/cos/fmod
430 setOperationAction(ISD::FSIN , MVT::f32, Expand);
431 setOperationAction(ISD::FCOS , MVT::f32, Expand);
433 // Special cases we handle for FP constants.
434 addLegalFPImmediate(APFloat(+0.0f)); // xorps
435 addLegalFPImmediate(APFloat(+0.0)); // FLD0
436 addLegalFPImmediate(APFloat(+1.0)); // FLD1
437 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
438 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
441 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
442 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
444 } else if (!UseSoftFloat) {
445 // f32 and f64 in x87.
446 // Set up the FP register classes.
447 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
448 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
450 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
451 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
452 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
453 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
456 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
457 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
459 addLegalFPImmediate(APFloat(+0.0)); // FLD0
460 addLegalFPImmediate(APFloat(+1.0)); // FLD1
461 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
462 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
463 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
464 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
465 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
466 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
469 // Long double always uses X87.
471 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
472 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
473 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
476 APFloat TmpFlt(+0.0);
477 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
479 addLegalFPImmediate(TmpFlt); // FLD0
481 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
482 APFloat TmpFlt2(+1.0);
483 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
485 addLegalFPImmediate(TmpFlt2); // FLD1
486 TmpFlt2.changeSign();
487 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
491 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
492 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
496 // Always use a library call for pow.
497 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
498 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
499 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
501 setOperationAction(ISD::FLOG, MVT::f80, Expand);
502 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
503 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
504 setOperationAction(ISD::FEXP, MVT::f80, Expand);
505 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
507 // First set operation action for all vector types to either promote
508 // (for widening) or expand (for scalarization). Then we will selectively
509 // turn on ones that can be effectively codegen'd.
510 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
511 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
512 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
513 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
514 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
515 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
516 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
517 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
518 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
519 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
520 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
521 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
522 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
523 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
524 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
525 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
526 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
527 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
528 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
529 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
530 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
531 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
532 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
533 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
534 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
535 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
536 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
537 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
538 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
539 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
540 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
541 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
542 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
543 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
544 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
545 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
546 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
547 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
548 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
549 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
550 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
551 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
552 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
553 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
554 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
555 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
556 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
557 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
558 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
559 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
562 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
563 // with -msoft-float, disable use of MMX as well.
564 if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
565 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
566 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
567 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
568 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
569 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
571 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
572 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
573 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
574 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
576 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
577 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
578 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
579 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
581 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
582 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
584 setOperationAction(ISD::AND, MVT::v8i8, Promote);
585 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
586 setOperationAction(ISD::AND, MVT::v4i16, Promote);
587 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
588 setOperationAction(ISD::AND, MVT::v2i32, Promote);
589 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
590 setOperationAction(ISD::AND, MVT::v1i64, Legal);
592 setOperationAction(ISD::OR, MVT::v8i8, Promote);
593 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
594 setOperationAction(ISD::OR, MVT::v4i16, Promote);
595 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
596 setOperationAction(ISD::OR, MVT::v2i32, Promote);
597 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
598 setOperationAction(ISD::OR, MVT::v1i64, Legal);
600 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
601 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
602 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
603 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
604 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
605 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
606 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
608 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
609 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
610 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
611 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
612 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
613 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
614 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
615 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
616 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
618 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
619 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
620 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
621 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
622 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
624 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
625 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
626 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
627 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
629 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
630 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
631 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
632 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
634 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
636 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
637 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Expand);
638 setOperationAction(ISD::SELECT, MVT::v8i8, Promote);
639 setOperationAction(ISD::SELECT, MVT::v4i16, Promote);
640 setOperationAction(ISD::SELECT, MVT::v2i32, Promote);
641 setOperationAction(ISD::SELECT, MVT::v1i64, Custom);
644 if (!UseSoftFloat && Subtarget->hasSSE1()) {
645 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
647 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
648 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
649 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
650 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
651 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
652 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
653 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
654 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
655 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
656 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
657 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
658 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
661 if (!UseSoftFloat && Subtarget->hasSSE2()) {
662 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
664 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
665 // registers cannot be used even for integer operations.
666 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
667 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
668 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
669 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
671 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
672 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
673 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
674 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
675 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
676 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
677 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
678 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
679 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
680 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
681 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
682 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
683 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
684 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
685 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
686 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
688 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
689 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
690 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
691 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
693 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
694 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
695 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
696 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
697 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
699 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
700 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
701 MVT VT = (MVT::SimpleValueType)i;
702 // Do not attempt to custom lower non-power-of-2 vectors
703 if (!isPowerOf2_32(VT.getVectorNumElements()))
705 // Do not attempt to custom lower non-128-bit vectors
706 if (!VT.is128BitVector())
708 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
709 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
710 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
713 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
714 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
715 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
716 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
717 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
718 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
720 if (Subtarget->is64Bit()) {
721 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
722 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
725 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
726 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
727 MVT VT = (MVT::SimpleValueType)i;
729 // Do not attempt to promote non-128-bit vectors
730 if (!VT.is128BitVector()) {
733 setOperationAction(ISD::AND, VT, Promote);
734 AddPromotedToType (ISD::AND, VT, MVT::v2i64);
735 setOperationAction(ISD::OR, VT, Promote);
736 AddPromotedToType (ISD::OR, VT, MVT::v2i64);
737 setOperationAction(ISD::XOR, VT, Promote);
738 AddPromotedToType (ISD::XOR, VT, MVT::v2i64);
739 setOperationAction(ISD::LOAD, VT, Promote);
740 AddPromotedToType (ISD::LOAD, VT, MVT::v2i64);
741 setOperationAction(ISD::SELECT, VT, Promote);
742 AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
745 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
747 // Custom lower v2i64 and v2f64 selects.
748 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
749 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
750 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
751 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
753 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
754 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
755 if (!DisableMMX && Subtarget->hasMMX()) {
756 setOperationAction(ISD::FP_TO_SINT, MVT::v2i32, Custom);
757 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
761 if (Subtarget->hasSSE41()) {
762 // FIXME: Do we need to handle scalar-to-vector here?
763 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
765 // i8 and i16 vectors are custom , because the source register and source
766 // source memory operand types are not the same width. f32 vectors are
767 // custom since the immediate controlling the insert encodes additional
769 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
770 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
771 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
772 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
774 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
775 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
776 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
777 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
779 if (Subtarget->is64Bit()) {
780 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
781 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
785 if (Subtarget->hasSSE42()) {
786 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
789 if (!UseSoftFloat && Subtarget->hasAVX()) {
790 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
791 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
792 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
793 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
795 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
796 setOperationAction(ISD::LOAD, MVT::v8i32, Legal);
797 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
798 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
799 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
800 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
801 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
802 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
803 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
804 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
805 //setOperationAction(ISD::BUILD_VECTOR, MVT::v8f32, Custom);
806 //setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Custom);
807 //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
808 //setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
809 //setOperationAction(ISD::VSETCC, MVT::v8f32, Custom);
811 // Operations to consider commented out -v16i16 v32i8
812 //setOperationAction(ISD::ADD, MVT::v16i16, Legal);
813 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
814 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
815 //setOperationAction(ISD::SUB, MVT::v32i8, Legal);
816 //setOperationAction(ISD::SUB, MVT::v16i16, Legal);
817 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
818 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
819 //setOperationAction(ISD::MUL, MVT::v16i16, Legal);
820 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
821 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
822 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
823 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
824 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
825 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
827 setOperationAction(ISD::VSETCC, MVT::v4f64, Custom);
828 // setOperationAction(ISD::VSETCC, MVT::v32i8, Custom);
829 // setOperationAction(ISD::VSETCC, MVT::v16i16, Custom);
830 setOperationAction(ISD::VSETCC, MVT::v8i32, Custom);
832 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v32i8, Custom);
833 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i16, Custom);
834 // setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i16, Custom);
835 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i32, Custom);
836 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8f32, Custom);
838 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
839 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i64, Custom);
840 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f64, Custom);
841 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i64, Custom);
842 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f64, Custom);
843 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
846 // Not sure we want to do this since there are no 256-bit integer
849 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
850 // This includes 256-bit vectors
851 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
852 MVT VT = (MVT::SimpleValueType)i;
854 // Do not attempt to custom lower non-power-of-2 vectors
855 if (!isPowerOf2_32(VT.getVectorNumElements()))
858 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
859 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
860 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
863 if (Subtarget->is64Bit()) {
864 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i64, Custom);
865 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
870 // Not sure we want to do this since there are no 256-bit integer
873 // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
874 // Including 256-bit vectors
875 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
876 MVT VT = (MVT::SimpleValueType)i;
878 if (!VT.is256BitVector()) {
881 setOperationAction(ISD::AND, VT, Promote);
882 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
883 setOperationAction(ISD::OR, VT, Promote);
884 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
885 setOperationAction(ISD::XOR, VT, Promote);
886 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
887 setOperationAction(ISD::LOAD, VT, Promote);
888 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
889 setOperationAction(ISD::SELECT, VT, Promote);
890 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
893 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
897 // We want to custom lower some of our intrinsics.
898 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
900 // Add/Sub/Mul with overflow operations are custom lowered.
901 setOperationAction(ISD::SADDO, MVT::i32, Custom);
902 setOperationAction(ISD::SADDO, MVT::i64, Custom);
903 setOperationAction(ISD::UADDO, MVT::i32, Custom);
904 setOperationAction(ISD::UADDO, MVT::i64, Custom);
905 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
906 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
907 setOperationAction(ISD::USUBO, MVT::i32, Custom);
908 setOperationAction(ISD::USUBO, MVT::i64, Custom);
909 setOperationAction(ISD::SMULO, MVT::i32, Custom);
910 setOperationAction(ISD::SMULO, MVT::i64, Custom);
912 if (!Subtarget->is64Bit()) {
913 // These libcalls are not available in 32-bit.
914 setLibcallName(RTLIB::SHL_I128, 0);
915 setLibcallName(RTLIB::SRL_I128, 0);
916 setLibcallName(RTLIB::SRA_I128, 0);
919 // We have target-specific dag combine patterns for the following nodes:
920 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
921 setTargetDAGCombine(ISD::BUILD_VECTOR);
922 setTargetDAGCombine(ISD::SELECT);
923 setTargetDAGCombine(ISD::SHL);
924 setTargetDAGCombine(ISD::SRA);
925 setTargetDAGCombine(ISD::SRL);
926 setTargetDAGCombine(ISD::STORE);
927 setTargetDAGCombine(ISD::MEMBARRIER);
928 if (Subtarget->is64Bit())
929 setTargetDAGCombine(ISD::MUL);
931 computeRegisterProperties();
933 // FIXME: These should be based on subtarget info. Plus, the values should
934 // be smaller when we are in optimizing for size mode.
935 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
936 maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
937 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
938 allowUnalignedMemoryAccesses = true; // x86 supports it!
939 setPrefLoopAlignment(16);
940 benefitFromCodePlacementOpt = true;
944 MVT X86TargetLowering::getSetCCResultType(MVT VT) const {
949 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
950 /// the desired ByVal argument alignment.
951 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
954 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
955 if (VTy->getBitWidth() == 128)
957 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
958 unsigned EltAlign = 0;
959 getMaxByValAlign(ATy->getElementType(), EltAlign);
960 if (EltAlign > MaxAlign)
962 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
963 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
964 unsigned EltAlign = 0;
965 getMaxByValAlign(STy->getElementType(i), EltAlign);
966 if (EltAlign > MaxAlign)
975 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
976 /// function arguments in the caller parameter area. For X86, aggregates
977 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
978 /// are at 4-byte boundaries.
979 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
980 if (Subtarget->is64Bit()) {
981 // Max of 8 and alignment of type.
982 unsigned TyAlign = TD->getABITypeAlignment(Ty);
989 if (Subtarget->hasSSE1())
990 getMaxByValAlign(Ty, Align);
994 /// getOptimalMemOpType - Returns the target specific optimal type for load
995 /// and store operations as a result of memset, memcpy, and memmove
996 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
999 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
1000 bool isSrcConst, bool isSrcStr,
1001 SelectionDAG &DAG) const {
1002 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1003 // linux. This is because the stack realignment code can't handle certain
1004 // cases like PR2962. This should be removed when PR2962 is fixed.
1005 const Function *F = DAG.getMachineFunction().getFunction();
1006 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
1007 if (!NoImplicitFloatOps && Subtarget->getStackAlignment() >= 16) {
1008 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
1010 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
1013 if (Subtarget->is64Bit() && Size >= 8)
1018 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1020 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1021 SelectionDAG &DAG) const {
1022 if (usesGlobalOffsetTable())
1023 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy());
1024 if (!Subtarget->isPICStyleRIPRel())
1025 // This doesn't have DebugLoc associated with it, but is not really the
1026 // same as a Register.
1027 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc::getUnknownLoc(),
1032 /// getFunctionAlignment - Return the Log2 alignment of this function.
1033 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1034 return F->hasFnAttr(Attribute::OptimizeForSize) ? 1 : 4;
1037 //===----------------------------------------------------------------------===//
1038 // Return Value Calling Convention Implementation
1039 //===----------------------------------------------------------------------===//
1041 #include "X86GenCallingConv.inc"
1043 /// LowerRET - Lower an ISD::RET node.
1044 SDValue X86TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
1045 DebugLoc dl = Op.getDebugLoc();
1046 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
1048 SmallVector<CCValAssign, 16> RVLocs;
1049 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
1050 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
1051 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
1052 CCInfo.AnalyzeReturn(Op.getNode(), RetCC_X86);
1054 // If this is the first return lowered for this function, add the regs to the
1055 // liveout set for the function.
1056 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1057 for (unsigned i = 0; i != RVLocs.size(); ++i)
1058 if (RVLocs[i].isRegLoc())
1059 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1061 SDValue Chain = Op.getOperand(0);
1063 // Handle tail call return.
1064 Chain = GetPossiblePreceedingTailCall(Chain, X86ISD::TAILCALL);
1065 if (Chain.getOpcode() == X86ISD::TAILCALL) {
1066 SDValue TailCall = Chain;
1067 SDValue TargetAddress = TailCall.getOperand(1);
1068 SDValue StackAdjustment = TailCall.getOperand(2);
1069 assert(((TargetAddress.getOpcode() == ISD::Register &&
1070 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::EAX ||
1071 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R11)) ||
1072 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
1073 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
1074 "Expecting an global address, external symbol, or register");
1075 assert(StackAdjustment.getOpcode() == ISD::Constant &&
1076 "Expecting a const value");
1078 SmallVector<SDValue,8> Operands;
1079 Operands.push_back(Chain.getOperand(0));
1080 Operands.push_back(TargetAddress);
1081 Operands.push_back(StackAdjustment);
1082 // Copy registers used by the call. Last operand is a flag so it is not
1084 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
1085 Operands.push_back(Chain.getOperand(i));
1087 return DAG.getNode(X86ISD::TC_RETURN, dl, MVT::Other, &Operands[0],
1094 SmallVector<SDValue, 6> RetOps;
1095 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1096 // Operand #1 = Bytes To Pop
1097 RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
1099 // Copy the result values into the output registers.
1100 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1101 CCValAssign &VA = RVLocs[i];
1102 assert(VA.isRegLoc() && "Can only return in registers!");
1103 SDValue ValToCopy = Op.getOperand(i*2+1);
1105 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1106 // the RET instruction and handled by the FP Stackifier.
1107 if (VA.getLocReg() == X86::ST0 ||
1108 VA.getLocReg() == X86::ST1) {
1109 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1110 // change the value to the FP stack register class.
1111 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1112 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1113 RetOps.push_back(ValToCopy);
1114 // Don't emit a copytoreg.
1118 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1119 // which is returned in RAX / RDX.
1120 if (Subtarget->is64Bit()) {
1121 MVT ValVT = ValToCopy.getValueType();
1122 if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1123 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1124 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1125 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1129 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1130 Flag = Chain.getValue(1);
1133 // The x86-64 ABI for returning structs by value requires that we copy
1134 // the sret argument into %rax for the return. We saved the argument into
1135 // a virtual register in the entry block, so now we copy the value out
1137 if (Subtarget->is64Bit() &&
1138 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1139 MachineFunction &MF = DAG.getMachineFunction();
1140 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1141 unsigned Reg = FuncInfo->getSRetReturnReg();
1143 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1144 FuncInfo->setSRetReturnReg(Reg);
1146 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1148 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1149 Flag = Chain.getValue(1);
1152 RetOps[0] = Chain; // Update chain.
1154 // Add the flag if we have it.
1156 RetOps.push_back(Flag);
1158 return DAG.getNode(X86ISD::RET_FLAG, dl,
1159 MVT::Other, &RetOps[0], RetOps.size());
1163 /// LowerCallResult - Lower the result values of an ISD::CALL into the
1164 /// appropriate copies out of appropriate physical registers. This assumes that
1165 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
1166 /// being lowered. The returns a SDNode with the same number of values as the
1168 SDNode *X86TargetLowering::
1169 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall,
1170 unsigned CallingConv, SelectionDAG &DAG) {
1172 DebugLoc dl = TheCall->getDebugLoc();
1173 // Assign locations to each value returned by this call.
1174 SmallVector<CCValAssign, 16> RVLocs;
1175 bool isVarArg = TheCall->isVarArg();
1176 bool Is64Bit = Subtarget->is64Bit();
1177 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
1178 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
1180 SmallVector<SDValue, 8> ResultVals;
1182 // Copy all of the result registers out of their specified physreg.
1183 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1184 CCValAssign &VA = RVLocs[i];
1185 MVT CopyVT = VA.getValVT();
1187 // If this is x86-64, and we disabled SSE, we can't return FP values
1188 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1189 ((Is64Bit || TheCall->isInreg()) && !Subtarget->hasSSE1())) {
1190 llvm_report_error("SSE register return with SSE disabled");
1193 // If this is a call to a function that returns an fp value on the floating
1194 // point stack, but where we prefer to use the value in xmm registers, copy
1195 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1196 if ((VA.getLocReg() == X86::ST0 ||
1197 VA.getLocReg() == X86::ST1) &&
1198 isScalarFPTypeInSSEReg(VA.getValVT())) {
1203 if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1204 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1205 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1206 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1207 MVT::v2i64, InFlag).getValue(1);
1208 Val = Chain.getValue(0);
1209 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1210 Val, DAG.getConstant(0, MVT::i64));
1212 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1213 MVT::i64, InFlag).getValue(1);
1214 Val = Chain.getValue(0);
1216 Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1218 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1219 CopyVT, InFlag).getValue(1);
1220 Val = Chain.getValue(0);
1222 InFlag = Chain.getValue(2);
1224 if (CopyVT != VA.getValVT()) {
1225 // Round the F80 the right size, which also moves to the appropriate xmm
1227 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1228 // This truncation won't change the value.
1229 DAG.getIntPtrConstant(1));
1232 ResultVals.push_back(Val);
1235 // Merge everything together with a MERGE_VALUES node.
1236 ResultVals.push_back(Chain);
1237 return DAG.getNode(ISD::MERGE_VALUES, dl, TheCall->getVTList(),
1238 &ResultVals[0], ResultVals.size()).getNode();
1242 //===----------------------------------------------------------------------===//
1243 // C & StdCall & Fast Calling Convention implementation
1244 //===----------------------------------------------------------------------===//
1245 // StdCall calling convention seems to be standard for many Windows' API
1246 // routines and around. It differs from C calling convention just a little:
1247 // callee should clean up the stack, not caller. Symbols should be also
1248 // decorated in some fancy way :) It doesn't support any vector arguments.
1249 // For info on fast calling convention see Fast Calling Convention (tail call)
1250 // implementation LowerX86_32FastCCCallTo.
1252 /// CallIsStructReturn - Determines whether a CALL node uses struct return
1254 static bool CallIsStructReturn(CallSDNode *TheCall) {
1255 unsigned NumOps = TheCall->getNumArgs();
1259 return TheCall->getArgFlags(0).isSRet();
1262 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
1263 /// return semantics.
1264 static bool ArgsAreStructReturn(SDValue Op) {
1265 unsigned NumArgs = Op.getNode()->getNumValues() - 1;
1269 return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
1272 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
1273 /// the callee to pop its own arguments. Callee pop is necessary to support tail
1275 bool X86TargetLowering::IsCalleePop(bool IsVarArg, unsigned CallingConv) {
1279 switch (CallingConv) {
1282 case CallingConv::X86_StdCall:
1283 return !Subtarget->is64Bit();
1284 case CallingConv::X86_FastCall:
1285 return !Subtarget->is64Bit();
1286 case CallingConv::Fast:
1287 return PerformTailCallOpt;
1291 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1292 /// given CallingConvention value.
1293 CCAssignFn *X86TargetLowering::CCAssignFnForNode(unsigned CC) const {
1294 if (Subtarget->is64Bit()) {
1295 if (Subtarget->isTargetWin64())
1296 return CC_X86_Win64_C;
1301 if (CC == CallingConv::X86_FastCall)
1302 return CC_X86_32_FastCall;
1303 else if (CC == CallingConv::Fast)
1304 return CC_X86_32_FastCC;
1309 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1310 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1312 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDValue Op) {
1313 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1314 if (CC == CallingConv::X86_FastCall)
1316 else if (CC == CallingConv::X86_StdCall)
1322 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1323 /// in a register before calling.
1324 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1325 return !IsTailCall && !Is64Bit &&
1326 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1327 Subtarget->isPICStyleGOT();
1330 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1331 /// address to be loaded in a register.
1333 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1334 return !Is64Bit && IsTailCall &&
1335 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1336 Subtarget->isPICStyleGOT();
1339 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1340 /// by "Src" to address "Dst" with size and alignment information specified by
1341 /// the specific parameter attribute. The copy will be passed as a byval
1342 /// function parameter.
1344 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1345 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1347 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1348 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1349 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1352 SDValue X86TargetLowering::LowerMemArgument(SDValue Op, SelectionDAG &DAG,
1353 const CCValAssign &VA,
1354 MachineFrameInfo *MFI,
1356 SDValue Root, unsigned i) {
1357 // Create the nodes corresponding to a load from this parameter slot.
1358 ISD::ArgFlagsTy Flags =
1359 cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1360 bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1361 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1363 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1364 // changed with more analysis.
1365 // In case of tail call optimization mark all arguments mutable. Since they
1366 // could be overwritten by lowering of arguments in case of a tail call.
1367 int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1368 VA.getLocMemOffset(), isImmutable);
1369 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1370 if (Flags.isByVal())
1372 return DAG.getLoad(VA.getValVT(), Op.getDebugLoc(), Root, FIN,
1373 PseudoSourceValue::getFixedStack(FI), 0);
1377 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) {
1378 MachineFunction &MF = DAG.getMachineFunction();
1379 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1380 DebugLoc dl = Op.getDebugLoc();
1382 const Function* Fn = MF.getFunction();
1383 if (Fn->hasExternalLinkage() &&
1384 Subtarget->isTargetCygMing() &&
1385 Fn->getName() == "main")
1386 FuncInfo->setForceFramePointer(true);
1388 // Decorate the function name.
1389 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1391 MachineFrameInfo *MFI = MF.getFrameInfo();
1392 SDValue Root = Op.getOperand(0);
1393 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
1394 unsigned CC = MF.getFunction()->getCallingConv();
1395 bool Is64Bit = Subtarget->is64Bit();
1396 bool IsWin64 = Subtarget->isTargetWin64();
1398 assert(!(isVarArg && CC == CallingConv::Fast) &&
1399 "Var args not supported with calling convention fastcc");
1401 // Assign locations to all of the incoming arguments.
1402 SmallVector<CCValAssign, 16> ArgLocs;
1403 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1404 CCInfo.AnalyzeFormalArguments(Op.getNode(), CCAssignFnForNode(CC));
1406 SmallVector<SDValue, 8> ArgValues;
1407 unsigned LastVal = ~0U;
1408 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1409 CCValAssign &VA = ArgLocs[i];
1410 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1412 assert(VA.getValNo() != LastVal &&
1413 "Don't support value assigned to multiple locs yet");
1414 LastVal = VA.getValNo();
1416 if (VA.isRegLoc()) {
1417 MVT RegVT = VA.getLocVT();
1418 TargetRegisterClass *RC = NULL;
1419 if (RegVT == MVT::i32)
1420 RC = X86::GR32RegisterClass;
1421 else if (Is64Bit && RegVT == MVT::i64)
1422 RC = X86::GR64RegisterClass;
1423 else if (RegVT == MVT::f32)
1424 RC = X86::FR32RegisterClass;
1425 else if (RegVT == MVT::f64)
1426 RC = X86::FR64RegisterClass;
1427 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1428 RC = X86::VR128RegisterClass;
1429 else if (RegVT.isVector()) {
1430 assert(RegVT.getSizeInBits() == 64);
1432 RC = X86::VR64RegisterClass; // MMX values are passed in MMXs.
1434 // Darwin calling convention passes MMX values in either GPRs or
1435 // XMMs in x86-64. Other targets pass them in memory.
1436 if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1437 RC = X86::VR128RegisterClass; // MMX values are passed in XMMs.
1440 RC = X86::GR64RegisterClass; // v1i64 values are passed in GPRs.
1445 assert(0 && "Unknown argument type!");
1448 unsigned Reg = DAG.getMachineFunction().addLiveIn(VA.getLocReg(), RC);
1449 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, RegVT);
1451 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1452 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1454 if (VA.getLocInfo() == CCValAssign::SExt)
1455 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1456 DAG.getValueType(VA.getValVT()));
1457 else if (VA.getLocInfo() == CCValAssign::ZExt)
1458 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1459 DAG.getValueType(VA.getValVT()));
1461 if (VA.getLocInfo() != CCValAssign::Full)
1462 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1464 // Handle MMX values passed in GPRs.
1465 if (Is64Bit && RegVT != VA.getLocVT()) {
1466 if (RegVT.getSizeInBits() == 64 && RC == X86::GR64RegisterClass)
1467 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1468 else if (RC == X86::VR128RegisterClass) {
1469 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1470 ArgValue, DAG.getConstant(0, MVT::i64));
1471 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1475 ArgValues.push_back(ArgValue);
1477 assert(VA.isMemLoc());
1478 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1482 // The x86-64 ABI for returning structs by value requires that we copy
1483 // the sret argument into %rax for the return. Save the argument into
1484 // a virtual register so that we can access it from the return points.
1485 if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1486 MachineFunction &MF = DAG.getMachineFunction();
1487 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1488 unsigned Reg = FuncInfo->getSRetReturnReg();
1490 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1491 FuncInfo->setSRetReturnReg(Reg);
1493 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, ArgValues[0]);
1494 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Root);
1497 unsigned StackSize = CCInfo.getNextStackOffset();
1498 // align stack specially for tail calls
1499 if (PerformTailCallOpt && CC == CallingConv::Fast)
1500 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1502 // If the function takes variable number of arguments, make a frame index for
1503 // the start of the first vararg value... for expansion of llvm.va_start.
1505 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1506 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1509 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1511 // FIXME: We should really autogenerate these arrays
1512 static const unsigned GPR64ArgRegsWin64[] = {
1513 X86::RCX, X86::RDX, X86::R8, X86::R9
1515 static const unsigned XMMArgRegsWin64[] = {
1516 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1518 static const unsigned GPR64ArgRegs64Bit[] = {
1519 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1521 static const unsigned XMMArgRegs64Bit[] = {
1522 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1523 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1525 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1528 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1529 GPR64ArgRegs = GPR64ArgRegsWin64;
1530 XMMArgRegs = XMMArgRegsWin64;
1532 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1533 GPR64ArgRegs = GPR64ArgRegs64Bit;
1534 XMMArgRegs = XMMArgRegs64Bit;
1536 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1538 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1541 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1542 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1543 "SSE register cannot be used when SSE is disabled!");
1544 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1545 "SSE register cannot be used when SSE is disabled!");
1546 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1547 // Kernel mode asks for SSE to be disabled, so don't push them
1549 TotalNumXMMRegs = 0;
1551 // For X86-64, if there are vararg parameters that are passed via
1552 // registers, then we must store them to their spots on the stack so they
1553 // may be loaded by deferencing the result of va_next.
1554 VarArgsGPOffset = NumIntRegs * 8;
1555 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1556 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1557 TotalNumXMMRegs * 16, 16);
1559 // Store the integer parameter registers.
1560 SmallVector<SDValue, 8> MemOps;
1561 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1562 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1563 DAG.getIntPtrConstant(VarArgsGPOffset));
1564 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1565 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1566 X86::GR64RegisterClass);
1567 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::i64);
1569 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1570 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1571 MemOps.push_back(Store);
1572 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1573 DAG.getIntPtrConstant(8));
1576 // Now store the XMM (fp + vector) parameter registers.
1577 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1578 DAG.getIntPtrConstant(VarArgsFPOffset));
1579 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1580 unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1581 X86::VR128RegisterClass);
1582 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::v4f32);
1584 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1585 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1586 MemOps.push_back(Store);
1587 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1588 DAG.getIntPtrConstant(16));
1590 if (!MemOps.empty())
1591 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1592 &MemOps[0], MemOps.size());
1596 ArgValues.push_back(Root);
1598 // Some CCs need callee pop.
1599 if (IsCalleePop(isVarArg, CC)) {
1600 BytesToPopOnReturn = StackSize; // Callee pops everything.
1601 BytesCallerReserves = 0;
1603 BytesToPopOnReturn = 0; // Callee pops nothing.
1604 // If this is an sret function, the return should pop the hidden pointer.
1605 if (!Is64Bit && CC != CallingConv::Fast && ArgsAreStructReturn(Op))
1606 BytesToPopOnReturn = 4;
1607 BytesCallerReserves = StackSize;
1611 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1612 if (CC == CallingConv::X86_FastCall)
1613 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1616 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1618 // Return the new list of results.
1619 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(),
1620 &ArgValues[0], ArgValues.size()).getValue(Op.getResNo());
1624 X86TargetLowering::LowerMemOpCallTo(CallSDNode *TheCall, SelectionDAG &DAG,
1625 const SDValue &StackPtr,
1626 const CCValAssign &VA,
1628 SDValue Arg, ISD::ArgFlagsTy Flags) {
1629 DebugLoc dl = TheCall->getDebugLoc();
1630 unsigned LocMemOffset = VA.getLocMemOffset();
1631 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1632 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1633 if (Flags.isByVal()) {
1634 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1636 return DAG.getStore(Chain, dl, Arg, PtrOff,
1637 PseudoSourceValue::getStack(), LocMemOffset);
1640 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1641 /// optimization is performed and it is required.
1643 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1644 SDValue &OutRetAddr,
1650 if (!IsTailCall || FPDiff==0) return Chain;
1652 // Adjust the Return address stack slot.
1653 MVT VT = getPointerTy();
1654 OutRetAddr = getReturnAddressFrameIndex(DAG);
1656 // Load the "old" Return address.
1657 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0);
1658 return SDValue(OutRetAddr.getNode(), 1);
1661 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1662 /// optimization is performed and it is required (FPDiff!=0).
1664 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1665 SDValue Chain, SDValue RetAddrFrIdx,
1666 bool Is64Bit, int FPDiff, DebugLoc dl) {
1667 // Store the return address to the appropriate stack slot.
1668 if (!FPDiff) return Chain;
1669 // Calculate the new stack slot for the return address.
1670 int SlotSize = Is64Bit ? 8 : 4;
1671 int NewReturnAddrFI =
1672 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1673 MVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1674 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1675 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1676 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1680 SDValue X86TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1681 MachineFunction &MF = DAG.getMachineFunction();
1682 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
1683 SDValue Chain = TheCall->getChain();
1684 unsigned CC = TheCall->getCallingConv();
1685 bool isVarArg = TheCall->isVarArg();
1686 bool IsTailCall = TheCall->isTailCall() &&
1687 CC == CallingConv::Fast && PerformTailCallOpt;
1688 SDValue Callee = TheCall->getCallee();
1689 bool Is64Bit = Subtarget->is64Bit();
1690 bool IsStructRet = CallIsStructReturn(TheCall);
1691 DebugLoc dl = TheCall->getDebugLoc();
1693 assert(!(isVarArg && CC == CallingConv::Fast) &&
1694 "Var args not supported with calling convention fastcc");
1696 // Analyze operands of the call, assigning locations to each operand.
1697 SmallVector<CCValAssign, 16> ArgLocs;
1698 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1699 CCInfo.AnalyzeCallOperands(TheCall, CCAssignFnForNode(CC));
1701 // Get a count of how many bytes are to be pushed on the stack.
1702 unsigned NumBytes = CCInfo.getNextStackOffset();
1703 if (PerformTailCallOpt && CC == CallingConv::Fast)
1704 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1708 // Lower arguments at fp - stackoffset + fpdiff.
1709 unsigned NumBytesCallerPushed =
1710 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1711 FPDiff = NumBytesCallerPushed - NumBytes;
1713 // Set the delta of movement of the returnaddr stackslot.
1714 // But only set if delta is greater than previous delta.
1715 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1716 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1719 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1721 SDValue RetAddrFrIdx;
1722 // Load return adress for tail calls.
1723 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1726 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1727 SmallVector<SDValue, 8> MemOpChains;
1730 // Walk the register/memloc assignments, inserting copies/loads. In the case
1731 // of tail call optimization arguments are handle later.
1732 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1733 CCValAssign &VA = ArgLocs[i];
1734 SDValue Arg = TheCall->getArg(i);
1735 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1736 bool isByVal = Flags.isByVal();
1738 // Promote the value if needed.
1739 switch (VA.getLocInfo()) {
1740 default: assert(0 && "Unknown loc info!");
1741 case CCValAssign::Full: break;
1742 case CCValAssign::SExt:
1743 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1745 case CCValAssign::ZExt:
1746 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1748 case CCValAssign::AExt:
1749 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1753 if (VA.isRegLoc()) {
1755 MVT RegVT = VA.getLocVT();
1756 if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1757 switch (VA.getLocReg()) {
1760 case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1762 // Special case: passing MMX values in GPR registers.
1763 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1766 case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1767 case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1768 // Special case: passing MMX values in XMM registers.
1769 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1770 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1771 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1776 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1778 if (!IsTailCall || (IsTailCall && isByVal)) {
1779 assert(VA.isMemLoc());
1780 if (StackPtr.getNode() == 0)
1781 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1783 MemOpChains.push_back(LowerMemOpCallTo(TheCall, DAG, StackPtr, VA,
1784 Chain, Arg, Flags));
1789 if (!MemOpChains.empty())
1790 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1791 &MemOpChains[0], MemOpChains.size());
1793 // Build a sequence of copy-to-reg nodes chained together with token chain
1794 // and flag operands which copy the outgoing args into registers.
1796 // Tail call byval lowering might overwrite argument registers so in case of
1797 // tail call optimization the copies to registers are lowered later.
1799 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1800 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1801 RegsToPass[i].second, InFlag);
1802 InFlag = Chain.getValue(1);
1805 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1807 if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1808 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1809 DAG.getNode(X86ISD::GlobalBaseReg,
1810 DebugLoc::getUnknownLoc(),
1813 InFlag = Chain.getValue(1);
1815 // If we are tail calling and generating PIC/GOT style code load the address
1816 // of the callee into ecx. The value in ecx is used as target of the tail
1817 // jump. This is done to circumvent the ebx/callee-saved problem for tail
1818 // calls on PIC/GOT architectures. Normally we would just put the address of
1819 // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1820 // restored (since ebx is callee saved) before jumping to the target@PLT.
1821 if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1822 // Note: The actual moving to ecx is done further down.
1823 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1824 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1825 !G->getGlobal()->hasProtectedVisibility())
1826 Callee = LowerGlobalAddress(Callee, DAG);
1827 else if (isa<ExternalSymbolSDNode>(Callee))
1828 Callee = LowerExternalSymbol(Callee,DAG);
1831 if (Is64Bit && isVarArg) {
1832 // From AMD64 ABI document:
1833 // For calls that may call functions that use varargs or stdargs
1834 // (prototype-less calls or calls to functions containing ellipsis (...) in
1835 // the declaration) %al is used as hidden argument to specify the number
1836 // of SSE registers used. The contents of %al do not need to match exactly
1837 // the number of registers, but must be an ubound on the number of SSE
1838 // registers used and is in the range 0 - 8 inclusive.
1840 // FIXME: Verify this on Win64
1841 // Count the number of XMM registers allocated.
1842 static const unsigned XMMArgRegs[] = {
1843 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1844 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1846 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1847 assert((Subtarget->hasSSE1() || !NumXMMRegs)
1848 && "SSE registers cannot be used when SSE is disabled");
1850 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1851 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1852 InFlag = Chain.getValue(1);
1856 // For tail calls lower the arguments to the 'real' stack slot.
1858 SmallVector<SDValue, 8> MemOpChains2;
1861 // Do not flag preceeding copytoreg stuff together with the following stuff.
1863 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1864 CCValAssign &VA = ArgLocs[i];
1865 if (!VA.isRegLoc()) {
1866 assert(VA.isMemLoc());
1867 SDValue Arg = TheCall->getArg(i);
1868 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1869 // Create frame index.
1870 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1871 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1872 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1873 FIN = DAG.getFrameIndex(FI, getPointerTy());
1875 if (Flags.isByVal()) {
1876 // Copy relative to framepointer.
1877 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1878 if (StackPtr.getNode() == 0)
1879 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
1881 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
1883 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1886 // Store relative to framepointer.
1887 MemOpChains2.push_back(
1888 DAG.getStore(Chain, dl, Arg, FIN,
1889 PseudoSourceValue::getFixedStack(FI), 0));
1894 if (!MemOpChains2.empty())
1895 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1896 &MemOpChains2[0], MemOpChains2.size());
1898 // Copy arguments to their registers.
1899 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1900 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1901 RegsToPass[i].second, InFlag);
1902 InFlag = Chain.getValue(1);
1906 // Store the return address to the appropriate stack slot.
1907 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1911 // If the callee is a GlobalAddress node (quite common, every direct call is)
1912 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1913 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1914 // We should use extra load for direct calls to dllimported functions in
1916 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1917 getTargetMachine(), true))
1918 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy(),
1920 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1921 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1922 } else if (IsTailCall) {
1923 unsigned Opc = Is64Bit ? X86::R11 : X86::EAX;
1925 Chain = DAG.getCopyToReg(Chain, dl,
1926 DAG.getRegister(Opc, getPointerTy()),
1928 Callee = DAG.getRegister(Opc, getPointerTy());
1929 // Add register as live out.
1930 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1933 // Returns a chain & a flag for retval copy to use.
1934 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1935 SmallVector<SDValue, 8> Ops;
1938 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1939 DAG.getIntPtrConstant(0, true), InFlag);
1940 InFlag = Chain.getValue(1);
1942 // Returns a chain & a flag for retval copy to use.
1943 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1947 Ops.push_back(Chain);
1948 Ops.push_back(Callee);
1951 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1953 // Add argument registers to the end of the list so that they are known live
1955 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1956 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1957 RegsToPass[i].second.getValueType()));
1959 // Add an implicit use GOT pointer in EBX.
1960 if (!IsTailCall && !Is64Bit &&
1961 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1962 Subtarget->isPICStyleGOT())
1963 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1965 // Add an implicit use of AL for x86 vararg functions.
1966 if (Is64Bit && isVarArg)
1967 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1969 if (InFlag.getNode())
1970 Ops.push_back(InFlag);
1973 assert(InFlag.getNode() &&
1974 "Flag must be set. Depend on flag being set in LowerRET");
1975 Chain = DAG.getNode(X86ISD::TAILCALL, dl,
1976 TheCall->getVTList(), &Ops[0], Ops.size());
1978 return SDValue(Chain.getNode(), Op.getResNo());
1981 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
1982 InFlag = Chain.getValue(1);
1984 // Create the CALLSEQ_END node.
1985 unsigned NumBytesForCalleeToPush;
1986 if (IsCalleePop(isVarArg, CC))
1987 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1988 else if (!Is64Bit && CC != CallingConv::Fast && IsStructRet)
1989 // If this is is a call to a struct-return function, the callee
1990 // pops the hidden struct pointer, so we have to push it back.
1991 // This is common for Darwin/X86, Linux & Mingw32 targets.
1992 NumBytesForCalleeToPush = 4;
1994 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1996 // Returns a flag for retval copy to use.
1997 Chain = DAG.getCALLSEQ_END(Chain,
1998 DAG.getIntPtrConstant(NumBytes, true),
1999 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2002 InFlag = Chain.getValue(1);
2004 // Handle result values, copying them out of physregs into vregs that we
2006 return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
2011 //===----------------------------------------------------------------------===//
2012 // Fast Calling Convention (tail call) implementation
2013 //===----------------------------------------------------------------------===//
2015 // Like std call, callee cleans arguments, convention except that ECX is
2016 // reserved for storing the tail called function address. Only 2 registers are
2017 // free for argument passing (inreg). Tail call optimization is performed
2019 // * tailcallopt is enabled
2020 // * caller/callee are fastcc
2021 // On X86_64 architecture with GOT-style position independent code only local
2022 // (within module) calls are supported at the moment.
2023 // To keep the stack aligned according to platform abi the function
2024 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2025 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2026 // If a tail called function callee has more arguments than the caller the
2027 // caller needs to make sure that there is room to move the RETADDR to. This is
2028 // achieved by reserving an area the size of the argument delta right after the
2029 // original REtADDR, but before the saved framepointer or the spilled registers
2030 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2042 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2043 /// for a 16 byte align requirement.
2044 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2045 SelectionDAG& DAG) {
2046 MachineFunction &MF = DAG.getMachineFunction();
2047 const TargetMachine &TM = MF.getTarget();
2048 const TargetFrameInfo &TFI = *TM.getFrameInfo();
2049 unsigned StackAlignment = TFI.getStackAlignment();
2050 uint64_t AlignMask = StackAlignment - 1;
2051 int64_t Offset = StackSize;
2052 uint64_t SlotSize = TD->getPointerSize();
2053 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2054 // Number smaller than 12 so just add the difference.
2055 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2057 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2058 Offset = ((~AlignMask) & Offset) + StackAlignment +
2059 (StackAlignment-SlotSize);
2064 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
2065 /// following the call is a return. A function is eligible if caller/callee
2066 /// calling conventions match, currently only fastcc supports tail calls, and
2067 /// the function CALL is immediatly followed by a RET.
2068 bool X86TargetLowering::IsEligibleForTailCallOptimization(CallSDNode *TheCall,
2070 SelectionDAG& DAG) const {
2071 if (!PerformTailCallOpt)
2074 if (CheckTailCallReturnConstraints(TheCall, Ret)) {
2075 MachineFunction &MF = DAG.getMachineFunction();
2076 unsigned CallerCC = MF.getFunction()->getCallingConv();
2077 unsigned CalleeCC= TheCall->getCallingConv();
2078 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
2079 SDValue Callee = TheCall->getCallee();
2080 // On x86/32Bit PIC/GOT tail calls are supported.
2081 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
2082 !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
2085 // Can only do local tail calls (in same module, hidden or protected) on
2086 // x86_64 PIC/GOT at the moment.
2087 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2088 return G->getGlobal()->hasHiddenVisibility()
2089 || G->getGlobal()->hasProtectedVisibility();
2097 X86TargetLowering::createFastISel(MachineFunction &mf,
2098 MachineModuleInfo *mmo,
2100 DenseMap<const Value *, unsigned> &vm,
2101 DenseMap<const BasicBlock *,
2102 MachineBasicBlock *> &bm,
2103 DenseMap<const AllocaInst *, int> &am
2105 , SmallSet<Instruction*, 8> &cil
2108 return X86::createFastISel(mf, mmo, dw, vm, bm, am
2116 //===----------------------------------------------------------------------===//
2117 // Other Lowering Hooks
2118 //===----------------------------------------------------------------------===//
2121 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2122 MachineFunction &MF = DAG.getMachineFunction();
2123 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2124 int ReturnAddrIndex = FuncInfo->getRAIndex();
2126 if (ReturnAddrIndex == 0) {
2127 // Set up a frame object for the return address.
2128 uint64_t SlotSize = TD->getPointerSize();
2129 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize);
2130 FuncInfo->setRAIndex(ReturnAddrIndex);
2133 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2137 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2138 /// specific condition code, returning the condition code and the LHS/RHS of the
2139 /// comparison to make.
2140 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2141 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2143 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2144 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2145 // X > -1 -> X == 0, jump !sign.
2146 RHS = DAG.getConstant(0, RHS.getValueType());
2147 return X86::COND_NS;
2148 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2149 // X < 0 -> X == 0, jump on sign.
2151 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2153 RHS = DAG.getConstant(0, RHS.getValueType());
2154 return X86::COND_LE;
2158 switch (SetCCOpcode) {
2159 default: assert(0 && "Invalid integer condition!");
2160 case ISD::SETEQ: return X86::COND_E;
2161 case ISD::SETGT: return X86::COND_G;
2162 case ISD::SETGE: return X86::COND_GE;
2163 case ISD::SETLT: return X86::COND_L;
2164 case ISD::SETLE: return X86::COND_LE;
2165 case ISD::SETNE: return X86::COND_NE;
2166 case ISD::SETULT: return X86::COND_B;
2167 case ISD::SETUGT: return X86::COND_A;
2168 case ISD::SETULE: return X86::COND_BE;
2169 case ISD::SETUGE: return X86::COND_AE;
2173 // First determine if it is required or is profitable to flip the operands.
2175 // If LHS is a foldable load, but RHS is not, flip the condition.
2176 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2177 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2178 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2179 std::swap(LHS, RHS);
2182 switch (SetCCOpcode) {
2188 std::swap(LHS, RHS);
2192 // On a floating point condition, the flags are set as follows:
2194 // 0 | 0 | 0 | X > Y
2195 // 0 | 0 | 1 | X < Y
2196 // 1 | 0 | 0 | X == Y
2197 // 1 | 1 | 1 | unordered
2198 switch (SetCCOpcode) {
2199 default: assert(0 && "Condcode should be pre-legalized away");
2201 case ISD::SETEQ: return X86::COND_E;
2202 case ISD::SETOLT: // flipped
2204 case ISD::SETGT: return X86::COND_A;
2205 case ISD::SETOLE: // flipped
2207 case ISD::SETGE: return X86::COND_AE;
2208 case ISD::SETUGT: // flipped
2210 case ISD::SETLT: return X86::COND_B;
2211 case ISD::SETUGE: // flipped
2213 case ISD::SETLE: return X86::COND_BE;
2215 case ISD::SETNE: return X86::COND_NE;
2216 case ISD::SETUO: return X86::COND_P;
2217 case ISD::SETO: return X86::COND_NP;
2221 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2222 /// code. Current x86 isa includes the following FP cmov instructions:
2223 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2224 static bool hasFPCMov(unsigned X86CC) {
2240 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2241 /// the specified range (L, H].
2242 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2243 return (Val < 0) || (Val >= Low && Val < Hi);
2246 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2247 /// specified value.
2248 static bool isUndefOrEqual(int Val, int CmpVal) {
2249 if (Val < 0 || Val == CmpVal)
2254 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2255 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2256 /// the second operand.
2257 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2258 if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2259 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2260 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2261 return (Mask[0] < 2 && Mask[1] < 2);
2265 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2266 SmallVector<int, 8> M;
2268 return ::isPSHUFDMask(M, N->getValueType(0));
2271 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2272 /// is suitable for input to PSHUFHW.
2273 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2274 if (VT != MVT::v8i16)
2277 // Lower quadword copied in order or undef.
2278 for (int i = 0; i != 4; ++i)
2279 if (Mask[i] >= 0 && Mask[i] != i)
2282 // Upper quadword shuffled.
2283 for (int i = 4; i != 8; ++i)
2284 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2290 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2291 SmallVector<int, 8> M;
2293 return ::isPSHUFHWMask(M, N->getValueType(0));
2296 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2297 /// is suitable for input to PSHUFLW.
2298 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2299 if (VT != MVT::v8i16)
2302 // Upper quadword copied in order.
2303 for (int i = 4; i != 8; ++i)
2304 if (Mask[i] >= 0 && Mask[i] != i)
2307 // Lower quadword shuffled.
2308 for (int i = 0; i != 4; ++i)
2315 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2316 SmallVector<int, 8> M;
2318 return ::isPSHUFLWMask(M, N->getValueType(0));
2321 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2322 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2323 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2324 int NumElems = VT.getVectorNumElements();
2325 if (NumElems != 2 && NumElems != 4)
2328 int Half = NumElems / 2;
2329 for (int i = 0; i < Half; ++i)
2330 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2332 for (int i = Half; i < NumElems; ++i)
2333 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2339 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2340 SmallVector<int, 8> M;
2342 return ::isSHUFPMask(M, N->getValueType(0));
2345 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2346 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2347 /// half elements to come from vector 1 (which would equal the dest.) and
2348 /// the upper half to come from vector 2.
2349 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2350 int NumElems = VT.getVectorNumElements();
2352 if (NumElems != 2 && NumElems != 4)
2355 int Half = NumElems / 2;
2356 for (int i = 0; i < Half; ++i)
2357 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2359 for (int i = Half; i < NumElems; ++i)
2360 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2365 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2366 SmallVector<int, 8> M;
2368 return isCommutedSHUFPMask(M, N->getValueType(0));
2371 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2372 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2373 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2374 if (N->getValueType(0).getVectorNumElements() != 4)
2377 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2378 return isUndefOrEqual(N->getMaskElt(0), 6) &&
2379 isUndefOrEqual(N->getMaskElt(1), 7) &&
2380 isUndefOrEqual(N->getMaskElt(2), 2) &&
2381 isUndefOrEqual(N->getMaskElt(3), 3);
2384 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2385 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2386 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2387 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2389 if (NumElems != 2 && NumElems != 4)
2392 for (unsigned i = 0; i < NumElems/2; ++i)
2393 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2396 for (unsigned i = NumElems/2; i < NumElems; ++i)
2397 if (!isUndefOrEqual(N->getMaskElt(i), i))
2403 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2404 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2406 bool X86::isMOVHPMask(ShuffleVectorSDNode *N) {
2407 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2409 if (NumElems != 2 && NumElems != 4)
2412 for (unsigned i = 0; i < NumElems/2; ++i)
2413 if (!isUndefOrEqual(N->getMaskElt(i), i))
2416 for (unsigned i = 0; i < NumElems/2; ++i)
2417 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2423 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2424 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2426 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2427 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2432 return isUndefOrEqual(N->getMaskElt(0), 2) &&
2433 isUndefOrEqual(N->getMaskElt(1), 3) &&
2434 isUndefOrEqual(N->getMaskElt(2), 2) &&
2435 isUndefOrEqual(N->getMaskElt(3), 3);
2438 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2439 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2440 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, MVT VT,
2441 bool V2IsSplat = false) {
2442 int NumElts = VT.getVectorNumElements();
2443 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2446 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2448 int BitI1 = Mask[i+1];
2449 if (!isUndefOrEqual(BitI, j))
2452 if (!isUndefOrEqual(BitI1, NumElts))
2455 if (!isUndefOrEqual(BitI1, j + NumElts))
2462 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2463 SmallVector<int, 8> M;
2465 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2468 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2469 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2470 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, MVT VT,
2471 bool V2IsSplat = false) {
2472 int NumElts = VT.getVectorNumElements();
2473 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2476 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2478 int BitI1 = Mask[i+1];
2479 if (!isUndefOrEqual(BitI, j + NumElts/2))
2482 if (isUndefOrEqual(BitI1, NumElts))
2485 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2492 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2493 SmallVector<int, 8> M;
2495 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2498 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2499 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2501 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, MVT VT) {
2502 int NumElems = VT.getVectorNumElements();
2503 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2506 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2508 int BitI1 = Mask[i+1];
2509 if (!isUndefOrEqual(BitI, j))
2511 if (!isUndefOrEqual(BitI1, j))
2517 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2518 SmallVector<int, 8> M;
2520 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2523 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2524 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2526 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, MVT VT) {
2527 int NumElems = VT.getVectorNumElements();
2528 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2531 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2533 int BitI1 = Mask[i+1];
2534 if (!isUndefOrEqual(BitI, j))
2536 if (!isUndefOrEqual(BitI1, j))
2542 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2543 SmallVector<int, 8> M;
2545 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2548 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2549 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2550 /// MOVSD, and MOVD, i.e. setting the lowest element.
2551 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2552 if (VT.getVectorElementType().getSizeInBits() < 32)
2555 int NumElts = VT.getVectorNumElements();
2557 if (!isUndefOrEqual(Mask[0], NumElts))
2560 for (int i = 1; i < NumElts; ++i)
2561 if (!isUndefOrEqual(Mask[i], i))
2567 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2568 SmallVector<int, 8> M;
2570 return ::isMOVLMask(M, N->getValueType(0));
2573 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2574 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2575 /// element of vector 2 and the other elements to come from vector 1 in order.
2576 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, MVT VT,
2577 bool V2IsSplat = false, bool V2IsUndef = false) {
2578 int NumOps = VT.getVectorNumElements();
2579 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2582 if (!isUndefOrEqual(Mask[0], 0))
2585 for (int i = 1; i < NumOps; ++i)
2586 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
2587 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
2588 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
2594 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
2595 bool V2IsUndef = false) {
2596 SmallVector<int, 8> M;
2598 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
2601 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2602 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2603 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
2604 if (N->getValueType(0).getVectorNumElements() != 4)
2607 // Expect 1, 1, 3, 3
2608 for (unsigned i = 0; i < 2; ++i) {
2609 int Elt = N->getMaskElt(i);
2610 if (Elt >= 0 && Elt != 1)
2615 for (unsigned i = 2; i < 4; ++i) {
2616 int Elt = N->getMaskElt(i);
2617 if (Elt >= 0 && Elt != 3)
2622 // Don't use movshdup if it can be done with a shufps.
2623 // FIXME: verify that matching u, u, 3, 3 is what we want.
2627 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2628 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2629 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
2630 if (N->getValueType(0).getVectorNumElements() != 4)
2633 // Expect 0, 0, 2, 2
2634 for (unsigned i = 0; i < 2; ++i)
2635 if (N->getMaskElt(i) > 0)
2639 for (unsigned i = 2; i < 4; ++i) {
2640 int Elt = N->getMaskElt(i);
2641 if (Elt >= 0 && Elt != 2)
2646 // Don't use movsldup if it can be done with a shufps.
2650 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2651 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2652 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
2653 int e = N->getValueType(0).getVectorNumElements() / 2;
2655 for (int i = 0; i < e; ++i)
2656 if (!isUndefOrEqual(N->getMaskElt(i), i))
2658 for (int i = 0; i < e; ++i)
2659 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
2664 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2665 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2667 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2668 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2669 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
2671 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2673 for (int i = 0; i < NumOperands; ++i) {
2674 int Val = SVOp->getMaskElt(NumOperands-i-1);
2675 if (Val < 0) Val = 0;
2676 if (Val >= NumOperands) Val -= NumOperands;
2678 if (i != NumOperands - 1)
2684 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2685 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2687 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2688 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2690 // 8 nodes, but we only care about the last 4.
2691 for (unsigned i = 7; i >= 4; --i) {
2692 int Val = SVOp->getMaskElt(i);
2701 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2702 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2704 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2705 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2707 // 8 nodes, but we only care about the first 4.
2708 for (int i = 3; i >= 0; --i) {
2709 int Val = SVOp->getMaskElt(i);
2718 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
2719 /// their permute mask.
2720 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
2721 SelectionDAG &DAG) {
2722 MVT VT = SVOp->getValueType(0);
2723 unsigned NumElems = VT.getVectorNumElements();
2724 SmallVector<int, 8> MaskVec;
2726 for (unsigned i = 0; i != NumElems; ++i) {
2727 int idx = SVOp->getMaskElt(i);
2729 MaskVec.push_back(idx);
2730 else if (idx < (int)NumElems)
2731 MaskVec.push_back(idx + NumElems);
2733 MaskVec.push_back(idx - NumElems);
2735 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
2736 SVOp->getOperand(0), &MaskVec[0]);
2739 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2740 /// the two vector operands have swapped position.
2741 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, MVT VT) {
2742 unsigned NumElems = VT.getVectorNumElements();
2743 for (unsigned i = 0; i != NumElems; ++i) {
2747 else if (idx < (int)NumElems)
2748 Mask[i] = idx + NumElems;
2750 Mask[i] = idx - NumElems;
2754 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2755 /// match movhlps. The lower half elements should come from upper half of
2756 /// V1 (and in order), and the upper half elements should come from the upper
2757 /// half of V2 (and in order).
2758 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
2759 if (Op->getValueType(0).getVectorNumElements() != 4)
2761 for (unsigned i = 0, e = 2; i != e; ++i)
2762 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
2764 for (unsigned i = 2; i != 4; ++i)
2765 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
2770 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2771 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2773 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2774 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
2776 N = N->getOperand(0).getNode();
2777 if (!ISD::isNON_EXTLoad(N))
2780 *LD = cast<LoadSDNode>(N);
2784 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2785 /// match movlp{s|d}. The lower half elements should come from lower half of
2786 /// V1 (and in order), and the upper half elements should come from the upper
2787 /// half of V2 (and in order). And since V1 will become the source of the
2788 /// MOVLP, it must be either a vector load or a scalar load to vector.
2789 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
2790 ShuffleVectorSDNode *Op) {
2791 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2793 // Is V2 is a vector load, don't do this transformation. We will try to use
2794 // load folding shufps op.
2795 if (ISD::isNON_EXTLoad(V2))
2798 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
2800 if (NumElems != 2 && NumElems != 4)
2802 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2803 if (!isUndefOrEqual(Op->getMaskElt(i), i))
2805 for (unsigned i = NumElems/2; i != NumElems; ++i)
2806 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
2811 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2813 static bool isSplatVector(SDNode *N) {
2814 if (N->getOpcode() != ISD::BUILD_VECTOR)
2817 SDValue SplatValue = N->getOperand(0);
2818 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2819 if (N->getOperand(i) != SplatValue)
2824 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2826 static inline bool isZeroNode(SDValue Elt) {
2827 return ((isa<ConstantSDNode>(Elt) &&
2828 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2829 (isa<ConstantFPSDNode>(Elt) &&
2830 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2833 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2834 /// to an zero vector.
2835 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
2836 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
2837 SDValue V1 = N->getOperand(0);
2838 SDValue V2 = N->getOperand(1);
2839 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2840 for (unsigned i = 0; i != NumElems; ++i) {
2841 int Idx = N->getMaskElt(i);
2842 if (Idx >= (int)NumElems) {
2843 unsigned Opc = V2.getOpcode();
2844 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
2846 if (Opc != ISD::BUILD_VECTOR || !isZeroNode(V2.getOperand(Idx-NumElems)))
2848 } else if (Idx >= 0) {
2849 unsigned Opc = V1.getOpcode();
2850 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
2852 if (Opc != ISD::BUILD_VECTOR || !isZeroNode(V1.getOperand(Idx)))
2859 /// getZeroVector - Returns a vector of specified type with all zero elements.
2861 static SDValue getZeroVector(MVT VT, bool HasSSE2, SelectionDAG &DAG,
2863 assert(VT.isVector() && "Expected a vector type");
2865 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2866 // type. This ensures they get CSE'd.
2868 if (VT.getSizeInBits() == 64) { // MMX
2869 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2870 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2871 } else if (HasSSE2) { // SSE2
2872 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2873 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2875 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2876 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
2878 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2881 /// getOnesVector - Returns a vector of specified type with all bits set.
2883 static SDValue getOnesVector(MVT VT, SelectionDAG &DAG, DebugLoc dl) {
2884 assert(VT.isVector() && "Expected a vector type");
2886 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2887 // type. This ensures they get CSE'd.
2888 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2890 if (VT.getSizeInBits() == 64) // MMX
2891 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2893 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2894 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2898 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2899 /// that point to V2 points to its first element.
2900 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
2901 MVT VT = SVOp->getValueType(0);
2902 unsigned NumElems = VT.getVectorNumElements();
2904 bool Changed = false;
2905 SmallVector<int, 8> MaskVec;
2906 SVOp->getMask(MaskVec);
2908 for (unsigned i = 0; i != NumElems; ++i) {
2909 if (MaskVec[i] > (int)NumElems) {
2910 MaskVec[i] = NumElems;
2915 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
2916 SVOp->getOperand(1), &MaskVec[0]);
2917 return SDValue(SVOp, 0);
2920 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2921 /// operation of specified width.
2922 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
2924 unsigned NumElems = VT.getVectorNumElements();
2925 SmallVector<int, 8> Mask;
2926 Mask.push_back(NumElems);
2927 for (unsigned i = 1; i != NumElems; ++i)
2929 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2932 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
2933 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
2935 unsigned NumElems = VT.getVectorNumElements();
2936 SmallVector<int, 8> Mask;
2937 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2939 Mask.push_back(i + NumElems);
2941 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2944 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
2945 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
2947 unsigned NumElems = VT.getVectorNumElements();
2948 unsigned Half = NumElems/2;
2949 SmallVector<int, 8> Mask;
2950 for (unsigned i = 0; i != Half; ++i) {
2951 Mask.push_back(i + Half);
2952 Mask.push_back(i + NumElems + Half);
2954 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2957 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
2958 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
2960 if (SV->getValueType(0).getVectorNumElements() <= 4)
2961 return SDValue(SV, 0);
2963 MVT PVT = MVT::v4f32;
2964 MVT VT = SV->getValueType(0);
2965 DebugLoc dl = SV->getDebugLoc();
2966 SDValue V1 = SV->getOperand(0);
2967 int NumElems = VT.getVectorNumElements();
2968 int EltNo = SV->getSplatIndex();
2970 // unpack elements to the correct location
2971 while (NumElems > 4) {
2972 if (EltNo < NumElems/2) {
2973 V1 = getUnpackl(DAG, dl, VT, V1, V1);
2975 V1 = getUnpackh(DAG, dl, VT, V1, V1);
2976 EltNo -= NumElems/2;
2981 // Perform the splat.
2982 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
2983 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
2984 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
2985 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
2988 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2989 /// vector of zero or undef vector. This produces a shuffle where the low
2990 /// element of V2 is swizzled into the zero/undef vector, landing at element
2991 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
2992 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
2993 bool isZero, bool HasSSE2,
2994 SelectionDAG &DAG) {
2995 MVT VT = V2.getValueType();
2997 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
2998 unsigned NumElems = VT.getVectorNumElements();
2999 SmallVector<int, 16> MaskVec;
3000 for (unsigned i = 0; i != NumElems; ++i)
3001 // If this is the insertion idx, put the low elt of V2 here.
3002 MaskVec.push_back(i == Idx ? NumElems : i);
3003 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3006 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3007 /// a shuffle that is zero.
3009 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3010 bool Low, SelectionDAG &DAG) {
3011 unsigned NumZeros = 0;
3012 for (int i = 0; i < NumElems; ++i) {
3013 unsigned Index = Low ? i : NumElems-i-1;
3014 int Idx = SVOp->getMaskElt(Index);
3019 SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3020 if (Elt.getNode() && isZeroNode(Elt))
3028 /// isVectorShift - Returns true if the shuffle can be implemented as a
3029 /// logical left or right shift of a vector.
3030 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3031 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3032 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3033 int NumElems = SVOp->getValueType(0).getVectorNumElements();
3036 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3039 NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3043 bool SeenV1 = false;
3044 bool SeenV2 = false;
3045 for (int i = NumZeros; i < NumElems; ++i) {
3046 int Val = isLeft ? (i - NumZeros) : i;
3047 int Idx = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3059 if (SeenV1 && SeenV2)
3062 ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3068 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3070 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3071 unsigned NumNonZero, unsigned NumZero,
3072 SelectionDAG &DAG, TargetLowering &TLI) {
3076 DebugLoc dl = Op.getDebugLoc();
3079 for (unsigned i = 0; i < 16; ++i) {
3080 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3081 if (ThisIsNonZero && First) {
3083 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3085 V = DAG.getUNDEF(MVT::v8i16);
3090 SDValue ThisElt(0, 0), LastElt(0, 0);
3091 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3092 if (LastIsNonZero) {
3093 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3094 MVT::i16, Op.getOperand(i-1));
3096 if (ThisIsNonZero) {
3097 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3098 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3099 ThisElt, DAG.getConstant(8, MVT::i8));
3101 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3105 if (ThisElt.getNode())
3106 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3107 DAG.getIntPtrConstant(i/2));
3111 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3114 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3116 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3117 unsigned NumNonZero, unsigned NumZero,
3118 SelectionDAG &DAG, TargetLowering &TLI) {
3122 DebugLoc dl = Op.getDebugLoc();
3125 for (unsigned i = 0; i < 8; ++i) {
3126 bool isNonZero = (NonZeros & (1 << i)) != 0;
3130 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3132 V = DAG.getUNDEF(MVT::v8i16);
3135 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3136 MVT::v8i16, V, Op.getOperand(i),
3137 DAG.getIntPtrConstant(i));
3144 /// getVShift - Return a vector logical shift node.
3146 static SDValue getVShift(bool isLeft, MVT VT, SDValue SrcOp,
3147 unsigned NumBits, SelectionDAG &DAG,
3148 const TargetLowering &TLI, DebugLoc dl) {
3149 bool isMMX = VT.getSizeInBits() == 64;
3150 MVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3151 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3152 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3153 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3154 DAG.getNode(Opc, dl, ShVT, SrcOp,
3155 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3159 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3160 DebugLoc dl = Op.getDebugLoc();
3161 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3162 if (ISD::isBuildVectorAllZeros(Op.getNode())
3163 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3164 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3165 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3166 // eliminated on x86-32 hosts.
3167 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3170 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3171 return getOnesVector(Op.getValueType(), DAG, dl);
3172 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3175 MVT VT = Op.getValueType();
3176 MVT EVT = VT.getVectorElementType();
3177 unsigned EVTBits = EVT.getSizeInBits();
3179 unsigned NumElems = Op.getNumOperands();
3180 unsigned NumZero = 0;
3181 unsigned NumNonZero = 0;
3182 unsigned NonZeros = 0;
3183 bool IsAllConstants = true;
3184 SmallSet<SDValue, 8> Values;
3185 for (unsigned i = 0; i < NumElems; ++i) {
3186 SDValue Elt = Op.getOperand(i);
3187 if (Elt.getOpcode() == ISD::UNDEF)
3190 if (Elt.getOpcode() != ISD::Constant &&
3191 Elt.getOpcode() != ISD::ConstantFP)
3192 IsAllConstants = false;
3193 if (isZeroNode(Elt))
3196 NonZeros |= (1 << i);
3201 if (NumNonZero == 0) {
3202 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3203 return DAG.getUNDEF(VT);
3206 // Special case for single non-zero, non-undef, element.
3207 if (NumNonZero == 1) {
3208 unsigned Idx = CountTrailingZeros_32(NonZeros);
3209 SDValue Item = Op.getOperand(Idx);
3211 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3212 // the value are obviously zero, truncate the value to i32 and do the
3213 // insertion that way. Only do this if the value is non-constant or if the
3214 // value is a constant being inserted into element 0. It is cheaper to do
3215 // a constant pool load than it is to do a movd + shuffle.
3216 if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3217 (!IsAllConstants || Idx == 0)) {
3218 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3219 // Handle MMX and SSE both.
3220 MVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3221 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3223 // Truncate the value (which may itself be a constant) to i32, and
3224 // convert it to a vector with movd (S2V+shuffle to zero extend).
3225 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3226 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3227 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3228 Subtarget->hasSSE2(), DAG);
3230 // Now we have our 32-bit value zero extended in the low element of
3231 // a vector. If Idx != 0, swizzle it into place.
3233 SmallVector<int, 4> Mask;
3234 Mask.push_back(Idx);
3235 for (unsigned i = 1; i != VecElts; ++i)
3237 Item = DAG.getVectorShuffle(VecVT, dl, Item,
3238 DAG.getUNDEF(Item.getValueType()),
3241 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3245 // If we have a constant or non-constant insertion into the low element of
3246 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3247 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3248 // depending on what the source datatype is.
3251 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3252 } else if (EVT == MVT::i32 || EVT == MVT::f32 || EVT == MVT::f64 ||
3253 (EVT == MVT::i64 && Subtarget->is64Bit())) {
3254 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3255 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3256 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3258 } else if (EVT == MVT::i16 || EVT == MVT::i8) {
3259 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3260 MVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3261 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3262 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3263 Subtarget->hasSSE2(), DAG);
3264 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3268 // Is it a vector logical left shift?
3269 if (NumElems == 2 && Idx == 1 &&
3270 isZeroNode(Op.getOperand(0)) && !isZeroNode(Op.getOperand(1))) {
3271 unsigned NumBits = VT.getSizeInBits();
3272 return getVShift(true, VT,
3273 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3274 VT, Op.getOperand(1)),
3275 NumBits/2, DAG, *this, dl);
3278 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3281 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3282 // is a non-constant being inserted into an element other than the low one,
3283 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3284 // movd/movss) to move this into the low element, then shuffle it into
3286 if (EVTBits == 32) {
3287 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3289 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3290 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3291 Subtarget->hasSSE2(), DAG);
3292 SmallVector<int, 8> MaskVec;
3293 for (unsigned i = 0; i < NumElems; i++)
3294 MaskVec.push_back(i == Idx ? 0 : 1);
3295 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3299 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3300 if (Values.size() == 1)
3303 // A vector full of immediates; various special cases are already
3304 // handled, so this is best done with a single constant-pool load.
3308 // Let legalizer expand 2-wide build_vectors.
3309 if (EVTBits == 64) {
3310 if (NumNonZero == 1) {
3311 // One half is zero or undef.
3312 unsigned Idx = CountTrailingZeros_32(NonZeros);
3313 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3314 Op.getOperand(Idx));
3315 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3316 Subtarget->hasSSE2(), DAG);
3321 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3322 if (EVTBits == 8 && NumElems == 16) {
3323 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3325 if (V.getNode()) return V;
3328 if (EVTBits == 16 && NumElems == 8) {
3329 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3331 if (V.getNode()) return V;
3334 // If element VT is == 32 bits, turn it into a number of shuffles.
3335 SmallVector<SDValue, 8> V;
3337 if (NumElems == 4 && NumZero > 0) {
3338 for (unsigned i = 0; i < 4; ++i) {
3339 bool isZero = !(NonZeros & (1 << i));
3341 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3343 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3346 for (unsigned i = 0; i < 2; ++i) {
3347 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3350 V[i] = V[i*2]; // Must be a zero vector.
3353 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3356 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3359 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3364 SmallVector<int, 8> MaskVec;
3365 bool Reverse = (NonZeros & 0x3) == 2;
3366 for (unsigned i = 0; i < 2; ++i)
3367 MaskVec.push_back(Reverse ? 1-i : i);
3368 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3369 for (unsigned i = 0; i < 2; ++i)
3370 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3371 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3374 if (Values.size() > 2) {
3375 // If we have SSE 4.1, Expand into a number of inserts unless the number of
3376 // values to be inserted is equal to the number of elements, in which case
3377 // use the unpack code below in the hopes of matching the consecutive elts
3378 // load merge pattern for shuffles.
3379 // FIXME: We could probably just check that here directly.
3380 if (Values.size() < NumElems && VT.getSizeInBits() == 128 &&
3381 getSubtarget()->hasSSE41()) {
3382 V[0] = DAG.getUNDEF(VT);
3383 for (unsigned i = 0; i < NumElems; ++i)
3384 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3385 V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3386 Op.getOperand(i), DAG.getIntPtrConstant(i));
3389 // Expand into a number of unpckl*.
3391 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3392 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3393 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3394 for (unsigned i = 0; i < NumElems; ++i)
3395 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3397 while (NumElems != 0) {
3398 for (unsigned i = 0; i < NumElems; ++i)
3399 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3408 // v8i16 shuffles - Prefer shuffles in the following order:
3409 // 1. [all] pshuflw, pshufhw, optional move
3410 // 2. [ssse3] 1 x pshufb
3411 // 3. [ssse3] 2 x pshufb + 1 x por
3412 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
3414 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
3415 SelectionDAG &DAG, X86TargetLowering &TLI) {
3416 SDValue V1 = SVOp->getOperand(0);
3417 SDValue V2 = SVOp->getOperand(1);
3418 DebugLoc dl = SVOp->getDebugLoc();
3419 SmallVector<int, 8> MaskVals;
3421 // Determine if more than 1 of the words in each of the low and high quadwords
3422 // of the result come from the same quadword of one of the two inputs. Undef
3423 // mask values count as coming from any quadword, for better codegen.
3424 SmallVector<unsigned, 4> LoQuad(4);
3425 SmallVector<unsigned, 4> HiQuad(4);
3426 BitVector InputQuads(4);
3427 for (unsigned i = 0; i < 8; ++i) {
3428 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
3429 int EltIdx = SVOp->getMaskElt(i);
3430 MaskVals.push_back(EltIdx);
3439 InputQuads.set(EltIdx / 4);
3442 int BestLoQuad = -1;
3443 unsigned MaxQuad = 1;
3444 for (unsigned i = 0; i < 4; ++i) {
3445 if (LoQuad[i] > MaxQuad) {
3447 MaxQuad = LoQuad[i];
3451 int BestHiQuad = -1;
3453 for (unsigned i = 0; i < 4; ++i) {
3454 if (HiQuad[i] > MaxQuad) {
3456 MaxQuad = HiQuad[i];
3460 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
3461 // of the two input vectors, shuffle them into one input vector so only a
3462 // single pshufb instruction is necessary. If There are more than 2 input
3463 // quads, disable the next transformation since it does not help SSSE3.
3464 bool V1Used = InputQuads[0] || InputQuads[1];
3465 bool V2Used = InputQuads[2] || InputQuads[3];
3466 if (TLI.getSubtarget()->hasSSSE3()) {
3467 if (InputQuads.count() == 2 && V1Used && V2Used) {
3468 BestLoQuad = InputQuads.find_first();
3469 BestHiQuad = InputQuads.find_next(BestLoQuad);
3471 if (InputQuads.count() > 2) {
3477 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
3478 // the shuffle mask. If a quad is scored as -1, that means that it contains
3479 // words from all 4 input quadwords.
3481 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
3482 SmallVector<int, 8> MaskV;
3483 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
3484 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
3485 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
3486 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
3487 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
3488 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
3490 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
3491 // source words for the shuffle, to aid later transformations.
3492 bool AllWordsInNewV = true;
3493 bool InOrder[2] = { true, true };
3494 for (unsigned i = 0; i != 8; ++i) {
3495 int idx = MaskVals[i];
3497 InOrder[i/4] = false;
3498 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
3500 AllWordsInNewV = false;
3504 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
3505 if (AllWordsInNewV) {
3506 for (int i = 0; i != 8; ++i) {
3507 int idx = MaskVals[i];
3510 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
3511 if ((idx != i) && idx < 4)
3513 if ((idx != i) && idx > 3)
3522 // If we've eliminated the use of V2, and the new mask is a pshuflw or
3523 // pshufhw, that's as cheap as it gets. Return the new shuffle.
3524 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
3525 return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
3526 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
3530 // If we have SSSE3, and all words of the result are from 1 input vector,
3531 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
3532 // is present, fall back to case 4.
3533 if (TLI.getSubtarget()->hasSSSE3()) {
3534 SmallVector<SDValue,16> pshufbMask;
3536 // If we have elements from both input vectors, set the high bit of the
3537 // shuffle mask element to zero out elements that come from V2 in the V1
3538 // mask, and elements that come from V1 in the V2 mask, so that the two
3539 // results can be OR'd together.
3540 bool TwoInputs = V1Used && V2Used;
3541 for (unsigned i = 0; i != 8; ++i) {
3542 int EltIdx = MaskVals[i] * 2;
3543 if (TwoInputs && (EltIdx >= 16)) {
3544 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3545 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3548 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3549 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
3551 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
3552 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3553 DAG.getNode(ISD::BUILD_VECTOR, dl,
3554 MVT::v16i8, &pshufbMask[0], 16));
3556 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3558 // Calculate the shuffle mask for the second input, shuffle it, and
3559 // OR it with the first shuffled input.
3561 for (unsigned i = 0; i != 8; ++i) {
3562 int EltIdx = MaskVals[i] * 2;
3564 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3565 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3568 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3569 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
3571 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
3572 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3573 DAG.getNode(ISD::BUILD_VECTOR, dl,
3574 MVT::v16i8, &pshufbMask[0], 16));
3575 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3576 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3579 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
3580 // and update MaskVals with new element order.
3581 BitVector InOrder(8);
3582 if (BestLoQuad >= 0) {
3583 SmallVector<int, 8> MaskV;
3584 for (int i = 0; i != 4; ++i) {
3585 int idx = MaskVals[i];
3587 MaskV.push_back(-1);
3589 } else if ((idx / 4) == BestLoQuad) {
3590 MaskV.push_back(idx & 3);
3593 MaskV.push_back(-1);
3596 for (unsigned i = 4; i != 8; ++i)
3598 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3602 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
3603 // and update MaskVals with the new element order.
3604 if (BestHiQuad >= 0) {
3605 SmallVector<int, 8> MaskV;
3606 for (unsigned i = 0; i != 4; ++i)
3608 for (unsigned i = 4; i != 8; ++i) {
3609 int idx = MaskVals[i];
3611 MaskV.push_back(-1);
3613 } else if ((idx / 4) == BestHiQuad) {
3614 MaskV.push_back((idx & 3) + 4);
3617 MaskV.push_back(-1);
3620 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3624 // In case BestHi & BestLo were both -1, which means each quadword has a word
3625 // from each of the four input quadwords, calculate the InOrder bitvector now
3626 // before falling through to the insert/extract cleanup.
3627 if (BestLoQuad == -1 && BestHiQuad == -1) {
3629 for (int i = 0; i != 8; ++i)
3630 if (MaskVals[i] < 0 || MaskVals[i] == i)
3634 // The other elements are put in the right place using pextrw and pinsrw.
3635 for (unsigned i = 0; i != 8; ++i) {
3638 int EltIdx = MaskVals[i];
3641 SDValue ExtOp = (EltIdx < 8)
3642 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
3643 DAG.getIntPtrConstant(EltIdx))
3644 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
3645 DAG.getIntPtrConstant(EltIdx - 8));
3646 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3647 DAG.getIntPtrConstant(i));
3652 // v16i8 shuffles - Prefer shuffles in the following order:
3653 // 1. [ssse3] 1 x pshufb
3654 // 2. [ssse3] 2 x pshufb + 1 x por
3655 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
3657 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
3658 SelectionDAG &DAG, X86TargetLowering &TLI) {
3659 SDValue V1 = SVOp->getOperand(0);
3660 SDValue V2 = SVOp->getOperand(1);
3661 DebugLoc dl = SVOp->getDebugLoc();
3662 SmallVector<int, 16> MaskVals;
3663 SVOp->getMask(MaskVals);
3665 // If we have SSSE3, case 1 is generated when all result bytes come from
3666 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
3667 // present, fall back to case 3.
3668 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
3671 for (unsigned i = 0; i < 16; ++i) {
3672 int EltIdx = MaskVals[i];
3681 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
3682 if (TLI.getSubtarget()->hasSSSE3()) {
3683 SmallVector<SDValue,16> pshufbMask;
3685 // If all result elements are from one input vector, then only translate
3686 // undef mask values to 0x80 (zero out result) in the pshufb mask.
3688 // Otherwise, we have elements from both input vectors, and must zero out
3689 // elements that come from V2 in the first mask, and V1 in the second mask
3690 // so that we can OR them together.
3691 bool TwoInputs = !(V1Only || V2Only);
3692 for (unsigned i = 0; i != 16; ++i) {
3693 int EltIdx = MaskVals[i];
3694 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
3695 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3698 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3700 // If all the elements are from V2, assign it to V1 and return after
3701 // building the first pshufb.
3704 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3705 DAG.getNode(ISD::BUILD_VECTOR, dl,
3706 MVT::v16i8, &pshufbMask[0], 16));
3710 // Calculate the shuffle mask for the second input, shuffle it, and
3711 // OR it with the first shuffled input.
3713 for (unsigned i = 0; i != 16; ++i) {
3714 int EltIdx = MaskVals[i];
3716 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3719 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3721 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3722 DAG.getNode(ISD::BUILD_VECTOR, dl,
3723 MVT::v16i8, &pshufbMask[0], 16));
3724 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3727 // No SSSE3 - Calculate in place words and then fix all out of place words
3728 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
3729 // the 16 different words that comprise the two doublequadword input vectors.
3730 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3731 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
3732 SDValue NewV = V2Only ? V2 : V1;
3733 for (int i = 0; i != 8; ++i) {
3734 int Elt0 = MaskVals[i*2];
3735 int Elt1 = MaskVals[i*2+1];
3737 // This word of the result is all undef, skip it.
3738 if (Elt0 < 0 && Elt1 < 0)
3741 // This word of the result is already in the correct place, skip it.
3742 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
3744 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
3747 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
3748 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
3751 // If Elt0 and Elt1 are defined, are consecutive, and can be load
3752 // using a single extract together, load it and store it.
3753 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
3754 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3755 DAG.getIntPtrConstant(Elt1 / 2));
3756 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3757 DAG.getIntPtrConstant(i));
3761 // If Elt1 is defined, extract it from the appropriate source. If the
3762 // source byte is not also odd, shift the extracted word left 8 bits
3763 // otherwise clear the bottom 8 bits if we need to do an or.
3765 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3766 DAG.getIntPtrConstant(Elt1 / 2));
3767 if ((Elt1 & 1) == 0)
3768 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
3769 DAG.getConstant(8, TLI.getShiftAmountTy()));
3771 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
3772 DAG.getConstant(0xFF00, MVT::i16));
3774 // If Elt0 is defined, extract it from the appropriate source. If the
3775 // source byte is not also even, shift the extracted word right 8 bits. If
3776 // Elt1 was also defined, OR the extracted values together before
3777 // inserting them in the result.
3779 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
3780 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
3781 if ((Elt0 & 1) != 0)
3782 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
3783 DAG.getConstant(8, TLI.getShiftAmountTy()));
3785 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
3786 DAG.getConstant(0x00FF, MVT::i16));
3787 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
3790 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3791 DAG.getIntPtrConstant(i));
3793 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
3796 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3797 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3798 /// done when every pair / quad of shuffle mask elements point to elements in
3799 /// the right sequence. e.g.
3800 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3802 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
3804 TargetLowering &TLI, DebugLoc dl) {
3805 MVT VT = SVOp->getValueType(0);
3806 SDValue V1 = SVOp->getOperand(0);
3807 SDValue V2 = SVOp->getOperand(1);
3808 unsigned NumElems = VT.getVectorNumElements();
3809 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3810 MVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3811 MVT MaskEltVT = MaskVT.getVectorElementType();
3813 switch (VT.getSimpleVT()) {
3814 default: assert(false && "Unexpected!");
3815 case MVT::v4f32: NewVT = MVT::v2f64; break;
3816 case MVT::v4i32: NewVT = MVT::v2i64; break;
3817 case MVT::v8i16: NewVT = MVT::v4i32; break;
3818 case MVT::v16i8: NewVT = MVT::v4i32; break;
3821 if (NewWidth == 2) {
3827 int Scale = NumElems / NewWidth;
3828 SmallVector<int, 8> MaskVec;
3829 for (unsigned i = 0; i < NumElems; i += Scale) {
3831 for (int j = 0; j < Scale; ++j) {
3832 int EltIdx = SVOp->getMaskElt(i+j);
3836 StartIdx = EltIdx - (EltIdx % Scale);
3837 if (EltIdx != StartIdx + j)
3841 MaskVec.push_back(-1);
3843 MaskVec.push_back(StartIdx / Scale);
3846 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
3847 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
3848 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
3851 /// getVZextMovL - Return a zero-extending vector move low node.
3853 static SDValue getVZextMovL(MVT VT, MVT OpVT,
3854 SDValue SrcOp, SelectionDAG &DAG,
3855 const X86Subtarget *Subtarget, DebugLoc dl) {
3856 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3857 LoadSDNode *LD = NULL;
3858 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
3859 LD = dyn_cast<LoadSDNode>(SrcOp);
3861 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3863 MVT EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3864 if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
3865 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3866 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3867 SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
3869 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3870 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3871 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3872 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3880 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3881 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3882 DAG.getNode(ISD::BIT_CONVERT, dl,
3886 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
3889 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3890 SDValue V1 = SVOp->getOperand(0);
3891 SDValue V2 = SVOp->getOperand(1);
3892 DebugLoc dl = SVOp->getDebugLoc();
3893 MVT VT = SVOp->getValueType(0);
3895 SmallVector<std::pair<int, int>, 8> Locs;
3897 SmallVector<int, 8> Mask1(4U, -1);
3898 SmallVector<int, 8> PermMask;
3899 SVOp->getMask(PermMask);
3903 for (unsigned i = 0; i != 4; ++i) {
3904 int Idx = PermMask[i];
3906 Locs[i] = std::make_pair(-1, -1);
3908 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
3910 Locs[i] = std::make_pair(0, NumLo);
3914 Locs[i] = std::make_pair(1, NumHi);
3916 Mask1[2+NumHi] = Idx;
3922 if (NumLo <= 2 && NumHi <= 2) {
3923 // If no more than two elements come from either vector. This can be
3924 // implemented with two shuffles. First shuffle gather the elements.
3925 // The second shuffle, which takes the first shuffle as both of its
3926 // vector operands, put the elements into the right order.
3927 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
3929 SmallVector<int, 8> Mask2(4U, -1);
3931 for (unsigned i = 0; i != 4; ++i) {
3932 if (Locs[i].first == -1)
3935 unsigned Idx = (i < 2) ? 0 : 4;
3936 Idx += Locs[i].first * 2 + Locs[i].second;
3941 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
3942 } else if (NumLo == 3 || NumHi == 3) {
3943 // Otherwise, we must have three elements from one vector, call it X, and
3944 // one element from the other, call it Y. First, use a shufps to build an
3945 // intermediate vector with the one element from Y and the element from X
3946 // that will be in the same half in the final destination (the indexes don't
3947 // matter). Then, use a shufps to build the final vector, taking the half
3948 // containing the element from Y from the intermediate, and the other half
3951 // Normalize it so the 3 elements come from V1.
3952 CommuteVectorShuffleMask(PermMask, VT);
3956 // Find the element from V2.
3958 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
3959 int Val = PermMask[HiIndex];
3966 Mask1[0] = PermMask[HiIndex];
3968 Mask1[2] = PermMask[HiIndex^1];
3970 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
3973 Mask1[0] = PermMask[0];
3974 Mask1[1] = PermMask[1];
3975 Mask1[2] = HiIndex & 1 ? 6 : 4;
3976 Mask1[3] = HiIndex & 1 ? 4 : 6;
3977 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
3979 Mask1[0] = HiIndex & 1 ? 2 : 0;
3980 Mask1[1] = HiIndex & 1 ? 0 : 2;
3981 Mask1[2] = PermMask[2];
3982 Mask1[3] = PermMask[3];
3987 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
3991 // Break it into (shuffle shuffle_hi, shuffle_lo).
3993 SmallVector<int,8> LoMask(4U, -1);
3994 SmallVector<int,8> HiMask(4U, -1);
3996 SmallVector<int,8> *MaskPtr = &LoMask;
3997 unsigned MaskIdx = 0;
4000 for (unsigned i = 0; i != 4; ++i) {
4007 int Idx = PermMask[i];
4009 Locs[i] = std::make_pair(-1, -1);
4010 } else if (Idx < 4) {
4011 Locs[i] = std::make_pair(MaskIdx, LoIdx);
4012 (*MaskPtr)[LoIdx] = Idx;
4015 Locs[i] = std::make_pair(MaskIdx, HiIdx);
4016 (*MaskPtr)[HiIdx] = Idx;
4021 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4022 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4023 SmallVector<int, 8> MaskOps;
4024 for (unsigned i = 0; i != 4; ++i) {
4025 if (Locs[i].first == -1) {
4026 MaskOps.push_back(-1);
4028 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4029 MaskOps.push_back(Idx);
4032 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4036 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4037 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4038 SDValue V1 = Op.getOperand(0);
4039 SDValue V2 = Op.getOperand(1);
4040 MVT VT = Op.getValueType();
4041 DebugLoc dl = Op.getDebugLoc();
4042 unsigned NumElems = VT.getVectorNumElements();
4043 bool isMMX = VT.getSizeInBits() == 64;
4044 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4045 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4046 bool V1IsSplat = false;
4047 bool V2IsSplat = false;
4049 if (isZeroShuffle(SVOp))
4050 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4052 // Promote splats to v4f32.
4053 if (SVOp->isSplat()) {
4054 if (isMMX || NumElems < 4)
4056 return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4059 // If the shuffle can be profitably rewritten as a narrower shuffle, then
4061 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4062 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4063 if (NewOp.getNode())
4064 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4065 LowerVECTOR_SHUFFLE(NewOp, DAG));
4066 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4067 // FIXME: Figure out a cleaner way to do this.
4068 // Try to make use of movq to zero out the top part.
4069 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4070 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4071 if (NewOp.getNode()) {
4072 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4073 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4074 DAG, Subtarget, dl);
4076 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4077 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4078 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4079 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4080 DAG, Subtarget, dl);
4084 if (X86::isPSHUFDMask(SVOp))
4087 // Check if this can be converted into a logical shift.
4088 bool isLeft = false;
4091 bool isShift = getSubtarget()->hasSSE2() &&
4092 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4093 if (isShift && ShVal.hasOneUse()) {
4094 // If the shifted value has multiple uses, it may be cheaper to use
4095 // v_set0 + movlhps or movhlps, etc.
4096 MVT EVT = VT.getVectorElementType();
4097 ShAmt *= EVT.getSizeInBits();
4098 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4101 if (X86::isMOVLMask(SVOp)) {
4104 if (ISD::isBuildVectorAllZeros(V1.getNode()))
4105 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4110 // FIXME: fold these into legal mask.
4111 if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4112 X86::isMOVSLDUPMask(SVOp) ||
4113 X86::isMOVHLPSMask(SVOp) ||
4114 X86::isMOVHPMask(SVOp) ||
4115 X86::isMOVLPMask(SVOp)))
4118 if (ShouldXformToMOVHLPS(SVOp) ||
4119 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4120 return CommuteVectorShuffle(SVOp, DAG);
4123 // No better options. Use a vshl / vsrl.
4124 MVT EVT = VT.getVectorElementType();
4125 ShAmt *= EVT.getSizeInBits();
4126 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4129 bool Commuted = false;
4130 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4131 // 1,1,1,1 -> v8i16 though.
4132 V1IsSplat = isSplatVector(V1.getNode());
4133 V2IsSplat = isSplatVector(V2.getNode());
4135 // Canonicalize the splat or undef, if present, to be on the RHS.
4136 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4137 Op = CommuteVectorShuffle(SVOp, DAG);
4138 SVOp = cast<ShuffleVectorSDNode>(Op);
4139 V1 = SVOp->getOperand(0);
4140 V2 = SVOp->getOperand(1);
4141 std::swap(V1IsSplat, V2IsSplat);
4142 std::swap(V1IsUndef, V2IsUndef);
4146 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4147 // Shuffling low element of v1 into undef, just return v1.
4150 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4151 // the instruction selector will not match, so get a canonical MOVL with
4152 // swapped operands to undo the commute.
4153 return getMOVL(DAG, dl, VT, V2, V1);
4156 if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4157 X86::isUNPCKH_v_undef_Mask(SVOp) ||
4158 X86::isUNPCKLMask(SVOp) ||
4159 X86::isUNPCKHMask(SVOp))
4163 // Normalize mask so all entries that point to V2 points to its first
4164 // element then try to match unpck{h|l} again. If match, return a
4165 // new vector_shuffle with the corrected mask.
4166 SDValue NewMask = NormalizeMask(SVOp, DAG);
4167 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4168 if (NSVOp != SVOp) {
4169 if (X86::isUNPCKLMask(NSVOp, true)) {
4171 } else if (X86::isUNPCKHMask(NSVOp, true)) {
4178 // Commute is back and try unpck* again.
4179 // FIXME: this seems wrong.
4180 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4181 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4182 if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4183 X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4184 X86::isUNPCKLMask(NewSVOp) ||
4185 X86::isUNPCKHMask(NewSVOp))
4189 // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4191 // Normalize the node to match x86 shuffle ops if needed
4192 if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4193 return CommuteVectorShuffle(SVOp, DAG);
4195 // Check for legal shuffle and return?
4196 SmallVector<int, 16> PermMask;
4197 SVOp->getMask(PermMask);
4198 if (isShuffleMaskLegal(PermMask, VT))
4201 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4202 if (VT == MVT::v8i16) {
4203 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4204 if (NewOp.getNode())
4208 if (VT == MVT::v16i8) {
4209 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4210 if (NewOp.getNode())
4214 // Handle all 4 wide cases with a number of shuffles except for MMX.
4215 if (NumElems == 4 && !isMMX)
4216 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4222 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4223 SelectionDAG &DAG) {
4224 MVT VT = Op.getValueType();
4225 DebugLoc dl = Op.getDebugLoc();
4226 if (VT.getSizeInBits() == 8) {
4227 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4228 Op.getOperand(0), Op.getOperand(1));
4229 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4230 DAG.getValueType(VT));
4231 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4232 } else if (VT.getSizeInBits() == 16) {
4233 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4234 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4236 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4237 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4238 DAG.getNode(ISD::BIT_CONVERT, dl,
4242 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4243 Op.getOperand(0), Op.getOperand(1));
4244 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4245 DAG.getValueType(VT));
4246 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4247 } else if (VT == MVT::f32) {
4248 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4249 // the result back to FR32 register. It's only worth matching if the
4250 // result has a single use which is a store or a bitcast to i32. And in
4251 // the case of a store, it's not worth it if the index is a constant 0,
4252 // because a MOVSSmr can be used instead, which is smaller and faster.
4253 if (!Op.hasOneUse())
4255 SDNode *User = *Op.getNode()->use_begin();
4256 if ((User->getOpcode() != ISD::STORE ||
4257 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4258 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4259 (User->getOpcode() != ISD::BIT_CONVERT ||
4260 User->getValueType(0) != MVT::i32))
4262 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4263 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4266 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4267 } else if (VT == MVT::i32) {
4268 // ExtractPS works with constant index.
4269 if (isa<ConstantSDNode>(Op.getOperand(1)))
4277 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4278 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4281 if (Subtarget->hasSSE41()) {
4282 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4287 MVT VT = Op.getValueType();
4288 DebugLoc dl = Op.getDebugLoc();
4289 // TODO: handle v16i8.
4290 if (VT.getSizeInBits() == 16) {
4291 SDValue Vec = Op.getOperand(0);
4292 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4294 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4295 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4296 DAG.getNode(ISD::BIT_CONVERT, dl,
4299 // Transform it so it match pextrw which produces a 32-bit result.
4300 MVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT()+1);
4301 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EVT,
4302 Op.getOperand(0), Op.getOperand(1));
4303 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EVT, Extract,
4304 DAG.getValueType(VT));
4305 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4306 } else if (VT.getSizeInBits() == 32) {
4307 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4311 // SHUFPS the element to the lowest double word, then movss.
4312 int Mask[4] = { Idx, -1, -1, -1 };
4313 MVT VVT = Op.getOperand(0).getValueType();
4314 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4315 DAG.getUNDEF(VVT), Mask);
4316 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4317 DAG.getIntPtrConstant(0));
4318 } else if (VT.getSizeInBits() == 64) {
4319 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4320 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4321 // to match extract_elt for f64.
4322 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4326 // UNPCKHPD the element to the lowest double word, then movsd.
4327 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4328 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4329 int Mask[2] = { 1, -1 };
4330 MVT VVT = Op.getOperand(0).getValueType();
4331 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4332 DAG.getUNDEF(VVT), Mask);
4333 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4334 DAG.getIntPtrConstant(0));
4341 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4342 MVT VT = Op.getValueType();
4343 MVT EVT = VT.getVectorElementType();
4344 DebugLoc dl = Op.getDebugLoc();
4346 SDValue N0 = Op.getOperand(0);
4347 SDValue N1 = Op.getOperand(1);
4348 SDValue N2 = Op.getOperand(2);
4350 if ((EVT.getSizeInBits() == 8 || EVT.getSizeInBits() == 16) &&
4351 isa<ConstantSDNode>(N2)) {
4352 unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4354 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4356 if (N1.getValueType() != MVT::i32)
4357 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4358 if (N2.getValueType() != MVT::i32)
4359 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4360 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4361 } else if (EVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4362 // Bits [7:6] of the constant are the source select. This will always be
4363 // zero here. The DAG Combiner may combine an extract_elt index into these
4364 // bits. For example (insert (extract, 3), 2) could be matched by putting
4365 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4366 // Bits [5:4] of the constant are the destination select. This is the
4367 // value of the incoming immediate.
4368 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4369 // combine either bitwise AND or insert of float 0.0 to set these bits.
4370 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4371 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4372 } else if (EVT == MVT::i32) {
4373 // InsertPS works with constant index.
4374 if (isa<ConstantSDNode>(N2))
4381 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4382 MVT VT = Op.getValueType();
4383 MVT EVT = VT.getVectorElementType();
4385 if (Subtarget->hasSSE41())
4386 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4391 DebugLoc dl = Op.getDebugLoc();
4392 SDValue N0 = Op.getOperand(0);
4393 SDValue N1 = Op.getOperand(1);
4394 SDValue N2 = Op.getOperand(2);
4396 if (EVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
4397 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4398 // as its second argument.
4399 if (N1.getValueType() != MVT::i32)
4400 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4401 if (N2.getValueType() != MVT::i32)
4402 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4403 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
4409 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4410 DebugLoc dl = Op.getDebugLoc();
4411 if (Op.getValueType() == MVT::v2f32)
4412 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4413 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4414 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4415 Op.getOperand(0))));
4417 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4418 MVT VT = MVT::v2i32;
4419 switch (Op.getValueType().getSimpleVT()) {
4426 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4427 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4430 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4431 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4432 // one of the above mentioned nodes. It has to be wrapped because otherwise
4433 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4434 // be used to form addressing mode. These wrapped nodes will be selected
4437 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4438 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4440 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4442 unsigned char OpFlag = 0;
4443 unsigned WrapperKind = X86ISD::Wrapper;
4444 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
4445 if (Subtarget->isPICStyleStub())
4446 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4447 else if (Subtarget->isPICStyleGOT())
4448 OpFlag = X86II::MO_GOTOFF;
4449 else if (Subtarget->isPICStyleRIPRel() &&
4450 getTargetMachine().getCodeModel() == CodeModel::Small)
4451 WrapperKind = X86ISD::WrapperRIP;
4454 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
4456 CP->getOffset(), OpFlag);
4457 DebugLoc DL = CP->getDebugLoc();
4458 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4459 // With PIC, the address is actually $g + Offset.
4461 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4462 DAG.getNode(X86ISD::GlobalBaseReg,
4463 DebugLoc::getUnknownLoc(), getPointerTy()),
4470 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4471 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4473 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4475 unsigned char OpFlag = 0;
4476 unsigned WrapperKind = X86ISD::Wrapper;
4477 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
4478 if (Subtarget->isPICStyleStub())
4479 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4480 else if (Subtarget->isPICStyleGOT())
4481 OpFlag = X86II::MO_GOTOFF;
4482 else if (Subtarget->isPICStyleRIPRel())
4483 WrapperKind = X86ISD::WrapperRIP;
4486 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
4488 DebugLoc DL = JT->getDebugLoc();
4489 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4491 // With PIC, the address is actually $g + Offset.
4493 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4494 DAG.getNode(X86ISD::GlobalBaseReg,
4495 DebugLoc::getUnknownLoc(), getPointerTy()),
4503 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4504 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4506 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4508 unsigned char OpFlag = 0;
4509 unsigned WrapperKind = X86ISD::Wrapper;
4510 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
4511 if (Subtarget->isPICStyleStub())
4512 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4513 else if (Subtarget->isPICStyleGOT())
4514 OpFlag = X86II::MO_GOTOFF;
4515 else if (Subtarget->isPICStyleRIPRel())
4516 WrapperKind = X86ISD::WrapperRIP;
4519 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
4521 DebugLoc DL = Op.getDebugLoc();
4522 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4525 // With PIC, the address is actually $g + Offset.
4526 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4527 !Subtarget->isPICStyleRIPRel()) {
4528 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4529 DAG.getNode(X86ISD::GlobalBaseReg,
4530 DebugLoc::getUnknownLoc(),
4539 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
4541 SelectionDAG &DAG) const {
4542 bool IsPic = getTargetMachine().getRelocationModel() == Reloc::PIC_;
4543 bool ExtraLoadRequired =
4544 Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false);
4546 // Create the TargetGlobalAddress node, folding in the constant
4547 // offset if it is legal.
4549 if (!IsPic && !ExtraLoadRequired && isInt32(Offset)) {
4550 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4553 unsigned char OpFlags = 0;
4555 if (Subtarget->isPICStyleRIPRel() &&
4556 getTargetMachine().getRelocationModel() != Reloc::Static) {
4557 if (ExtraLoadRequired)
4558 OpFlags = X86II::MO_GOTPCREL;
4559 } else if (Subtarget->isPICStyleGOT() &&
4560 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
4561 if (ExtraLoadRequired)
4562 OpFlags = X86II::MO_GOT;
4564 OpFlags = X86II::MO_GOTOFF;
4567 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
4570 if (Subtarget->isPICStyleRIPRel() &&
4571 getTargetMachine().getCodeModel() == CodeModel::Small)
4572 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
4574 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4576 // With PIC, the address is actually $g + Offset.
4577 if (IsPic && !Subtarget->isPICStyleRIPRel()) {
4578 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4579 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4583 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4584 // load the value at address GV, not the value of GV itself. This means that
4585 // the GlobalAddress must be in the base or index register of the address, not
4586 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4587 // The same applies for external symbols during PIC codegen
4588 if (ExtraLoadRequired)
4589 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
4590 PseudoSourceValue::getGOT(), 0);
4592 // If there was a non-zero offset that we didn't fold, create an explicit
4595 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
4596 DAG.getConstant(Offset, getPointerTy()));
4602 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4603 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4604 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4605 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
4609 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
4610 SDValue *InFlag, const MVT PtrVT, unsigned ReturnReg,
4611 unsigned char OperandFlags) {
4612 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4613 DebugLoc dl = GA->getDebugLoc();
4614 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4615 GA->getValueType(0),
4619 SDValue Ops[] = { Chain, TGA, *InFlag };
4620 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
4622 SDValue Ops[] = { Chain, TGA };
4623 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
4625 SDValue Flag = Chain.getValue(1);
4626 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
4629 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4631 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4634 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
4635 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
4636 DAG.getNode(X86ISD::GlobalBaseReg,
4637 DebugLoc::getUnknownLoc(),
4639 InFlag = Chain.getValue(1);
4641 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
4644 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4646 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4648 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
4649 X86::RAX, X86II::MO_TLSGD);
4652 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4653 // "local exec" model.
4654 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4655 const MVT PtrVT, TLSModel::Model model,
4657 DebugLoc dl = GA->getDebugLoc();
4658 // Get the Thread Pointer
4659 SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
4660 DebugLoc::getUnknownLoc(), PtrVT,
4661 DAG.getRegister(is64Bit? X86::FS : X86::GS,
4664 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
4667 unsigned char OperandFlags = 0;
4668 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
4670 unsigned WrapperKind = X86ISD::Wrapper;
4671 if (model == TLSModel::LocalExec) {
4672 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
4673 } else if (is64Bit) {
4674 assert(model == TLSModel::InitialExec);
4675 OperandFlags = X86II::MO_GOTTPOFF;
4676 WrapperKind = X86ISD::WrapperRIP;
4678 assert(model == TLSModel::InitialExec);
4679 OperandFlags = X86II::MO_INDNTPOFF;
4682 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4684 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
4685 GA->getOffset(), OperandFlags);
4686 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
4688 if (model == TLSModel::InitialExec)
4689 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
4690 PseudoSourceValue::getGOT(), 0);
4692 // The address of the thread local variable is the add of the thread
4693 // pointer with the offset of the variable.
4694 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
4698 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4699 // TODO: implement the "local dynamic" model
4700 // TODO: implement the "initial exec"model for pic executables
4701 assert(Subtarget->isTargetELF() &&
4702 "TLS not implemented for non-ELF targets");
4703 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4704 const GlobalValue *GV = GA->getGlobal();
4706 // If GV is an alias then use the aliasee for determining
4707 // thread-localness.
4708 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
4709 GV = GA->resolveAliasedGlobal(false);
4711 TLSModel::Model model = getTLSModel(GV,
4712 getTargetMachine().getRelocationModel());
4715 case TLSModel::GeneralDynamic:
4716 case TLSModel::LocalDynamic: // not implemented
4717 if (Subtarget->is64Bit())
4718 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4719 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4721 case TLSModel::InitialExec:
4722 case TLSModel::LocalExec:
4723 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
4724 Subtarget->is64Bit());
4727 assert(0 && "Unreachable");
4732 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4733 /// take a 2 x i32 value to shift plus a shift amount.
4734 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4735 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4736 MVT VT = Op.getValueType();
4737 unsigned VTBits = VT.getSizeInBits();
4738 DebugLoc dl = Op.getDebugLoc();
4739 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4740 SDValue ShOpLo = Op.getOperand(0);
4741 SDValue ShOpHi = Op.getOperand(1);
4742 SDValue ShAmt = Op.getOperand(2);
4743 SDValue Tmp1 = isSRA ?
4744 DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
4745 DAG.getConstant(VTBits - 1, MVT::i8)) :
4746 DAG.getConstant(0, VT);
4749 if (Op.getOpcode() == ISD::SHL_PARTS) {
4750 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
4751 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4753 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
4754 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
4757 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
4758 DAG.getConstant(VTBits, MVT::i8));
4759 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, VT,
4760 AndNode, DAG.getConstant(0, MVT::i8));
4763 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4764 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4765 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4767 if (Op.getOpcode() == ISD::SHL_PARTS) {
4768 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4769 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4771 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4772 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4775 SDValue Ops[2] = { Lo, Hi };
4776 return DAG.getMergeValues(Ops, 2, dl);
4779 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4780 MVT SrcVT = Op.getOperand(0).getValueType();
4782 if (SrcVT.isVector()) {
4783 if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
4789 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4790 "Unknown SINT_TO_FP to lower!");
4792 // These are really Legal; return the operand so the caller accepts it as
4794 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4796 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
4797 Subtarget->is64Bit()) {
4801 DebugLoc dl = Op.getDebugLoc();
4802 unsigned Size = SrcVT.getSizeInBits()/8;
4803 MachineFunction &MF = DAG.getMachineFunction();
4804 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4805 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4806 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
4808 PseudoSourceValue::getFixedStack(SSFI), 0);
4809 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
4812 SDValue X86TargetLowering::BuildFILD(SDValue Op, MVT SrcVT, SDValue Chain,
4814 SelectionDAG &DAG) {
4816 DebugLoc dl = Op.getDebugLoc();
4818 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4820 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4822 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4823 SmallVector<SDValue, 8> Ops;
4824 Ops.push_back(Chain);
4825 Ops.push_back(StackSlot);
4826 Ops.push_back(DAG.getValueType(SrcVT));
4827 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
4828 Tys, &Ops[0], Ops.size());
4831 Chain = Result.getValue(1);
4832 SDValue InFlag = Result.getValue(2);
4834 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4835 // shouldn't be necessary except that RFP cannot be live across
4836 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4837 MachineFunction &MF = DAG.getMachineFunction();
4838 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4839 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4840 Tys = DAG.getVTList(MVT::Other);
4841 SmallVector<SDValue, 8> Ops;
4842 Ops.push_back(Chain);
4843 Ops.push_back(Result);
4844 Ops.push_back(StackSlot);
4845 Ops.push_back(DAG.getValueType(Op.getValueType()));
4846 Ops.push_back(InFlag);
4847 Chain = DAG.getNode(X86ISD::FST, dl, Tys, &Ops[0], Ops.size());
4848 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
4849 PseudoSourceValue::getFixedStack(SSFI), 0);
4855 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
4856 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
4857 // This algorithm is not obvious. Here it is in C code, more or less:
4859 double uint64_to_double( uint32_t hi, uint32_t lo ) {
4860 static const __m128i exp = { 0x4330000045300000ULL, 0 };
4861 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
4863 // Copy ints to xmm registers.
4864 __m128i xh = _mm_cvtsi32_si128( hi );
4865 __m128i xl = _mm_cvtsi32_si128( lo );
4867 // Combine into low half of a single xmm register.
4868 __m128i x = _mm_unpacklo_epi32( xh, xl );
4872 // Merge in appropriate exponents to give the integer bits the right
4874 x = _mm_unpacklo_epi32( x, exp );
4876 // Subtract away the biases to deal with the IEEE-754 double precision
4878 d = _mm_sub_pd( (__m128d) x, bias );
4880 // All conversions up to here are exact. The correctly rounded result is
4881 // calculated using the current rounding mode using the following
4883 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
4884 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
4885 // store doesn't really need to be here (except
4886 // maybe to zero the other double)
4891 DebugLoc dl = Op.getDebugLoc();
4893 // Build some magic constants.
4894 std::vector<Constant*> CV0;
4895 CV0.push_back(ConstantInt::get(APInt(32, 0x45300000)));
4896 CV0.push_back(ConstantInt::get(APInt(32, 0x43300000)));
4897 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4898 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4899 Constant *C0 = ConstantVector::get(CV0);
4900 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
4902 std::vector<Constant*> CV1;
4903 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4530000000000000ULL))));
4904 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4330000000000000ULL))));
4905 Constant *C1 = ConstantVector::get(CV1);
4906 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
4908 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4909 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4911 DAG.getIntPtrConstant(1)));
4912 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4913 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4915 DAG.getIntPtrConstant(0)));
4916 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
4917 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
4918 PseudoSourceValue::getConstantPool(), 0,
4920 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
4921 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
4922 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
4923 PseudoSourceValue::getConstantPool(), 0,
4925 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
4927 // Add the halves; easiest way is to swap them into another reg first.
4928 int ShufMask[2] = { 1, -1 };
4929 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
4930 DAG.getUNDEF(MVT::v2f64), ShufMask);
4931 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
4932 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
4933 DAG.getIntPtrConstant(0));
4936 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
4937 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
4938 DebugLoc dl = Op.getDebugLoc();
4939 // FP constant to bias correct the final result.
4940 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
4943 // Load the 32-bit value into an XMM register.
4944 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4945 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4947 DAG.getIntPtrConstant(0)));
4949 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
4950 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
4951 DAG.getIntPtrConstant(0));
4953 // Or the load with the bias.
4954 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
4955 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4956 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4958 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4959 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4960 MVT::v2f64, Bias)));
4961 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
4962 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
4963 DAG.getIntPtrConstant(0));
4965 // Subtract the bias.
4966 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
4968 // Handle final rounding.
4969 MVT DestVT = Op.getValueType();
4971 if (DestVT.bitsLT(MVT::f64)) {
4972 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
4973 DAG.getIntPtrConstant(0));
4974 } else if (DestVT.bitsGT(MVT::f64)) {
4975 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
4978 // Handle final rounding.
4982 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4983 SDValue N0 = Op.getOperand(0);
4984 DebugLoc dl = Op.getDebugLoc();
4986 // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
4987 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
4988 // the optimization here.
4989 if (DAG.SignBitIsZero(N0))
4990 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
4992 MVT SrcVT = N0.getValueType();
4993 if (SrcVT == MVT::i64) {
4994 // We only handle SSE2 f64 target here; caller can expand the rest.
4995 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
4998 return LowerUINT_TO_FP_i64(Op, DAG);
4999 } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
5000 return LowerUINT_TO_FP_i32(Op, DAG);
5003 assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
5005 // Make a 64-bit buffer, and use it to build an FILD.
5006 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5007 SDValue WordOff = DAG.getConstant(4, getPointerTy());
5008 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5009 getPointerTy(), StackSlot, WordOff);
5010 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5011 StackSlot, NULL, 0);
5012 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5013 OffsetSlot, NULL, 0);
5014 return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5017 std::pair<SDValue,SDValue> X86TargetLowering::
5018 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) {
5019 DebugLoc dl = Op.getDebugLoc();
5021 MVT DstTy = Op.getValueType();
5024 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5028 assert(DstTy.getSimpleVT() <= MVT::i64 &&
5029 DstTy.getSimpleVT() >= MVT::i16 &&
5030 "Unknown FP_TO_SINT to lower!");
5032 // These are really Legal.
5033 if (DstTy == MVT::i32 &&
5034 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5035 return std::make_pair(SDValue(), SDValue());
5036 if (Subtarget->is64Bit() &&
5037 DstTy == MVT::i64 &&
5038 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5039 return std::make_pair(SDValue(), SDValue());
5041 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5043 MachineFunction &MF = DAG.getMachineFunction();
5044 unsigned MemSize = DstTy.getSizeInBits()/8;
5045 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
5046 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5049 switch (DstTy.getSimpleVT()) {
5050 default: assert(0 && "Invalid FP_TO_SINT to lower!");
5051 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5052 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5053 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5056 SDValue Chain = DAG.getEntryNode();
5057 SDValue Value = Op.getOperand(0);
5058 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5059 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5060 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5061 PseudoSourceValue::getFixedStack(SSFI), 0);
5062 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5064 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5066 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5067 Chain = Value.getValue(1);
5068 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
5069 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5072 // Build the FP_TO_INT*_IN_MEM
5073 SDValue Ops[] = { Chain, Value, StackSlot };
5074 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5076 return std::make_pair(FIST, StackSlot);
5079 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
5080 if (Op.getValueType().isVector()) {
5081 if (Op.getValueType() == MVT::v2i32 &&
5082 Op.getOperand(0).getValueType() == MVT::v2f64) {
5088 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5089 SDValue FIST = Vals.first, StackSlot = Vals.second;
5090 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5091 if (FIST.getNode() == 0) return Op;
5094 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5095 FIST, StackSlot, NULL, 0);
5098 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG) {
5099 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5100 SDValue FIST = Vals.first, StackSlot = Vals.second;
5101 assert(FIST.getNode() && "Unexpected failure");
5104 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5105 FIST, StackSlot, NULL, 0);
5108 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
5109 DebugLoc dl = Op.getDebugLoc();
5110 MVT VT = Op.getValueType();
5113 EltVT = VT.getVectorElementType();
5114 std::vector<Constant*> CV;
5115 if (EltVT == MVT::f64) {
5116 Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
5120 Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
5126 Constant *C = ConstantVector::get(CV);
5127 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5128 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5129 PseudoSourceValue::getConstantPool(), 0,
5131 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5134 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
5135 DebugLoc dl = Op.getDebugLoc();
5136 MVT VT = Op.getValueType();
5138 unsigned EltNum = 1;
5139 if (VT.isVector()) {
5140 EltVT = VT.getVectorElementType();
5141 EltNum = VT.getVectorNumElements();
5143 std::vector<Constant*> CV;
5144 if (EltVT == MVT::f64) {
5145 Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
5149 Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
5155 Constant *C = ConstantVector::get(CV);
5156 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5157 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5158 PseudoSourceValue::getConstantPool(), 0,
5160 if (VT.isVector()) {
5161 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5162 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5163 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5165 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5167 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5171 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5172 SDValue Op0 = Op.getOperand(0);
5173 SDValue Op1 = Op.getOperand(1);
5174 DebugLoc dl = Op.getDebugLoc();
5175 MVT VT = Op.getValueType();
5176 MVT SrcVT = Op1.getValueType();
5178 // If second operand is smaller, extend it first.
5179 if (SrcVT.bitsLT(VT)) {
5180 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5183 // And if it is bigger, shrink it first.
5184 if (SrcVT.bitsGT(VT)) {
5185 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5189 // At this point the operands and the result should have the same
5190 // type, and that won't be f80 since that is not custom lowered.
5192 // First get the sign bit of second operand.
5193 std::vector<Constant*> CV;
5194 if (SrcVT == MVT::f64) {
5195 CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
5196 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
5198 CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
5199 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5200 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5201 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5203 Constant *C = ConstantVector::get(CV);
5204 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5205 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5206 PseudoSourceValue::getConstantPool(), 0,
5208 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5210 // Shift sign bit right or left if the two operands have different types.
5211 if (SrcVT.bitsGT(VT)) {
5212 // Op0 is MVT::f32, Op1 is MVT::f64.
5213 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5214 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5215 DAG.getConstant(32, MVT::i32));
5216 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5217 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5218 DAG.getIntPtrConstant(0));
5221 // Clear first operand sign bit.
5223 if (VT == MVT::f64) {
5224 CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
5225 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
5227 CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
5228 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5229 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5230 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5232 C = ConstantVector::get(CV);
5233 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5234 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5235 PseudoSourceValue::getConstantPool(), 0,
5237 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5239 // Or the value with the sign bit.
5240 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5243 /// Emit nodes that will be selected as "test Op0,Op0", or something
5245 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5246 SelectionDAG &DAG) {
5247 DebugLoc dl = Op.getDebugLoc();
5249 // CF and OF aren't always set the way we want. Determine which
5250 // of these we need.
5251 bool NeedCF = false;
5252 bool NeedOF = false;
5254 case X86::COND_A: case X86::COND_AE:
5255 case X86::COND_B: case X86::COND_BE:
5258 case X86::COND_G: case X86::COND_GE:
5259 case X86::COND_L: case X86::COND_LE:
5260 case X86::COND_O: case X86::COND_NO:
5266 // See if we can use the EFLAGS value from the operand instead of
5267 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5268 // we prove that the arithmetic won't overflow, we can't use OF or CF.
5269 if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5270 unsigned Opcode = 0;
5271 unsigned NumOperands = 0;
5272 switch (Op.getNode()->getOpcode()) {
5274 // Due to an isel shortcoming, be conservative if this add is likely to
5275 // be selected as part of a load-modify-store instruction. When the root
5276 // node in a match is a store, isel doesn't know how to remap non-chain
5277 // non-flag uses of other nodes in the match, such as the ADD in this
5278 // case. This leads to the ADD being left around and reselected, with
5279 // the result being two adds in the output.
5280 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5281 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5282 if (UI->getOpcode() == ISD::STORE)
5284 if (ConstantSDNode *C =
5285 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5286 // An add of one will be selected as an INC.
5287 if (C->getAPIntValue() == 1) {
5288 Opcode = X86ISD::INC;
5292 // An add of negative one (subtract of one) will be selected as a DEC.
5293 if (C->getAPIntValue().isAllOnesValue()) {
5294 Opcode = X86ISD::DEC;
5299 // Otherwise use a regular EFLAGS-setting add.
5300 Opcode = X86ISD::ADD;
5304 // Due to the ISEL shortcoming noted above, be conservative if this sub is
5305 // likely to be selected as part of a load-modify-store instruction.
5306 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5307 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5308 if (UI->getOpcode() == ISD::STORE)
5310 // Otherwise use a regular EFLAGS-setting sub.
5311 Opcode = X86ISD::SUB;
5318 return SDValue(Op.getNode(), 1);
5324 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
5325 SmallVector<SDValue, 4> Ops;
5326 for (unsigned i = 0; i != NumOperands; ++i)
5327 Ops.push_back(Op.getOperand(i));
5328 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
5329 DAG.ReplaceAllUsesWith(Op, New);
5330 return SDValue(New.getNode(), 1);
5334 // Otherwise just emit a CMP with 0, which is the TEST pattern.
5335 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5336 DAG.getConstant(0, Op.getValueType()));
5339 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
5341 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5342 SelectionDAG &DAG) {
5343 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5344 if (C->getAPIntValue() == 0)
5345 return EmitTest(Op0, X86CC, DAG);
5347 DebugLoc dl = Op0.getDebugLoc();
5348 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5351 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5352 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5353 SDValue Op0 = Op.getOperand(0);
5354 SDValue Op1 = Op.getOperand(1);
5355 DebugLoc dl = Op.getDebugLoc();
5356 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5358 // Lower (X & (1 << N)) == 0 to BT(X, N).
5359 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5360 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5361 if (Op0.getOpcode() == ISD::AND &&
5363 Op1.getOpcode() == ISD::Constant &&
5364 cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5365 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5367 if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
5368 if (ConstantSDNode *Op010C =
5369 dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
5370 if (Op010C->getZExtValue() == 1) {
5371 LHS = Op0.getOperand(0);
5372 RHS = Op0.getOperand(1).getOperand(1);
5374 } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
5375 if (ConstantSDNode *Op000C =
5376 dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
5377 if (Op000C->getZExtValue() == 1) {
5378 LHS = Op0.getOperand(1);
5379 RHS = Op0.getOperand(0).getOperand(1);
5381 } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
5382 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5383 SDValue AndLHS = Op0.getOperand(0);
5384 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5385 LHS = AndLHS.getOperand(0);
5386 RHS = AndLHS.getOperand(1);
5390 if (LHS.getNode()) {
5391 // If LHS is i8, promote it to i16 with any_extend. There is no i8 BT
5392 // instruction. Since the shift amount is in-range-or-undefined, we know
5393 // that doing a bittest on the i16 value is ok. We extend to i32 because
5394 // the encoding for the i16 version is larger than the i32 version.
5395 if (LHS.getValueType() == MVT::i8)
5396 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5398 // If the operand types disagree, extend the shift amount to match. Since
5399 // BT ignores high bits (like shifts) we can use anyextend.
5400 if (LHS.getValueType() != RHS.getValueType())
5401 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5403 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5404 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5405 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5406 DAG.getConstant(Cond, MVT::i8), BT);
5410 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5411 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5413 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
5414 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5415 DAG.getConstant(X86CC, MVT::i8), Cond);
5418 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5420 SDValue Op0 = Op.getOperand(0);
5421 SDValue Op1 = Op.getOperand(1);
5422 SDValue CC = Op.getOperand(2);
5423 MVT VT = Op.getValueType();
5424 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5425 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5426 DebugLoc dl = Op.getDebugLoc();
5430 MVT VT0 = Op0.getValueType();
5431 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5432 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5435 switch (SetCCOpcode) {
5438 case ISD::SETEQ: SSECC = 0; break;
5440 case ISD::SETGT: Swap = true; // Fallthrough
5442 case ISD::SETOLT: SSECC = 1; break;
5444 case ISD::SETGE: Swap = true; // Fallthrough
5446 case ISD::SETOLE: SSECC = 2; break;
5447 case ISD::SETUO: SSECC = 3; break;
5449 case ISD::SETNE: SSECC = 4; break;
5450 case ISD::SETULE: Swap = true;
5451 case ISD::SETUGE: SSECC = 5; break;
5452 case ISD::SETULT: Swap = true;
5453 case ISD::SETUGT: SSECC = 6; break;
5454 case ISD::SETO: SSECC = 7; break;
5457 std::swap(Op0, Op1);
5459 // In the two special cases we can't handle, emit two comparisons.
5461 if (SetCCOpcode == ISD::SETUEQ) {
5463 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5464 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5465 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
5467 else if (SetCCOpcode == ISD::SETONE) {
5469 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5470 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5471 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
5473 assert(0 && "Illegal FP comparison");
5475 // Handle all other FP comparisons here.
5476 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5479 // We are handling one of the integer comparisons here. Since SSE only has
5480 // GT and EQ comparisons for integer, swapping operands and multiple
5481 // operations may be required for some comparisons.
5482 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5483 bool Swap = false, Invert = false, FlipSigns = false;
5485 switch (VT.getSimpleVT()) {
5487 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5488 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5489 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5490 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5493 switch (SetCCOpcode) {
5495 case ISD::SETNE: Invert = true;
5496 case ISD::SETEQ: Opc = EQOpc; break;
5497 case ISD::SETLT: Swap = true;
5498 case ISD::SETGT: Opc = GTOpc; break;
5499 case ISD::SETGE: Swap = true;
5500 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
5501 case ISD::SETULT: Swap = true;
5502 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5503 case ISD::SETUGE: Swap = true;
5504 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5507 std::swap(Op0, Op1);
5509 // Since SSE has no unsigned integer comparisons, we need to flip the sign
5510 // bits of the inputs before performing those operations.
5512 MVT EltVT = VT.getVectorElementType();
5513 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
5515 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5516 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
5518 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
5519 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
5522 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
5524 // If the logical-not of the result is required, perform that now.
5526 Result = DAG.getNOT(dl, Result, VT);
5531 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5532 static bool isX86LogicalCmp(SDValue Op) {
5533 unsigned Opc = Op.getNode()->getOpcode();
5534 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
5536 if (Op.getResNo() == 1 &&
5537 (Opc == X86ISD::ADD ||
5538 Opc == X86ISD::SUB ||
5539 Opc == X86ISD::SMUL ||
5540 Opc == X86ISD::UMUL ||
5541 Opc == X86ISD::INC ||
5542 Opc == X86ISD::DEC))
5548 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5549 bool addTest = true;
5550 SDValue Cond = Op.getOperand(0);
5551 DebugLoc dl = Op.getDebugLoc();
5554 if (Cond.getOpcode() == ISD::SETCC)
5555 Cond = LowerSETCC(Cond, DAG);
5557 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5558 // setting operand in place of the X86ISD::SETCC.
5559 if (Cond.getOpcode() == X86ISD::SETCC) {
5560 CC = Cond.getOperand(0);
5562 SDValue Cmp = Cond.getOperand(1);
5563 unsigned Opc = Cmp.getOpcode();
5564 MVT VT = Op.getValueType();
5566 bool IllegalFPCMov = false;
5567 if (VT.isFloatingPoint() && !VT.isVector() &&
5568 !isScalarFPTypeInSSEReg(VT)) // FPStack?
5569 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
5571 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
5572 Opc == X86ISD::BT) { // FIXME
5579 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5580 Cond = EmitTest(Cond, X86::COND_NE, DAG);
5583 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
5584 SmallVector<SDValue, 4> Ops;
5585 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
5586 // condition is true.
5587 Ops.push_back(Op.getOperand(2));
5588 Ops.push_back(Op.getOperand(1));
5590 Ops.push_back(Cond);
5591 return DAG.getNode(X86ISD::CMOV, dl, VTs, &Ops[0], Ops.size());
5594 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
5595 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
5596 // from the AND / OR.
5597 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
5598 Opc = Op.getOpcode();
5599 if (Opc != ISD::OR && Opc != ISD::AND)
5601 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5602 Op.getOperand(0).hasOneUse() &&
5603 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
5604 Op.getOperand(1).hasOneUse());
5607 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
5608 // 1 and that the SETCC node has a single use.
5609 static bool isXor1OfSetCC(SDValue Op) {
5610 if (Op.getOpcode() != ISD::XOR)
5612 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5613 if (N1C && N1C->getAPIntValue() == 1) {
5614 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5615 Op.getOperand(0).hasOneUse();
5620 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
5621 bool addTest = true;
5622 SDValue Chain = Op.getOperand(0);
5623 SDValue Cond = Op.getOperand(1);
5624 SDValue Dest = Op.getOperand(2);
5625 DebugLoc dl = Op.getDebugLoc();
5628 if (Cond.getOpcode() == ISD::SETCC)
5629 Cond = LowerSETCC(Cond, DAG);
5631 // FIXME: LowerXALUO doesn't handle these!!
5632 else if (Cond.getOpcode() == X86ISD::ADD ||
5633 Cond.getOpcode() == X86ISD::SUB ||
5634 Cond.getOpcode() == X86ISD::SMUL ||
5635 Cond.getOpcode() == X86ISD::UMUL)
5636 Cond = LowerXALUO(Cond, DAG);
5639 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5640 // setting operand in place of the X86ISD::SETCC.
5641 if (Cond.getOpcode() == X86ISD::SETCC) {
5642 CC = Cond.getOperand(0);
5644 SDValue Cmp = Cond.getOperand(1);
5645 unsigned Opc = Cmp.getOpcode();
5646 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
5647 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
5651 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
5655 // These can only come from an arithmetic instruction with overflow,
5656 // e.g. SADDO, UADDO.
5657 Cond = Cond.getNode()->getOperand(1);
5664 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
5665 SDValue Cmp = Cond.getOperand(0).getOperand(1);
5666 if (CondOpc == ISD::OR) {
5667 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
5668 // two branches instead of an explicit OR instruction with a
5670 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5671 isX86LogicalCmp(Cmp)) {
5672 CC = Cond.getOperand(0).getOperand(0);
5673 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5674 Chain, Dest, CC, Cmp);
5675 CC = Cond.getOperand(1).getOperand(0);
5679 } else { // ISD::AND
5680 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
5681 // two branches instead of an explicit AND instruction with a
5682 // separate test. However, we only do this if this block doesn't
5683 // have a fall-through edge, because this requires an explicit
5684 // jmp when the condition is false.
5685 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5686 isX86LogicalCmp(Cmp) &&
5687 Op.getNode()->hasOneUse()) {
5688 X86::CondCode CCode =
5689 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5690 CCode = X86::GetOppositeBranchCondition(CCode);
5691 CC = DAG.getConstant(CCode, MVT::i8);
5692 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
5693 // Look for an unconditional branch following this conditional branch.
5694 // We need this because we need to reverse the successors in order
5695 // to implement FCMP_OEQ.
5696 if (User.getOpcode() == ISD::BR) {
5697 SDValue FalseBB = User.getOperand(1);
5699 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
5700 assert(NewBR == User);
5703 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5704 Chain, Dest, CC, Cmp);
5705 X86::CondCode CCode =
5706 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
5707 CCode = X86::GetOppositeBranchCondition(CCode);
5708 CC = DAG.getConstant(CCode, MVT::i8);
5714 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
5715 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
5716 // It should be transformed during dag combiner except when the condition
5717 // is set by a arithmetics with overflow node.
5718 X86::CondCode CCode =
5719 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5720 CCode = X86::GetOppositeBranchCondition(CCode);
5721 CC = DAG.getConstant(CCode, MVT::i8);
5722 Cond = Cond.getOperand(0).getOperand(1);
5728 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5729 Cond = EmitTest(Cond, X86::COND_NE, DAG);
5731 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5732 Chain, Dest, CC, Cond);
5736 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
5737 // Calls to _alloca is needed to probe the stack when allocating more than 4k
5738 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
5739 // that the guard pages used by the OS virtual memory manager are allocated in
5740 // correct sequence.
5742 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5743 SelectionDAG &DAG) {
5744 assert(Subtarget->isTargetCygMing() &&
5745 "This should be used only on Cygwin/Mingw targets");
5746 DebugLoc dl = Op.getDebugLoc();
5749 SDValue Chain = Op.getOperand(0);
5750 SDValue Size = Op.getOperand(1);
5751 // FIXME: Ensure alignment here
5755 MVT IntPtr = getPointerTy();
5756 MVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
5758 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
5760 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
5761 Flag = Chain.getValue(1);
5763 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5764 SDValue Ops[] = { Chain,
5765 DAG.getTargetExternalSymbol("_alloca", IntPtr),
5766 DAG.getRegister(X86::EAX, IntPtr),
5767 DAG.getRegister(X86StackPtr, SPTy),
5769 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops, 5);
5770 Flag = Chain.getValue(1);
5772 Chain = DAG.getCALLSEQ_END(Chain,
5773 DAG.getIntPtrConstant(0, true),
5774 DAG.getIntPtrConstant(0, true),
5777 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
5779 SDValue Ops1[2] = { Chain.getValue(0), Chain };
5780 return DAG.getMergeValues(Ops1, 2, dl);
5784 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
5786 SDValue Dst, SDValue Src,
5787 SDValue Size, unsigned Align,
5789 uint64_t DstSVOff) {
5790 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5792 // If not DWORD aligned or size is more than the threshold, call the library.
5793 // The libc version is likely to be faster for these cases. It can use the
5794 // address value and run time information about the CPU.
5795 if ((Align & 3) != 0 ||
5797 ConstantSize->getZExtValue() >
5798 getSubtarget()->getMaxInlineSizeThreshold()) {
5799 SDValue InFlag(0, 0);
5801 // Check to see if there is a specialized entry-point for memory zeroing.
5802 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
5804 if (const char *bzeroEntry = V &&
5805 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
5806 MVT IntPtr = getPointerTy();
5807 const Type *IntPtrTy = TD->getIntPtrType();
5808 TargetLowering::ArgListTy Args;
5809 TargetLowering::ArgListEntry Entry;
5811 Entry.Ty = IntPtrTy;
5812 Args.push_back(Entry);
5814 Args.push_back(Entry);
5815 std::pair<SDValue,SDValue> CallResult =
5816 LowerCallTo(Chain, Type::VoidTy, false, false, false, false,
5817 0, CallingConv::C, false,
5818 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl);
5819 return CallResult.second;
5822 // Otherwise have the target-independent code call memset.
5826 uint64_t SizeVal = ConstantSize->getZExtValue();
5827 SDValue InFlag(0, 0);
5830 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
5831 unsigned BytesLeft = 0;
5832 bool TwoRepStos = false;
5835 uint64_t Val = ValC->getZExtValue() & 255;
5837 // If the value is a constant, then we can potentially use larger sets.
5838 switch (Align & 3) {
5839 case 2: // WORD aligned
5842 Val = (Val << 8) | Val;
5844 case 0: // DWORD aligned
5847 Val = (Val << 8) | Val;
5848 Val = (Val << 16) | Val;
5849 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
5852 Val = (Val << 32) | Val;
5855 default: // Byte aligned
5858 Count = DAG.getIntPtrConstant(SizeVal);
5862 if (AVT.bitsGT(MVT::i8)) {
5863 unsigned UBytes = AVT.getSizeInBits() / 8;
5864 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
5865 BytesLeft = SizeVal % UBytes;
5868 Chain = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
5870 InFlag = Chain.getValue(1);
5873 Count = DAG.getIntPtrConstant(SizeVal);
5874 Chain = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
5875 InFlag = Chain.getValue(1);
5878 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
5881 InFlag = Chain.getValue(1);
5882 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
5885 InFlag = Chain.getValue(1);
5887 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5888 SmallVector<SDValue, 8> Ops;
5889 Ops.push_back(Chain);
5890 Ops.push_back(DAG.getValueType(AVT));
5891 Ops.push_back(InFlag);
5892 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
5895 InFlag = Chain.getValue(1);
5897 MVT CVT = Count.getValueType();
5898 SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
5899 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
5900 Chain = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
5903 InFlag = Chain.getValue(1);
5904 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5906 Ops.push_back(Chain);
5907 Ops.push_back(DAG.getValueType(MVT::i8));
5908 Ops.push_back(InFlag);
5909 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
5910 } else if (BytesLeft) {
5911 // Handle the last 1 - 7 bytes.
5912 unsigned Offset = SizeVal - BytesLeft;
5913 MVT AddrVT = Dst.getValueType();
5914 MVT SizeVT = Size.getValueType();
5916 Chain = DAG.getMemset(Chain, dl,
5917 DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
5918 DAG.getConstant(Offset, AddrVT)),
5920 DAG.getConstant(BytesLeft, SizeVT),
5921 Align, DstSV, DstSVOff + Offset);
5924 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
5929 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
5930 SDValue Chain, SDValue Dst, SDValue Src,
5931 SDValue Size, unsigned Align,
5933 const Value *DstSV, uint64_t DstSVOff,
5934 const Value *SrcSV, uint64_t SrcSVOff) {
5935 // This requires the copy size to be a constant, preferrably
5936 // within a subtarget-specific limit.
5937 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5940 uint64_t SizeVal = ConstantSize->getZExtValue();
5941 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
5944 /// If not DWORD aligned, call the library.
5945 if ((Align & 3) != 0)
5950 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
5953 unsigned UBytes = AVT.getSizeInBits() / 8;
5954 unsigned CountVal = SizeVal / UBytes;
5955 SDValue Count = DAG.getIntPtrConstant(CountVal);
5956 unsigned BytesLeft = SizeVal % UBytes;
5958 SDValue InFlag(0, 0);
5959 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
5962 InFlag = Chain.getValue(1);
5963 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
5966 InFlag = Chain.getValue(1);
5967 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
5970 InFlag = Chain.getValue(1);
5972 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5973 SmallVector<SDValue, 8> Ops;
5974 Ops.push_back(Chain);
5975 Ops.push_back(DAG.getValueType(AVT));
5976 Ops.push_back(InFlag);
5977 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, &Ops[0], Ops.size());
5979 SmallVector<SDValue, 4> Results;
5980 Results.push_back(RepMovs);
5982 // Handle the last 1 - 7 bytes.
5983 unsigned Offset = SizeVal - BytesLeft;
5984 MVT DstVT = Dst.getValueType();
5985 MVT SrcVT = Src.getValueType();
5986 MVT SizeVT = Size.getValueType();
5987 Results.push_back(DAG.getMemcpy(Chain, dl,
5988 DAG.getNode(ISD::ADD, dl, DstVT, Dst,
5989 DAG.getConstant(Offset, DstVT)),
5990 DAG.getNode(ISD::ADD, dl, SrcVT, Src,
5991 DAG.getConstant(Offset, SrcVT)),
5992 DAG.getConstant(BytesLeft, SizeVT),
5993 Align, AlwaysInline,
5994 DstSV, DstSVOff + Offset,
5995 SrcSV, SrcSVOff + Offset));
5998 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5999 &Results[0], Results.size());
6002 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
6003 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6004 DebugLoc dl = Op.getDebugLoc();
6006 if (!Subtarget->is64Bit()) {
6007 // vastart just stores the address of the VarArgsFrameIndex slot into the
6008 // memory location argument.
6009 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6010 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
6014 // gp_offset (0 - 6 * 8)
6015 // fp_offset (48 - 48 + 8 * 16)
6016 // overflow_arg_area (point to parameters coming in memory).
6018 SmallVector<SDValue, 8> MemOps;
6019 SDValue FIN = Op.getOperand(1);
6021 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6022 DAG.getConstant(VarArgsGPOffset, MVT::i32),
6024 MemOps.push_back(Store);
6027 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6028 FIN, DAG.getIntPtrConstant(4));
6029 Store = DAG.getStore(Op.getOperand(0), dl,
6030 DAG.getConstant(VarArgsFPOffset, MVT::i32),
6032 MemOps.push_back(Store);
6034 // Store ptr to overflow_arg_area
6035 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6036 FIN, DAG.getIntPtrConstant(4));
6037 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6038 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0);
6039 MemOps.push_back(Store);
6041 // Store ptr to reg_save_area.
6042 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6043 FIN, DAG.getIntPtrConstant(8));
6044 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
6045 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0);
6046 MemOps.push_back(Store);
6047 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6048 &MemOps[0], MemOps.size());
6051 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
6052 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6053 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6054 SDValue Chain = Op.getOperand(0);
6055 SDValue SrcPtr = Op.getOperand(1);
6056 SDValue SrcSV = Op.getOperand(2);
6058 llvm_report_error("VAArgInst is not yet implemented for x86-64!");
6062 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
6063 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6064 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6065 SDValue Chain = Op.getOperand(0);
6066 SDValue DstPtr = Op.getOperand(1);
6067 SDValue SrcPtr = Op.getOperand(2);
6068 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6069 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6070 DebugLoc dl = Op.getDebugLoc();
6072 return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6073 DAG.getIntPtrConstant(24), 8, false,
6074 DstSV, 0, SrcSV, 0);
6078 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
6079 DebugLoc dl = Op.getDebugLoc();
6080 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6082 default: return SDValue(); // Don't custom lower most intrinsics.
6083 // Comparison intrinsics.
6084 case Intrinsic::x86_sse_comieq_ss:
6085 case Intrinsic::x86_sse_comilt_ss:
6086 case Intrinsic::x86_sse_comile_ss:
6087 case Intrinsic::x86_sse_comigt_ss:
6088 case Intrinsic::x86_sse_comige_ss:
6089 case Intrinsic::x86_sse_comineq_ss:
6090 case Intrinsic::x86_sse_ucomieq_ss:
6091 case Intrinsic::x86_sse_ucomilt_ss:
6092 case Intrinsic::x86_sse_ucomile_ss:
6093 case Intrinsic::x86_sse_ucomigt_ss:
6094 case Intrinsic::x86_sse_ucomige_ss:
6095 case Intrinsic::x86_sse_ucomineq_ss:
6096 case Intrinsic::x86_sse2_comieq_sd:
6097 case Intrinsic::x86_sse2_comilt_sd:
6098 case Intrinsic::x86_sse2_comile_sd:
6099 case Intrinsic::x86_sse2_comigt_sd:
6100 case Intrinsic::x86_sse2_comige_sd:
6101 case Intrinsic::x86_sse2_comineq_sd:
6102 case Intrinsic::x86_sse2_ucomieq_sd:
6103 case Intrinsic::x86_sse2_ucomilt_sd:
6104 case Intrinsic::x86_sse2_ucomile_sd:
6105 case Intrinsic::x86_sse2_ucomigt_sd:
6106 case Intrinsic::x86_sse2_ucomige_sd:
6107 case Intrinsic::x86_sse2_ucomineq_sd: {
6109 ISD::CondCode CC = ISD::SETCC_INVALID;
6112 case Intrinsic::x86_sse_comieq_ss:
6113 case Intrinsic::x86_sse2_comieq_sd:
6117 case Intrinsic::x86_sse_comilt_ss:
6118 case Intrinsic::x86_sse2_comilt_sd:
6122 case Intrinsic::x86_sse_comile_ss:
6123 case Intrinsic::x86_sse2_comile_sd:
6127 case Intrinsic::x86_sse_comigt_ss:
6128 case Intrinsic::x86_sse2_comigt_sd:
6132 case Intrinsic::x86_sse_comige_ss:
6133 case Intrinsic::x86_sse2_comige_sd:
6137 case Intrinsic::x86_sse_comineq_ss:
6138 case Intrinsic::x86_sse2_comineq_sd:
6142 case Intrinsic::x86_sse_ucomieq_ss:
6143 case Intrinsic::x86_sse2_ucomieq_sd:
6144 Opc = X86ISD::UCOMI;
6147 case Intrinsic::x86_sse_ucomilt_ss:
6148 case Intrinsic::x86_sse2_ucomilt_sd:
6149 Opc = X86ISD::UCOMI;
6152 case Intrinsic::x86_sse_ucomile_ss:
6153 case Intrinsic::x86_sse2_ucomile_sd:
6154 Opc = X86ISD::UCOMI;
6157 case Intrinsic::x86_sse_ucomigt_ss:
6158 case Intrinsic::x86_sse2_ucomigt_sd:
6159 Opc = X86ISD::UCOMI;
6162 case Intrinsic::x86_sse_ucomige_ss:
6163 case Intrinsic::x86_sse2_ucomige_sd:
6164 Opc = X86ISD::UCOMI;
6167 case Intrinsic::x86_sse_ucomineq_ss:
6168 case Intrinsic::x86_sse2_ucomineq_sd:
6169 Opc = X86ISD::UCOMI;
6174 SDValue LHS = Op.getOperand(1);
6175 SDValue RHS = Op.getOperand(2);
6176 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6177 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6178 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6179 DAG.getConstant(X86CC, MVT::i8), Cond);
6180 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6183 // Fix vector shift instructions where the last operand is a non-immediate
6185 case Intrinsic::x86_sse2_pslli_w:
6186 case Intrinsic::x86_sse2_pslli_d:
6187 case Intrinsic::x86_sse2_pslli_q:
6188 case Intrinsic::x86_sse2_psrli_w:
6189 case Intrinsic::x86_sse2_psrli_d:
6190 case Intrinsic::x86_sse2_psrli_q:
6191 case Intrinsic::x86_sse2_psrai_w:
6192 case Intrinsic::x86_sse2_psrai_d:
6193 case Intrinsic::x86_mmx_pslli_w:
6194 case Intrinsic::x86_mmx_pslli_d:
6195 case Intrinsic::x86_mmx_pslli_q:
6196 case Intrinsic::x86_mmx_psrli_w:
6197 case Intrinsic::x86_mmx_psrli_d:
6198 case Intrinsic::x86_mmx_psrli_q:
6199 case Intrinsic::x86_mmx_psrai_w:
6200 case Intrinsic::x86_mmx_psrai_d: {
6201 SDValue ShAmt = Op.getOperand(2);
6202 if (isa<ConstantSDNode>(ShAmt))
6205 unsigned NewIntNo = 0;
6206 MVT ShAmtVT = MVT::v4i32;
6208 case Intrinsic::x86_sse2_pslli_w:
6209 NewIntNo = Intrinsic::x86_sse2_psll_w;
6211 case Intrinsic::x86_sse2_pslli_d:
6212 NewIntNo = Intrinsic::x86_sse2_psll_d;
6214 case Intrinsic::x86_sse2_pslli_q:
6215 NewIntNo = Intrinsic::x86_sse2_psll_q;
6217 case Intrinsic::x86_sse2_psrli_w:
6218 NewIntNo = Intrinsic::x86_sse2_psrl_w;
6220 case Intrinsic::x86_sse2_psrli_d:
6221 NewIntNo = Intrinsic::x86_sse2_psrl_d;
6223 case Intrinsic::x86_sse2_psrli_q:
6224 NewIntNo = Intrinsic::x86_sse2_psrl_q;
6226 case Intrinsic::x86_sse2_psrai_w:
6227 NewIntNo = Intrinsic::x86_sse2_psra_w;
6229 case Intrinsic::x86_sse2_psrai_d:
6230 NewIntNo = Intrinsic::x86_sse2_psra_d;
6233 ShAmtVT = MVT::v2i32;
6235 case Intrinsic::x86_mmx_pslli_w:
6236 NewIntNo = Intrinsic::x86_mmx_psll_w;
6238 case Intrinsic::x86_mmx_pslli_d:
6239 NewIntNo = Intrinsic::x86_mmx_psll_d;
6241 case Intrinsic::x86_mmx_pslli_q:
6242 NewIntNo = Intrinsic::x86_mmx_psll_q;
6244 case Intrinsic::x86_mmx_psrli_w:
6245 NewIntNo = Intrinsic::x86_mmx_psrl_w;
6247 case Intrinsic::x86_mmx_psrli_d:
6248 NewIntNo = Intrinsic::x86_mmx_psrl_d;
6250 case Intrinsic::x86_mmx_psrli_q:
6251 NewIntNo = Intrinsic::x86_mmx_psrl_q;
6253 case Intrinsic::x86_mmx_psrai_w:
6254 NewIntNo = Intrinsic::x86_mmx_psra_w;
6256 case Intrinsic::x86_mmx_psrai_d:
6257 NewIntNo = Intrinsic::x86_mmx_psra_d;
6259 default: LLVM_UNREACHABLE("Impossible intrinsic"); // Can't reach here.
6264 MVT VT = Op.getValueType();
6265 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT,
6266 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShAmtVT, ShAmt));
6267 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6268 DAG.getConstant(NewIntNo, MVT::i32),
6269 Op.getOperand(1), ShAmt);
6274 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
6275 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6276 DebugLoc dl = Op.getDebugLoc();
6279 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6281 DAG.getConstant(TD->getPointerSize(),
6282 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6283 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6284 DAG.getNode(ISD::ADD, dl, getPointerTy(),
6289 // Just load the return address.
6290 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6291 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6292 RetAddrFI, NULL, 0);
6295 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
6296 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6297 MFI->setFrameAddressIsTaken(true);
6298 MVT VT = Op.getValueType();
6299 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
6300 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6301 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6302 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6304 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
6308 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6309 SelectionDAG &DAG) {
6310 return DAG.getIntPtrConstant(2*TD->getPointerSize());
6313 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
6315 MachineFunction &MF = DAG.getMachineFunction();
6316 SDValue Chain = Op.getOperand(0);
6317 SDValue Offset = Op.getOperand(1);
6318 SDValue Handler = Op.getOperand(2);
6319 DebugLoc dl = Op.getDebugLoc();
6321 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6323 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6325 SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
6326 DAG.getIntPtrConstant(-TD->getPointerSize()));
6327 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
6328 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0);
6329 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
6330 MF.getRegInfo().addLiveOut(StoreAddrReg);
6332 return DAG.getNode(X86ISD::EH_RETURN, dl,
6334 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6337 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6338 SelectionDAG &DAG) {
6339 SDValue Root = Op.getOperand(0);
6340 SDValue Trmp = Op.getOperand(1); // trampoline
6341 SDValue FPtr = Op.getOperand(2); // nested function
6342 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6343 DebugLoc dl = Op.getDebugLoc();
6345 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6347 const X86InstrInfo *TII =
6348 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
6350 if (Subtarget->is64Bit()) {
6351 SDValue OutChains[6];
6353 // Large code-model.
6355 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
6356 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
6358 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
6359 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
6361 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
6363 // Load the pointer to the nested function into R11.
6364 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
6365 SDValue Addr = Trmp;
6366 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6369 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6370 DAG.getConstant(2, MVT::i64));
6371 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2, false, 2);
6373 // Load the 'nest' parameter value into R10.
6374 // R10 is specified in X86CallingConv.td
6375 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
6376 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6377 DAG.getConstant(10, MVT::i64));
6378 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6379 Addr, TrmpAddr, 10);
6381 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6382 DAG.getConstant(12, MVT::i64));
6383 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12, false, 2);
6385 // Jump to the nested function.
6386 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
6387 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6388 DAG.getConstant(20, MVT::i64));
6389 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6390 Addr, TrmpAddr, 20);
6392 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
6393 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6394 DAG.getConstant(22, MVT::i64));
6395 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
6399 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
6400 return DAG.getMergeValues(Ops, 2, dl);
6402 const Function *Func =
6403 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
6404 unsigned CC = Func->getCallingConv();
6409 assert(0 && "Unsupported calling convention");
6410 case CallingConv::C:
6411 case CallingConv::X86_StdCall: {
6412 // Pass 'nest' parameter in ECX.
6413 // Must be kept in sync with X86CallingConv.td
6416 // Check that ECX wasn't needed by an 'inreg' parameter.
6417 const FunctionType *FTy = Func->getFunctionType();
6418 const AttrListPtr &Attrs = Func->getAttributes();
6420 if (!Attrs.isEmpty() && !Func->isVarArg()) {
6421 unsigned InRegCount = 0;
6424 for (FunctionType::param_iterator I = FTy->param_begin(),
6425 E = FTy->param_end(); I != E; ++I, ++Idx)
6426 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6427 // FIXME: should only count parameters that are lowered to integers.
6428 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6430 if (InRegCount > 2) {
6431 llvm_report_error("Nest register in use - reduce number of inreg parameters!");
6436 case CallingConv::X86_FastCall:
6437 case CallingConv::Fast:
6438 // Pass 'nest' parameter in EAX.
6439 // Must be kept in sync with X86CallingConv.td
6444 SDValue OutChains[4];
6447 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6448 DAG.getConstant(10, MVT::i32));
6449 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
6451 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
6452 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
6453 OutChains[0] = DAG.getStore(Root, dl,
6454 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
6457 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6458 DAG.getConstant(1, MVT::i32));
6459 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1, false, 1);
6461 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
6462 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6463 DAG.getConstant(5, MVT::i32));
6464 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
6465 TrmpAddr, 5, false, 1);
6467 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6468 DAG.getConstant(6, MVT::i32));
6469 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6, false, 1);
6472 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
6473 return DAG.getMergeValues(Ops, 2, dl);
6477 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
6479 The rounding mode is in bits 11:10 of FPSR, and has the following
6486 FLT_ROUNDS, on the other hand, expects the following:
6493 To perform the conversion, we do:
6494 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
6497 MachineFunction &MF = DAG.getMachineFunction();
6498 const TargetMachine &TM = MF.getTarget();
6499 const TargetFrameInfo &TFI = *TM.getFrameInfo();
6500 unsigned StackAlignment = TFI.getStackAlignment();
6501 MVT VT = Op.getValueType();
6502 DebugLoc dl = Op.getDebugLoc();
6504 // Save FP Control Word to stack slot
6505 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
6506 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6508 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
6509 DAG.getEntryNode(), StackSlot);
6511 // Load FP Control Word from stack slot
6512 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0);
6514 // Transform as necessary
6516 DAG.getNode(ISD::SRL, dl, MVT::i16,
6517 DAG.getNode(ISD::AND, dl, MVT::i16,
6518 CWD, DAG.getConstant(0x800, MVT::i16)),
6519 DAG.getConstant(11, MVT::i8));
6521 DAG.getNode(ISD::SRL, dl, MVT::i16,
6522 DAG.getNode(ISD::AND, dl, MVT::i16,
6523 CWD, DAG.getConstant(0x400, MVT::i16)),
6524 DAG.getConstant(9, MVT::i8));
6527 DAG.getNode(ISD::AND, dl, MVT::i16,
6528 DAG.getNode(ISD::ADD, dl, MVT::i16,
6529 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
6530 DAG.getConstant(1, MVT::i16)),
6531 DAG.getConstant(3, MVT::i16));
6534 return DAG.getNode((VT.getSizeInBits() < 16 ?
6535 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6538 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
6539 MVT VT = Op.getValueType();
6541 unsigned NumBits = VT.getSizeInBits();
6542 DebugLoc dl = Op.getDebugLoc();
6544 Op = Op.getOperand(0);
6545 if (VT == MVT::i8) {
6546 // Zero extend to i32 since there is not an i8 bsr.
6548 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6551 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
6552 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6553 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
6555 // If src is zero (i.e. bsr sets ZF), returns NumBits.
6556 SmallVector<SDValue, 4> Ops;
6558 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
6559 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6560 Ops.push_back(Op.getValue(1));
6561 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6563 // Finally xor with NumBits-1.
6564 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
6567 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6571 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
6572 MVT VT = Op.getValueType();
6574 unsigned NumBits = VT.getSizeInBits();
6575 DebugLoc dl = Op.getDebugLoc();
6577 Op = Op.getOperand(0);
6578 if (VT == MVT::i8) {
6580 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6583 // Issue a bsf (scan bits forward) which also sets EFLAGS.
6584 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6585 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
6587 // If src is zero (i.e. bsf sets ZF), returns NumBits.
6588 SmallVector<SDValue, 4> Ops;
6590 Ops.push_back(DAG.getConstant(NumBits, OpVT));
6591 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6592 Ops.push_back(Op.getValue(1));
6593 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6596 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6600 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
6601 MVT VT = Op.getValueType();
6602 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
6603 DebugLoc dl = Op.getDebugLoc();
6605 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
6606 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
6607 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
6608 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
6609 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
6611 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
6612 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
6613 // return AloBlo + AloBhi + AhiBlo;
6615 SDValue A = Op.getOperand(0);
6616 SDValue B = Op.getOperand(1);
6618 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6619 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6620 A, DAG.getConstant(32, MVT::i32));
6621 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6622 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6623 B, DAG.getConstant(32, MVT::i32));
6624 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6625 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6627 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6628 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6630 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6631 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6633 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6634 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6635 AloBhi, DAG.getConstant(32, MVT::i32));
6636 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6637 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6638 AhiBlo, DAG.getConstant(32, MVT::i32));
6639 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
6640 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
6645 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
6646 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
6647 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
6648 // looks for this combo and may remove the "setcc" instruction if the "setcc"
6649 // has only one use.
6650 SDNode *N = Op.getNode();
6651 SDValue LHS = N->getOperand(0);
6652 SDValue RHS = N->getOperand(1);
6653 unsigned BaseOp = 0;
6655 DebugLoc dl = Op.getDebugLoc();
6657 switch (Op.getOpcode()) {
6658 default: assert(0 && "Unknown ovf instruction!");
6660 // A subtract of one will be selected as a INC. Note that INC doesn't
6661 // set CF, so we can't do this for UADDO.
6662 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6663 if (C->getAPIntValue() == 1) {
6664 BaseOp = X86ISD::INC;
6668 BaseOp = X86ISD::ADD;
6672 BaseOp = X86ISD::ADD;
6676 // A subtract of one will be selected as a DEC. Note that DEC doesn't
6677 // set CF, so we can't do this for USUBO.
6678 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6679 if (C->getAPIntValue() == 1) {
6680 BaseOp = X86ISD::DEC;
6684 BaseOp = X86ISD::SUB;
6688 BaseOp = X86ISD::SUB;
6692 BaseOp = X86ISD::SMUL;
6696 BaseOp = X86ISD::UMUL;
6701 // Also sets EFLAGS.
6702 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
6703 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
6706 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
6707 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
6709 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
6713 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
6714 MVT T = Op.getValueType();
6715 DebugLoc dl = Op.getDebugLoc();
6718 switch(T.getSimpleVT()) {
6720 assert(false && "Invalid value type!");
6721 case MVT::i8: Reg = X86::AL; size = 1; break;
6722 case MVT::i16: Reg = X86::AX; size = 2; break;
6723 case MVT::i32: Reg = X86::EAX; size = 4; break;
6725 assert(Subtarget->is64Bit() && "Node not type legal!");
6726 Reg = X86::RAX; size = 8;
6729 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
6730 Op.getOperand(2), SDValue());
6731 SDValue Ops[] = { cpIn.getValue(0),
6734 DAG.getTargetConstant(size, MVT::i8),
6736 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6737 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
6739 DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
6743 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
6744 SelectionDAG &DAG) {
6745 assert(Subtarget->is64Bit() && "Result not type legalized?");
6746 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6747 SDValue TheChain = Op.getOperand(0);
6748 DebugLoc dl = Op.getDebugLoc();
6749 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6750 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
6751 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
6753 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
6754 DAG.getConstant(32, MVT::i8));
6756 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
6759 return DAG.getMergeValues(Ops, 2, dl);
6762 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
6763 SDNode *Node = Op.getNode();
6764 DebugLoc dl = Node->getDebugLoc();
6765 MVT T = Node->getValueType(0);
6766 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
6767 DAG.getConstant(0, T), Node->getOperand(2));
6768 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
6769 cast<AtomicSDNode>(Node)->getMemoryVT(),
6770 Node->getOperand(0),
6771 Node->getOperand(1), negOp,
6772 cast<AtomicSDNode>(Node)->getSrcValue(),
6773 cast<AtomicSDNode>(Node)->getAlignment());
6776 /// LowerOperation - Provide custom lowering hooks for some operations.
6778 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
6779 switch (Op.getOpcode()) {
6780 default: assert(0 && "Should not custom lower this!");
6781 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
6782 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
6783 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6784 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6785 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6786 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6787 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6788 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6789 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6790 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6791 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
6792 case ISD::SHL_PARTS:
6793 case ISD::SRA_PARTS:
6794 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
6795 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
6796 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
6797 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
6798 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
6799 case ISD::FABS: return LowerFABS(Op, DAG);
6800 case ISD::FNEG: return LowerFNEG(Op, DAG);
6801 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6802 case ISD::SETCC: return LowerSETCC(Op, DAG);
6803 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
6804 case ISD::SELECT: return LowerSELECT(Op, DAG);
6805 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
6806 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6807 case ISD::CALL: return LowerCALL(Op, DAG);
6808 case ISD::RET: return LowerRET(Op, DAG);
6809 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
6810 case ISD::VASTART: return LowerVASTART(Op, DAG);
6811 case ISD::VAARG: return LowerVAARG(Op, DAG);
6812 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
6813 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6814 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6815 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6816 case ISD::FRAME_TO_ARGS_OFFSET:
6817 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
6818 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
6819 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
6820 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
6821 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6822 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
6823 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
6824 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
6830 case ISD::UMULO: return LowerXALUO(Op, DAG);
6831 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
6835 void X86TargetLowering::
6836 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
6837 SelectionDAG &DAG, unsigned NewOp) {
6838 MVT T = Node->getValueType(0);
6839 DebugLoc dl = Node->getDebugLoc();
6840 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
6842 SDValue Chain = Node->getOperand(0);
6843 SDValue In1 = Node->getOperand(1);
6844 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6845 Node->getOperand(2), DAG.getIntPtrConstant(0));
6846 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6847 Node->getOperand(2), DAG.getIntPtrConstant(1));
6848 // This is a generalized SDNode, not an AtomicSDNode, so it doesn't
6849 // have a MemOperand. Pass the info through as a normal operand.
6850 SDValue LSI = DAG.getMemOperand(cast<MemSDNode>(Node)->getMemOperand());
6851 SDValue Ops[] = { Chain, In1, In2L, In2H, LSI };
6852 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6853 SDValue Result = DAG.getNode(NewOp, dl, Tys, Ops, 5);
6854 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
6855 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6856 Results.push_back(Result.getValue(2));
6859 /// ReplaceNodeResults - Replace a node with an illegal result type
6860 /// with a new node built out of custom code.
6861 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
6862 SmallVectorImpl<SDValue>&Results,
6863 SelectionDAG &DAG) {
6864 DebugLoc dl = N->getDebugLoc();
6865 switch (N->getOpcode()) {
6867 assert(false && "Do not know how to custom type legalize this operation!");
6869 case ISD::FP_TO_SINT: {
6870 std::pair<SDValue,SDValue> Vals =
6871 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
6872 SDValue FIST = Vals.first, StackSlot = Vals.second;
6873 if (FIST.getNode() != 0) {
6874 MVT VT = N->getValueType(0);
6875 // Return a load from the stack slot.
6876 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0));
6880 case ISD::READCYCLECOUNTER: {
6881 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6882 SDValue TheChain = N->getOperand(0);
6883 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6884 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
6886 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
6888 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
6889 SDValue Ops[] = { eax, edx };
6890 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
6891 Results.push_back(edx.getValue(1));
6894 case ISD::ATOMIC_CMP_SWAP: {
6895 MVT T = N->getValueType(0);
6896 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
6897 SDValue cpInL, cpInH;
6898 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
6899 DAG.getConstant(0, MVT::i32));
6900 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
6901 DAG.getConstant(1, MVT::i32));
6902 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
6903 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
6905 SDValue swapInL, swapInH;
6906 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
6907 DAG.getConstant(0, MVT::i32));
6908 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
6909 DAG.getConstant(1, MVT::i32));
6910 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
6912 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
6913 swapInL.getValue(1));
6914 SDValue Ops[] = { swapInH.getValue(0),
6916 swapInH.getValue(1) };
6917 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6918 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
6919 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
6920 MVT::i32, Result.getValue(1));
6921 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
6922 MVT::i32, cpOutL.getValue(2));
6923 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
6924 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6925 Results.push_back(cpOutH.getValue(1));
6928 case ISD::ATOMIC_LOAD_ADD:
6929 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
6931 case ISD::ATOMIC_LOAD_AND:
6932 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
6934 case ISD::ATOMIC_LOAD_NAND:
6935 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
6937 case ISD::ATOMIC_LOAD_OR:
6938 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
6940 case ISD::ATOMIC_LOAD_SUB:
6941 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
6943 case ISD::ATOMIC_LOAD_XOR:
6944 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
6946 case ISD::ATOMIC_SWAP:
6947 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
6952 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
6954 default: return NULL;
6955 case X86ISD::BSF: return "X86ISD::BSF";
6956 case X86ISD::BSR: return "X86ISD::BSR";
6957 case X86ISD::SHLD: return "X86ISD::SHLD";
6958 case X86ISD::SHRD: return "X86ISD::SHRD";
6959 case X86ISD::FAND: return "X86ISD::FAND";
6960 case X86ISD::FOR: return "X86ISD::FOR";
6961 case X86ISD::FXOR: return "X86ISD::FXOR";
6962 case X86ISD::FSRL: return "X86ISD::FSRL";
6963 case X86ISD::FILD: return "X86ISD::FILD";
6964 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
6965 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
6966 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
6967 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
6968 case X86ISD::FLD: return "X86ISD::FLD";
6969 case X86ISD::FST: return "X86ISD::FST";
6970 case X86ISD::CALL: return "X86ISD::CALL";
6971 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
6972 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
6973 case X86ISD::BT: return "X86ISD::BT";
6974 case X86ISD::CMP: return "X86ISD::CMP";
6975 case X86ISD::COMI: return "X86ISD::COMI";
6976 case X86ISD::UCOMI: return "X86ISD::UCOMI";
6977 case X86ISD::SETCC: return "X86ISD::SETCC";
6978 case X86ISD::CMOV: return "X86ISD::CMOV";
6979 case X86ISD::BRCOND: return "X86ISD::BRCOND";
6980 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
6981 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
6982 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
6983 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
6984 case X86ISD::Wrapper: return "X86ISD::Wrapper";
6985 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
6986 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
6987 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
6988 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
6989 case X86ISD::PINSRB: return "X86ISD::PINSRB";
6990 case X86ISD::PINSRW: return "X86ISD::PINSRW";
6991 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
6992 case X86ISD::FMAX: return "X86ISD::FMAX";
6993 case X86ISD::FMIN: return "X86ISD::FMIN";
6994 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
6995 case X86ISD::FRCP: return "X86ISD::FRCP";
6996 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
6997 case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
6998 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
6999 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
7000 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
7001 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
7002 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
7003 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
7004 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
7005 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
7006 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
7007 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
7008 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
7009 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
7010 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
7011 case X86ISD::VSHL: return "X86ISD::VSHL";
7012 case X86ISD::VSRL: return "X86ISD::VSRL";
7013 case X86ISD::CMPPD: return "X86ISD::CMPPD";
7014 case X86ISD::CMPPS: return "X86ISD::CMPPS";
7015 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
7016 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
7017 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
7018 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
7019 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
7020 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
7021 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
7022 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
7023 case X86ISD::ADD: return "X86ISD::ADD";
7024 case X86ISD::SUB: return "X86ISD::SUB";
7025 case X86ISD::SMUL: return "X86ISD::SMUL";
7026 case X86ISD::UMUL: return "X86ISD::UMUL";
7027 case X86ISD::INC: return "X86ISD::INC";
7028 case X86ISD::DEC: return "X86ISD::DEC";
7029 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
7033 // isLegalAddressingMode - Return true if the addressing mode represented
7034 // by AM is legal for this target, for a load/store of the specified type.
7035 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7036 const Type *Ty) const {
7037 // X86 supports extremely general addressing modes.
7039 // X86 allows a sign-extended 32-bit immediate field as a displacement.
7040 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
7044 // We can only fold this if we don't need an extra load.
7045 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
7047 // If BaseGV requires a register, we cannot also have a BaseReg.
7048 if (Subtarget->GVRequiresRegister(AM.BaseGV, getTargetMachine(), false) &&
7052 // X86-64 only supports addr of globals in small code model.
7053 if (Subtarget->is64Bit()) {
7054 if (getTargetMachine().getCodeModel() != CodeModel::Small)
7056 // If lower 4G is not available, then we must use rip-relative addressing.
7057 if (AM.BaseOffs || AM.Scale > 1)
7068 // These scales always work.
7073 // These scales are formed with basereg+scalereg. Only accept if there is
7078 default: // Other stuff never works.
7086 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7087 if (!Ty1->isInteger() || !Ty2->isInteger())
7089 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7090 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7091 if (NumBits1 <= NumBits2)
7093 return Subtarget->is64Bit() || NumBits1 < 64;
7096 bool X86TargetLowering::isTruncateFree(MVT VT1, MVT VT2) const {
7097 if (!VT1.isInteger() || !VT2.isInteger())
7099 unsigned NumBits1 = VT1.getSizeInBits();
7100 unsigned NumBits2 = VT2.getSizeInBits();
7101 if (NumBits1 <= NumBits2)
7103 return Subtarget->is64Bit() || NumBits1 < 64;
7106 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7107 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7108 return Ty1 == Type::Int32Ty && Ty2 == Type::Int64Ty && Subtarget->is64Bit();
7111 bool X86TargetLowering::isZExtFree(MVT VT1, MVT VT2) const {
7112 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7113 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7116 bool X86TargetLowering::isNarrowingProfitable(MVT VT1, MVT VT2) const {
7117 // i16 instructions are longer (0x66 prefix) and potentially slower.
7118 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7121 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7122 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7123 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7124 /// are assumed to be legal.
7126 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
7128 // Only do shuffles on 128-bit vector types for now.
7129 if (VT.getSizeInBits() == 64)
7132 // FIXME: pshufb, blends, palignr, shifts.
7133 return (VT.getVectorNumElements() == 2 ||
7134 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7135 isMOVLMask(M, VT) ||
7136 isSHUFPMask(M, VT) ||
7137 isPSHUFDMask(M, VT) ||
7138 isPSHUFHWMask(M, VT) ||
7139 isPSHUFLWMask(M, VT) ||
7140 isUNPCKLMask(M, VT) ||
7141 isUNPCKHMask(M, VT) ||
7142 isUNPCKL_v_undef_Mask(M, VT) ||
7143 isUNPCKH_v_undef_Mask(M, VT));
7147 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
7149 unsigned NumElts = VT.getVectorNumElements();
7150 // FIXME: This collection of masks seems suspect.
7153 if (NumElts == 4 && VT.getSizeInBits() == 128) {
7154 return (isMOVLMask(Mask, VT) ||
7155 isCommutedMOVLMask(Mask, VT, true) ||
7156 isSHUFPMask(Mask, VT) ||
7157 isCommutedSHUFPMask(Mask, VT));
7162 //===----------------------------------------------------------------------===//
7163 // X86 Scheduler Hooks
7164 //===----------------------------------------------------------------------===//
7166 // private utility function
7168 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7169 MachineBasicBlock *MBB,
7177 TargetRegisterClass *RC,
7178 bool invSrc) const {
7179 // For the atomic bitwise operator, we generate
7182 // ld t1 = [bitinstr.addr]
7183 // op t2 = t1, [bitinstr.val]
7185 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7187 // fallthrough -->nextMBB
7188 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7189 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7190 MachineFunction::iterator MBBIter = MBB;
7193 /// First build the CFG
7194 MachineFunction *F = MBB->getParent();
7195 MachineBasicBlock *thisMBB = MBB;
7196 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7197 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7198 F->insert(MBBIter, newMBB);
7199 F->insert(MBBIter, nextMBB);
7201 // Move all successors to thisMBB to nextMBB
7202 nextMBB->transferSuccessors(thisMBB);
7204 // Update thisMBB to fall through to newMBB
7205 thisMBB->addSuccessor(newMBB);
7207 // newMBB jumps to itself and fall through to nextMBB
7208 newMBB->addSuccessor(nextMBB);
7209 newMBB->addSuccessor(newMBB);
7211 // Insert instructions into newMBB based on incoming instruction
7212 assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7213 "unexpected number of operands");
7214 DebugLoc dl = bInstr->getDebugLoc();
7215 MachineOperand& destOper = bInstr->getOperand(0);
7216 MachineOperand* argOpers[2 + X86AddrNumOperands];
7217 int numArgs = bInstr->getNumOperands() - 1;
7218 for (int i=0; i < numArgs; ++i)
7219 argOpers[i] = &bInstr->getOperand(i+1);
7221 // x86 address has 4 operands: base, index, scale, and displacement
7222 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7223 int valArgIndx = lastAddrIndx + 1;
7225 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7226 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7227 for (int i=0; i <= lastAddrIndx; ++i)
7228 (*MIB).addOperand(*argOpers[i]);
7230 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7232 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7237 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7238 assert((argOpers[valArgIndx]->isReg() ||
7239 argOpers[valArgIndx]->isImm()) &&
7241 if (argOpers[valArgIndx]->isReg())
7242 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7244 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7246 (*MIB).addOperand(*argOpers[valArgIndx]);
7248 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7251 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7252 for (int i=0; i <= lastAddrIndx; ++i)
7253 (*MIB).addOperand(*argOpers[i]);
7255 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7256 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7258 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7262 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7264 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7268 // private utility function: 64 bit atomics on 32 bit host.
7270 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7271 MachineBasicBlock *MBB,
7276 bool invSrc) const {
7277 // For the atomic bitwise operator, we generate
7278 // thisMBB (instructions are in pairs, except cmpxchg8b)
7279 // ld t1,t2 = [bitinstr.addr]
7281 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7282 // op t5, t6 <- out1, out2, [bitinstr.val]
7283 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
7284 // mov ECX, EBX <- t5, t6
7285 // mov EAX, EDX <- t1, t2
7286 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
7287 // mov t3, t4 <- EAX, EDX
7289 // result in out1, out2
7290 // fallthrough -->nextMBB
7292 const TargetRegisterClass *RC = X86::GR32RegisterClass;
7293 const unsigned LoadOpc = X86::MOV32rm;
7294 const unsigned copyOpc = X86::MOV32rr;
7295 const unsigned NotOpc = X86::NOT32r;
7296 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7297 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7298 MachineFunction::iterator MBBIter = MBB;
7301 /// First build the CFG
7302 MachineFunction *F = MBB->getParent();
7303 MachineBasicBlock *thisMBB = MBB;
7304 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7305 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7306 F->insert(MBBIter, newMBB);
7307 F->insert(MBBIter, nextMBB);
7309 // Move all successors to thisMBB to nextMBB
7310 nextMBB->transferSuccessors(thisMBB);
7312 // Update thisMBB to fall through to newMBB
7313 thisMBB->addSuccessor(newMBB);
7315 // newMBB jumps to itself and fall through to nextMBB
7316 newMBB->addSuccessor(nextMBB);
7317 newMBB->addSuccessor(newMBB);
7319 DebugLoc dl = bInstr->getDebugLoc();
7320 // Insert instructions into newMBB based on incoming instruction
7321 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7322 assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
7323 "unexpected number of operands");
7324 MachineOperand& dest1Oper = bInstr->getOperand(0);
7325 MachineOperand& dest2Oper = bInstr->getOperand(1);
7326 MachineOperand* argOpers[2 + X86AddrNumOperands];
7327 for (int i=0; i < 2 + X86AddrNumOperands; ++i)
7328 argOpers[i] = &bInstr->getOperand(i+2);
7330 // x86 address has 4 operands: base, index, scale, and displacement
7331 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7333 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7334 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
7335 for (int i=0; i <= lastAddrIndx; ++i)
7336 (*MIB).addOperand(*argOpers[i]);
7337 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7338 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
7339 // add 4 to displacement.
7340 for (int i=0; i <= lastAddrIndx-2; ++i)
7341 (*MIB).addOperand(*argOpers[i]);
7342 MachineOperand newOp3 = *(argOpers[3]);
7344 newOp3.setImm(newOp3.getImm()+4);
7346 newOp3.setOffset(newOp3.getOffset()+4);
7347 (*MIB).addOperand(newOp3);
7348 (*MIB).addOperand(*argOpers[lastAddrIndx]);
7350 // t3/4 are defined later, at the bottom of the loop
7351 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
7352 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
7353 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
7354 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
7355 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
7356 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
7358 unsigned tt1 = F->getRegInfo().createVirtualRegister(RC);
7359 unsigned tt2 = F->getRegInfo().createVirtualRegister(RC);
7361 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt1).addReg(t1);
7362 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt2).addReg(t2);
7368 int valArgIndx = lastAddrIndx + 1;
7369 assert((argOpers[valArgIndx]->isReg() ||
7370 argOpers[valArgIndx]->isImm()) &&
7372 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
7373 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
7374 if (argOpers[valArgIndx]->isReg())
7375 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
7377 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
7378 if (regOpcL != X86::MOV32rr)
7380 (*MIB).addOperand(*argOpers[valArgIndx]);
7381 assert(argOpers[valArgIndx + 1]->isReg() ==
7382 argOpers[valArgIndx]->isReg());
7383 assert(argOpers[valArgIndx + 1]->isImm() ==
7384 argOpers[valArgIndx]->isImm());
7385 if (argOpers[valArgIndx + 1]->isReg())
7386 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
7388 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
7389 if (regOpcH != X86::MOV32rr)
7391 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
7393 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
7395 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
7398 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
7400 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
7403 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
7404 for (int i=0; i <= lastAddrIndx; ++i)
7405 (*MIB).addOperand(*argOpers[i]);
7407 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7408 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7410 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
7411 MIB.addReg(X86::EAX);
7412 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
7413 MIB.addReg(X86::EDX);
7416 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7418 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7422 // private utility function
7424 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
7425 MachineBasicBlock *MBB,
7426 unsigned cmovOpc) const {
7427 // For the atomic min/max operator, we generate
7430 // ld t1 = [min/max.addr]
7431 // mov t2 = [min/max.val]
7433 // cmov[cond] t2 = t1
7435 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7437 // fallthrough -->nextMBB
7439 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7440 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7441 MachineFunction::iterator MBBIter = MBB;
7444 /// First build the CFG
7445 MachineFunction *F = MBB->getParent();
7446 MachineBasicBlock *thisMBB = MBB;
7447 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7448 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7449 F->insert(MBBIter, newMBB);
7450 F->insert(MBBIter, nextMBB);
7452 // Move all successors to thisMBB to nextMBB
7453 nextMBB->transferSuccessors(thisMBB);
7455 // Update thisMBB to fall through to newMBB
7456 thisMBB->addSuccessor(newMBB);
7458 // newMBB jumps to newMBB and fall through to nextMBB
7459 newMBB->addSuccessor(nextMBB);
7460 newMBB->addSuccessor(newMBB);
7462 DebugLoc dl = mInstr->getDebugLoc();
7463 // Insert instructions into newMBB based on incoming instruction
7464 assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7465 "unexpected number of operands");
7466 MachineOperand& destOper = mInstr->getOperand(0);
7467 MachineOperand* argOpers[2 + X86AddrNumOperands];
7468 int numArgs = mInstr->getNumOperands() - 1;
7469 for (int i=0; i < numArgs; ++i)
7470 argOpers[i] = &mInstr->getOperand(i+1);
7472 // x86 address has 4 operands: base, index, scale, and displacement
7473 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7474 int valArgIndx = lastAddrIndx + 1;
7476 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7477 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
7478 for (int i=0; i <= lastAddrIndx; ++i)
7479 (*MIB).addOperand(*argOpers[i]);
7481 // We only support register and immediate values
7482 assert((argOpers[valArgIndx]->isReg() ||
7483 argOpers[valArgIndx]->isImm()) &&
7486 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7487 if (argOpers[valArgIndx]->isReg())
7488 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7490 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7491 (*MIB).addOperand(*argOpers[valArgIndx]);
7493 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
7496 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
7501 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7502 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
7506 // Cmp and exchange if none has modified the memory location
7507 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
7508 for (int i=0; i <= lastAddrIndx; ++i)
7509 (*MIB).addOperand(*argOpers[i]);
7511 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7512 (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
7514 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
7515 MIB.addReg(X86::EAX);
7518 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7520 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
7526 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7527 MachineBasicBlock *BB) const {
7528 DebugLoc dl = MI->getDebugLoc();
7529 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7530 switch (MI->getOpcode()) {
7531 default: assert(false && "Unexpected instr type to insert");
7532 case X86::CMOV_V1I64:
7533 case X86::CMOV_FR32:
7534 case X86::CMOV_FR64:
7535 case X86::CMOV_V4F32:
7536 case X86::CMOV_V2F64:
7537 case X86::CMOV_V2I64: {
7538 // To "insert" a SELECT_CC instruction, we actually have to insert the
7539 // diamond control-flow pattern. The incoming instruction knows the
7540 // destination vreg to set, the condition code register to branch on, the
7541 // true/false values to select between, and a branch opcode to use.
7542 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7543 MachineFunction::iterator It = BB;
7549 // cmpTY ccX, r1, r2
7551 // fallthrough --> copy0MBB
7552 MachineBasicBlock *thisMBB = BB;
7553 MachineFunction *F = BB->getParent();
7554 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7555 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7557 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
7558 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
7559 F->insert(It, copy0MBB);
7560 F->insert(It, sinkMBB);
7561 // Update machine-CFG edges by transferring all successors of the current
7562 // block to the new block which will contain the Phi node for the select.
7563 sinkMBB->transferSuccessors(BB);
7565 // Add the true and fallthrough blocks as its successors.
7566 BB->addSuccessor(copy0MBB);
7567 BB->addSuccessor(sinkMBB);
7570 // %FalseValue = ...
7571 // # fallthrough to sinkMBB
7574 // Update machine-CFG edges
7575 BB->addSuccessor(sinkMBB);
7578 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7581 BuildMI(BB, dl, TII->get(X86::PHI), MI->getOperand(0).getReg())
7582 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7583 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7585 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7589 case X86::FP32_TO_INT16_IN_MEM:
7590 case X86::FP32_TO_INT32_IN_MEM:
7591 case X86::FP32_TO_INT64_IN_MEM:
7592 case X86::FP64_TO_INT16_IN_MEM:
7593 case X86::FP64_TO_INT32_IN_MEM:
7594 case X86::FP64_TO_INT64_IN_MEM:
7595 case X86::FP80_TO_INT16_IN_MEM:
7596 case X86::FP80_TO_INT32_IN_MEM:
7597 case X86::FP80_TO_INT64_IN_MEM: {
7598 // Change the floating point control register to use "round towards zero"
7599 // mode when truncating to an integer value.
7600 MachineFunction *F = BB->getParent();
7601 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
7602 addFrameReference(BuildMI(BB, dl, TII->get(X86::FNSTCW16m)), CWFrameIdx);
7604 // Load the old value of the high byte of the control word...
7606 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
7607 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16rm), OldCW),
7610 // Set the high part to be round to zero...
7611 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mi)), CWFrameIdx)
7614 // Reload the modified control word now...
7615 addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7617 // Restore the memory image of control word to original value
7618 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mr)), CWFrameIdx)
7621 // Get the X86 opcode to use.
7623 switch (MI->getOpcode()) {
7624 default: assert(0 && "illegal opcode!");
7625 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
7626 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
7627 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
7628 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
7629 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
7630 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
7631 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
7632 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
7633 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
7637 MachineOperand &Op = MI->getOperand(0);
7639 AM.BaseType = X86AddressMode::RegBase;
7640 AM.Base.Reg = Op.getReg();
7642 AM.BaseType = X86AddressMode::FrameIndexBase;
7643 AM.Base.FrameIndex = Op.getIndex();
7645 Op = MI->getOperand(1);
7647 AM.Scale = Op.getImm();
7648 Op = MI->getOperand(2);
7650 AM.IndexReg = Op.getImm();
7651 Op = MI->getOperand(3);
7652 if (Op.isGlobal()) {
7653 AM.GV = Op.getGlobal();
7655 AM.Disp = Op.getImm();
7657 addFullAddress(BuildMI(BB, dl, TII->get(Opc)), AM)
7658 .addReg(MI->getOperand(X86AddrNumOperands).getReg());
7660 // Reload the original control word now.
7661 addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7663 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7666 case X86::ATOMAND32:
7667 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7668 X86::AND32ri, X86::MOV32rm,
7669 X86::LCMPXCHG32, X86::MOV32rr,
7670 X86::NOT32r, X86::EAX,
7671 X86::GR32RegisterClass);
7673 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
7674 X86::OR32ri, X86::MOV32rm,
7675 X86::LCMPXCHG32, X86::MOV32rr,
7676 X86::NOT32r, X86::EAX,
7677 X86::GR32RegisterClass);
7678 case X86::ATOMXOR32:
7679 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
7680 X86::XOR32ri, X86::MOV32rm,
7681 X86::LCMPXCHG32, X86::MOV32rr,
7682 X86::NOT32r, X86::EAX,
7683 X86::GR32RegisterClass);
7684 case X86::ATOMNAND32:
7685 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7686 X86::AND32ri, X86::MOV32rm,
7687 X86::LCMPXCHG32, X86::MOV32rr,
7688 X86::NOT32r, X86::EAX,
7689 X86::GR32RegisterClass, true);
7690 case X86::ATOMMIN32:
7691 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
7692 case X86::ATOMMAX32:
7693 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
7694 case X86::ATOMUMIN32:
7695 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
7696 case X86::ATOMUMAX32:
7697 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
7699 case X86::ATOMAND16:
7700 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7701 X86::AND16ri, X86::MOV16rm,
7702 X86::LCMPXCHG16, X86::MOV16rr,
7703 X86::NOT16r, X86::AX,
7704 X86::GR16RegisterClass);
7706 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
7707 X86::OR16ri, X86::MOV16rm,
7708 X86::LCMPXCHG16, X86::MOV16rr,
7709 X86::NOT16r, X86::AX,
7710 X86::GR16RegisterClass);
7711 case X86::ATOMXOR16:
7712 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
7713 X86::XOR16ri, X86::MOV16rm,
7714 X86::LCMPXCHG16, X86::MOV16rr,
7715 X86::NOT16r, X86::AX,
7716 X86::GR16RegisterClass);
7717 case X86::ATOMNAND16:
7718 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7719 X86::AND16ri, X86::MOV16rm,
7720 X86::LCMPXCHG16, X86::MOV16rr,
7721 X86::NOT16r, X86::AX,
7722 X86::GR16RegisterClass, true);
7723 case X86::ATOMMIN16:
7724 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
7725 case X86::ATOMMAX16:
7726 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
7727 case X86::ATOMUMIN16:
7728 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
7729 case X86::ATOMUMAX16:
7730 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
7733 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7734 X86::AND8ri, X86::MOV8rm,
7735 X86::LCMPXCHG8, X86::MOV8rr,
7736 X86::NOT8r, X86::AL,
7737 X86::GR8RegisterClass);
7739 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
7740 X86::OR8ri, X86::MOV8rm,
7741 X86::LCMPXCHG8, X86::MOV8rr,
7742 X86::NOT8r, X86::AL,
7743 X86::GR8RegisterClass);
7745 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
7746 X86::XOR8ri, X86::MOV8rm,
7747 X86::LCMPXCHG8, X86::MOV8rr,
7748 X86::NOT8r, X86::AL,
7749 X86::GR8RegisterClass);
7750 case X86::ATOMNAND8:
7751 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7752 X86::AND8ri, X86::MOV8rm,
7753 X86::LCMPXCHG8, X86::MOV8rr,
7754 X86::NOT8r, X86::AL,
7755 X86::GR8RegisterClass, true);
7756 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
7757 // This group is for 64-bit host.
7758 case X86::ATOMAND64:
7759 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7760 X86::AND64ri32, X86::MOV64rm,
7761 X86::LCMPXCHG64, X86::MOV64rr,
7762 X86::NOT64r, X86::RAX,
7763 X86::GR64RegisterClass);
7765 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
7766 X86::OR64ri32, X86::MOV64rm,
7767 X86::LCMPXCHG64, X86::MOV64rr,
7768 X86::NOT64r, X86::RAX,
7769 X86::GR64RegisterClass);
7770 case X86::ATOMXOR64:
7771 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
7772 X86::XOR64ri32, X86::MOV64rm,
7773 X86::LCMPXCHG64, X86::MOV64rr,
7774 X86::NOT64r, X86::RAX,
7775 X86::GR64RegisterClass);
7776 case X86::ATOMNAND64:
7777 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7778 X86::AND64ri32, X86::MOV64rm,
7779 X86::LCMPXCHG64, X86::MOV64rr,
7780 X86::NOT64r, X86::RAX,
7781 X86::GR64RegisterClass, true);
7782 case X86::ATOMMIN64:
7783 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
7784 case X86::ATOMMAX64:
7785 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
7786 case X86::ATOMUMIN64:
7787 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
7788 case X86::ATOMUMAX64:
7789 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
7791 // This group does 64-bit operations on a 32-bit host.
7792 case X86::ATOMAND6432:
7793 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7794 X86::AND32rr, X86::AND32rr,
7795 X86::AND32ri, X86::AND32ri,
7797 case X86::ATOMOR6432:
7798 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7799 X86::OR32rr, X86::OR32rr,
7800 X86::OR32ri, X86::OR32ri,
7802 case X86::ATOMXOR6432:
7803 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7804 X86::XOR32rr, X86::XOR32rr,
7805 X86::XOR32ri, X86::XOR32ri,
7807 case X86::ATOMNAND6432:
7808 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7809 X86::AND32rr, X86::AND32rr,
7810 X86::AND32ri, X86::AND32ri,
7812 case X86::ATOMADD6432:
7813 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7814 X86::ADD32rr, X86::ADC32rr,
7815 X86::ADD32ri, X86::ADC32ri,
7817 case X86::ATOMSUB6432:
7818 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7819 X86::SUB32rr, X86::SBB32rr,
7820 X86::SUB32ri, X86::SBB32ri,
7822 case X86::ATOMSWAP6432:
7823 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7824 X86::MOV32rr, X86::MOV32rr,
7825 X86::MOV32ri, X86::MOV32ri,
7830 //===----------------------------------------------------------------------===//
7831 // X86 Optimization Hooks
7832 //===----------------------------------------------------------------------===//
7834 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
7838 const SelectionDAG &DAG,
7839 unsigned Depth) const {
7840 unsigned Opc = Op.getOpcode();
7841 assert((Opc >= ISD::BUILTIN_OP_END ||
7842 Opc == ISD::INTRINSIC_WO_CHAIN ||
7843 Opc == ISD::INTRINSIC_W_CHAIN ||
7844 Opc == ISD::INTRINSIC_VOID) &&
7845 "Should use MaskedValueIsZero if you don't know whether Op"
7846 " is a target node!");
7848 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
7857 // These nodes' second result is a boolean.
7858 if (Op.getResNo() == 0)
7862 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
7863 Mask.getBitWidth() - 1);
7868 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
7869 /// node is a GlobalAddress + offset.
7870 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
7871 GlobalValue* &GA, int64_t &Offset) const{
7872 if (N->getOpcode() == X86ISD::Wrapper) {
7873 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
7874 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
7875 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
7879 return TargetLowering::isGAPlusOffset(N, GA, Offset);
7882 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
7883 const TargetLowering &TLI) {
7886 if (TLI.isGAPlusOffset(Base, GV, Offset))
7887 return (GV->getAlignment() >= N && (Offset % N) == 0);
7888 // DAG combine handles the stack object case.
7892 static bool EltsFromConsecutiveLoads(ShuffleVectorSDNode *N, unsigned NumElems,
7893 MVT EVT, LoadSDNode *&LDBase,
7894 unsigned &LastLoadedElt,
7895 SelectionDAG &DAG, MachineFrameInfo *MFI,
7896 const TargetLowering &TLI) {
7898 LastLoadedElt = -1U;
7899 for (unsigned i = 0; i < NumElems; ++i) {
7900 if (N->getMaskElt(i) < 0) {
7906 SDValue Elt = DAG.getShuffleScalarElt(N, i);
7907 if (!Elt.getNode() ||
7908 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
7911 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
7913 LDBase = cast<LoadSDNode>(Elt.getNode());
7917 if (Elt.getOpcode() == ISD::UNDEF)
7920 LoadSDNode *LD = cast<LoadSDNode>(Elt);
7921 if (!TLI.isConsecutiveLoad(LD, LDBase, EVT.getSizeInBits()/8, i, MFI))
7928 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
7929 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
7930 /// if the load addresses are consecutive, non-overlapping, and in the right
7931 /// order. In the case of v2i64, it will see if it can rewrite the
7932 /// shuffle to be an appropriate build vector so it can take advantage of
7933 // performBuildVectorCombine.
7934 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
7935 const TargetLowering &TLI) {
7936 DebugLoc dl = N->getDebugLoc();
7937 MVT VT = N->getValueType(0);
7938 MVT EVT = VT.getVectorElementType();
7939 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
7940 unsigned NumElems = VT.getVectorNumElements();
7942 if (VT.getSizeInBits() != 128)
7945 // Try to combine a vector_shuffle into a 128-bit load.
7946 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7947 LoadSDNode *LD = NULL;
7948 unsigned LastLoadedElt;
7949 if (!EltsFromConsecutiveLoads(SVN, NumElems, EVT, LD, LastLoadedElt, DAG,
7953 if (LastLoadedElt == NumElems - 1) {
7954 if (isBaseAlignmentOfN(16, LD->getBasePtr().getNode(), TLI))
7955 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
7956 LD->getSrcValue(), LD->getSrcValueOffset(),
7958 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
7959 LD->getSrcValue(), LD->getSrcValueOffset(),
7960 LD->isVolatile(), LD->getAlignment());
7961 } else if (NumElems == 4 && LastLoadedElt == 1) {
7962 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
7963 SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
7964 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
7965 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
7970 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
7971 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
7972 const X86Subtarget *Subtarget) {
7973 DebugLoc DL = N->getDebugLoc();
7974 SDValue Cond = N->getOperand(0);
7975 // Get the LHS/RHS of the select.
7976 SDValue LHS = N->getOperand(1);
7977 SDValue RHS = N->getOperand(2);
7979 // If we have SSE[12] support, try to form min/max nodes.
7980 if (Subtarget->hasSSE2() &&
7981 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
7982 Cond.getOpcode() == ISD::SETCC) {
7983 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
7985 unsigned Opcode = 0;
7986 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
7989 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
7992 if (!UnsafeFPMath) break;
7994 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
7996 Opcode = X86ISD::FMIN;
7999 case ISD::SETOGT: // (X > Y) ? X : Y -> max
8002 if (!UnsafeFPMath) break;
8004 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
8006 Opcode = X86ISD::FMAX;
8009 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
8012 case ISD::SETOGT: // (X > Y) ? Y : X -> min
8015 if (!UnsafeFPMath) break;
8017 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
8019 Opcode = X86ISD::FMIN;
8022 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
8025 if (!UnsafeFPMath) break;
8027 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
8029 Opcode = X86ISD::FMAX;
8035 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
8038 // If this is a select between two integer constants, try to do some
8040 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
8041 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
8042 // Don't do this for crazy integer types.
8043 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
8044 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
8045 // so that TrueC (the true value) is larger than FalseC.
8046 bool NeedsCondInvert = false;
8048 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
8049 // Efficiently invertible.
8050 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
8051 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
8052 isa<ConstantSDNode>(Cond.getOperand(1))))) {
8053 NeedsCondInvert = true;
8054 std::swap(TrueC, FalseC);
8057 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
8058 if (FalseC->getAPIntValue() == 0 &&
8059 TrueC->getAPIntValue().isPowerOf2()) {
8060 if (NeedsCondInvert) // Invert the condition if needed.
8061 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8062 DAG.getConstant(1, Cond.getValueType()));
8064 // Zero extend the condition if needed.
8065 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
8067 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8068 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
8069 DAG.getConstant(ShAmt, MVT::i8));
8072 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
8073 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8074 if (NeedsCondInvert) // Invert the condition if needed.
8075 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8076 DAG.getConstant(1, Cond.getValueType()));
8078 // Zero extend the condition if needed.
8079 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8080 FalseC->getValueType(0), Cond);
8081 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8082 SDValue(FalseC, 0));
8085 // Optimize cases that will turn into an LEA instruction. This requires
8086 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8087 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8088 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8089 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8091 bool isFastMultiplier = false;
8093 switch ((unsigned char)Diff) {
8095 case 1: // result = add base, cond
8096 case 2: // result = lea base( , cond*2)
8097 case 3: // result = lea base(cond, cond*2)
8098 case 4: // result = lea base( , cond*4)
8099 case 5: // result = lea base(cond, cond*4)
8100 case 8: // result = lea base( , cond*8)
8101 case 9: // result = lea base(cond, cond*8)
8102 isFastMultiplier = true;
8107 if (isFastMultiplier) {
8108 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8109 if (NeedsCondInvert) // Invert the condition if needed.
8110 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8111 DAG.getConstant(1, Cond.getValueType()));
8113 // Zero extend the condition if needed.
8114 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8116 // Scale the condition by the difference.
8118 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8119 DAG.getConstant(Diff, Cond.getValueType()));
8121 // Add the base if non-zero.
8122 if (FalseC->getAPIntValue() != 0)
8123 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8124 SDValue(FalseC, 0));
8134 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
8135 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
8136 TargetLowering::DAGCombinerInfo &DCI) {
8137 DebugLoc DL = N->getDebugLoc();
8139 // If the flag operand isn't dead, don't touch this CMOV.
8140 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
8143 // If this is a select between two integer constants, try to do some
8144 // optimizations. Note that the operands are ordered the opposite of SELECT
8146 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
8147 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8148 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
8149 // larger than FalseC (the false value).
8150 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
8152 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
8153 CC = X86::GetOppositeBranchCondition(CC);
8154 std::swap(TrueC, FalseC);
8157 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
8158 // This is efficient for any integer data type (including i8/i16) and
8160 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
8161 SDValue Cond = N->getOperand(3);
8162 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8163 DAG.getConstant(CC, MVT::i8), Cond);
8165 // Zero extend the condition if needed.
8166 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
8168 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8169 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
8170 DAG.getConstant(ShAmt, MVT::i8));
8171 if (N->getNumValues() == 2) // Dead flag value?
8172 return DCI.CombineTo(N, Cond, SDValue());
8176 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
8177 // for any integer data type, including i8/i16.
8178 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8179 SDValue Cond = N->getOperand(3);
8180 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8181 DAG.getConstant(CC, MVT::i8), Cond);
8183 // Zero extend the condition if needed.
8184 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8185 FalseC->getValueType(0), Cond);
8186 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8187 SDValue(FalseC, 0));
8189 if (N->getNumValues() == 2) // Dead flag value?
8190 return DCI.CombineTo(N, Cond, SDValue());
8194 // Optimize cases that will turn into an LEA instruction. This requires
8195 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8196 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8197 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8198 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8200 bool isFastMultiplier = false;
8202 switch ((unsigned char)Diff) {
8204 case 1: // result = add base, cond
8205 case 2: // result = lea base( , cond*2)
8206 case 3: // result = lea base(cond, cond*2)
8207 case 4: // result = lea base( , cond*4)
8208 case 5: // result = lea base(cond, cond*4)
8209 case 8: // result = lea base( , cond*8)
8210 case 9: // result = lea base(cond, cond*8)
8211 isFastMultiplier = true;
8216 if (isFastMultiplier) {
8217 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8218 SDValue Cond = N->getOperand(3);
8219 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8220 DAG.getConstant(CC, MVT::i8), Cond);
8221 // Zero extend the condition if needed.
8222 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8224 // Scale the condition by the difference.
8226 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8227 DAG.getConstant(Diff, Cond.getValueType()));
8229 // Add the base if non-zero.
8230 if (FalseC->getAPIntValue() != 0)
8231 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8232 SDValue(FalseC, 0));
8233 if (N->getNumValues() == 2) // Dead flag value?
8234 return DCI.CombineTo(N, Cond, SDValue());
8244 /// PerformMulCombine - Optimize a single multiply with constant into two
8245 /// in order to implement it with two cheaper instructions, e.g.
8246 /// LEA + SHL, LEA + LEA.
8247 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
8248 TargetLowering::DAGCombinerInfo &DCI) {
8249 if (DAG.getMachineFunction().
8250 getFunction()->hasFnAttr(Attribute::OptimizeForSize))
8253 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8256 MVT VT = N->getValueType(0);
8260 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8263 uint64_t MulAmt = C->getZExtValue();
8264 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
8267 uint64_t MulAmt1 = 0;
8268 uint64_t MulAmt2 = 0;
8269 if ((MulAmt % 9) == 0) {
8271 MulAmt2 = MulAmt / 9;
8272 } else if ((MulAmt % 5) == 0) {
8274 MulAmt2 = MulAmt / 5;
8275 } else if ((MulAmt % 3) == 0) {
8277 MulAmt2 = MulAmt / 3;
8280 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
8281 DebugLoc DL = N->getDebugLoc();
8283 if (isPowerOf2_64(MulAmt2) &&
8284 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
8285 // If second multiplifer is pow2, issue it first. We want the multiply by
8286 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
8288 std::swap(MulAmt1, MulAmt2);
8291 if (isPowerOf2_64(MulAmt1))
8292 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
8293 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
8295 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
8296 DAG.getConstant(MulAmt1, VT));
8298 if (isPowerOf2_64(MulAmt2))
8299 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
8300 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
8302 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
8303 DAG.getConstant(MulAmt2, VT));
8305 // Do not add new nodes to DAG combiner worklist.
8306 DCI.CombineTo(N, NewMul, false);
8312 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
8314 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
8315 const X86Subtarget *Subtarget) {
8316 // On X86 with SSE2 support, we can transform this to a vector shift if
8317 // all elements are shifted by the same amount. We can't do this in legalize
8318 // because the a constant vector is typically transformed to a constant pool
8319 // so we have no knowledge of the shift amount.
8320 if (!Subtarget->hasSSE2())
8323 MVT VT = N->getValueType(0);
8324 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
8327 SDValue ShAmtOp = N->getOperand(1);
8328 MVT EltVT = VT.getVectorElementType();
8329 DebugLoc DL = N->getDebugLoc();
8331 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
8332 unsigned NumElts = VT.getVectorNumElements();
8334 for (; i != NumElts; ++i) {
8335 SDValue Arg = ShAmtOp.getOperand(i);
8336 if (Arg.getOpcode() == ISD::UNDEF) continue;
8340 for (; i != NumElts; ++i) {
8341 SDValue Arg = ShAmtOp.getOperand(i);
8342 if (Arg.getOpcode() == ISD::UNDEF) continue;
8343 if (Arg != BaseShAmt) {
8347 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
8348 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
8349 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
8350 DAG.getIntPtrConstant(0));
8354 if (EltVT.bitsGT(MVT::i32))
8355 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
8356 else if (EltVT.bitsLT(MVT::i32))
8357 BaseShAmt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, BaseShAmt);
8359 // The shift amount is identical so we can do a vector shift.
8360 SDValue ValOp = N->getOperand(0);
8361 switch (N->getOpcode()) {
8363 assert(0 && "Unknown shift opcode!");
8366 if (VT == MVT::v2i64)
8367 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8368 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8370 if (VT == MVT::v4i32)
8371 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8372 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8374 if (VT == MVT::v8i16)
8375 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8376 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8380 if (VT == MVT::v4i32)
8381 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8382 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8384 if (VT == MVT::v8i16)
8385 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8386 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8390 if (VT == MVT::v2i64)
8391 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8392 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8394 if (VT == MVT::v4i32)
8395 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8396 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8398 if (VT == MVT::v8i16)
8399 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8400 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8407 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
8408 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
8409 const X86Subtarget *Subtarget) {
8410 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
8411 // the FP state in cases where an emms may be missing.
8412 // A preferable solution to the general problem is to figure out the right
8413 // places to insert EMMS. This qualifies as a quick hack.
8415 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
8416 StoreSDNode *St = cast<StoreSDNode>(N);
8417 MVT VT = St->getValue().getValueType();
8418 if (VT.getSizeInBits() != 64)
8421 const Function *F = DAG.getMachineFunction().getFunction();
8422 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
8423 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
8424 && Subtarget->hasSSE2();
8425 if ((VT.isVector() ||
8426 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
8427 isa<LoadSDNode>(St->getValue()) &&
8428 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
8429 St->getChain().hasOneUse() && !St->isVolatile()) {
8430 SDNode* LdVal = St->getValue().getNode();
8432 int TokenFactorIndex = -1;
8433 SmallVector<SDValue, 8> Ops;
8434 SDNode* ChainVal = St->getChain().getNode();
8435 // Must be a store of a load. We currently handle two cases: the load
8436 // is a direct child, and it's under an intervening TokenFactor. It is
8437 // possible to dig deeper under nested TokenFactors.
8438 if (ChainVal == LdVal)
8439 Ld = cast<LoadSDNode>(St->getChain());
8440 else if (St->getValue().hasOneUse() &&
8441 ChainVal->getOpcode() == ISD::TokenFactor) {
8442 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
8443 if (ChainVal->getOperand(i).getNode() == LdVal) {
8444 TokenFactorIndex = i;
8445 Ld = cast<LoadSDNode>(St->getValue());
8447 Ops.push_back(ChainVal->getOperand(i));
8451 if (!Ld || !ISD::isNormalLoad(Ld))
8454 // If this is not the MMX case, i.e. we are just turning i64 load/store
8455 // into f64 load/store, avoid the transformation if there are multiple
8456 // uses of the loaded value.
8457 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
8460 DebugLoc LdDL = Ld->getDebugLoc();
8461 DebugLoc StDL = N->getDebugLoc();
8462 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
8463 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
8465 if (Subtarget->is64Bit() || F64IsLegal) {
8466 MVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
8467 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
8468 Ld->getBasePtr(), Ld->getSrcValue(),
8469 Ld->getSrcValueOffset(), Ld->isVolatile(),
8470 Ld->getAlignment());
8471 SDValue NewChain = NewLd.getValue(1);
8472 if (TokenFactorIndex != -1) {
8473 Ops.push_back(NewChain);
8474 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
8477 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
8478 St->getSrcValue(), St->getSrcValueOffset(),
8479 St->isVolatile(), St->getAlignment());
8482 // Otherwise, lower to two pairs of 32-bit loads / stores.
8483 SDValue LoAddr = Ld->getBasePtr();
8484 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
8485 DAG.getConstant(4, MVT::i32));
8487 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
8488 Ld->getSrcValue(), Ld->getSrcValueOffset(),
8489 Ld->isVolatile(), Ld->getAlignment());
8490 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
8491 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
8493 MinAlign(Ld->getAlignment(), 4));
8495 SDValue NewChain = LoLd.getValue(1);
8496 if (TokenFactorIndex != -1) {
8497 Ops.push_back(LoLd);
8498 Ops.push_back(HiLd);
8499 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
8503 LoAddr = St->getBasePtr();
8504 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
8505 DAG.getConstant(4, MVT::i32));
8507 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
8508 St->getSrcValue(), St->getSrcValueOffset(),
8509 St->isVolatile(), St->getAlignment());
8510 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
8512 St->getSrcValueOffset() + 4,
8514 MinAlign(St->getAlignment(), 4));
8515 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
8520 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
8521 /// X86ISD::FXOR nodes.
8522 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
8523 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
8524 // F[X]OR(0.0, x) -> x
8525 // F[X]OR(x, 0.0) -> x
8526 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8527 if (C->getValueAPF().isPosZero())
8528 return N->getOperand(1);
8529 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8530 if (C->getValueAPF().isPosZero())
8531 return N->getOperand(0);
8535 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
8536 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
8537 // FAND(0.0, x) -> 0.0
8538 // FAND(x, 0.0) -> 0.0
8539 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8540 if (C->getValueAPF().isPosZero())
8541 return N->getOperand(0);
8542 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8543 if (C->getValueAPF().isPosZero())
8544 return N->getOperand(1);
8548 static SDValue PerformBTCombine(SDNode *N,
8550 TargetLowering::DAGCombinerInfo &DCI) {
8551 // BT ignores high bits in the bit index operand.
8552 SDValue Op1 = N->getOperand(1);
8553 if (Op1.hasOneUse()) {
8554 unsigned BitWidth = Op1.getValueSizeInBits();
8555 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
8556 APInt KnownZero, KnownOne;
8557 TargetLowering::TargetLoweringOpt TLO(DAG);
8558 TargetLowering &TLI = DAG.getTargetLoweringInfo();
8559 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
8560 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
8561 DCI.CommitTargetLoweringOpt(TLO);
8566 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
8567 SDValue Op = N->getOperand(0);
8568 if (Op.getOpcode() == ISD::BIT_CONVERT)
8569 Op = Op.getOperand(0);
8570 MVT VT = N->getValueType(0), OpVT = Op.getValueType();
8571 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
8572 VT.getVectorElementType().getSizeInBits() ==
8573 OpVT.getVectorElementType().getSizeInBits()) {
8574 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
8579 // On X86 and X86-64, atomic operations are lowered to locked instructions.
8580 // Locked instructions, in turn, have implicit fence semantics (all memory
8581 // operations are flushed before issuing the locked instruction, and the
8582 // are not buffered), so we can fold away the common pattern of
8583 // fence-atomic-fence.
8584 static SDValue PerformMEMBARRIERCombine(SDNode* N, SelectionDAG &DAG) {
8585 SDValue atomic = N->getOperand(0);
8586 switch (atomic.getOpcode()) {
8587 case ISD::ATOMIC_CMP_SWAP:
8588 case ISD::ATOMIC_SWAP:
8589 case ISD::ATOMIC_LOAD_ADD:
8590 case ISD::ATOMIC_LOAD_SUB:
8591 case ISD::ATOMIC_LOAD_AND:
8592 case ISD::ATOMIC_LOAD_OR:
8593 case ISD::ATOMIC_LOAD_XOR:
8594 case ISD::ATOMIC_LOAD_NAND:
8595 case ISD::ATOMIC_LOAD_MIN:
8596 case ISD::ATOMIC_LOAD_MAX:
8597 case ISD::ATOMIC_LOAD_UMIN:
8598 case ISD::ATOMIC_LOAD_UMAX:
8604 SDValue fence = atomic.getOperand(0);
8605 if (fence.getOpcode() != ISD::MEMBARRIER)
8608 switch (atomic.getOpcode()) {
8609 case ISD::ATOMIC_CMP_SWAP:
8610 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
8611 atomic.getOperand(1), atomic.getOperand(2),
8612 atomic.getOperand(3));
8613 case ISD::ATOMIC_SWAP:
8614 case ISD::ATOMIC_LOAD_ADD:
8615 case ISD::ATOMIC_LOAD_SUB:
8616 case ISD::ATOMIC_LOAD_AND:
8617 case ISD::ATOMIC_LOAD_OR:
8618 case ISD::ATOMIC_LOAD_XOR:
8619 case ISD::ATOMIC_LOAD_NAND:
8620 case ISD::ATOMIC_LOAD_MIN:
8621 case ISD::ATOMIC_LOAD_MAX:
8622 case ISD::ATOMIC_LOAD_UMIN:
8623 case ISD::ATOMIC_LOAD_UMAX:
8624 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
8625 atomic.getOperand(1), atomic.getOperand(2));
8631 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
8632 DAGCombinerInfo &DCI) const {
8633 SelectionDAG &DAG = DCI.DAG;
8634 switch (N->getOpcode()) {
8636 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
8637 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
8638 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
8639 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
8642 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
8643 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
8645 case X86ISD::FOR: return PerformFORCombine(N, DAG);
8646 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
8647 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
8648 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
8649 case ISD::MEMBARRIER: return PerformMEMBARRIERCombine(N, DAG);
8655 //===----------------------------------------------------------------------===//
8656 // X86 Inline Assembly Support
8657 //===----------------------------------------------------------------------===//
8659 /// getConstraintType - Given a constraint letter, return the type of
8660 /// constraint it is for this target.
8661 X86TargetLowering::ConstraintType
8662 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
8663 if (Constraint.size() == 1) {
8664 switch (Constraint[0]) {
8676 return C_RegisterClass;
8684 return TargetLowering::getConstraintType(Constraint);
8687 /// LowerXConstraint - try to replace an X constraint, which matches anything,
8688 /// with another that has more specific requirements based on the type of the
8689 /// corresponding operand.
8690 const char *X86TargetLowering::
8691 LowerXConstraint(MVT ConstraintVT) const {
8692 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
8693 // 'f' like normal targets.
8694 if (ConstraintVT.isFloatingPoint()) {
8695 if (Subtarget->hasSSE2())
8697 if (Subtarget->hasSSE1())
8701 return TargetLowering::LowerXConstraint(ConstraintVT);
8704 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8705 /// vector. If it is invalid, don't add anything to Ops.
8706 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8709 std::vector<SDValue>&Ops,
8710 SelectionDAG &DAG) const {
8711 SDValue Result(0, 0);
8713 switch (Constraint) {
8716 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8717 if (C->getZExtValue() <= 31) {
8718 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8724 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8725 if (C->getZExtValue() <= 63) {
8726 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8732 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8733 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
8734 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8740 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8741 if (C->getZExtValue() <= 255) {
8742 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8748 // 32-bit signed value
8749 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8750 const ConstantInt *CI = C->getConstantIntValue();
8751 if (CI->isValueValidForType(Type::Int32Ty, C->getSExtValue())) {
8752 // Widen to 64 bits here to get it sign extended.
8753 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
8756 // FIXME gcc accepts some relocatable values here too, but only in certain
8757 // memory models; it's complicated.
8762 // 32-bit unsigned value
8763 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8764 const ConstantInt *CI = C->getConstantIntValue();
8765 if (CI->isValueValidForType(Type::Int32Ty, C->getZExtValue())) {
8766 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8770 // FIXME gcc accepts some relocatable values here too, but only in certain
8771 // memory models; it's complicated.
8775 // Literal immediates are always ok.
8776 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
8777 // Widen to 64 bits here to get it sign extended.
8778 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
8782 // If we are in non-pic codegen mode, we allow the address of a global (with
8783 // an optional displacement) to be used with 'i'.
8784 GlobalAddressSDNode *GA = 0;
8787 // Match either (GA), (GA+C), (GA+C1+C2), etc.
8789 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
8790 Offset += GA->getOffset();
8792 } else if (Op.getOpcode() == ISD::ADD) {
8793 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8794 Offset += C->getZExtValue();
8795 Op = Op.getOperand(0);
8798 } else if (Op.getOpcode() == ISD::SUB) {
8799 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8800 Offset += -C->getZExtValue();
8801 Op = Op.getOperand(0);
8806 // Otherwise, this isn't something we can handle, reject it.
8809 // If we require an extra load to get this address, as in PIC mode, we
8811 if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(),
8812 getTargetMachine(), false))
8816 Op = LowerGlobalAddress(GA->getGlobal(), Op.getDebugLoc(), Offset, DAG);
8818 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
8825 if (Result.getNode()) {
8826 Ops.push_back(Result);
8829 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
8833 std::vector<unsigned> X86TargetLowering::
8834 getRegClassForInlineAsmConstraint(const std::string &Constraint,
8836 if (Constraint.size() == 1) {
8837 // FIXME: not handling fp-stack yet!
8838 switch (Constraint[0]) { // GCC X86 Constraint Letters
8839 default: break; // Unknown constraint letter
8840 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
8843 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
8844 else if (VT == MVT::i16)
8845 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
8846 else if (VT == MVT::i8)
8847 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
8848 else if (VT == MVT::i64)
8849 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
8854 return std::vector<unsigned>();
8857 std::pair<unsigned, const TargetRegisterClass*>
8858 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8860 // First, see if this is a constraint that directly corresponds to an LLVM
8862 if (Constraint.size() == 1) {
8863 // GCC Constraint Letters
8864 switch (Constraint[0]) {
8866 case 'r': // GENERAL_REGS
8867 case 'R': // LEGACY_REGS
8868 case 'l': // INDEX_REGS
8870 return std::make_pair(0U, X86::GR8RegisterClass);
8872 return std::make_pair(0U, X86::GR16RegisterClass);
8873 if (VT == MVT::i32 || !Subtarget->is64Bit())
8874 return std::make_pair(0U, X86::GR32RegisterClass);
8875 return std::make_pair(0U, X86::GR64RegisterClass);
8876 case 'f': // FP Stack registers.
8877 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
8878 // value to the correct fpstack register class.
8879 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
8880 return std::make_pair(0U, X86::RFP32RegisterClass);
8881 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
8882 return std::make_pair(0U, X86::RFP64RegisterClass);
8883 return std::make_pair(0U, X86::RFP80RegisterClass);
8884 case 'y': // MMX_REGS if MMX allowed.
8885 if (!Subtarget->hasMMX()) break;
8886 return std::make_pair(0U, X86::VR64RegisterClass);
8887 case 'Y': // SSE_REGS if SSE2 allowed
8888 if (!Subtarget->hasSSE2()) break;
8890 case 'x': // SSE_REGS if SSE1 allowed
8891 if (!Subtarget->hasSSE1()) break;
8893 switch (VT.getSimpleVT()) {
8895 // Scalar SSE types.
8898 return std::make_pair(0U, X86::FR32RegisterClass);
8901 return std::make_pair(0U, X86::FR64RegisterClass);
8909 return std::make_pair(0U, X86::VR128RegisterClass);
8915 // Use the default implementation in TargetLowering to convert the register
8916 // constraint into a member of a register class.
8917 std::pair<unsigned, const TargetRegisterClass*> Res;
8918 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8920 // Not found as a standard register?
8921 if (Res.second == 0) {
8922 // GCC calls "st(0)" just plain "st".
8923 if (StringsEqualNoCase("{st}", Constraint)) {
8924 Res.first = X86::ST0;
8925 Res.second = X86::RFP80RegisterClass;
8927 // 'A' means EAX + EDX.
8928 if (Constraint == "A") {
8929 Res.first = X86::EAX;
8930 Res.second = X86::GRADRegisterClass;
8935 // Otherwise, check to see if this is a register class of the wrong value
8936 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
8937 // turn into {ax},{dx}.
8938 if (Res.second->hasType(VT))
8939 return Res; // Correct type already, nothing to do.
8941 // All of the single-register GCC register classes map their values onto
8942 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
8943 // really want an 8-bit or 32-bit register, map to the appropriate register
8944 // class and return the appropriate register.
8945 if (Res.second == X86::GR16RegisterClass) {
8946 if (VT == MVT::i8) {
8947 unsigned DestReg = 0;
8948 switch (Res.first) {
8950 case X86::AX: DestReg = X86::AL; break;
8951 case X86::DX: DestReg = X86::DL; break;
8952 case X86::CX: DestReg = X86::CL; break;
8953 case X86::BX: DestReg = X86::BL; break;
8956 Res.first = DestReg;
8957 Res.second = X86::GR8RegisterClass;
8959 } else if (VT == MVT::i32) {
8960 unsigned DestReg = 0;
8961 switch (Res.first) {
8963 case X86::AX: DestReg = X86::EAX; break;
8964 case X86::DX: DestReg = X86::EDX; break;
8965 case X86::CX: DestReg = X86::ECX; break;
8966 case X86::BX: DestReg = X86::EBX; break;
8967 case X86::SI: DestReg = X86::ESI; break;
8968 case X86::DI: DestReg = X86::EDI; break;
8969 case X86::BP: DestReg = X86::EBP; break;
8970 case X86::SP: DestReg = X86::ESP; break;
8973 Res.first = DestReg;
8974 Res.second = X86::GR32RegisterClass;
8976 } else if (VT == MVT::i64) {
8977 unsigned DestReg = 0;
8978 switch (Res.first) {
8980 case X86::AX: DestReg = X86::RAX; break;
8981 case X86::DX: DestReg = X86::RDX; break;
8982 case X86::CX: DestReg = X86::RCX; break;
8983 case X86::BX: DestReg = X86::RBX; break;
8984 case X86::SI: DestReg = X86::RSI; break;
8985 case X86::DI: DestReg = X86::RDI; break;
8986 case X86::BP: DestReg = X86::RBP; break;
8987 case X86::SP: DestReg = X86::RSP; break;
8990 Res.first = DestReg;
8991 Res.second = X86::GR64RegisterClass;
8994 } else if (Res.second == X86::FR32RegisterClass ||
8995 Res.second == X86::FR64RegisterClass ||
8996 Res.second == X86::VR128RegisterClass) {
8997 // Handle references to XMM physical registers that got mapped into the
8998 // wrong class. This can happen with constraints like {xmm0} where the
8999 // target independent register mapper will just pick the first match it can
9000 // find, ignoring the required type.
9002 Res.second = X86::FR32RegisterClass;
9003 else if (VT == MVT::f64)
9004 Res.second = X86::FR64RegisterClass;
9005 else if (X86::VR128RegisterClass->hasType(VT))
9006 Res.second = X86::VR128RegisterClass;
9012 //===----------------------------------------------------------------------===//
9013 // X86 Widen vector type
9014 //===----------------------------------------------------------------------===//
9016 /// getWidenVectorType: given a vector type, returns the type to widen
9017 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
9018 /// If there is no vector type that we want to widen to, returns MVT::Other
9019 /// When and where to widen is target dependent based on the cost of
9020 /// scalarizing vs using the wider vector type.
9022 MVT X86TargetLowering::getWidenVectorType(MVT VT) const {
9023 assert(VT.isVector());
9024 if (isTypeLegal(VT))
9027 // TODO: In computeRegisterProperty, we can compute the list of legal vector
9028 // type based on element type. This would speed up our search (though
9029 // it may not be worth it since the size of the list is relatively
9031 MVT EltVT = VT.getVectorElementType();
9032 unsigned NElts = VT.getVectorNumElements();
9034 // On X86, it make sense to widen any vector wider than 1
9038 for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
9039 nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
9040 MVT SVT = (MVT::SimpleValueType)nVT;
9042 if (isTypeLegal(SVT) &&
9043 SVT.getVectorElementType() == EltVT &&
9044 SVT.getVectorNumElements() > NElts)