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/GlobalVariable.h"
23 #include "llvm/Function.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/ADT/BitVector.h"
26 #include "llvm/ADT/VectorExtras.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineModuleInfo.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/PseudoSourceValue.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Target/TargetOptions.h"
36 #include "llvm/ADT/SmallSet.h"
37 #include "llvm/ADT/StringExtras.h"
38 #include "llvm/Support/CommandLine.h"
42 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
44 // Forward declarations.
45 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
48 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
49 : TargetLowering(TM) {
50 Subtarget = &TM.getSubtarget<X86Subtarget>();
51 X86ScalarSSEf64 = Subtarget->hasSSE2();
52 X86ScalarSSEf32 = Subtarget->hasSSE1();
53 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
55 RegInfo = TM.getRegisterInfo();
58 // Set up the TargetLowering object.
60 // X86 is weird, it always uses i8 for shift amounts and setcc results.
61 setShiftAmountType(MVT::i8);
62 setBooleanContents(ZeroOrOneBooleanContent);
63 setSchedulingPreference(SchedulingForRegPressure);
64 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
65 setStackPointerRegisterToSaveRestore(X86StackPtr);
67 if (Subtarget->isTargetDarwin()) {
68 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
69 setUseUnderscoreSetJmp(false);
70 setUseUnderscoreLongJmp(false);
71 } else if (Subtarget->isTargetMingw()) {
72 // MS runtime is weird: it exports _setjmp, but longjmp!
73 setUseUnderscoreSetJmp(true);
74 setUseUnderscoreLongJmp(false);
76 setUseUnderscoreSetJmp(true);
77 setUseUnderscoreLongJmp(true);
80 // Set up the register classes.
81 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
82 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
83 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
84 if (Subtarget->is64Bit())
85 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
87 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
89 // We don't accept any truncstore of integer registers.
90 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
91 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
92 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
93 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
94 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
95 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
97 // SETOEQ and SETUNE require checking two conditions.
98 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
99 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
100 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
101 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
102 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
103 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
105 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
107 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
108 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
109 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
111 if (Subtarget->is64Bit()) {
112 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
113 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
114 } else if (!UseSoftFloat) {
115 if (X86ScalarSSEf64) {
116 // We have an impenetrably clever algorithm for ui64->double only.
117 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
119 // We have an algorithm for SSE2, and we turn this into a 64-bit
120 // FILD for other targets.
121 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
124 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
126 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
127 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
130 // SSE has no i16 to fp conversion, only i32
131 if (X86ScalarSSEf32) {
132 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
133 // f32 and f64 cases are Legal, f80 case is not
134 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
136 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
137 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
140 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
141 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
144 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
145 // are Legal, f80 is custom lowered.
146 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
147 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
149 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
151 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
152 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
154 if (X86ScalarSSEf32) {
155 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
156 // f32 and f64 cases are Legal, f80 case is not
157 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
159 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
160 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
163 // Handle FP_TO_UINT by promoting the destination to a larger signed
165 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
166 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
167 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
169 if (Subtarget->is64Bit()) {
170 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
171 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
172 } else if (!UseSoftFloat) {
173 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
174 // Expand FP_TO_UINT into a select.
175 // FIXME: We would like to use a Custom expander here eventually to do
176 // the optimal thing for SSE vs. the default expansion in the legalizer.
177 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
179 // With SSE3 we can use fisttpll to convert to a signed i64; without
180 // SSE, we're stuck with a fistpll.
181 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
184 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
185 if (!X86ScalarSSEf64) {
186 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
187 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
190 // Scalar integer divide and remainder are lowered to use operations that
191 // produce two results, to match the available instructions. This exposes
192 // the two-result form to trivial CSE, which is able to combine x/y and x%y
193 // into a single instruction.
195 // Scalar integer multiply-high is also lowered to use two-result
196 // operations, to match the available instructions. However, plain multiply
197 // (low) operations are left as Legal, as there are single-result
198 // instructions for this in x86. Using the two-result multiply instructions
199 // when both high and low results are needed must be arranged by dagcombine.
200 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
201 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
202 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
203 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
204 setOperationAction(ISD::SREM , MVT::i8 , Expand);
205 setOperationAction(ISD::UREM , MVT::i8 , Expand);
206 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
207 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
208 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
209 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
210 setOperationAction(ISD::SREM , MVT::i16 , Expand);
211 setOperationAction(ISD::UREM , MVT::i16 , Expand);
212 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
213 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
214 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
215 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
216 setOperationAction(ISD::SREM , MVT::i32 , Expand);
217 setOperationAction(ISD::UREM , MVT::i32 , Expand);
218 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
219 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
220 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
221 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
222 setOperationAction(ISD::SREM , MVT::i64 , Expand);
223 setOperationAction(ISD::UREM , MVT::i64 , Expand);
225 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
226 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
227 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
228 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
229 if (Subtarget->is64Bit())
230 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
231 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
232 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
233 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
234 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
235 setOperationAction(ISD::FREM , MVT::f32 , Expand);
236 setOperationAction(ISD::FREM , MVT::f64 , Expand);
237 setOperationAction(ISD::FREM , MVT::f80 , Expand);
238 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
240 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
241 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
242 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
243 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
244 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
245 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
246 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
247 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
248 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
249 if (Subtarget->is64Bit()) {
250 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
251 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
252 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
255 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
256 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
258 // These should be promoted to a larger select which is supported.
259 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
260 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
261 // X86 wants to expand cmov itself.
262 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
263 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
264 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
265 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
266 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
267 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
268 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
269 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
270 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
271 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
272 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
273 if (Subtarget->is64Bit()) {
274 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
275 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
277 // X86 ret instruction may pop stack.
278 setOperationAction(ISD::RET , MVT::Other, Custom);
279 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
282 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
283 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
284 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
285 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
286 if (Subtarget->is64Bit())
287 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
288 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
289 if (Subtarget->is64Bit()) {
290 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
291 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
292 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
293 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
295 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
296 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
297 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
298 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
299 if (Subtarget->is64Bit()) {
300 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
301 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
302 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
305 if (Subtarget->hasSSE1())
306 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
308 if (!Subtarget->hasSSE2())
309 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
311 // Expand certain atomics
312 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
313 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
314 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
315 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
317 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
318 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
319 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
320 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
322 if (!Subtarget->is64Bit()) {
323 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
324 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
325 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
326 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
327 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
328 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
329 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
332 // Use the default ISD::DBG_STOPPOINT, ISD::DECLARE expansion.
333 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
334 // FIXME - use subtarget debug flags
335 if (!Subtarget->isTargetDarwin() &&
336 !Subtarget->isTargetELF() &&
337 !Subtarget->isTargetCygMing()) {
338 setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
339 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
342 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
343 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
344 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
345 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
346 if (Subtarget->is64Bit()) {
347 setExceptionPointerRegister(X86::RAX);
348 setExceptionSelectorRegister(X86::RDX);
350 setExceptionPointerRegister(X86::EAX);
351 setExceptionSelectorRegister(X86::EDX);
353 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
354 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
356 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
358 setOperationAction(ISD::TRAP, MVT::Other, Legal);
360 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
361 setOperationAction(ISD::VASTART , MVT::Other, Custom);
362 setOperationAction(ISD::VAEND , MVT::Other, Expand);
363 if (Subtarget->is64Bit()) {
364 setOperationAction(ISD::VAARG , MVT::Other, Custom);
365 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
367 setOperationAction(ISD::VAARG , MVT::Other, Expand);
368 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
371 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
372 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
373 if (Subtarget->is64Bit())
374 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
375 if (Subtarget->isTargetCygMing())
376 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
378 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
380 if (!UseSoftFloat && X86ScalarSSEf64) {
381 // f32 and f64 use SSE.
382 // Set up the FP register classes.
383 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
384 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
386 // Use ANDPD to simulate FABS.
387 setOperationAction(ISD::FABS , MVT::f64, Custom);
388 setOperationAction(ISD::FABS , MVT::f32, Custom);
390 // Use XORP to simulate FNEG.
391 setOperationAction(ISD::FNEG , MVT::f64, Custom);
392 setOperationAction(ISD::FNEG , MVT::f32, Custom);
394 // Use ANDPD and ORPD to simulate FCOPYSIGN.
395 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
396 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
398 // We don't support sin/cos/fmod
399 setOperationAction(ISD::FSIN , MVT::f64, Expand);
400 setOperationAction(ISD::FCOS , MVT::f64, Expand);
401 setOperationAction(ISD::FSIN , MVT::f32, Expand);
402 setOperationAction(ISD::FCOS , MVT::f32, Expand);
404 // Expand FP immediates into loads from the stack, except for the special
406 addLegalFPImmediate(APFloat(+0.0)); // xorpd
407 addLegalFPImmediate(APFloat(+0.0f)); // xorps
408 } else if (!UseSoftFloat && X86ScalarSSEf32) {
409 // Use SSE for f32, x87 for f64.
410 // Set up the FP register classes.
411 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
412 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
414 // Use ANDPS to simulate FABS.
415 setOperationAction(ISD::FABS , MVT::f32, Custom);
417 // Use XORP to simulate FNEG.
418 setOperationAction(ISD::FNEG , MVT::f32, Custom);
420 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
422 // Use ANDPS and ORPS to simulate FCOPYSIGN.
423 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
424 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
426 // We don't support sin/cos/fmod
427 setOperationAction(ISD::FSIN , MVT::f32, Expand);
428 setOperationAction(ISD::FCOS , MVT::f32, Expand);
430 // Special cases we handle for FP constants.
431 addLegalFPImmediate(APFloat(+0.0f)); // xorps
432 addLegalFPImmediate(APFloat(+0.0)); // FLD0
433 addLegalFPImmediate(APFloat(+1.0)); // FLD1
434 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
435 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
438 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
439 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
441 } else if (!UseSoftFloat) {
442 // f32 and f64 in x87.
443 // Set up the FP register classes.
444 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
445 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
447 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
448 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
449 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
450 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
453 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
454 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
456 addLegalFPImmediate(APFloat(+0.0)); // FLD0
457 addLegalFPImmediate(APFloat(+1.0)); // FLD1
458 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
459 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
460 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
461 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
462 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
463 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
466 // Long double always uses X87.
468 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
469 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
470 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
473 APFloat TmpFlt(+0.0);
474 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
476 addLegalFPImmediate(TmpFlt); // FLD0
478 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
479 APFloat TmpFlt2(+1.0);
480 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
482 addLegalFPImmediate(TmpFlt2); // FLD1
483 TmpFlt2.changeSign();
484 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
488 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
489 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
493 // Always use a library call for pow.
494 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
495 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
496 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
498 setOperationAction(ISD::FLOG, MVT::f80, Expand);
499 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
500 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
501 setOperationAction(ISD::FEXP, MVT::f80, Expand);
502 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
504 // First set operation action for all vector types to either promote
505 // (for widening) or expand (for scalarization). Then we will selectively
506 // turn on ones that can be effectively codegen'd.
507 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
508 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
509 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
510 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
511 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
512 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
513 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
514 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
515 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
516 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
517 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
518 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
519 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
520 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
521 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
522 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
523 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
524 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
525 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
526 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
527 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
528 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
529 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
530 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
531 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
532 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
533 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
534 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
535 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
536 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
537 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
538 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
539 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
540 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
541 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
542 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
543 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
544 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
545 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
546 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
547 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
548 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
549 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
550 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
551 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
552 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
553 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
554 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
555 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
556 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
559 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
560 // with -msoft-float, disable use of MMX as well.
561 if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
562 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
563 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
564 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
565 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
566 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
568 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
569 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
570 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
571 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
573 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
574 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
575 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
576 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
578 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
579 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
581 setOperationAction(ISD::AND, MVT::v8i8, Promote);
582 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
583 setOperationAction(ISD::AND, MVT::v4i16, Promote);
584 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
585 setOperationAction(ISD::AND, MVT::v2i32, Promote);
586 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
587 setOperationAction(ISD::AND, MVT::v1i64, Legal);
589 setOperationAction(ISD::OR, MVT::v8i8, Promote);
590 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
591 setOperationAction(ISD::OR, MVT::v4i16, Promote);
592 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
593 setOperationAction(ISD::OR, MVT::v2i32, Promote);
594 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
595 setOperationAction(ISD::OR, MVT::v1i64, Legal);
597 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
598 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
599 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
600 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
601 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
602 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
603 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
605 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
606 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
607 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
608 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
609 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
610 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
611 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
612 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
613 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
615 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
616 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
617 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
618 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
619 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
621 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
622 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
623 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
624 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
626 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
627 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
628 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
629 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
631 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
633 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
634 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Expand);
635 setOperationAction(ISD::SELECT, MVT::v8i8, Promote);
636 setOperationAction(ISD::SELECT, MVT::v4i16, Promote);
637 setOperationAction(ISD::SELECT, MVT::v2i32, Promote);
638 setOperationAction(ISD::SELECT, MVT::v1i64, Custom);
641 if (!UseSoftFloat && Subtarget->hasSSE1()) {
642 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
644 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
645 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
646 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
647 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
648 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
649 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
650 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
651 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
652 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
653 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
654 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
655 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
658 if (!UseSoftFloat && Subtarget->hasSSE2()) {
659 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
661 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
662 // registers cannot be used even for integer operations.
663 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
664 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
665 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
666 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
668 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
669 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
670 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
671 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
672 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
673 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
674 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
675 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
676 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
677 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
678 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
679 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
680 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
681 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
682 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
683 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
685 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
686 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
687 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
688 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
690 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
691 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
692 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
693 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
694 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
696 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
697 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
698 MVT VT = (MVT::SimpleValueType)i;
699 // Do not attempt to custom lower non-power-of-2 vectors
700 if (!isPowerOf2_32(VT.getVectorNumElements()))
702 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
703 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
704 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
707 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
708 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
709 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
710 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
711 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
712 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
714 if (Subtarget->is64Bit()) {
715 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
716 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
719 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
720 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
721 setOperationAction(ISD::AND, (MVT::SimpleValueType)VT, Promote);
722 AddPromotedToType (ISD::AND, (MVT::SimpleValueType)VT, MVT::v2i64);
723 setOperationAction(ISD::OR, (MVT::SimpleValueType)VT, Promote);
724 AddPromotedToType (ISD::OR, (MVT::SimpleValueType)VT, MVT::v2i64);
725 setOperationAction(ISD::XOR, (MVT::SimpleValueType)VT, Promote);
726 AddPromotedToType (ISD::XOR, (MVT::SimpleValueType)VT, MVT::v2i64);
727 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Promote);
728 AddPromotedToType (ISD::LOAD, (MVT::SimpleValueType)VT, MVT::v2i64);
729 setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
730 AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v2i64);
733 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
735 // Custom lower v2i64 and v2f64 selects.
736 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
737 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
738 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
739 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
741 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
742 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
743 if (!DisableMMX && Subtarget->hasMMX()) {
744 setOperationAction(ISD::FP_TO_SINT, MVT::v2i32, Custom);
745 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
749 if (Subtarget->hasSSE41()) {
750 // FIXME: Do we need to handle scalar-to-vector here?
751 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
753 // i8 and i16 vectors are custom , because the source register and source
754 // source memory operand types are not the same width. f32 vectors are
755 // custom since the immediate controlling the insert encodes additional
757 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
758 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
759 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
760 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
762 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
763 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
764 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
765 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
767 if (Subtarget->is64Bit()) {
768 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
769 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
773 if (Subtarget->hasSSE42()) {
774 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
777 // We want to custom lower some of our intrinsics.
778 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
780 // Add/Sub/Mul with overflow operations are custom lowered.
781 setOperationAction(ISD::SADDO, MVT::i32, Custom);
782 setOperationAction(ISD::SADDO, MVT::i64, Custom);
783 setOperationAction(ISD::UADDO, MVT::i32, Custom);
784 setOperationAction(ISD::UADDO, MVT::i64, Custom);
785 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
786 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
787 setOperationAction(ISD::USUBO, MVT::i32, Custom);
788 setOperationAction(ISD::USUBO, MVT::i64, Custom);
789 setOperationAction(ISD::SMULO, MVT::i32, Custom);
790 setOperationAction(ISD::SMULO, MVT::i64, Custom);
791 setOperationAction(ISD::UMULO, MVT::i32, Custom);
792 setOperationAction(ISD::UMULO, MVT::i64, Custom);
794 if (!Subtarget->is64Bit()) {
795 // These libcalls are not available in 32-bit.
796 setLibcallName(RTLIB::SHL_I128, 0);
797 setLibcallName(RTLIB::SRL_I128, 0);
798 setLibcallName(RTLIB::SRA_I128, 0);
801 // We have target-specific dag combine patterns for the following nodes:
802 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
803 setTargetDAGCombine(ISD::BUILD_VECTOR);
804 setTargetDAGCombine(ISD::SELECT);
805 setTargetDAGCombine(ISD::SHL);
806 setTargetDAGCombine(ISD::SRA);
807 setTargetDAGCombine(ISD::SRL);
808 setTargetDAGCombine(ISD::STORE);
809 if (Subtarget->is64Bit())
810 setTargetDAGCombine(ISD::MUL);
812 computeRegisterProperties();
814 // FIXME: These should be based on subtarget info. Plus, the values should
815 // be smaller when we are in optimizing for size mode.
816 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
817 maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
818 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
819 allowUnalignedMemoryAccesses = true; // x86 supports it!
820 setPrefLoopAlignment(16);
821 benefitFromCodePlacementOpt = true;
825 MVT X86TargetLowering::getSetCCResultType(MVT VT) const {
830 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
831 /// the desired ByVal argument alignment.
832 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
835 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
836 if (VTy->getBitWidth() == 128)
838 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
839 unsigned EltAlign = 0;
840 getMaxByValAlign(ATy->getElementType(), EltAlign);
841 if (EltAlign > MaxAlign)
843 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
844 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
845 unsigned EltAlign = 0;
846 getMaxByValAlign(STy->getElementType(i), EltAlign);
847 if (EltAlign > MaxAlign)
856 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
857 /// function arguments in the caller parameter area. For X86, aggregates
858 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
859 /// are at 4-byte boundaries.
860 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
861 if (Subtarget->is64Bit()) {
862 // Max of 8 and alignment of type.
863 unsigned TyAlign = TD->getABITypeAlignment(Ty);
870 if (Subtarget->hasSSE1())
871 getMaxByValAlign(Ty, Align);
875 /// getOptimalMemOpType - Returns the target specific optimal type for load
876 /// and store operations as a result of memset, memcpy, and memmove
877 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
880 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
881 bool isSrcConst, bool isSrcStr,
882 SelectionDAG &DAG) const {
883 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
884 // linux. This is because the stack realignment code can't handle certain
885 // cases like PR2962. This should be removed when PR2962 is fixed.
886 const Function *F = DAG.getMachineFunction().getFunction();
887 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
888 if (!NoImplicitFloatOps && Subtarget->getStackAlignment() >= 16) {
889 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
891 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
894 if (Subtarget->is64Bit() && Size >= 8)
899 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
901 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
902 SelectionDAG &DAG) const {
903 if (usesGlobalOffsetTable())
904 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy());
905 if (!Subtarget->isPICStyleRIPRel())
906 // This doesn't have DebugLoc associated with it, but is not really the
907 // same as a Register.
908 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc::getUnknownLoc(),
913 //===----------------------------------------------------------------------===//
914 // Return Value Calling Convention Implementation
915 //===----------------------------------------------------------------------===//
917 #include "X86GenCallingConv.inc"
919 /// LowerRET - Lower an ISD::RET node.
920 SDValue X86TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
921 DebugLoc dl = Op.getDebugLoc();
922 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
924 SmallVector<CCValAssign, 16> RVLocs;
925 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
926 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
927 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
928 CCInfo.AnalyzeReturn(Op.getNode(), RetCC_X86);
930 // If this is the first return lowered for this function, add the regs to the
931 // liveout set for the function.
932 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
933 for (unsigned i = 0; i != RVLocs.size(); ++i)
934 if (RVLocs[i].isRegLoc())
935 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
937 SDValue Chain = Op.getOperand(0);
939 // Handle tail call return.
940 Chain = GetPossiblePreceedingTailCall(Chain, X86ISD::TAILCALL);
941 if (Chain.getOpcode() == X86ISD::TAILCALL) {
942 SDValue TailCall = Chain;
943 SDValue TargetAddress = TailCall.getOperand(1);
944 SDValue StackAdjustment = TailCall.getOperand(2);
945 assert(((TargetAddress.getOpcode() == ISD::Register &&
946 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::EAX ||
947 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R11)) ||
948 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
949 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
950 "Expecting an global address, external symbol, or register");
951 assert(StackAdjustment.getOpcode() == ISD::Constant &&
952 "Expecting a const value");
954 SmallVector<SDValue,8> Operands;
955 Operands.push_back(Chain.getOperand(0));
956 Operands.push_back(TargetAddress);
957 Operands.push_back(StackAdjustment);
958 // Copy registers used by the call. Last operand is a flag so it is not
960 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
961 Operands.push_back(Chain.getOperand(i));
963 return DAG.getNode(X86ISD::TC_RETURN, dl, MVT::Other, &Operands[0],
970 SmallVector<SDValue, 6> RetOps;
971 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
972 // Operand #1 = Bytes To Pop
973 RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
975 // Copy the result values into the output registers.
976 for (unsigned i = 0; i != RVLocs.size(); ++i) {
977 CCValAssign &VA = RVLocs[i];
978 assert(VA.isRegLoc() && "Can only return in registers!");
979 SDValue ValToCopy = Op.getOperand(i*2+1);
981 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
982 // the RET instruction and handled by the FP Stackifier.
983 if (VA.getLocReg() == X86::ST0 ||
984 VA.getLocReg() == X86::ST1) {
985 // If this is a copy from an xmm register to ST(0), use an FPExtend to
986 // change the value to the FP stack register class.
987 if (isScalarFPTypeInSSEReg(VA.getValVT()))
988 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
989 RetOps.push_back(ValToCopy);
990 // Don't emit a copytoreg.
994 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
995 // which is returned in RAX / RDX.
996 if (Subtarget->is64Bit()) {
997 MVT ValVT = ValToCopy.getValueType();
998 if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
999 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1000 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1001 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1005 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1006 Flag = Chain.getValue(1);
1009 // The x86-64 ABI for returning structs by value requires that we copy
1010 // the sret argument into %rax for the return. We saved the argument into
1011 // a virtual register in the entry block, so now we copy the value out
1013 if (Subtarget->is64Bit() &&
1014 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1015 MachineFunction &MF = DAG.getMachineFunction();
1016 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1017 unsigned Reg = FuncInfo->getSRetReturnReg();
1019 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1020 FuncInfo->setSRetReturnReg(Reg);
1022 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1024 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1025 Flag = Chain.getValue(1);
1028 RetOps[0] = Chain; // Update chain.
1030 // Add the flag if we have it.
1032 RetOps.push_back(Flag);
1034 return DAG.getNode(X86ISD::RET_FLAG, dl,
1035 MVT::Other, &RetOps[0], RetOps.size());
1039 /// LowerCallResult - Lower the result values of an ISD::CALL into the
1040 /// appropriate copies out of appropriate physical registers. This assumes that
1041 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
1042 /// being lowered. The returns a SDNode with the same number of values as the
1044 SDNode *X86TargetLowering::
1045 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall,
1046 unsigned CallingConv, SelectionDAG &DAG) {
1048 DebugLoc dl = TheCall->getDebugLoc();
1049 // Assign locations to each value returned by this call.
1050 SmallVector<CCValAssign, 16> RVLocs;
1051 bool isVarArg = TheCall->isVarArg();
1052 bool Is64Bit = Subtarget->is64Bit();
1053 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
1054 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
1056 SmallVector<SDValue, 8> ResultVals;
1058 // Copy all of the result registers out of their specified physreg.
1059 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1060 CCValAssign &VA = RVLocs[i];
1061 MVT CopyVT = VA.getValVT();
1063 // If this is x86-64, and we disabled SSE, we can't return FP values
1064 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1065 ((Is64Bit || TheCall->isInreg()) && !Subtarget->hasSSE1())) {
1066 cerr << "SSE register return with SSE disabled\n";
1070 // If this is a call to a function that returns an fp value on the floating
1071 // point stack, but where we prefer to use the value in xmm registers, copy
1072 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1073 if ((VA.getLocReg() == X86::ST0 ||
1074 VA.getLocReg() == X86::ST1) &&
1075 isScalarFPTypeInSSEReg(VA.getValVT())) {
1080 if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1081 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1082 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1083 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1084 MVT::v2i64, InFlag).getValue(1);
1085 Val = Chain.getValue(0);
1086 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1087 Val, DAG.getConstant(0, MVT::i64));
1089 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1090 MVT::i64, InFlag).getValue(1);
1091 Val = Chain.getValue(0);
1093 Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1095 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1096 CopyVT, InFlag).getValue(1);
1097 Val = Chain.getValue(0);
1099 InFlag = Chain.getValue(2);
1101 if (CopyVT != VA.getValVT()) {
1102 // Round the F80 the right size, which also moves to the appropriate xmm
1104 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1105 // This truncation won't change the value.
1106 DAG.getIntPtrConstant(1));
1109 ResultVals.push_back(Val);
1112 // Merge everything together with a MERGE_VALUES node.
1113 ResultVals.push_back(Chain);
1114 return DAG.getNode(ISD::MERGE_VALUES, dl, TheCall->getVTList(),
1115 &ResultVals[0], ResultVals.size()).getNode();
1119 //===----------------------------------------------------------------------===//
1120 // C & StdCall & Fast Calling Convention implementation
1121 //===----------------------------------------------------------------------===//
1122 // StdCall calling convention seems to be standard for many Windows' API
1123 // routines and around. It differs from C calling convention just a little:
1124 // callee should clean up the stack, not caller. Symbols should be also
1125 // decorated in some fancy way :) It doesn't support any vector arguments.
1126 // For info on fast calling convention see Fast Calling Convention (tail call)
1127 // implementation LowerX86_32FastCCCallTo.
1129 /// CallIsStructReturn - Determines whether a CALL node uses struct return
1131 static bool CallIsStructReturn(CallSDNode *TheCall) {
1132 unsigned NumOps = TheCall->getNumArgs();
1136 return TheCall->getArgFlags(0).isSRet();
1139 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
1140 /// return semantics.
1141 static bool ArgsAreStructReturn(SDValue Op) {
1142 unsigned NumArgs = Op.getNode()->getNumValues() - 1;
1146 return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
1149 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
1150 /// the callee to pop its own arguments. Callee pop is necessary to support tail
1152 bool X86TargetLowering::IsCalleePop(bool IsVarArg, unsigned CallingConv) {
1156 switch (CallingConv) {
1159 case CallingConv::X86_StdCall:
1160 return !Subtarget->is64Bit();
1161 case CallingConv::X86_FastCall:
1162 return !Subtarget->is64Bit();
1163 case CallingConv::Fast:
1164 return PerformTailCallOpt;
1168 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1169 /// given CallingConvention value.
1170 CCAssignFn *X86TargetLowering::CCAssignFnForNode(unsigned CC) const {
1171 if (Subtarget->is64Bit()) {
1172 if (Subtarget->isTargetWin64())
1173 return CC_X86_Win64_C;
1178 if (CC == CallingConv::X86_FastCall)
1179 return CC_X86_32_FastCall;
1180 else if (CC == CallingConv::Fast)
1181 return CC_X86_32_FastCC;
1186 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1187 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1189 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDValue Op) {
1190 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1191 if (CC == CallingConv::X86_FastCall)
1193 else if (CC == CallingConv::X86_StdCall)
1199 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1200 /// in a register before calling.
1201 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1202 return !IsTailCall && !Is64Bit &&
1203 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1204 Subtarget->isPICStyleGOT();
1207 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1208 /// address to be loaded in a register.
1210 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1211 return !Is64Bit && IsTailCall &&
1212 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1213 Subtarget->isPICStyleGOT();
1216 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1217 /// by "Src" to address "Dst" with size and alignment information specified by
1218 /// the specific parameter attribute. The copy will be passed as a byval
1219 /// function parameter.
1221 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1222 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1224 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1225 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1226 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1229 SDValue X86TargetLowering::LowerMemArgument(SDValue Op, SelectionDAG &DAG,
1230 const CCValAssign &VA,
1231 MachineFrameInfo *MFI,
1233 SDValue Root, unsigned i) {
1234 // Create the nodes corresponding to a load from this parameter slot.
1235 ISD::ArgFlagsTy Flags =
1236 cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1237 bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1238 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1240 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1241 // changed with more analysis.
1242 // In case of tail call optimization mark all arguments mutable. Since they
1243 // could be overwritten by lowering of arguments in case of a tail call.
1244 int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1245 VA.getLocMemOffset(), isImmutable);
1246 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1247 if (Flags.isByVal())
1249 return DAG.getLoad(VA.getValVT(), Op.getDebugLoc(), Root, FIN,
1250 PseudoSourceValue::getFixedStack(FI), 0);
1254 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) {
1255 MachineFunction &MF = DAG.getMachineFunction();
1256 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1257 DebugLoc dl = Op.getDebugLoc();
1259 const Function* Fn = MF.getFunction();
1260 if (Fn->hasExternalLinkage() &&
1261 Subtarget->isTargetCygMing() &&
1262 Fn->getName() == "main")
1263 FuncInfo->setForceFramePointer(true);
1265 // Decorate the function name.
1266 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1268 MachineFrameInfo *MFI = MF.getFrameInfo();
1269 SDValue Root = Op.getOperand(0);
1270 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
1271 unsigned CC = MF.getFunction()->getCallingConv();
1272 bool Is64Bit = Subtarget->is64Bit();
1273 bool IsWin64 = Subtarget->isTargetWin64();
1275 assert(!(isVarArg && CC == CallingConv::Fast) &&
1276 "Var args not supported with calling convention fastcc");
1278 // Assign locations to all of the incoming arguments.
1279 SmallVector<CCValAssign, 16> ArgLocs;
1280 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1281 CCInfo.AnalyzeFormalArguments(Op.getNode(), CCAssignFnForNode(CC));
1283 SmallVector<SDValue, 8> ArgValues;
1284 unsigned LastVal = ~0U;
1285 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1286 CCValAssign &VA = ArgLocs[i];
1287 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1289 assert(VA.getValNo() != LastVal &&
1290 "Don't support value assigned to multiple locs yet");
1291 LastVal = VA.getValNo();
1293 if (VA.isRegLoc()) {
1294 MVT RegVT = VA.getLocVT();
1295 TargetRegisterClass *RC = NULL;
1296 if (RegVT == MVT::i32)
1297 RC = X86::GR32RegisterClass;
1298 else if (Is64Bit && RegVT == MVT::i64)
1299 RC = X86::GR64RegisterClass;
1300 else if (RegVT == MVT::f32)
1301 RC = X86::FR32RegisterClass;
1302 else if (RegVT == MVT::f64)
1303 RC = X86::FR64RegisterClass;
1304 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1305 RC = X86::VR128RegisterClass;
1306 else if (RegVT.isVector()) {
1307 assert(RegVT.getSizeInBits() == 64);
1309 RC = X86::VR64RegisterClass; // MMX values are passed in MMXs.
1311 // Darwin calling convention passes MMX values in either GPRs or
1312 // XMMs in x86-64. Other targets pass them in memory.
1313 if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1314 RC = X86::VR128RegisterClass; // MMX values are passed in XMMs.
1317 RC = X86::GR64RegisterClass; // v1i64 values are passed in GPRs.
1322 assert(0 && "Unknown argument type!");
1325 unsigned Reg = DAG.getMachineFunction().addLiveIn(VA.getLocReg(), RC);
1326 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, RegVT);
1328 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1329 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1331 if (VA.getLocInfo() == CCValAssign::SExt)
1332 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1333 DAG.getValueType(VA.getValVT()));
1334 else if (VA.getLocInfo() == CCValAssign::ZExt)
1335 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1336 DAG.getValueType(VA.getValVT()));
1338 if (VA.getLocInfo() != CCValAssign::Full)
1339 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1341 // Handle MMX values passed in GPRs.
1342 if (Is64Bit && RegVT != VA.getLocVT()) {
1343 if (RegVT.getSizeInBits() == 64 && RC == X86::GR64RegisterClass)
1344 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1345 else if (RC == X86::VR128RegisterClass) {
1346 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1347 ArgValue, DAG.getConstant(0, MVT::i64));
1348 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1352 ArgValues.push_back(ArgValue);
1354 assert(VA.isMemLoc());
1355 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1359 // The x86-64 ABI for returning structs by value requires that we copy
1360 // the sret argument into %rax for the return. Save the argument into
1361 // a virtual register so that we can access it from the return points.
1362 if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1363 MachineFunction &MF = DAG.getMachineFunction();
1364 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1365 unsigned Reg = FuncInfo->getSRetReturnReg();
1367 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1368 FuncInfo->setSRetReturnReg(Reg);
1370 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, ArgValues[0]);
1371 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Root);
1374 unsigned StackSize = CCInfo.getNextStackOffset();
1375 // align stack specially for tail calls
1376 if (PerformTailCallOpt && CC == CallingConv::Fast)
1377 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1379 // If the function takes variable number of arguments, make a frame index for
1380 // the start of the first vararg value... for expansion of llvm.va_start.
1382 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1383 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1386 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1388 // FIXME: We should really autogenerate these arrays
1389 static const unsigned GPR64ArgRegsWin64[] = {
1390 X86::RCX, X86::RDX, X86::R8, X86::R9
1392 static const unsigned XMMArgRegsWin64[] = {
1393 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1395 static const unsigned GPR64ArgRegs64Bit[] = {
1396 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1398 static const unsigned XMMArgRegs64Bit[] = {
1399 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1400 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1402 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1405 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1406 GPR64ArgRegs = GPR64ArgRegsWin64;
1407 XMMArgRegs = XMMArgRegsWin64;
1409 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1410 GPR64ArgRegs = GPR64ArgRegs64Bit;
1411 XMMArgRegs = XMMArgRegs64Bit;
1413 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1415 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1418 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1419 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1420 "SSE register cannot be used when SSE is disabled!");
1421 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1422 "SSE register cannot be used when SSE is disabled!");
1423 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1424 // Kernel mode asks for SSE to be disabled, so don't push them
1426 TotalNumXMMRegs = 0;
1428 // For X86-64, if there are vararg parameters that are passed via
1429 // registers, then we must store them to their spots on the stack so they
1430 // may be loaded by deferencing the result of va_next.
1431 VarArgsGPOffset = NumIntRegs * 8;
1432 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1433 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1434 TotalNumXMMRegs * 16, 16);
1436 // Store the integer parameter registers.
1437 SmallVector<SDValue, 8> MemOps;
1438 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1439 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1440 DAG.getIntPtrConstant(VarArgsGPOffset));
1441 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1442 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1443 X86::GR64RegisterClass);
1444 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::i64);
1446 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1447 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1448 MemOps.push_back(Store);
1449 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1450 DAG.getIntPtrConstant(8));
1453 // Now store the XMM (fp + vector) parameter registers.
1454 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1455 DAG.getIntPtrConstant(VarArgsFPOffset));
1456 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1457 unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1458 X86::VR128RegisterClass);
1459 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::v4f32);
1461 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1462 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1463 MemOps.push_back(Store);
1464 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1465 DAG.getIntPtrConstant(16));
1467 if (!MemOps.empty())
1468 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1469 &MemOps[0], MemOps.size());
1473 ArgValues.push_back(Root);
1475 // Some CCs need callee pop.
1476 if (IsCalleePop(isVarArg, CC)) {
1477 BytesToPopOnReturn = StackSize; // Callee pops everything.
1478 BytesCallerReserves = 0;
1480 BytesToPopOnReturn = 0; // Callee pops nothing.
1481 // If this is an sret function, the return should pop the hidden pointer.
1482 if (!Is64Bit && CC != CallingConv::Fast && ArgsAreStructReturn(Op))
1483 BytesToPopOnReturn = 4;
1484 BytesCallerReserves = StackSize;
1488 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1489 if (CC == CallingConv::X86_FastCall)
1490 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1493 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1495 // Return the new list of results.
1496 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(),
1497 &ArgValues[0], ArgValues.size()).getValue(Op.getResNo());
1501 X86TargetLowering::LowerMemOpCallTo(CallSDNode *TheCall, SelectionDAG &DAG,
1502 const SDValue &StackPtr,
1503 const CCValAssign &VA,
1505 SDValue Arg, ISD::ArgFlagsTy Flags) {
1506 DebugLoc dl = TheCall->getDebugLoc();
1507 unsigned LocMemOffset = VA.getLocMemOffset();
1508 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1509 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1510 if (Flags.isByVal()) {
1511 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1513 return DAG.getStore(Chain, dl, Arg, PtrOff,
1514 PseudoSourceValue::getStack(), LocMemOffset);
1517 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1518 /// optimization is performed and it is required.
1520 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1521 SDValue &OutRetAddr,
1527 if (!IsTailCall || FPDiff==0) return Chain;
1529 // Adjust the Return address stack slot.
1530 MVT VT = getPointerTy();
1531 OutRetAddr = getReturnAddressFrameIndex(DAG);
1533 // Load the "old" Return address.
1534 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0);
1535 return SDValue(OutRetAddr.getNode(), 1);
1538 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1539 /// optimization is performed and it is required (FPDiff!=0).
1541 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1542 SDValue Chain, SDValue RetAddrFrIdx,
1543 bool Is64Bit, int FPDiff, DebugLoc dl) {
1544 // Store the return address to the appropriate stack slot.
1545 if (!FPDiff) return Chain;
1546 // Calculate the new stack slot for the return address.
1547 int SlotSize = Is64Bit ? 8 : 4;
1548 int NewReturnAddrFI =
1549 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1550 MVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1551 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1552 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1553 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1557 SDValue X86TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1558 MachineFunction &MF = DAG.getMachineFunction();
1559 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
1560 SDValue Chain = TheCall->getChain();
1561 unsigned CC = TheCall->getCallingConv();
1562 bool isVarArg = TheCall->isVarArg();
1563 bool IsTailCall = TheCall->isTailCall() &&
1564 CC == CallingConv::Fast && PerformTailCallOpt;
1565 SDValue Callee = TheCall->getCallee();
1566 bool Is64Bit = Subtarget->is64Bit();
1567 bool IsStructRet = CallIsStructReturn(TheCall);
1568 DebugLoc dl = TheCall->getDebugLoc();
1570 assert(!(isVarArg && CC == CallingConv::Fast) &&
1571 "Var args not supported with calling convention fastcc");
1573 // Analyze operands of the call, assigning locations to each operand.
1574 SmallVector<CCValAssign, 16> ArgLocs;
1575 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1576 CCInfo.AnalyzeCallOperands(TheCall, CCAssignFnForNode(CC));
1578 // Get a count of how many bytes are to be pushed on the stack.
1579 unsigned NumBytes = CCInfo.getNextStackOffset();
1580 if (PerformTailCallOpt && CC == CallingConv::Fast)
1581 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1585 // Lower arguments at fp - stackoffset + fpdiff.
1586 unsigned NumBytesCallerPushed =
1587 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1588 FPDiff = NumBytesCallerPushed - NumBytes;
1590 // Set the delta of movement of the returnaddr stackslot.
1591 // But only set if delta is greater than previous delta.
1592 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1593 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1596 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1598 SDValue RetAddrFrIdx;
1599 // Load return adress for tail calls.
1600 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1603 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1604 SmallVector<SDValue, 8> MemOpChains;
1607 // Walk the register/memloc assignments, inserting copies/loads. In the case
1608 // of tail call optimization arguments are handle later.
1609 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1610 CCValAssign &VA = ArgLocs[i];
1611 SDValue Arg = TheCall->getArg(i);
1612 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1613 bool isByVal = Flags.isByVal();
1615 // Promote the value if needed.
1616 switch (VA.getLocInfo()) {
1617 default: assert(0 && "Unknown loc info!");
1618 case CCValAssign::Full: break;
1619 case CCValAssign::SExt:
1620 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1622 case CCValAssign::ZExt:
1623 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1625 case CCValAssign::AExt:
1626 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1630 if (VA.isRegLoc()) {
1632 MVT RegVT = VA.getLocVT();
1633 if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1634 switch (VA.getLocReg()) {
1637 case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1639 // Special case: passing MMX values in GPR registers.
1640 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1643 case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1644 case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1645 // Special case: passing MMX values in XMM registers.
1646 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1647 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1648 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1653 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1655 if (!IsTailCall || (IsTailCall && isByVal)) {
1656 assert(VA.isMemLoc());
1657 if (StackPtr.getNode() == 0)
1658 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1660 MemOpChains.push_back(LowerMemOpCallTo(TheCall, DAG, StackPtr, VA,
1661 Chain, Arg, Flags));
1666 if (!MemOpChains.empty())
1667 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1668 &MemOpChains[0], MemOpChains.size());
1670 // Build a sequence of copy-to-reg nodes chained together with token chain
1671 // and flag operands which copy the outgoing args into registers.
1673 // Tail call byval lowering might overwrite argument registers so in case of
1674 // tail call optimization the copies to registers are lowered later.
1676 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1677 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1678 RegsToPass[i].second, InFlag);
1679 InFlag = Chain.getValue(1);
1682 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1684 if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1685 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1686 DAG.getNode(X86ISD::GlobalBaseReg,
1687 DebugLoc::getUnknownLoc(),
1690 InFlag = Chain.getValue(1);
1692 // If we are tail calling and generating PIC/GOT style code load the address
1693 // of the callee into ecx. The value in ecx is used as target of the tail
1694 // jump. This is done to circumvent the ebx/callee-saved problem for tail
1695 // calls on PIC/GOT architectures. Normally we would just put the address of
1696 // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1697 // restored (since ebx is callee saved) before jumping to the target@PLT.
1698 if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1699 // Note: The actual moving to ecx is done further down.
1700 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1701 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1702 !G->getGlobal()->hasProtectedVisibility())
1703 Callee = LowerGlobalAddress(Callee, DAG);
1704 else if (isa<ExternalSymbolSDNode>(Callee))
1705 Callee = LowerExternalSymbol(Callee,DAG);
1708 if (Is64Bit && isVarArg) {
1709 // From AMD64 ABI document:
1710 // For calls that may call functions that use varargs or stdargs
1711 // (prototype-less calls or calls to functions containing ellipsis (...) in
1712 // the declaration) %al is used as hidden argument to specify the number
1713 // of SSE registers used. The contents of %al do not need to match exactly
1714 // the number of registers, but must be an ubound on the number of SSE
1715 // registers used and is in the range 0 - 8 inclusive.
1717 // FIXME: Verify this on Win64
1718 // Count the number of XMM registers allocated.
1719 static const unsigned XMMArgRegs[] = {
1720 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1721 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1723 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1724 assert((Subtarget->hasSSE1() || !NumXMMRegs)
1725 && "SSE registers cannot be used when SSE is disabled");
1727 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1728 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1729 InFlag = Chain.getValue(1);
1733 // For tail calls lower the arguments to the 'real' stack slot.
1735 SmallVector<SDValue, 8> MemOpChains2;
1738 // Do not flag preceeding copytoreg stuff together with the following stuff.
1740 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1741 CCValAssign &VA = ArgLocs[i];
1742 if (!VA.isRegLoc()) {
1743 assert(VA.isMemLoc());
1744 SDValue Arg = TheCall->getArg(i);
1745 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1746 // Create frame index.
1747 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1748 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1749 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1750 FIN = DAG.getFrameIndex(FI, getPointerTy());
1752 if (Flags.isByVal()) {
1753 // Copy relative to framepointer.
1754 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1755 if (StackPtr.getNode() == 0)
1756 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
1758 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
1760 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1763 // Store relative to framepointer.
1764 MemOpChains2.push_back(
1765 DAG.getStore(Chain, dl, Arg, FIN,
1766 PseudoSourceValue::getFixedStack(FI), 0));
1771 if (!MemOpChains2.empty())
1772 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1773 &MemOpChains2[0], MemOpChains2.size());
1775 // Copy arguments to their registers.
1776 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1777 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1778 RegsToPass[i].second, InFlag);
1779 InFlag = Chain.getValue(1);
1783 // Store the return address to the appropriate stack slot.
1784 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1788 // If the callee is a GlobalAddress node (quite common, every direct call is)
1789 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1790 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1791 // We should use extra load for direct calls to dllimported functions in
1793 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1794 getTargetMachine(), true))
1795 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy(),
1797 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1798 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1799 } else if (IsTailCall) {
1800 unsigned Opc = Is64Bit ? X86::R11 : X86::EAX;
1802 Chain = DAG.getCopyToReg(Chain, dl,
1803 DAG.getRegister(Opc, getPointerTy()),
1805 Callee = DAG.getRegister(Opc, getPointerTy());
1806 // Add register as live out.
1807 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1810 // Returns a chain & a flag for retval copy to use.
1811 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1812 SmallVector<SDValue, 8> Ops;
1815 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1816 DAG.getIntPtrConstant(0, true), InFlag);
1817 InFlag = Chain.getValue(1);
1819 // Returns a chain & a flag for retval copy to use.
1820 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1824 Ops.push_back(Chain);
1825 Ops.push_back(Callee);
1828 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1830 // Add argument registers to the end of the list so that they are known live
1832 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1833 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1834 RegsToPass[i].second.getValueType()));
1836 // Add an implicit use GOT pointer in EBX.
1837 if (!IsTailCall && !Is64Bit &&
1838 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1839 Subtarget->isPICStyleGOT())
1840 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1842 // Add an implicit use of AL for x86 vararg functions.
1843 if (Is64Bit && isVarArg)
1844 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1846 if (InFlag.getNode())
1847 Ops.push_back(InFlag);
1850 assert(InFlag.getNode() &&
1851 "Flag must be set. Depend on flag being set in LowerRET");
1852 Chain = DAG.getNode(X86ISD::TAILCALL, dl,
1853 TheCall->getVTList(), &Ops[0], Ops.size());
1855 return SDValue(Chain.getNode(), Op.getResNo());
1858 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
1859 InFlag = Chain.getValue(1);
1861 // Create the CALLSEQ_END node.
1862 unsigned NumBytesForCalleeToPush;
1863 if (IsCalleePop(isVarArg, CC))
1864 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1865 else if (!Is64Bit && CC != CallingConv::Fast && IsStructRet)
1866 // If this is is a call to a struct-return function, the callee
1867 // pops the hidden struct pointer, so we have to push it back.
1868 // This is common for Darwin/X86, Linux & Mingw32 targets.
1869 NumBytesForCalleeToPush = 4;
1871 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1873 // Returns a flag for retval copy to use.
1874 Chain = DAG.getCALLSEQ_END(Chain,
1875 DAG.getIntPtrConstant(NumBytes, true),
1876 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
1879 InFlag = Chain.getValue(1);
1881 // Handle result values, copying them out of physregs into vregs that we
1883 return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
1888 //===----------------------------------------------------------------------===//
1889 // Fast Calling Convention (tail call) implementation
1890 //===----------------------------------------------------------------------===//
1892 // Like std call, callee cleans arguments, convention except that ECX is
1893 // reserved for storing the tail called function address. Only 2 registers are
1894 // free for argument passing (inreg). Tail call optimization is performed
1896 // * tailcallopt is enabled
1897 // * caller/callee are fastcc
1898 // On X86_64 architecture with GOT-style position independent code only local
1899 // (within module) calls are supported at the moment.
1900 // To keep the stack aligned according to platform abi the function
1901 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1902 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1903 // If a tail called function callee has more arguments than the caller the
1904 // caller needs to make sure that there is room to move the RETADDR to. This is
1905 // achieved by reserving an area the size of the argument delta right after the
1906 // original REtADDR, but before the saved framepointer or the spilled registers
1907 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1919 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1920 /// for a 16 byte align requirement.
1921 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1922 SelectionDAG& DAG) {
1923 MachineFunction &MF = DAG.getMachineFunction();
1924 const TargetMachine &TM = MF.getTarget();
1925 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1926 unsigned StackAlignment = TFI.getStackAlignment();
1927 uint64_t AlignMask = StackAlignment - 1;
1928 int64_t Offset = StackSize;
1929 uint64_t SlotSize = TD->getPointerSize();
1930 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1931 // Number smaller than 12 so just add the difference.
1932 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1934 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1935 Offset = ((~AlignMask) & Offset) + StackAlignment +
1936 (StackAlignment-SlotSize);
1941 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1942 /// following the call is a return. A function is eligible if caller/callee
1943 /// calling conventions match, currently only fastcc supports tail calls, and
1944 /// the function CALL is immediatly followed by a RET.
1945 bool X86TargetLowering::IsEligibleForTailCallOptimization(CallSDNode *TheCall,
1947 SelectionDAG& DAG) const {
1948 if (!PerformTailCallOpt)
1951 if (CheckTailCallReturnConstraints(TheCall, Ret)) {
1952 MachineFunction &MF = DAG.getMachineFunction();
1953 unsigned CallerCC = MF.getFunction()->getCallingConv();
1954 unsigned CalleeCC= TheCall->getCallingConv();
1955 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1956 SDValue Callee = TheCall->getCallee();
1957 // On x86/32Bit PIC/GOT tail calls are supported.
1958 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1959 !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1962 // Can only do local tail calls (in same module, hidden or protected) on
1963 // x86_64 PIC/GOT at the moment.
1964 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1965 return G->getGlobal()->hasHiddenVisibility()
1966 || G->getGlobal()->hasProtectedVisibility();
1974 X86TargetLowering::createFastISel(MachineFunction &mf,
1975 MachineModuleInfo *mmo,
1977 DenseMap<const Value *, unsigned> &vm,
1978 DenseMap<const BasicBlock *,
1979 MachineBasicBlock *> &bm,
1980 DenseMap<const AllocaInst *, int> &am
1982 , SmallSet<Instruction*, 8> &cil
1985 return X86::createFastISel(mf, mmo, dw, vm, bm, am
1993 //===----------------------------------------------------------------------===//
1994 // Other Lowering Hooks
1995 //===----------------------------------------------------------------------===//
1998 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1999 MachineFunction &MF = DAG.getMachineFunction();
2000 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2001 int ReturnAddrIndex = FuncInfo->getRAIndex();
2003 if (ReturnAddrIndex == 0) {
2004 // Set up a frame object for the return address.
2005 uint64_t SlotSize = TD->getPointerSize();
2006 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize);
2007 FuncInfo->setRAIndex(ReturnAddrIndex);
2010 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2014 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2015 /// specific condition code, returning the condition code and the LHS/RHS of the
2016 /// comparison to make.
2017 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2018 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2020 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2021 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2022 // X > -1 -> X == 0, jump !sign.
2023 RHS = DAG.getConstant(0, RHS.getValueType());
2024 return X86::COND_NS;
2025 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2026 // X < 0 -> X == 0, jump on sign.
2028 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2030 RHS = DAG.getConstant(0, RHS.getValueType());
2031 return X86::COND_LE;
2035 switch (SetCCOpcode) {
2036 default: assert(0 && "Invalid integer condition!");
2037 case ISD::SETEQ: return X86::COND_E;
2038 case ISD::SETGT: return X86::COND_G;
2039 case ISD::SETGE: return X86::COND_GE;
2040 case ISD::SETLT: return X86::COND_L;
2041 case ISD::SETLE: return X86::COND_LE;
2042 case ISD::SETNE: return X86::COND_NE;
2043 case ISD::SETULT: return X86::COND_B;
2044 case ISD::SETUGT: return X86::COND_A;
2045 case ISD::SETULE: return X86::COND_BE;
2046 case ISD::SETUGE: return X86::COND_AE;
2050 // First determine if it is required or is profitable to flip the operands.
2052 // If LHS is a foldable load, but RHS is not, flip the condition.
2053 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2054 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2055 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2056 std::swap(LHS, RHS);
2059 switch (SetCCOpcode) {
2065 std::swap(LHS, RHS);
2069 // On a floating point condition, the flags are set as follows:
2071 // 0 | 0 | 0 | X > Y
2072 // 0 | 0 | 1 | X < Y
2073 // 1 | 0 | 0 | X == Y
2074 // 1 | 1 | 1 | unordered
2075 switch (SetCCOpcode) {
2076 default: assert(0 && "Condcode should be pre-legalized away");
2078 case ISD::SETEQ: return X86::COND_E;
2079 case ISD::SETOLT: // flipped
2081 case ISD::SETGT: return X86::COND_A;
2082 case ISD::SETOLE: // flipped
2084 case ISD::SETGE: return X86::COND_AE;
2085 case ISD::SETUGT: // flipped
2087 case ISD::SETLT: return X86::COND_B;
2088 case ISD::SETUGE: // flipped
2090 case ISD::SETLE: return X86::COND_BE;
2092 case ISD::SETNE: return X86::COND_NE;
2093 case ISD::SETUO: return X86::COND_P;
2094 case ISD::SETO: return X86::COND_NP;
2098 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2099 /// code. Current x86 isa includes the following FP cmov instructions:
2100 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2101 static bool hasFPCMov(unsigned X86CC) {
2117 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2118 /// the specified range (L, H].
2119 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2120 return (Val < 0) || (Val >= Low && Val < Hi);
2123 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2124 /// specified value.
2125 static bool isUndefOrEqual(int Val, int CmpVal) {
2126 if (Val < 0 || Val == CmpVal)
2131 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2132 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2133 /// the second operand.
2134 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2135 if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2136 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2137 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2138 return (Mask[0] < 2 && Mask[1] < 2);
2142 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2143 SmallVector<int, 8> M;
2145 return ::isPSHUFDMask(M, N->getValueType(0));
2148 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2149 /// is suitable for input to PSHUFHW.
2150 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2151 if (VT != MVT::v8i16)
2154 // Lower quadword copied in order or undef.
2155 for (int i = 0; i != 4; ++i)
2156 if (Mask[i] >= 0 && Mask[i] != i)
2159 // Upper quadword shuffled.
2160 for (int i = 4; i != 8; ++i)
2161 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2167 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2168 SmallVector<int, 8> M;
2170 return ::isPSHUFHWMask(M, N->getValueType(0));
2173 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2174 /// is suitable for input to PSHUFLW.
2175 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2176 if (VT != MVT::v8i16)
2179 // Upper quadword copied in order.
2180 for (int i = 4; i != 8; ++i)
2181 if (Mask[i] >= 0 && Mask[i] != i)
2184 // Lower quadword shuffled.
2185 for (int i = 0; i != 4; ++i)
2192 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2193 SmallVector<int, 8> M;
2195 return ::isPSHUFLWMask(M, N->getValueType(0));
2198 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2199 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2200 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2201 int NumElems = VT.getVectorNumElements();
2202 if (NumElems != 2 && NumElems != 4)
2205 int Half = NumElems / 2;
2206 for (int i = 0; i < Half; ++i)
2207 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2209 for (int i = Half; i < NumElems; ++i)
2210 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2216 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2217 SmallVector<int, 8> M;
2219 return ::isSHUFPMask(M, N->getValueType(0));
2222 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2223 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2224 /// half elements to come from vector 1 (which would equal the dest.) and
2225 /// the upper half to come from vector 2.
2226 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2227 int NumElems = VT.getVectorNumElements();
2229 if (NumElems != 2 && NumElems != 4)
2232 int Half = NumElems / 2;
2233 for (int i = 0; i < Half; ++i)
2234 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2236 for (int i = Half; i < NumElems; ++i)
2237 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2242 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2243 SmallVector<int, 8> M;
2245 return isCommutedSHUFPMask(M, N->getValueType(0));
2248 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2249 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2250 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2251 if (N->getValueType(0).getVectorNumElements() != 4)
2254 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2255 return isUndefOrEqual(N->getMaskElt(0), 6) &&
2256 isUndefOrEqual(N->getMaskElt(1), 7) &&
2257 isUndefOrEqual(N->getMaskElt(2), 2) &&
2258 isUndefOrEqual(N->getMaskElt(3), 3);
2261 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2262 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2263 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2264 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2266 if (NumElems != 2 && NumElems != 4)
2269 for (unsigned i = 0; i < NumElems/2; ++i)
2270 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2273 for (unsigned i = NumElems/2; i < NumElems; ++i)
2274 if (!isUndefOrEqual(N->getMaskElt(i), i))
2280 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2281 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2283 bool X86::isMOVHPMask(ShuffleVectorSDNode *N) {
2284 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2286 if (NumElems != 2 && NumElems != 4)
2289 for (unsigned i = 0; i < NumElems/2; ++i)
2290 if (!isUndefOrEqual(N->getMaskElt(i), i))
2293 for (unsigned i = 0; i < NumElems/2; ++i)
2294 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2300 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2301 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2303 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2304 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2309 return isUndefOrEqual(N->getMaskElt(0), 2) &&
2310 isUndefOrEqual(N->getMaskElt(1), 3) &&
2311 isUndefOrEqual(N->getMaskElt(2), 2) &&
2312 isUndefOrEqual(N->getMaskElt(3), 3);
2315 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2316 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2317 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, MVT VT,
2318 bool V2IsSplat = false) {
2319 int NumElts = VT.getVectorNumElements();
2320 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2323 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2325 int BitI1 = Mask[i+1];
2326 if (!isUndefOrEqual(BitI, j))
2329 if (!isUndefOrEqual(BitI1, NumElts))
2332 if (!isUndefOrEqual(BitI1, j + NumElts))
2339 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2340 SmallVector<int, 8> M;
2342 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2345 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2346 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2347 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, MVT VT,
2348 bool V2IsSplat = false) {
2349 int NumElts = VT.getVectorNumElements();
2350 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2353 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2355 int BitI1 = Mask[i+1];
2356 if (!isUndefOrEqual(BitI, j + NumElts/2))
2359 if (isUndefOrEqual(BitI1, NumElts))
2362 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2369 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2370 SmallVector<int, 8> M;
2372 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2375 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2376 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2378 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, MVT VT) {
2379 int NumElems = VT.getVectorNumElements();
2380 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2383 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2385 int BitI1 = Mask[i+1];
2386 if (!isUndefOrEqual(BitI, j))
2388 if (!isUndefOrEqual(BitI1, j))
2394 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2395 SmallVector<int, 8> M;
2397 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2400 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2401 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2403 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, MVT VT) {
2404 int NumElems = VT.getVectorNumElements();
2405 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2408 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2410 int BitI1 = Mask[i+1];
2411 if (!isUndefOrEqual(BitI, j))
2413 if (!isUndefOrEqual(BitI1, j))
2419 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2420 SmallVector<int, 8> M;
2422 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2425 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2426 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2427 /// MOVSD, and MOVD, i.e. setting the lowest element.
2428 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, MVT VT) {
2429 if (VT.getVectorElementType().getSizeInBits() < 32)
2432 int NumElts = VT.getVectorNumElements();
2434 if (!isUndefOrEqual(Mask[0], NumElts))
2437 for (int i = 1; i < NumElts; ++i)
2438 if (!isUndefOrEqual(Mask[i], i))
2444 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2445 SmallVector<int, 8> M;
2447 return ::isMOVLMask(M, N->getValueType(0));
2450 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2451 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2452 /// element of vector 2 and the other elements to come from vector 1 in order.
2453 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, MVT VT,
2454 bool V2IsSplat = false, bool V2IsUndef = false) {
2455 int NumOps = VT.getVectorNumElements();
2456 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2459 if (!isUndefOrEqual(Mask[0], 0))
2462 for (int i = 1; i < NumOps; ++i)
2463 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
2464 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
2465 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
2471 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
2472 bool V2IsUndef = false) {
2473 SmallVector<int, 8> M;
2475 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
2478 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2479 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2480 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
2481 if (N->getValueType(0).getVectorNumElements() != 4)
2484 // Expect 1, 1, 3, 3
2485 for (unsigned i = 0; i < 2; ++i) {
2486 int Elt = N->getMaskElt(i);
2487 if (Elt >= 0 && Elt != 1)
2492 for (unsigned i = 2; i < 4; ++i) {
2493 int Elt = N->getMaskElt(i);
2494 if (Elt >= 0 && Elt != 3)
2499 // Don't use movshdup if it can be done with a shufps.
2500 // FIXME: verify that matching u, u, 3, 3 is what we want.
2504 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2505 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2506 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
2507 if (N->getValueType(0).getVectorNumElements() != 4)
2510 // Expect 0, 0, 2, 2
2511 for (unsigned i = 0; i < 2; ++i)
2512 if (N->getMaskElt(i) > 0)
2516 for (unsigned i = 2; i < 4; ++i) {
2517 int Elt = N->getMaskElt(i);
2518 if (Elt >= 0 && Elt != 2)
2523 // Don't use movsldup if it can be done with a shufps.
2527 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2528 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2529 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
2530 int e = N->getValueType(0).getVectorNumElements() / 2;
2532 for (int i = 0; i < e; ++i)
2533 if (!isUndefOrEqual(N->getMaskElt(i), i))
2535 for (int i = 0; i < e; ++i)
2536 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
2541 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2542 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2544 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2545 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2546 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
2548 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2550 for (int i = 0; i < NumOperands; ++i) {
2551 int Val = SVOp->getMaskElt(NumOperands-i-1);
2552 if (Val < 0) Val = 0;
2553 if (Val >= NumOperands) Val -= NumOperands;
2555 if (i != NumOperands - 1)
2561 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2562 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2564 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2565 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2567 // 8 nodes, but we only care about the last 4.
2568 for (unsigned i = 7; i >= 4; --i) {
2569 int Val = SVOp->getMaskElt(i);
2578 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2579 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2581 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2582 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2584 // 8 nodes, but we only care about the first 4.
2585 for (int i = 3; i >= 0; --i) {
2586 int Val = SVOp->getMaskElt(i);
2595 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
2596 /// their permute mask.
2597 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
2598 SelectionDAG &DAG) {
2599 MVT VT = SVOp->getValueType(0);
2600 unsigned NumElems = VT.getVectorNumElements();
2601 SmallVector<int, 8> MaskVec;
2603 for (unsigned i = 0; i != NumElems; ++i) {
2604 int idx = SVOp->getMaskElt(i);
2606 MaskVec.push_back(idx);
2607 else if (idx < (int)NumElems)
2608 MaskVec.push_back(idx + NumElems);
2610 MaskVec.push_back(idx - NumElems);
2612 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
2613 SVOp->getOperand(0), &MaskVec[0]);
2616 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2617 /// the two vector operands have swapped position.
2618 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, MVT VT) {
2619 unsigned NumElems = VT.getVectorNumElements();
2620 for (unsigned i = 0; i != NumElems; ++i) {
2624 else if (idx < (int)NumElems)
2625 Mask[i] = idx + NumElems;
2627 Mask[i] = idx - NumElems;
2631 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2632 /// match movhlps. The lower half elements should come from upper half of
2633 /// V1 (and in order), and the upper half elements should come from the upper
2634 /// half of V2 (and in order).
2635 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
2636 if (Op->getValueType(0).getVectorNumElements() != 4)
2638 for (unsigned i = 0, e = 2; i != e; ++i)
2639 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
2641 for (unsigned i = 2; i != 4; ++i)
2642 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
2647 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2648 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2650 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2651 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
2653 N = N->getOperand(0).getNode();
2654 if (!ISD::isNON_EXTLoad(N))
2657 *LD = cast<LoadSDNode>(N);
2661 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2662 /// match movlp{s|d}. The lower half elements should come from lower half of
2663 /// V1 (and in order), and the upper half elements should come from the upper
2664 /// half of V2 (and in order). And since V1 will become the source of the
2665 /// MOVLP, it must be either a vector load or a scalar load to vector.
2666 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
2667 ShuffleVectorSDNode *Op) {
2668 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2670 // Is V2 is a vector load, don't do this transformation. We will try to use
2671 // load folding shufps op.
2672 if (ISD::isNON_EXTLoad(V2))
2675 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
2677 if (NumElems != 2 && NumElems != 4)
2679 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2680 if (!isUndefOrEqual(Op->getMaskElt(i), i))
2682 for (unsigned i = NumElems/2; i != NumElems; ++i)
2683 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
2688 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2690 static bool isSplatVector(SDNode *N) {
2691 if (N->getOpcode() != ISD::BUILD_VECTOR)
2694 SDValue SplatValue = N->getOperand(0);
2695 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2696 if (N->getOperand(i) != SplatValue)
2701 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2703 static inline bool isZeroNode(SDValue Elt) {
2704 return ((isa<ConstantSDNode>(Elt) &&
2705 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2706 (isa<ConstantFPSDNode>(Elt) &&
2707 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2710 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2711 /// to an zero vector.
2712 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
2713 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
2714 SDValue V1 = N->getOperand(0);
2715 SDValue V2 = N->getOperand(1);
2716 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2717 for (unsigned i = 0; i != NumElems; ++i) {
2718 int Idx = N->getMaskElt(i);
2719 if (Idx >= (int)NumElems) {
2720 unsigned Opc = V2.getOpcode();
2721 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
2723 if (Opc != ISD::BUILD_VECTOR || !isZeroNode(V2.getOperand(Idx-NumElems)))
2725 } else if (Idx >= 0) {
2726 unsigned Opc = V1.getOpcode();
2727 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
2729 if (Opc != ISD::BUILD_VECTOR || !isZeroNode(V1.getOperand(Idx)))
2736 /// getZeroVector - Returns a vector of specified type with all zero elements.
2738 static SDValue getZeroVector(MVT VT, bool HasSSE2, SelectionDAG &DAG,
2740 assert(VT.isVector() && "Expected a vector type");
2742 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2743 // type. This ensures they get CSE'd.
2745 if (VT.getSizeInBits() == 64) { // MMX
2746 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2747 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2748 } else if (HasSSE2) { // SSE2
2749 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2750 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2752 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2753 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
2755 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2758 /// getOnesVector - Returns a vector of specified type with all bits set.
2760 static SDValue getOnesVector(MVT VT, SelectionDAG &DAG, DebugLoc dl) {
2761 assert(VT.isVector() && "Expected a vector type");
2763 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2764 // type. This ensures they get CSE'd.
2765 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2767 if (VT.getSizeInBits() == 64) // MMX
2768 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2770 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2771 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2775 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2776 /// that point to V2 points to its first element.
2777 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
2778 MVT VT = SVOp->getValueType(0);
2779 unsigned NumElems = VT.getVectorNumElements();
2781 bool Changed = false;
2782 SmallVector<int, 8> MaskVec;
2783 SVOp->getMask(MaskVec);
2785 for (unsigned i = 0; i != NumElems; ++i) {
2786 if (MaskVec[i] > (int)NumElems) {
2787 MaskVec[i] = NumElems;
2792 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
2793 SVOp->getOperand(1), &MaskVec[0]);
2794 return SDValue(SVOp, 0);
2797 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2798 /// operation of specified width.
2799 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
2801 unsigned NumElems = VT.getVectorNumElements();
2802 SmallVector<int, 8> Mask;
2803 Mask.push_back(NumElems);
2804 for (unsigned i = 1; i != NumElems; ++i)
2806 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2809 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
2810 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
2812 unsigned NumElems = VT.getVectorNumElements();
2813 SmallVector<int, 8> Mask;
2814 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2816 Mask.push_back(i + NumElems);
2818 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2821 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
2822 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, MVT VT, SDValue V1,
2824 unsigned NumElems = VT.getVectorNumElements();
2825 unsigned Half = NumElems/2;
2826 SmallVector<int, 8> Mask;
2827 for (unsigned i = 0; i != Half; ++i) {
2828 Mask.push_back(i + Half);
2829 Mask.push_back(i + NumElems + Half);
2831 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
2834 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
2835 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
2837 if (SV->getValueType(0).getVectorNumElements() <= 4)
2838 return SDValue(SV, 0);
2840 MVT PVT = MVT::v4f32;
2841 MVT VT = SV->getValueType(0);
2842 DebugLoc dl = SV->getDebugLoc();
2843 SDValue V1 = SV->getOperand(0);
2844 int NumElems = VT.getVectorNumElements();
2845 int EltNo = SV->getSplatIndex();
2847 // unpack elements to the correct location
2848 while (NumElems > 4) {
2849 if (EltNo < NumElems/2) {
2850 V1 = getUnpackl(DAG, dl, VT, V1, V1);
2852 V1 = getUnpackh(DAG, dl, VT, V1, V1);
2853 EltNo -= NumElems/2;
2858 // Perform the splat.
2859 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
2860 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
2861 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
2862 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
2865 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2866 /// vector of zero or undef vector. This produces a shuffle where the low
2867 /// element of V2 is swizzled into the zero/undef vector, landing at element
2868 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
2869 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
2870 bool isZero, bool HasSSE2,
2871 SelectionDAG &DAG) {
2872 MVT VT = V2.getValueType();
2874 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
2875 unsigned NumElems = VT.getVectorNumElements();
2876 SmallVector<int, 16> MaskVec;
2877 for (unsigned i = 0; i != NumElems; ++i)
2878 // If this is the insertion idx, put the low elt of V2 here.
2879 MaskVec.push_back(i == Idx ? NumElems : i);
2880 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
2883 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
2884 /// a shuffle that is zero.
2886 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
2887 bool Low, SelectionDAG &DAG) {
2888 unsigned NumZeros = 0;
2889 for (int i = 0; i < NumElems; ++i) {
2890 unsigned Index = Low ? i : NumElems-i-1;
2891 int Idx = SVOp->getMaskElt(Index);
2896 SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
2897 if (Elt.getNode() && isZeroNode(Elt))
2905 /// isVectorShift - Returns true if the shuffle can be implemented as a
2906 /// logical left or right shift of a vector.
2907 /// FIXME: split into pslldqi, psrldqi, palignr variants.
2908 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
2909 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
2910 int NumElems = SVOp->getValueType(0).getVectorNumElements();
2913 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
2916 NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
2920 bool SeenV1 = false;
2921 bool SeenV2 = false;
2922 for (int i = NumZeros; i < NumElems; ++i) {
2923 int Val = isLeft ? (i - NumZeros) : i;
2924 int Idx = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
2936 if (SeenV1 && SeenV2)
2939 ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
2945 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2947 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
2948 unsigned NumNonZero, unsigned NumZero,
2949 SelectionDAG &DAG, TargetLowering &TLI) {
2953 DebugLoc dl = Op.getDebugLoc();
2956 for (unsigned i = 0; i < 16; ++i) {
2957 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
2958 if (ThisIsNonZero && First) {
2960 V = getZeroVector(MVT::v8i16, true, DAG, dl);
2962 V = DAG.getUNDEF(MVT::v8i16);
2967 SDValue ThisElt(0, 0), LastElt(0, 0);
2968 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
2969 if (LastIsNonZero) {
2970 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
2971 MVT::i16, Op.getOperand(i-1));
2973 if (ThisIsNonZero) {
2974 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
2975 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
2976 ThisElt, DAG.getConstant(8, MVT::i8));
2978 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
2982 if (ThisElt.getNode())
2983 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
2984 DAG.getIntPtrConstant(i/2));
2988 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
2991 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
2993 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
2994 unsigned NumNonZero, unsigned NumZero,
2995 SelectionDAG &DAG, TargetLowering &TLI) {
2999 DebugLoc dl = Op.getDebugLoc();
3002 for (unsigned i = 0; i < 8; ++i) {
3003 bool isNonZero = (NonZeros & (1 << i)) != 0;
3007 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3009 V = DAG.getUNDEF(MVT::v8i16);
3012 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3013 MVT::v8i16, V, Op.getOperand(i),
3014 DAG.getIntPtrConstant(i));
3021 /// getVShift - Return a vector logical shift node.
3023 static SDValue getVShift(bool isLeft, MVT VT, SDValue SrcOp,
3024 unsigned NumBits, SelectionDAG &DAG,
3025 const TargetLowering &TLI, DebugLoc dl) {
3026 bool isMMX = VT.getSizeInBits() == 64;
3027 MVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3028 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3029 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3030 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3031 DAG.getNode(Opc, dl, ShVT, SrcOp,
3032 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3036 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3037 DebugLoc dl = Op.getDebugLoc();
3038 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3039 if (ISD::isBuildVectorAllZeros(Op.getNode())
3040 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3041 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3042 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3043 // eliminated on x86-32 hosts.
3044 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3047 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3048 return getOnesVector(Op.getValueType(), DAG, dl);
3049 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3052 MVT VT = Op.getValueType();
3053 MVT EVT = VT.getVectorElementType();
3054 unsigned EVTBits = EVT.getSizeInBits();
3056 unsigned NumElems = Op.getNumOperands();
3057 unsigned NumZero = 0;
3058 unsigned NumNonZero = 0;
3059 unsigned NonZeros = 0;
3060 bool IsAllConstants = true;
3061 SmallSet<SDValue, 8> Values;
3062 for (unsigned i = 0; i < NumElems; ++i) {
3063 SDValue Elt = Op.getOperand(i);
3064 if (Elt.getOpcode() == ISD::UNDEF)
3067 if (Elt.getOpcode() != ISD::Constant &&
3068 Elt.getOpcode() != ISD::ConstantFP)
3069 IsAllConstants = false;
3070 if (isZeroNode(Elt))
3073 NonZeros |= (1 << i);
3078 if (NumNonZero == 0) {
3079 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3080 return DAG.getUNDEF(VT);
3083 // Special case for single non-zero, non-undef, element.
3084 if (NumNonZero == 1) {
3085 unsigned Idx = CountTrailingZeros_32(NonZeros);
3086 SDValue Item = Op.getOperand(Idx);
3088 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3089 // the value are obviously zero, truncate the value to i32 and do the
3090 // insertion that way. Only do this if the value is non-constant or if the
3091 // value is a constant being inserted into element 0. It is cheaper to do
3092 // a constant pool load than it is to do a movd + shuffle.
3093 if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3094 (!IsAllConstants || Idx == 0)) {
3095 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3096 // Handle MMX and SSE both.
3097 MVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3098 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3100 // Truncate the value (which may itself be a constant) to i32, and
3101 // convert it to a vector with movd (S2V+shuffle to zero extend).
3102 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3103 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3104 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3105 Subtarget->hasSSE2(), DAG);
3107 // Now we have our 32-bit value zero extended in the low element of
3108 // a vector. If Idx != 0, swizzle it into place.
3110 SmallVector<int, 4> Mask;
3111 Mask.push_back(Idx);
3112 for (unsigned i = 1; i != VecElts; ++i)
3114 Item = DAG.getVectorShuffle(VecVT, dl, Item,
3115 DAG.getUNDEF(Item.getValueType()),
3118 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3122 // If we have a constant or non-constant insertion into the low element of
3123 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3124 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3125 // depending on what the source datatype is.
3128 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3129 } else if (EVT == MVT::i32 || EVT == MVT::f32 || EVT == MVT::f64 ||
3130 (EVT == MVT::i64 && Subtarget->is64Bit())) {
3131 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3132 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3133 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3135 } else if (EVT == MVT::i16 || EVT == MVT::i8) {
3136 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3137 MVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3138 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3139 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3140 Subtarget->hasSSE2(), DAG);
3141 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3145 // Is it a vector logical left shift?
3146 if (NumElems == 2 && Idx == 1 &&
3147 isZeroNode(Op.getOperand(0)) && !isZeroNode(Op.getOperand(1))) {
3148 unsigned NumBits = VT.getSizeInBits();
3149 return getVShift(true, VT,
3150 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3151 VT, Op.getOperand(1)),
3152 NumBits/2, DAG, *this, dl);
3155 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3158 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3159 // is a non-constant being inserted into an element other than the low one,
3160 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3161 // movd/movss) to move this into the low element, then shuffle it into
3163 if (EVTBits == 32) {
3164 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3166 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3167 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3168 Subtarget->hasSSE2(), DAG);
3169 SmallVector<int, 8> MaskVec;
3170 for (unsigned i = 0; i < NumElems; i++)
3171 MaskVec.push_back(i == Idx ? 0 : 1);
3172 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3176 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3177 if (Values.size() == 1)
3180 // A vector full of immediates; various special cases are already
3181 // handled, so this is best done with a single constant-pool load.
3185 // Let legalizer expand 2-wide build_vectors.
3186 if (EVTBits == 64) {
3187 if (NumNonZero == 1) {
3188 // One half is zero or undef.
3189 unsigned Idx = CountTrailingZeros_32(NonZeros);
3190 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3191 Op.getOperand(Idx));
3192 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3193 Subtarget->hasSSE2(), DAG);
3198 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3199 if (EVTBits == 8 && NumElems == 16) {
3200 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3202 if (V.getNode()) return V;
3205 if (EVTBits == 16 && NumElems == 8) {
3206 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3208 if (V.getNode()) return V;
3211 // If element VT is == 32 bits, turn it into a number of shuffles.
3212 SmallVector<SDValue, 8> V;
3214 if (NumElems == 4 && NumZero > 0) {
3215 for (unsigned i = 0; i < 4; ++i) {
3216 bool isZero = !(NonZeros & (1 << i));
3218 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3220 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3223 for (unsigned i = 0; i < 2; ++i) {
3224 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3227 V[i] = V[i*2]; // Must be a zero vector.
3230 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3233 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3236 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3241 SmallVector<int, 8> MaskVec;
3242 bool Reverse = (NonZeros & 0x3) == 2;
3243 for (unsigned i = 0; i < 2; ++i)
3244 MaskVec.push_back(Reverse ? 1-i : i);
3245 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3246 for (unsigned i = 0; i < 2; ++i)
3247 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3248 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3251 if (Values.size() > 2) {
3252 // If we have SSE 4.1, Expand into a number of inserts unless the number of
3253 // values to be inserted is equal to the number of elements, in which case
3254 // use the unpack code below in the hopes of matching the consecutive elts
3255 // load merge pattern for shuffles.
3256 // FIXME: We could probably just check that here directly.
3257 if (Values.size() < NumElems && VT.getSizeInBits() == 128 &&
3258 getSubtarget()->hasSSE41()) {
3259 V[0] = DAG.getUNDEF(VT);
3260 for (unsigned i = 0; i < NumElems; ++i)
3261 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3262 V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3263 Op.getOperand(i), DAG.getIntPtrConstant(i));
3266 // Expand into a number of unpckl*.
3268 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3269 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3270 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3271 for (unsigned i = 0; i < NumElems; ++i)
3272 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3274 while (NumElems != 0) {
3275 for (unsigned i = 0; i < NumElems; ++i)
3276 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3285 // v8i16 shuffles - Prefer shuffles in the following order:
3286 // 1. [all] pshuflw, pshufhw, optional move
3287 // 2. [ssse3] 1 x pshufb
3288 // 3. [ssse3] 2 x pshufb + 1 x por
3289 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
3291 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
3292 SelectionDAG &DAG, X86TargetLowering &TLI) {
3293 SDValue V1 = SVOp->getOperand(0);
3294 SDValue V2 = SVOp->getOperand(1);
3295 DebugLoc dl = SVOp->getDebugLoc();
3296 SmallVector<int, 8> MaskVals;
3298 // Determine if more than 1 of the words in each of the low and high quadwords
3299 // of the result come from the same quadword of one of the two inputs. Undef
3300 // mask values count as coming from any quadword, for better codegen.
3301 SmallVector<unsigned, 4> LoQuad(4);
3302 SmallVector<unsigned, 4> HiQuad(4);
3303 BitVector InputQuads(4);
3304 for (unsigned i = 0; i < 8; ++i) {
3305 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
3306 int EltIdx = SVOp->getMaskElt(i);
3307 MaskVals.push_back(EltIdx);
3316 InputQuads.set(EltIdx / 4);
3319 int BestLoQuad = -1;
3320 unsigned MaxQuad = 1;
3321 for (unsigned i = 0; i < 4; ++i) {
3322 if (LoQuad[i] > MaxQuad) {
3324 MaxQuad = LoQuad[i];
3328 int BestHiQuad = -1;
3330 for (unsigned i = 0; i < 4; ++i) {
3331 if (HiQuad[i] > MaxQuad) {
3333 MaxQuad = HiQuad[i];
3337 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
3338 // of the two input vectors, shuffle them into one input vector so only a
3339 // single pshufb instruction is necessary. If There are more than 2 input
3340 // quads, disable the next transformation since it does not help SSSE3.
3341 bool V1Used = InputQuads[0] || InputQuads[1];
3342 bool V2Used = InputQuads[2] || InputQuads[3];
3343 if (TLI.getSubtarget()->hasSSSE3()) {
3344 if (InputQuads.count() == 2 && V1Used && V2Used) {
3345 BestLoQuad = InputQuads.find_first();
3346 BestHiQuad = InputQuads.find_next(BestLoQuad);
3348 if (InputQuads.count() > 2) {
3354 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
3355 // the shuffle mask. If a quad is scored as -1, that means that it contains
3356 // words from all 4 input quadwords.
3358 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
3359 SmallVector<int, 8> MaskV;
3360 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
3361 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
3362 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
3363 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
3364 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
3365 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
3367 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
3368 // source words for the shuffle, to aid later transformations.
3369 bool AllWordsInNewV = true;
3370 bool InOrder[2] = { true, true };
3371 for (unsigned i = 0; i != 8; ++i) {
3372 int idx = MaskVals[i];
3374 InOrder[i/4] = false;
3375 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
3377 AllWordsInNewV = false;
3381 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
3382 if (AllWordsInNewV) {
3383 for (int i = 0; i != 8; ++i) {
3384 int idx = MaskVals[i];
3387 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
3388 if ((idx != i) && idx < 4)
3390 if ((idx != i) && idx > 3)
3399 // If we've eliminated the use of V2, and the new mask is a pshuflw or
3400 // pshufhw, that's as cheap as it gets. Return the new shuffle.
3401 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
3402 return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
3403 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
3407 // If we have SSSE3, and all words of the result are from 1 input vector,
3408 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
3409 // is present, fall back to case 4.
3410 if (TLI.getSubtarget()->hasSSSE3()) {
3411 SmallVector<SDValue,16> pshufbMask;
3413 // If we have elements from both input vectors, set the high bit of the
3414 // shuffle mask element to zero out elements that come from V2 in the V1
3415 // mask, and elements that come from V1 in the V2 mask, so that the two
3416 // results can be OR'd together.
3417 bool TwoInputs = V1Used && V2Used;
3418 for (unsigned i = 0; i != 8; ++i) {
3419 int EltIdx = MaskVals[i] * 2;
3420 if (TwoInputs && (EltIdx >= 16)) {
3421 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3422 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3425 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3426 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
3428 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
3429 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3430 DAG.getNode(ISD::BUILD_VECTOR, dl,
3431 MVT::v16i8, &pshufbMask[0], 16));
3433 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3435 // Calculate the shuffle mask for the second input, shuffle it, and
3436 // OR it with the first shuffled input.
3438 for (unsigned i = 0; i != 8; ++i) {
3439 int EltIdx = MaskVals[i] * 2;
3441 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3442 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3445 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3446 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
3448 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
3449 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3450 DAG.getNode(ISD::BUILD_VECTOR, dl,
3451 MVT::v16i8, &pshufbMask[0], 16));
3452 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3453 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3456 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
3457 // and update MaskVals with new element order.
3458 BitVector InOrder(8);
3459 if (BestLoQuad >= 0) {
3460 SmallVector<int, 8> MaskV;
3461 for (int i = 0; i != 4; ++i) {
3462 int idx = MaskVals[i];
3464 MaskV.push_back(-1);
3466 } else if ((idx / 4) == BestLoQuad) {
3467 MaskV.push_back(idx & 3);
3470 MaskV.push_back(-1);
3473 for (unsigned i = 4; i != 8; ++i)
3475 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3479 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
3480 // and update MaskVals with the new element order.
3481 if (BestHiQuad >= 0) {
3482 SmallVector<int, 8> MaskV;
3483 for (unsigned i = 0; i != 4; ++i)
3485 for (unsigned i = 4; i != 8; ++i) {
3486 int idx = MaskVals[i];
3488 MaskV.push_back(-1);
3490 } else if ((idx / 4) == BestHiQuad) {
3491 MaskV.push_back((idx & 3) + 4);
3494 MaskV.push_back(-1);
3497 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3501 // In case BestHi & BestLo were both -1, which means each quadword has a word
3502 // from each of the four input quadwords, calculate the InOrder bitvector now
3503 // before falling through to the insert/extract cleanup.
3504 if (BestLoQuad == -1 && BestHiQuad == -1) {
3506 for (int i = 0; i != 8; ++i)
3507 if (MaskVals[i] < 0 || MaskVals[i] == i)
3511 // The other elements are put in the right place using pextrw and pinsrw.
3512 for (unsigned i = 0; i != 8; ++i) {
3515 int EltIdx = MaskVals[i];
3518 SDValue ExtOp = (EltIdx < 8)
3519 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
3520 DAG.getIntPtrConstant(EltIdx))
3521 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
3522 DAG.getIntPtrConstant(EltIdx - 8));
3523 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3524 DAG.getIntPtrConstant(i));
3529 // v16i8 shuffles - Prefer shuffles in the following order:
3530 // 1. [ssse3] 1 x pshufb
3531 // 2. [ssse3] 2 x pshufb + 1 x por
3532 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
3534 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
3535 SelectionDAG &DAG, X86TargetLowering &TLI) {
3536 SDValue V1 = SVOp->getOperand(0);
3537 SDValue V2 = SVOp->getOperand(1);
3538 DebugLoc dl = SVOp->getDebugLoc();
3539 SmallVector<int, 16> MaskVals;
3540 SVOp->getMask(MaskVals);
3542 // If we have SSSE3, case 1 is generated when all result bytes come from
3543 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
3544 // present, fall back to case 3.
3545 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
3548 for (unsigned i = 0; i < 16; ++i) {
3549 int EltIdx = MaskVals[i];
3558 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
3559 if (TLI.getSubtarget()->hasSSSE3()) {
3560 SmallVector<SDValue,16> pshufbMask;
3562 // If all result elements are from one input vector, then only translate
3563 // undef mask values to 0x80 (zero out result) in the pshufb mask.
3565 // Otherwise, we have elements from both input vectors, and must zero out
3566 // elements that come from V2 in the first mask, and V1 in the second mask
3567 // so that we can OR them together.
3568 bool TwoInputs = !(V1Only || V2Only);
3569 for (unsigned i = 0; i != 16; ++i) {
3570 int EltIdx = MaskVals[i];
3571 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
3572 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3575 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3577 // If all the elements are from V2, assign it to V1 and return after
3578 // building the first pshufb.
3581 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3582 DAG.getNode(ISD::BUILD_VECTOR, dl,
3583 MVT::v16i8, &pshufbMask[0], 16));
3587 // Calculate the shuffle mask for the second input, shuffle it, and
3588 // OR it with the first shuffled input.
3590 for (unsigned i = 0; i != 16; ++i) {
3591 int EltIdx = MaskVals[i];
3593 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3596 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3598 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3599 DAG.getNode(ISD::BUILD_VECTOR, dl,
3600 MVT::v16i8, &pshufbMask[0], 16));
3601 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3604 // No SSSE3 - Calculate in place words and then fix all out of place words
3605 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
3606 // the 16 different words that comprise the two doublequadword input vectors.
3607 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3608 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
3609 SDValue NewV = V2Only ? V2 : V1;
3610 for (int i = 0; i != 8; ++i) {
3611 int Elt0 = MaskVals[i*2];
3612 int Elt1 = MaskVals[i*2+1];
3614 // This word of the result is all undef, skip it.
3615 if (Elt0 < 0 && Elt1 < 0)
3618 // This word of the result is already in the correct place, skip it.
3619 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
3621 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
3624 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
3625 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
3628 // If Elt0 and Elt1 are defined, are consecutive, and can be load
3629 // using a single extract together, load it and store it.
3630 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
3631 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3632 DAG.getIntPtrConstant(Elt1 / 2));
3633 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3634 DAG.getIntPtrConstant(i));
3638 // If Elt1 is defined, extract it from the appropriate source. If the
3639 // source byte is not also odd, shift the extracted word left 8 bits
3640 // otherwise clear the bottom 8 bits if we need to do an or.
3642 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3643 DAG.getIntPtrConstant(Elt1 / 2));
3644 if ((Elt1 & 1) == 0)
3645 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
3646 DAG.getConstant(8, TLI.getShiftAmountTy()));
3648 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
3649 DAG.getConstant(0xFF00, MVT::i16));
3651 // If Elt0 is defined, extract it from the appropriate source. If the
3652 // source byte is not also even, shift the extracted word right 8 bits. If
3653 // Elt1 was also defined, OR the extracted values together before
3654 // inserting them in the result.
3656 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
3657 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
3658 if ((Elt0 & 1) != 0)
3659 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
3660 DAG.getConstant(8, TLI.getShiftAmountTy()));
3662 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
3663 DAG.getConstant(0x00FF, MVT::i16));
3664 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
3667 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3668 DAG.getIntPtrConstant(i));
3670 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
3673 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3674 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3675 /// done when every pair / quad of shuffle mask elements point to elements in
3676 /// the right sequence. e.g.
3677 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3679 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
3681 TargetLowering &TLI, DebugLoc dl) {
3682 MVT VT = SVOp->getValueType(0);
3683 SDValue V1 = SVOp->getOperand(0);
3684 SDValue V2 = SVOp->getOperand(1);
3685 unsigned NumElems = VT.getVectorNumElements();
3686 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3687 MVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3688 MVT MaskEltVT = MaskVT.getVectorElementType();
3690 switch (VT.getSimpleVT()) {
3691 default: assert(false && "Unexpected!");
3692 case MVT::v4f32: NewVT = MVT::v2f64; break;
3693 case MVT::v4i32: NewVT = MVT::v2i64; break;
3694 case MVT::v8i16: NewVT = MVT::v4i32; break;
3695 case MVT::v16i8: NewVT = MVT::v4i32; break;
3698 if (NewWidth == 2) {
3704 int Scale = NumElems / NewWidth;
3705 SmallVector<int, 8> MaskVec;
3706 for (unsigned i = 0; i < NumElems; i += Scale) {
3708 for (int j = 0; j < Scale; ++j) {
3709 int EltIdx = SVOp->getMaskElt(i+j);
3713 StartIdx = EltIdx - (EltIdx % Scale);
3714 if (EltIdx != StartIdx + j)
3718 MaskVec.push_back(-1);
3720 MaskVec.push_back(StartIdx / Scale);
3723 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
3724 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
3725 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
3728 /// getVZextMovL - Return a zero-extending vector move low node.
3730 static SDValue getVZextMovL(MVT VT, MVT OpVT,
3731 SDValue SrcOp, SelectionDAG &DAG,
3732 const X86Subtarget *Subtarget, DebugLoc dl) {
3733 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3734 LoadSDNode *LD = NULL;
3735 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
3736 LD = dyn_cast<LoadSDNode>(SrcOp);
3738 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3740 MVT EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3741 if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
3742 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3743 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3744 SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
3746 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3747 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3748 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3749 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3757 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3758 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3759 DAG.getNode(ISD::BIT_CONVERT, dl,
3763 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
3766 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3767 SDValue V1 = SVOp->getOperand(0);
3768 SDValue V2 = SVOp->getOperand(1);
3769 DebugLoc dl = SVOp->getDebugLoc();
3770 MVT VT = SVOp->getValueType(0);
3772 SmallVector<std::pair<int, int>, 8> Locs;
3774 SmallVector<int, 8> Mask1(4U, -1);
3775 SmallVector<int, 8> PermMask;
3776 SVOp->getMask(PermMask);
3780 for (unsigned i = 0; i != 4; ++i) {
3781 int Idx = PermMask[i];
3783 Locs[i] = std::make_pair(-1, -1);
3785 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
3787 Locs[i] = std::make_pair(0, NumLo);
3791 Locs[i] = std::make_pair(1, NumHi);
3793 Mask1[2+NumHi] = Idx;
3799 if (NumLo <= 2 && NumHi <= 2) {
3800 // If no more than two elements come from either vector. This can be
3801 // implemented with two shuffles. First shuffle gather the elements.
3802 // The second shuffle, which takes the first shuffle as both of its
3803 // vector operands, put the elements into the right order.
3804 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
3806 SmallVector<int, 8> Mask2(4U, -1);
3808 for (unsigned i = 0; i != 4; ++i) {
3809 if (Locs[i].first == -1)
3812 unsigned Idx = (i < 2) ? 0 : 4;
3813 Idx += Locs[i].first * 2 + Locs[i].second;
3818 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
3819 } else if (NumLo == 3 || NumHi == 3) {
3820 // Otherwise, we must have three elements from one vector, call it X, and
3821 // one element from the other, call it Y. First, use a shufps to build an
3822 // intermediate vector with the one element from Y and the element from X
3823 // that will be in the same half in the final destination (the indexes don't
3824 // matter). Then, use a shufps to build the final vector, taking the half
3825 // containing the element from Y from the intermediate, and the other half
3828 // Normalize it so the 3 elements come from V1.
3829 CommuteVectorShuffleMask(PermMask, VT);
3833 // Find the element from V2.
3835 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
3836 int Val = PermMask[HiIndex];
3843 Mask1[0] = PermMask[HiIndex];
3845 Mask1[2] = PermMask[HiIndex^1];
3847 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
3850 Mask1[0] = PermMask[0];
3851 Mask1[1] = PermMask[1];
3852 Mask1[2] = HiIndex & 1 ? 6 : 4;
3853 Mask1[3] = HiIndex & 1 ? 4 : 6;
3854 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
3856 Mask1[0] = HiIndex & 1 ? 2 : 0;
3857 Mask1[1] = HiIndex & 1 ? 0 : 2;
3858 Mask1[2] = PermMask[2];
3859 Mask1[3] = PermMask[3];
3864 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
3868 // Break it into (shuffle shuffle_hi, shuffle_lo).
3870 SmallVector<int,8> LoMask(4U, -1);
3871 SmallVector<int,8> HiMask(4U, -1);
3873 SmallVector<int,8> *MaskPtr = &LoMask;
3874 unsigned MaskIdx = 0;
3877 for (unsigned i = 0; i != 4; ++i) {
3884 int Idx = PermMask[i];
3886 Locs[i] = std::make_pair(-1, -1);
3887 } else if (Idx < 4) {
3888 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3889 (*MaskPtr)[LoIdx] = Idx;
3892 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3893 (*MaskPtr)[HiIdx] = Idx;
3898 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
3899 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
3900 SmallVector<int, 8> MaskOps;
3901 for (unsigned i = 0; i != 4; ++i) {
3902 if (Locs[i].first == -1) {
3903 MaskOps.push_back(-1);
3905 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
3906 MaskOps.push_back(Idx);
3909 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
3913 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
3914 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
3915 SDValue V1 = Op.getOperand(0);
3916 SDValue V2 = Op.getOperand(1);
3917 MVT VT = Op.getValueType();
3918 DebugLoc dl = Op.getDebugLoc();
3919 unsigned NumElems = VT.getVectorNumElements();
3920 bool isMMX = VT.getSizeInBits() == 64;
3921 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3922 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3923 bool V1IsSplat = false;
3924 bool V2IsSplat = false;
3926 if (isZeroShuffle(SVOp))
3927 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3929 // Promote splats to v4f32.
3930 if (SVOp->isSplat()) {
3931 if (isMMX || NumElems < 4)
3933 return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
3936 // If the shuffle can be profitably rewritten as a narrower shuffle, then
3938 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3939 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
3940 if (NewOp.getNode())
3941 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3942 LowerVECTOR_SHUFFLE(NewOp, DAG));
3943 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3944 // FIXME: Figure out a cleaner way to do this.
3945 // Try to make use of movq to zero out the top part.
3946 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
3947 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
3948 if (NewOp.getNode()) {
3949 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
3950 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
3951 DAG, Subtarget, dl);
3953 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
3954 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
3955 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
3956 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
3957 DAG, Subtarget, dl);
3961 if (X86::isPSHUFDMask(SVOp))
3964 // Check if this can be converted into a logical shift.
3965 bool isLeft = false;
3968 bool isShift = getSubtarget()->hasSSE2() &&
3969 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
3970 if (isShift && ShVal.hasOneUse()) {
3971 // If the shifted value has multiple uses, it may be cheaper to use
3972 // v_set0 + movlhps or movhlps, etc.
3973 MVT EVT = VT.getVectorElementType();
3974 ShAmt *= EVT.getSizeInBits();
3975 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
3978 if (X86::isMOVLMask(SVOp)) {
3981 if (ISD::isBuildVectorAllZeros(V1.getNode()))
3982 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
3987 // FIXME: fold these into legal mask.
3988 if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
3989 X86::isMOVSLDUPMask(SVOp) ||
3990 X86::isMOVHLPSMask(SVOp) ||
3991 X86::isMOVHPMask(SVOp) ||
3992 X86::isMOVLPMask(SVOp)))
3995 if (ShouldXformToMOVHLPS(SVOp) ||
3996 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
3997 return CommuteVectorShuffle(SVOp, DAG);
4000 // No better options. Use a vshl / vsrl.
4001 MVT EVT = VT.getVectorElementType();
4002 ShAmt *= EVT.getSizeInBits();
4003 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4006 bool Commuted = false;
4007 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4008 // 1,1,1,1 -> v8i16 though.
4009 V1IsSplat = isSplatVector(V1.getNode());
4010 V2IsSplat = isSplatVector(V2.getNode());
4012 // Canonicalize the splat or undef, if present, to be on the RHS.
4013 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4014 Op = CommuteVectorShuffle(SVOp, DAG);
4015 SVOp = cast<ShuffleVectorSDNode>(Op);
4016 V1 = SVOp->getOperand(0);
4017 V2 = SVOp->getOperand(1);
4018 std::swap(V1IsSplat, V2IsSplat);
4019 std::swap(V1IsUndef, V2IsUndef);
4023 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4024 // Shuffling low element of v1 into undef, just return v1.
4027 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4028 // the instruction selector will not match, so get a canonical MOVL with
4029 // swapped operands to undo the commute.
4030 return getMOVL(DAG, dl, VT, V2, V1);
4033 if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4034 X86::isUNPCKH_v_undef_Mask(SVOp) ||
4035 X86::isUNPCKLMask(SVOp) ||
4036 X86::isUNPCKHMask(SVOp))
4040 // Normalize mask so all entries that point to V2 points to its first
4041 // element then try to match unpck{h|l} again. If match, return a
4042 // new vector_shuffle with the corrected mask.
4043 SDValue NewMask = NormalizeMask(SVOp, DAG);
4044 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4045 if (NSVOp != SVOp) {
4046 if (X86::isUNPCKLMask(NSVOp, true)) {
4048 } else if (X86::isUNPCKHMask(NSVOp, true)) {
4055 // Commute is back and try unpck* again.
4056 // FIXME: this seems wrong.
4057 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4058 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4059 if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4060 X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4061 X86::isUNPCKLMask(NewSVOp) ||
4062 X86::isUNPCKHMask(NewSVOp))
4066 // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4068 // Normalize the node to match x86 shuffle ops if needed
4069 if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4070 return CommuteVectorShuffle(SVOp, DAG);
4072 // Check for legal shuffle and return?
4073 SmallVector<int, 16> PermMask;
4074 SVOp->getMask(PermMask);
4075 if (isShuffleMaskLegal(PermMask, VT))
4078 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4079 if (VT == MVT::v8i16) {
4080 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4081 if (NewOp.getNode())
4085 if (VT == MVT::v16i8) {
4086 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4087 if (NewOp.getNode())
4091 // Handle all 4 wide cases with a number of shuffles except for MMX.
4092 if (NumElems == 4 && !isMMX)
4093 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4099 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4100 SelectionDAG &DAG) {
4101 MVT VT = Op.getValueType();
4102 DebugLoc dl = Op.getDebugLoc();
4103 if (VT.getSizeInBits() == 8) {
4104 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4105 Op.getOperand(0), Op.getOperand(1));
4106 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4107 DAG.getValueType(VT));
4108 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4109 } else if (VT.getSizeInBits() == 16) {
4110 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4111 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4113 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4114 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4115 DAG.getNode(ISD::BIT_CONVERT, dl,
4119 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4120 Op.getOperand(0), Op.getOperand(1));
4121 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4122 DAG.getValueType(VT));
4123 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4124 } else if (VT == MVT::f32) {
4125 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4126 // the result back to FR32 register. It's only worth matching if the
4127 // result has a single use which is a store or a bitcast to i32. And in
4128 // the case of a store, it's not worth it if the index is a constant 0,
4129 // because a MOVSSmr can be used instead, which is smaller and faster.
4130 if (!Op.hasOneUse())
4132 SDNode *User = *Op.getNode()->use_begin();
4133 if ((User->getOpcode() != ISD::STORE ||
4134 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4135 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4136 (User->getOpcode() != ISD::BIT_CONVERT ||
4137 User->getValueType(0) != MVT::i32))
4139 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4140 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4143 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4144 } else if (VT == MVT::i32) {
4145 // ExtractPS works with constant index.
4146 if (isa<ConstantSDNode>(Op.getOperand(1)))
4154 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4155 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4158 if (Subtarget->hasSSE41()) {
4159 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4164 MVT VT = Op.getValueType();
4165 DebugLoc dl = Op.getDebugLoc();
4166 // TODO: handle v16i8.
4167 if (VT.getSizeInBits() == 16) {
4168 SDValue Vec = Op.getOperand(0);
4169 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4171 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4172 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4173 DAG.getNode(ISD::BIT_CONVERT, dl,
4176 // Transform it so it match pextrw which produces a 32-bit result.
4177 MVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT()+1);
4178 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EVT,
4179 Op.getOperand(0), Op.getOperand(1));
4180 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EVT, Extract,
4181 DAG.getValueType(VT));
4182 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4183 } else if (VT.getSizeInBits() == 32) {
4184 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4188 // SHUFPS the element to the lowest double word, then movss.
4189 int Mask[4] = { Idx, -1, -1, -1 };
4190 MVT VVT = Op.getOperand(0).getValueType();
4191 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4192 DAG.getUNDEF(VVT), Mask);
4193 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4194 DAG.getIntPtrConstant(0));
4195 } else if (VT.getSizeInBits() == 64) {
4196 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4197 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4198 // to match extract_elt for f64.
4199 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4203 // UNPCKHPD the element to the lowest double word, then movsd.
4204 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4205 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4206 int Mask[2] = { 1, -1 };
4207 MVT VVT = Op.getOperand(0).getValueType();
4208 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4209 DAG.getUNDEF(VVT), Mask);
4210 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4211 DAG.getIntPtrConstant(0));
4218 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4219 MVT VT = Op.getValueType();
4220 MVT EVT = VT.getVectorElementType();
4221 DebugLoc dl = Op.getDebugLoc();
4223 SDValue N0 = Op.getOperand(0);
4224 SDValue N1 = Op.getOperand(1);
4225 SDValue N2 = Op.getOperand(2);
4227 if ((EVT.getSizeInBits() == 8 || EVT.getSizeInBits() == 16) &&
4228 isa<ConstantSDNode>(N2)) {
4229 unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4231 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4233 if (N1.getValueType() != MVT::i32)
4234 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4235 if (N2.getValueType() != MVT::i32)
4236 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4237 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4238 } else if (EVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4239 // Bits [7:6] of the constant are the source select. This will always be
4240 // zero here. The DAG Combiner may combine an extract_elt index into these
4241 // bits. For example (insert (extract, 3), 2) could be matched by putting
4242 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4243 // Bits [5:4] of the constant are the destination select. This is the
4244 // value of the incoming immediate.
4245 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4246 // combine either bitwise AND or insert of float 0.0 to set these bits.
4247 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4248 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4249 } else if (EVT == MVT::i32) {
4250 // InsertPS works with constant index.
4251 if (isa<ConstantSDNode>(N2))
4258 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4259 MVT VT = Op.getValueType();
4260 MVT EVT = VT.getVectorElementType();
4262 if (Subtarget->hasSSE41())
4263 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4268 DebugLoc dl = Op.getDebugLoc();
4269 SDValue N0 = Op.getOperand(0);
4270 SDValue N1 = Op.getOperand(1);
4271 SDValue N2 = Op.getOperand(2);
4273 if (EVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
4274 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4275 // as its second argument.
4276 if (N1.getValueType() != MVT::i32)
4277 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4278 if (N2.getValueType() != MVT::i32)
4279 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4280 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
4286 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4287 DebugLoc dl = Op.getDebugLoc();
4288 if (Op.getValueType() == MVT::v2f32)
4289 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4290 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4291 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4292 Op.getOperand(0))));
4294 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4295 MVT VT = MVT::v2i32;
4296 switch (Op.getValueType().getSimpleVT()) {
4303 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4304 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4307 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4308 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4309 // one of the above mentioned nodes. It has to be wrapped because otherwise
4310 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4311 // be used to form addressing mode. These wrapped nodes will be selected
4314 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4315 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4316 // FIXME there isn't really any debug info here, should come from the parent
4317 DebugLoc dl = CP->getDebugLoc();
4318 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
4319 CP->getAlignment());
4320 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4321 // With PIC, the address is actually $g + Offset.
4322 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4323 !Subtarget->isPICStyleRIPRel()) {
4324 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4325 DAG.getNode(X86ISD::GlobalBaseReg,
4326 DebugLoc::getUnknownLoc(),
4335 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
4337 SelectionDAG &DAG) const {
4338 bool IsPic = getTargetMachine().getRelocationModel() == Reloc::PIC_;
4339 bool ExtraLoadRequired =
4340 Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false);
4342 // Create the TargetGlobalAddress node, folding in the constant
4343 // offset if it is legal.
4345 if (!IsPic && !ExtraLoadRequired && isInt32(Offset)) {
4346 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4349 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0);
4350 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4352 // With PIC, the address is actually $g + Offset.
4353 if (IsPic && !Subtarget->isPICStyleRIPRel()) {
4354 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4355 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4359 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4360 // load the value at address GV, not the value of GV itself. This means that
4361 // the GlobalAddress must be in the base or index register of the address, not
4362 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4363 // The same applies for external symbols during PIC codegen
4364 if (ExtraLoadRequired)
4365 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
4366 PseudoSourceValue::getGOT(), 0);
4368 // If there was a non-zero offset that we didn't fold, create an explicit
4371 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
4372 DAG.getConstant(Offset, getPointerTy()));
4378 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4379 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4380 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4381 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
4385 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
4386 SDValue *InFlag, const MVT PtrVT, unsigned ReturnReg) {
4387 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4388 DebugLoc dl = GA->getDebugLoc();
4389 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4390 GA->getValueType(0),
4393 SDValue Ops[] = { Chain, TGA, *InFlag };
4394 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
4396 SDValue Ops[] = { Chain, TGA };
4397 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
4399 SDValue Flag = Chain.getValue(1);
4400 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
4403 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4405 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4408 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
4409 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
4410 DAG.getNode(X86ISD::GlobalBaseReg,
4411 DebugLoc::getUnknownLoc(),
4413 InFlag = Chain.getValue(1);
4415 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX);
4418 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4420 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4422 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT, X86::RAX);
4425 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4426 // "local exec" model.
4427 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4428 const MVT PtrVT, TLSModel::Model model,
4430 DebugLoc dl = GA->getDebugLoc();
4431 // Get the Thread Pointer
4432 SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
4433 DebugLoc::getUnknownLoc(), PtrVT,
4434 DAG.getRegister(is64Bit? X86::FS : X86::GS,
4437 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
4440 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4442 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4443 GA->getValueType(0),
4445 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
4447 if (model == TLSModel::InitialExec)
4448 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
4449 PseudoSourceValue::getGOT(), 0);
4451 // The address of the thread local variable is the add of the thread
4452 // pointer with the offset of the variable.
4453 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
4457 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4458 // TODO: implement the "local dynamic" model
4459 // TODO: implement the "initial exec"model for pic executables
4460 assert(Subtarget->isTargetELF() &&
4461 "TLS not implemented for non-ELF targets");
4462 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4463 GlobalValue *GV = GA->getGlobal();
4464 TLSModel::Model model =
4465 getTLSModel (GV, getTargetMachine().getRelocationModel());
4466 if (Subtarget->is64Bit()) {
4468 case TLSModel::GeneralDynamic:
4469 case TLSModel::LocalDynamic: // not implemented
4470 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4472 case TLSModel::InitialExec:
4473 case TLSModel::LocalExec:
4474 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model, true);
4478 case TLSModel::GeneralDynamic:
4479 case TLSModel::LocalDynamic: // not implemented
4480 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4482 case TLSModel::InitialExec:
4483 case TLSModel::LocalExec:
4484 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model, false);
4487 assert(0 && "Unreachable");
4492 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4493 // FIXME there isn't really any debug info here
4494 DebugLoc dl = Op.getDebugLoc();
4495 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4496 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4497 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4498 // With PIC, the address is actually $g + Offset.
4499 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4500 !Subtarget->isPICStyleRIPRel()) {
4501 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4502 DAG.getNode(X86ISD::GlobalBaseReg,
4503 DebugLoc::getUnknownLoc(),
4511 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4512 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4513 // FIXME there isn't really any debug into here
4514 DebugLoc dl = JT->getDebugLoc();
4515 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4516 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4517 // With PIC, the address is actually $g + Offset.
4518 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4519 !Subtarget->isPICStyleRIPRel()) {
4520 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4521 DAG.getNode(X86ISD::GlobalBaseReg,
4522 DebugLoc::getUnknownLoc(),
4530 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4531 /// take a 2 x i32 value to shift plus a shift amount.
4532 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4533 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4534 MVT VT = Op.getValueType();
4535 unsigned VTBits = VT.getSizeInBits();
4536 DebugLoc dl = Op.getDebugLoc();
4537 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4538 SDValue ShOpLo = Op.getOperand(0);
4539 SDValue ShOpHi = Op.getOperand(1);
4540 SDValue ShAmt = Op.getOperand(2);
4541 SDValue Tmp1 = isSRA ?
4542 DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
4543 DAG.getConstant(VTBits - 1, MVT::i8)) :
4544 DAG.getConstant(0, VT);
4547 if (Op.getOpcode() == ISD::SHL_PARTS) {
4548 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
4549 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4551 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
4552 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
4555 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
4556 DAG.getConstant(VTBits, MVT::i8));
4557 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, VT,
4558 AndNode, DAG.getConstant(0, MVT::i8));
4561 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4562 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4563 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4565 if (Op.getOpcode() == ISD::SHL_PARTS) {
4566 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4567 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4569 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4570 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4573 SDValue Ops[2] = { Lo, Hi };
4574 return DAG.getMergeValues(Ops, 2, dl);
4577 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4578 MVT SrcVT = Op.getOperand(0).getValueType();
4580 if (SrcVT.isVector()) {
4581 if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
4587 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4588 "Unknown SINT_TO_FP to lower!");
4590 // These are really Legal; return the operand so the caller accepts it as
4592 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4594 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
4595 Subtarget->is64Bit()) {
4599 DebugLoc dl = Op.getDebugLoc();
4600 unsigned Size = SrcVT.getSizeInBits()/8;
4601 MachineFunction &MF = DAG.getMachineFunction();
4602 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4603 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4604 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
4606 PseudoSourceValue::getFixedStack(SSFI), 0);
4607 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
4610 SDValue X86TargetLowering::BuildFILD(SDValue Op, MVT SrcVT, SDValue Chain,
4612 SelectionDAG &DAG) {
4614 DebugLoc dl = Op.getDebugLoc();
4616 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4618 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4620 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4621 SmallVector<SDValue, 8> Ops;
4622 Ops.push_back(Chain);
4623 Ops.push_back(StackSlot);
4624 Ops.push_back(DAG.getValueType(SrcVT));
4625 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
4626 Tys, &Ops[0], Ops.size());
4629 Chain = Result.getValue(1);
4630 SDValue InFlag = Result.getValue(2);
4632 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4633 // shouldn't be necessary except that RFP cannot be live across
4634 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4635 MachineFunction &MF = DAG.getMachineFunction();
4636 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4637 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4638 Tys = DAG.getVTList(MVT::Other);
4639 SmallVector<SDValue, 8> Ops;
4640 Ops.push_back(Chain);
4641 Ops.push_back(Result);
4642 Ops.push_back(StackSlot);
4643 Ops.push_back(DAG.getValueType(Op.getValueType()));
4644 Ops.push_back(InFlag);
4645 Chain = DAG.getNode(X86ISD::FST, dl, Tys, &Ops[0], Ops.size());
4646 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
4647 PseudoSourceValue::getFixedStack(SSFI), 0);
4653 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
4654 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
4655 // This algorithm is not obvious. Here it is in C code, more or less:
4657 double uint64_to_double( uint32_t hi, uint32_t lo ) {
4658 static const __m128i exp = { 0x4330000045300000ULL, 0 };
4659 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
4661 // Copy ints to xmm registers.
4662 __m128i xh = _mm_cvtsi32_si128( hi );
4663 __m128i xl = _mm_cvtsi32_si128( lo );
4665 // Combine into low half of a single xmm register.
4666 __m128i x = _mm_unpacklo_epi32( xh, xl );
4670 // Merge in appropriate exponents to give the integer bits the right
4672 x = _mm_unpacklo_epi32( x, exp );
4674 // Subtract away the biases to deal with the IEEE-754 double precision
4676 d = _mm_sub_pd( (__m128d) x, bias );
4678 // All conversions up to here are exact. The correctly rounded result is
4679 // calculated using the current rounding mode using the following
4681 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
4682 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
4683 // store doesn't really need to be here (except
4684 // maybe to zero the other double)
4689 DebugLoc dl = Op.getDebugLoc();
4691 // Build some magic constants.
4692 std::vector<Constant*> CV0;
4693 CV0.push_back(ConstantInt::get(APInt(32, 0x45300000)));
4694 CV0.push_back(ConstantInt::get(APInt(32, 0x43300000)));
4695 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4696 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4697 Constant *C0 = ConstantVector::get(CV0);
4698 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
4700 std::vector<Constant*> CV1;
4701 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4530000000000000ULL))));
4702 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4330000000000000ULL))));
4703 Constant *C1 = ConstantVector::get(CV1);
4704 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
4706 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4707 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4709 DAG.getIntPtrConstant(1)));
4710 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4711 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4713 DAG.getIntPtrConstant(0)));
4714 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
4715 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
4716 PseudoSourceValue::getConstantPool(), 0,
4718 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
4719 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
4720 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
4721 PseudoSourceValue::getConstantPool(), 0,
4723 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
4725 // Add the halves; easiest way is to swap them into another reg first.
4726 int ShufMask[2] = { 1, -1 };
4727 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
4728 DAG.getUNDEF(MVT::v2f64), ShufMask);
4729 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
4730 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
4731 DAG.getIntPtrConstant(0));
4734 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
4735 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
4736 DebugLoc dl = Op.getDebugLoc();
4737 // FP constant to bias correct the final result.
4738 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
4741 // Load the 32-bit value into an XMM register.
4742 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4743 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4745 DAG.getIntPtrConstant(0)));
4747 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
4748 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
4749 DAG.getIntPtrConstant(0));
4751 // Or the load with the bias.
4752 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
4753 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4754 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4756 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4757 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4758 MVT::v2f64, Bias)));
4759 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
4760 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
4761 DAG.getIntPtrConstant(0));
4763 // Subtract the bias.
4764 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
4766 // Handle final rounding.
4767 MVT DestVT = Op.getValueType();
4769 if (DestVT.bitsLT(MVT::f64)) {
4770 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
4771 DAG.getIntPtrConstant(0));
4772 } else if (DestVT.bitsGT(MVT::f64)) {
4773 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
4776 // Handle final rounding.
4780 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4781 SDValue N0 = Op.getOperand(0);
4782 DebugLoc dl = Op.getDebugLoc();
4784 // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
4785 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
4786 // the optimization here.
4787 if (DAG.SignBitIsZero(N0))
4788 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
4790 MVT SrcVT = N0.getValueType();
4791 if (SrcVT == MVT::i64) {
4792 // We only handle SSE2 f64 target here; caller can expand the rest.
4793 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
4796 return LowerUINT_TO_FP_i64(Op, DAG);
4797 } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
4798 return LowerUINT_TO_FP_i32(Op, DAG);
4801 assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
4803 // Make a 64-bit buffer, and use it to build an FILD.
4804 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
4805 SDValue WordOff = DAG.getConstant(4, getPointerTy());
4806 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
4807 getPointerTy(), StackSlot, WordOff);
4808 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
4809 StackSlot, NULL, 0);
4810 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
4811 OffsetSlot, NULL, 0);
4812 return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
4815 std::pair<SDValue,SDValue> X86TargetLowering::
4816 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) {
4817 DebugLoc dl = Op.getDebugLoc();
4819 MVT DstTy = Op.getValueType();
4822 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
4826 assert(DstTy.getSimpleVT() <= MVT::i64 &&
4827 DstTy.getSimpleVT() >= MVT::i16 &&
4828 "Unknown FP_TO_SINT to lower!");
4830 // These are really Legal.
4831 if (DstTy == MVT::i32 &&
4832 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4833 return std::make_pair(SDValue(), SDValue());
4834 if (Subtarget->is64Bit() &&
4835 DstTy == MVT::i64 &&
4836 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4837 return std::make_pair(SDValue(), SDValue());
4839 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4841 MachineFunction &MF = DAG.getMachineFunction();
4842 unsigned MemSize = DstTy.getSizeInBits()/8;
4843 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4844 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4847 switch (DstTy.getSimpleVT()) {
4848 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4849 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4850 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4851 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4854 SDValue Chain = DAG.getEntryNode();
4855 SDValue Value = Op.getOperand(0);
4856 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4857 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4858 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
4859 PseudoSourceValue::getFixedStack(SSFI), 0);
4860 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4862 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4864 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
4865 Chain = Value.getValue(1);
4866 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4867 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4870 // Build the FP_TO_INT*_IN_MEM
4871 SDValue Ops[] = { Chain, Value, StackSlot };
4872 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
4874 return std::make_pair(FIST, StackSlot);
4877 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
4878 if (Op.getValueType().isVector()) {
4879 if (Op.getValueType() == MVT::v2i32 &&
4880 Op.getOperand(0).getValueType() == MVT::v2f64) {
4886 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
4887 SDValue FIST = Vals.first, StackSlot = Vals.second;
4888 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
4889 if (FIST.getNode() == 0) return Op;
4892 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
4893 FIST, StackSlot, NULL, 0);
4896 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG) {
4897 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
4898 SDValue FIST = Vals.first, StackSlot = Vals.second;
4899 assert(FIST.getNode() && "Unexpected failure");
4902 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
4903 FIST, StackSlot, NULL, 0);
4906 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
4907 DebugLoc dl = Op.getDebugLoc();
4908 MVT VT = Op.getValueType();
4911 EltVT = VT.getVectorElementType();
4912 std::vector<Constant*> CV;
4913 if (EltVT == MVT::f64) {
4914 Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
4918 Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
4924 Constant *C = ConstantVector::get(CV);
4925 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
4926 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
4927 PseudoSourceValue::getConstantPool(), 0,
4929 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
4932 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
4933 DebugLoc dl = Op.getDebugLoc();
4934 MVT VT = Op.getValueType();
4936 unsigned EltNum = 1;
4937 if (VT.isVector()) {
4938 EltVT = VT.getVectorElementType();
4939 EltNum = VT.getVectorNumElements();
4941 std::vector<Constant*> CV;
4942 if (EltVT == MVT::f64) {
4943 Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
4947 Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
4953 Constant *C = ConstantVector::get(CV);
4954 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
4955 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
4956 PseudoSourceValue::getConstantPool(), 0,
4958 if (VT.isVector()) {
4959 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4960 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
4961 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4963 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
4965 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
4969 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
4970 SDValue Op0 = Op.getOperand(0);
4971 SDValue Op1 = Op.getOperand(1);
4972 DebugLoc dl = Op.getDebugLoc();
4973 MVT VT = Op.getValueType();
4974 MVT SrcVT = Op1.getValueType();
4976 // If second operand is smaller, extend it first.
4977 if (SrcVT.bitsLT(VT)) {
4978 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
4981 // And if it is bigger, shrink it first.
4982 if (SrcVT.bitsGT(VT)) {
4983 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
4987 // At this point the operands and the result should have the same
4988 // type, and that won't be f80 since that is not custom lowered.
4990 // First get the sign bit of second operand.
4991 std::vector<Constant*> CV;
4992 if (SrcVT == MVT::f64) {
4993 CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
4994 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4996 CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
4997 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4998 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4999 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5001 Constant *C = ConstantVector::get(CV);
5002 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5003 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5004 PseudoSourceValue::getConstantPool(), 0,
5006 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5008 // Shift sign bit right or left if the two operands have different types.
5009 if (SrcVT.bitsGT(VT)) {
5010 // Op0 is MVT::f32, Op1 is MVT::f64.
5011 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5012 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5013 DAG.getConstant(32, MVT::i32));
5014 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5015 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5016 DAG.getIntPtrConstant(0));
5019 // Clear first operand sign bit.
5021 if (VT == MVT::f64) {
5022 CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
5023 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
5025 CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
5026 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5027 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5028 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5030 C = ConstantVector::get(CV);
5031 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5032 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5033 PseudoSourceValue::getConstantPool(), 0,
5035 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5037 // Or the value with the sign bit.
5038 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5041 /// Emit nodes that will be selected as "test Op0,Op0", or something
5043 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5044 SelectionDAG &DAG) {
5045 DebugLoc dl = Op.getDebugLoc();
5047 // CF and OF aren't always set the way we want. Determine which
5048 // of these we need.
5049 bool NeedCF = false;
5050 bool NeedOF = false;
5052 case X86::COND_A: case X86::COND_AE:
5053 case X86::COND_B: case X86::COND_BE:
5056 case X86::COND_G: case X86::COND_GE:
5057 case X86::COND_L: case X86::COND_LE:
5058 case X86::COND_O: case X86::COND_NO:
5064 // See if we can use the EFLAGS value from the operand instead of
5065 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5066 // we prove that the arithmetic won't overflow, we can't use OF or CF.
5067 if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5068 unsigned Opcode = 0;
5069 unsigned NumOperands = 0;
5070 switch (Op.getNode()->getOpcode()) {
5072 // Due to an isel shortcoming, be conservative if this add is likely to
5073 // be selected as part of a load-modify-store instruction. When the root
5074 // node in a match is a store, isel doesn't know how to remap non-chain
5075 // non-flag uses of other nodes in the match, such as the ADD in this
5076 // case. This leads to the ADD being left around and reselected, with
5077 // the result being two adds in the output.
5078 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5079 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5080 if (UI->getOpcode() == ISD::STORE)
5082 if (ConstantSDNode *C =
5083 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5084 // An add of one will be selected as an INC.
5085 if (C->getAPIntValue() == 1) {
5086 Opcode = X86ISD::INC;
5090 // An add of negative one (subtract of one) will be selected as a DEC.
5091 if (C->getAPIntValue().isAllOnesValue()) {
5092 Opcode = X86ISD::DEC;
5097 // Otherwise use a regular EFLAGS-setting add.
5098 Opcode = X86ISD::ADD;
5102 // Due to the ISEL shortcoming noted above, be conservative if this sub is
5103 // likely to be selected as part of a load-modify-store instruction.
5104 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5105 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5106 if (UI->getOpcode() == ISD::STORE)
5108 // Otherwise use a regular EFLAGS-setting sub.
5109 Opcode = X86ISD::SUB;
5116 return SDValue(Op.getNode(), 1);
5122 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
5123 SmallVector<SDValue, 4> Ops;
5124 for (unsigned i = 0; i != NumOperands; ++i)
5125 Ops.push_back(Op.getOperand(i));
5126 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
5127 DAG.ReplaceAllUsesWith(Op, New);
5128 return SDValue(New.getNode(), 1);
5132 // Otherwise just emit a CMP with 0, which is the TEST pattern.
5133 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5134 DAG.getConstant(0, Op.getValueType()));
5137 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
5139 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5140 SelectionDAG &DAG) {
5141 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5142 if (C->getAPIntValue() == 0)
5143 return EmitTest(Op0, X86CC, DAG);
5145 DebugLoc dl = Op0.getDebugLoc();
5146 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5149 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5150 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5151 SDValue Op0 = Op.getOperand(0);
5152 SDValue Op1 = Op.getOperand(1);
5153 DebugLoc dl = Op.getDebugLoc();
5154 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5156 // Lower (X & (1 << N)) == 0 to BT(X, N).
5157 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5158 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5159 if (Op0.getOpcode() == ISD::AND &&
5161 Op1.getOpcode() == ISD::Constant &&
5162 cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5163 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5165 if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
5166 if (ConstantSDNode *Op010C =
5167 dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
5168 if (Op010C->getZExtValue() == 1) {
5169 LHS = Op0.getOperand(0);
5170 RHS = Op0.getOperand(1).getOperand(1);
5172 } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
5173 if (ConstantSDNode *Op000C =
5174 dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
5175 if (Op000C->getZExtValue() == 1) {
5176 LHS = Op0.getOperand(1);
5177 RHS = Op0.getOperand(0).getOperand(1);
5179 } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
5180 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5181 SDValue AndLHS = Op0.getOperand(0);
5182 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5183 LHS = AndLHS.getOperand(0);
5184 RHS = AndLHS.getOperand(1);
5188 if (LHS.getNode()) {
5189 // If LHS is i8, promote it to i16 with any_extend. There is no i8 BT
5190 // instruction. Since the shift amount is in-range-or-undefined, we know
5191 // that doing a bittest on the i16 value is ok. We extend to i32 because
5192 // the encoding for the i16 version is larger than the i32 version.
5193 if (LHS.getValueType() == MVT::i8)
5194 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5196 // If the operand types disagree, extend the shift amount to match. Since
5197 // BT ignores high bits (like shifts) we can use anyextend.
5198 if (LHS.getValueType() != RHS.getValueType())
5199 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5201 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5202 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5203 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5204 DAG.getConstant(Cond, MVT::i8), BT);
5208 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5209 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5211 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
5212 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5213 DAG.getConstant(X86CC, MVT::i8), Cond);
5216 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5218 SDValue Op0 = Op.getOperand(0);
5219 SDValue Op1 = Op.getOperand(1);
5220 SDValue CC = Op.getOperand(2);
5221 MVT VT = Op.getValueType();
5222 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5223 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5224 DebugLoc dl = Op.getDebugLoc();
5228 MVT VT0 = Op0.getValueType();
5229 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5230 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5233 switch (SetCCOpcode) {
5236 case ISD::SETEQ: SSECC = 0; break;
5238 case ISD::SETGT: Swap = true; // Fallthrough
5240 case ISD::SETOLT: SSECC = 1; break;
5242 case ISD::SETGE: Swap = true; // Fallthrough
5244 case ISD::SETOLE: SSECC = 2; break;
5245 case ISD::SETUO: SSECC = 3; break;
5247 case ISD::SETNE: SSECC = 4; break;
5248 case ISD::SETULE: Swap = true;
5249 case ISD::SETUGE: SSECC = 5; break;
5250 case ISD::SETULT: Swap = true;
5251 case ISD::SETUGT: SSECC = 6; break;
5252 case ISD::SETO: SSECC = 7; break;
5255 std::swap(Op0, Op1);
5257 // In the two special cases we can't handle, emit two comparisons.
5259 if (SetCCOpcode == ISD::SETUEQ) {
5261 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5262 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5263 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
5265 else if (SetCCOpcode == ISD::SETONE) {
5267 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5268 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5269 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
5271 assert(0 && "Illegal FP comparison");
5273 // Handle all other FP comparisons here.
5274 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5277 // We are handling one of the integer comparisons here. Since SSE only has
5278 // GT and EQ comparisons for integer, swapping operands and multiple
5279 // operations may be required for some comparisons.
5280 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5281 bool Swap = false, Invert = false, FlipSigns = false;
5283 switch (VT.getSimpleVT()) {
5285 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5286 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5287 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5288 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5291 switch (SetCCOpcode) {
5293 case ISD::SETNE: Invert = true;
5294 case ISD::SETEQ: Opc = EQOpc; break;
5295 case ISD::SETLT: Swap = true;
5296 case ISD::SETGT: Opc = GTOpc; break;
5297 case ISD::SETGE: Swap = true;
5298 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
5299 case ISD::SETULT: Swap = true;
5300 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5301 case ISD::SETUGE: Swap = true;
5302 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5305 std::swap(Op0, Op1);
5307 // Since SSE has no unsigned integer comparisons, we need to flip the sign
5308 // bits of the inputs before performing those operations.
5310 MVT EltVT = VT.getVectorElementType();
5311 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
5313 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5314 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
5316 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
5317 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
5320 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
5322 // If the logical-not of the result is required, perform that now.
5324 Result = DAG.getNOT(dl, Result, VT);
5329 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5330 static bool isX86LogicalCmp(SDValue Op) {
5331 unsigned Opc = Op.getNode()->getOpcode();
5332 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
5334 if (Op.getResNo() == 1 &&
5335 (Opc == X86ISD::ADD ||
5336 Opc == X86ISD::SUB ||
5337 Opc == X86ISD::SMUL ||
5338 Opc == X86ISD::UMUL ||
5339 Opc == X86ISD::INC ||
5340 Opc == X86ISD::DEC))
5346 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5347 bool addTest = true;
5348 SDValue Cond = Op.getOperand(0);
5349 DebugLoc dl = Op.getDebugLoc();
5352 if (Cond.getOpcode() == ISD::SETCC)
5353 Cond = LowerSETCC(Cond, DAG);
5355 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5356 // setting operand in place of the X86ISD::SETCC.
5357 if (Cond.getOpcode() == X86ISD::SETCC) {
5358 CC = Cond.getOperand(0);
5360 SDValue Cmp = Cond.getOperand(1);
5361 unsigned Opc = Cmp.getOpcode();
5362 MVT VT = Op.getValueType();
5364 bool IllegalFPCMov = false;
5365 if (VT.isFloatingPoint() && !VT.isVector() &&
5366 !isScalarFPTypeInSSEReg(VT)) // FPStack?
5367 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
5369 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
5370 Opc == X86ISD::BT) { // FIXME
5377 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5378 Cond = EmitTest(Cond, X86::COND_NE, DAG);
5381 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
5382 SmallVector<SDValue, 4> Ops;
5383 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
5384 // condition is true.
5385 Ops.push_back(Op.getOperand(2));
5386 Ops.push_back(Op.getOperand(1));
5388 Ops.push_back(Cond);
5389 return DAG.getNode(X86ISD::CMOV, dl, VTs, &Ops[0], Ops.size());
5392 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
5393 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
5394 // from the AND / OR.
5395 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
5396 Opc = Op.getOpcode();
5397 if (Opc != ISD::OR && Opc != ISD::AND)
5399 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5400 Op.getOperand(0).hasOneUse() &&
5401 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
5402 Op.getOperand(1).hasOneUse());
5405 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
5406 // 1 and that the SETCC node has a single use.
5407 static bool isXor1OfSetCC(SDValue Op) {
5408 if (Op.getOpcode() != ISD::XOR)
5410 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5411 if (N1C && N1C->getAPIntValue() == 1) {
5412 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5413 Op.getOperand(0).hasOneUse();
5418 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
5419 bool addTest = true;
5420 SDValue Chain = Op.getOperand(0);
5421 SDValue Cond = Op.getOperand(1);
5422 SDValue Dest = Op.getOperand(2);
5423 DebugLoc dl = Op.getDebugLoc();
5426 if (Cond.getOpcode() == ISD::SETCC)
5427 Cond = LowerSETCC(Cond, DAG);
5429 // FIXME: LowerXALUO doesn't handle these!!
5430 else if (Cond.getOpcode() == X86ISD::ADD ||
5431 Cond.getOpcode() == X86ISD::SUB ||
5432 Cond.getOpcode() == X86ISD::SMUL ||
5433 Cond.getOpcode() == X86ISD::UMUL)
5434 Cond = LowerXALUO(Cond, DAG);
5437 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5438 // setting operand in place of the X86ISD::SETCC.
5439 if (Cond.getOpcode() == X86ISD::SETCC) {
5440 CC = Cond.getOperand(0);
5442 SDValue Cmp = Cond.getOperand(1);
5443 unsigned Opc = Cmp.getOpcode();
5444 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
5445 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
5449 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
5453 // These can only come from an arithmetic instruction with overflow,
5454 // e.g. SADDO, UADDO.
5455 Cond = Cond.getNode()->getOperand(1);
5462 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
5463 SDValue Cmp = Cond.getOperand(0).getOperand(1);
5464 if (CondOpc == ISD::OR) {
5465 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
5466 // two branches instead of an explicit OR instruction with a
5468 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5469 isX86LogicalCmp(Cmp)) {
5470 CC = Cond.getOperand(0).getOperand(0);
5471 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5472 Chain, Dest, CC, Cmp);
5473 CC = Cond.getOperand(1).getOperand(0);
5477 } else { // ISD::AND
5478 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
5479 // two branches instead of an explicit AND instruction with a
5480 // separate test. However, we only do this if this block doesn't
5481 // have a fall-through edge, because this requires an explicit
5482 // jmp when the condition is false.
5483 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5484 isX86LogicalCmp(Cmp) &&
5485 Op.getNode()->hasOneUse()) {
5486 X86::CondCode CCode =
5487 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5488 CCode = X86::GetOppositeBranchCondition(CCode);
5489 CC = DAG.getConstant(CCode, MVT::i8);
5490 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
5491 // Look for an unconditional branch following this conditional branch.
5492 // We need this because we need to reverse the successors in order
5493 // to implement FCMP_OEQ.
5494 if (User.getOpcode() == ISD::BR) {
5495 SDValue FalseBB = User.getOperand(1);
5497 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
5498 assert(NewBR == User);
5501 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5502 Chain, Dest, CC, Cmp);
5503 X86::CondCode CCode =
5504 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
5505 CCode = X86::GetOppositeBranchCondition(CCode);
5506 CC = DAG.getConstant(CCode, MVT::i8);
5512 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
5513 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
5514 // It should be transformed during dag combiner except when the condition
5515 // is set by a arithmetics with overflow node.
5516 X86::CondCode CCode =
5517 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5518 CCode = X86::GetOppositeBranchCondition(CCode);
5519 CC = DAG.getConstant(CCode, MVT::i8);
5520 Cond = Cond.getOperand(0).getOperand(1);
5526 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5527 Cond = EmitTest(Cond, X86::COND_NE, DAG);
5529 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5530 Chain, Dest, CC, Cond);
5534 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
5535 // Calls to _alloca is needed to probe the stack when allocating more than 4k
5536 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
5537 // that the guard pages used by the OS virtual memory manager are allocated in
5538 // correct sequence.
5540 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5541 SelectionDAG &DAG) {
5542 assert(Subtarget->isTargetCygMing() &&
5543 "This should be used only on Cygwin/Mingw targets");
5544 DebugLoc dl = Op.getDebugLoc();
5547 SDValue Chain = Op.getOperand(0);
5548 SDValue Size = Op.getOperand(1);
5549 // FIXME: Ensure alignment here
5553 MVT IntPtr = getPointerTy();
5554 MVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
5556 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
5558 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
5559 Flag = Chain.getValue(1);
5561 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5562 SDValue Ops[] = { Chain,
5563 DAG.getTargetExternalSymbol("_alloca", IntPtr),
5564 DAG.getRegister(X86::EAX, IntPtr),
5565 DAG.getRegister(X86StackPtr, SPTy),
5567 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops, 5);
5568 Flag = Chain.getValue(1);
5570 Chain = DAG.getCALLSEQ_END(Chain,
5571 DAG.getIntPtrConstant(0, true),
5572 DAG.getIntPtrConstant(0, true),
5575 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
5577 SDValue Ops1[2] = { Chain.getValue(0), Chain };
5578 return DAG.getMergeValues(Ops1, 2, dl);
5582 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
5584 SDValue Dst, SDValue Src,
5585 SDValue Size, unsigned Align,
5587 uint64_t DstSVOff) {
5588 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5590 // If not DWORD aligned or size is more than the threshold, call the library.
5591 // The libc version is likely to be faster for these cases. It can use the
5592 // address value and run time information about the CPU.
5593 if ((Align & 3) != 0 ||
5595 ConstantSize->getZExtValue() >
5596 getSubtarget()->getMaxInlineSizeThreshold()) {
5597 SDValue InFlag(0, 0);
5599 // Check to see if there is a specialized entry-point for memory zeroing.
5600 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
5602 if (const char *bzeroEntry = V &&
5603 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
5604 MVT IntPtr = getPointerTy();
5605 const Type *IntPtrTy = TD->getIntPtrType();
5606 TargetLowering::ArgListTy Args;
5607 TargetLowering::ArgListEntry Entry;
5609 Entry.Ty = IntPtrTy;
5610 Args.push_back(Entry);
5612 Args.push_back(Entry);
5613 std::pair<SDValue,SDValue> CallResult =
5614 LowerCallTo(Chain, Type::VoidTy, false, false, false, false,
5615 CallingConv::C, false,
5616 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl);
5617 return CallResult.second;
5620 // Otherwise have the target-independent code call memset.
5624 uint64_t SizeVal = ConstantSize->getZExtValue();
5625 SDValue InFlag(0, 0);
5628 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
5629 unsigned BytesLeft = 0;
5630 bool TwoRepStos = false;
5633 uint64_t Val = ValC->getZExtValue() & 255;
5635 // If the value is a constant, then we can potentially use larger sets.
5636 switch (Align & 3) {
5637 case 2: // WORD aligned
5640 Val = (Val << 8) | Val;
5642 case 0: // DWORD aligned
5645 Val = (Val << 8) | Val;
5646 Val = (Val << 16) | Val;
5647 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
5650 Val = (Val << 32) | Val;
5653 default: // Byte aligned
5656 Count = DAG.getIntPtrConstant(SizeVal);
5660 if (AVT.bitsGT(MVT::i8)) {
5661 unsigned UBytes = AVT.getSizeInBits() / 8;
5662 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
5663 BytesLeft = SizeVal % UBytes;
5666 Chain = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
5668 InFlag = Chain.getValue(1);
5671 Count = DAG.getIntPtrConstant(SizeVal);
5672 Chain = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
5673 InFlag = Chain.getValue(1);
5676 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
5679 InFlag = Chain.getValue(1);
5680 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
5683 InFlag = Chain.getValue(1);
5685 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5686 SmallVector<SDValue, 8> Ops;
5687 Ops.push_back(Chain);
5688 Ops.push_back(DAG.getValueType(AVT));
5689 Ops.push_back(InFlag);
5690 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
5693 InFlag = Chain.getValue(1);
5695 MVT CVT = Count.getValueType();
5696 SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
5697 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
5698 Chain = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
5701 InFlag = Chain.getValue(1);
5702 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5704 Ops.push_back(Chain);
5705 Ops.push_back(DAG.getValueType(MVT::i8));
5706 Ops.push_back(InFlag);
5707 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
5708 } else if (BytesLeft) {
5709 // Handle the last 1 - 7 bytes.
5710 unsigned Offset = SizeVal - BytesLeft;
5711 MVT AddrVT = Dst.getValueType();
5712 MVT SizeVT = Size.getValueType();
5714 Chain = DAG.getMemset(Chain, dl,
5715 DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
5716 DAG.getConstant(Offset, AddrVT)),
5718 DAG.getConstant(BytesLeft, SizeVT),
5719 Align, DstSV, DstSVOff + Offset);
5722 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
5727 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
5728 SDValue Chain, SDValue Dst, SDValue Src,
5729 SDValue Size, unsigned Align,
5731 const Value *DstSV, uint64_t DstSVOff,
5732 const Value *SrcSV, uint64_t SrcSVOff) {
5733 // This requires the copy size to be a constant, preferrably
5734 // within a subtarget-specific limit.
5735 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5738 uint64_t SizeVal = ConstantSize->getZExtValue();
5739 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
5742 /// If not DWORD aligned, call the library.
5743 if ((Align & 3) != 0)
5748 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
5751 unsigned UBytes = AVT.getSizeInBits() / 8;
5752 unsigned CountVal = SizeVal / UBytes;
5753 SDValue Count = DAG.getIntPtrConstant(CountVal);
5754 unsigned BytesLeft = SizeVal % UBytes;
5756 SDValue InFlag(0, 0);
5757 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
5760 InFlag = Chain.getValue(1);
5761 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
5764 InFlag = Chain.getValue(1);
5765 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
5768 InFlag = Chain.getValue(1);
5770 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5771 SmallVector<SDValue, 8> Ops;
5772 Ops.push_back(Chain);
5773 Ops.push_back(DAG.getValueType(AVT));
5774 Ops.push_back(InFlag);
5775 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, &Ops[0], Ops.size());
5777 SmallVector<SDValue, 4> Results;
5778 Results.push_back(RepMovs);
5780 // Handle the last 1 - 7 bytes.
5781 unsigned Offset = SizeVal - BytesLeft;
5782 MVT DstVT = Dst.getValueType();
5783 MVT SrcVT = Src.getValueType();
5784 MVT SizeVT = Size.getValueType();
5785 Results.push_back(DAG.getMemcpy(Chain, dl,
5786 DAG.getNode(ISD::ADD, dl, DstVT, Dst,
5787 DAG.getConstant(Offset, DstVT)),
5788 DAG.getNode(ISD::ADD, dl, SrcVT, Src,
5789 DAG.getConstant(Offset, SrcVT)),
5790 DAG.getConstant(BytesLeft, SizeVT),
5791 Align, AlwaysInline,
5792 DstSV, DstSVOff + Offset,
5793 SrcSV, SrcSVOff + Offset));
5796 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5797 &Results[0], Results.size());
5800 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
5801 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5802 DebugLoc dl = Op.getDebugLoc();
5804 if (!Subtarget->is64Bit()) {
5805 // vastart just stores the address of the VarArgsFrameIndex slot into the
5806 // memory location argument.
5807 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5808 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
5812 // gp_offset (0 - 6 * 8)
5813 // fp_offset (48 - 48 + 8 * 16)
5814 // overflow_arg_area (point to parameters coming in memory).
5816 SmallVector<SDValue, 8> MemOps;
5817 SDValue FIN = Op.getOperand(1);
5819 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
5820 DAG.getConstant(VarArgsGPOffset, MVT::i32),
5822 MemOps.push_back(Store);
5825 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5826 FIN, DAG.getIntPtrConstant(4));
5827 Store = DAG.getStore(Op.getOperand(0), dl,
5828 DAG.getConstant(VarArgsFPOffset, MVT::i32),
5830 MemOps.push_back(Store);
5832 // Store ptr to overflow_arg_area
5833 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5834 FIN, DAG.getIntPtrConstant(4));
5835 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5836 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0);
5837 MemOps.push_back(Store);
5839 // Store ptr to reg_save_area.
5840 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5841 FIN, DAG.getIntPtrConstant(8));
5842 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
5843 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0);
5844 MemOps.push_back(Store);
5845 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5846 &MemOps[0], MemOps.size());
5849 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
5850 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5851 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
5852 SDValue Chain = Op.getOperand(0);
5853 SDValue SrcPtr = Op.getOperand(1);
5854 SDValue SrcSV = Op.getOperand(2);
5856 assert(0 && "VAArgInst is not yet implemented for x86-64!");
5861 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
5862 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5863 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
5864 SDValue Chain = Op.getOperand(0);
5865 SDValue DstPtr = Op.getOperand(1);
5866 SDValue SrcPtr = Op.getOperand(2);
5867 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5868 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5869 DebugLoc dl = Op.getDebugLoc();
5871 return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
5872 DAG.getIntPtrConstant(24), 8, false,
5873 DstSV, 0, SrcSV, 0);
5877 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
5878 DebugLoc dl = Op.getDebugLoc();
5879 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5881 default: return SDValue(); // Don't custom lower most intrinsics.
5882 // Comparison intrinsics.
5883 case Intrinsic::x86_sse_comieq_ss:
5884 case Intrinsic::x86_sse_comilt_ss:
5885 case Intrinsic::x86_sse_comile_ss:
5886 case Intrinsic::x86_sse_comigt_ss:
5887 case Intrinsic::x86_sse_comige_ss:
5888 case Intrinsic::x86_sse_comineq_ss:
5889 case Intrinsic::x86_sse_ucomieq_ss:
5890 case Intrinsic::x86_sse_ucomilt_ss:
5891 case Intrinsic::x86_sse_ucomile_ss:
5892 case Intrinsic::x86_sse_ucomigt_ss:
5893 case Intrinsic::x86_sse_ucomige_ss:
5894 case Intrinsic::x86_sse_ucomineq_ss:
5895 case Intrinsic::x86_sse2_comieq_sd:
5896 case Intrinsic::x86_sse2_comilt_sd:
5897 case Intrinsic::x86_sse2_comile_sd:
5898 case Intrinsic::x86_sse2_comigt_sd:
5899 case Intrinsic::x86_sse2_comige_sd:
5900 case Intrinsic::x86_sse2_comineq_sd:
5901 case Intrinsic::x86_sse2_ucomieq_sd:
5902 case Intrinsic::x86_sse2_ucomilt_sd:
5903 case Intrinsic::x86_sse2_ucomile_sd:
5904 case Intrinsic::x86_sse2_ucomigt_sd:
5905 case Intrinsic::x86_sse2_ucomige_sd:
5906 case Intrinsic::x86_sse2_ucomineq_sd: {
5908 ISD::CondCode CC = ISD::SETCC_INVALID;
5911 case Intrinsic::x86_sse_comieq_ss:
5912 case Intrinsic::x86_sse2_comieq_sd:
5916 case Intrinsic::x86_sse_comilt_ss:
5917 case Intrinsic::x86_sse2_comilt_sd:
5921 case Intrinsic::x86_sse_comile_ss:
5922 case Intrinsic::x86_sse2_comile_sd:
5926 case Intrinsic::x86_sse_comigt_ss:
5927 case Intrinsic::x86_sse2_comigt_sd:
5931 case Intrinsic::x86_sse_comige_ss:
5932 case Intrinsic::x86_sse2_comige_sd:
5936 case Intrinsic::x86_sse_comineq_ss:
5937 case Intrinsic::x86_sse2_comineq_sd:
5941 case Intrinsic::x86_sse_ucomieq_ss:
5942 case Intrinsic::x86_sse2_ucomieq_sd:
5943 Opc = X86ISD::UCOMI;
5946 case Intrinsic::x86_sse_ucomilt_ss:
5947 case Intrinsic::x86_sse2_ucomilt_sd:
5948 Opc = X86ISD::UCOMI;
5951 case Intrinsic::x86_sse_ucomile_ss:
5952 case Intrinsic::x86_sse2_ucomile_sd:
5953 Opc = X86ISD::UCOMI;
5956 case Intrinsic::x86_sse_ucomigt_ss:
5957 case Intrinsic::x86_sse2_ucomigt_sd:
5958 Opc = X86ISD::UCOMI;
5961 case Intrinsic::x86_sse_ucomige_ss:
5962 case Intrinsic::x86_sse2_ucomige_sd:
5963 Opc = X86ISD::UCOMI;
5966 case Intrinsic::x86_sse_ucomineq_ss:
5967 case Intrinsic::x86_sse2_ucomineq_sd:
5968 Opc = X86ISD::UCOMI;
5973 SDValue LHS = Op.getOperand(1);
5974 SDValue RHS = Op.getOperand(2);
5975 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
5976 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
5977 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5978 DAG.getConstant(X86CC, MVT::i8), Cond);
5979 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
5982 // Fix vector shift instructions where the last operand is a non-immediate
5984 case Intrinsic::x86_sse2_pslli_w:
5985 case Intrinsic::x86_sse2_pslli_d:
5986 case Intrinsic::x86_sse2_pslli_q:
5987 case Intrinsic::x86_sse2_psrli_w:
5988 case Intrinsic::x86_sse2_psrli_d:
5989 case Intrinsic::x86_sse2_psrli_q:
5990 case Intrinsic::x86_sse2_psrai_w:
5991 case Intrinsic::x86_sse2_psrai_d:
5992 case Intrinsic::x86_mmx_pslli_w:
5993 case Intrinsic::x86_mmx_pslli_d:
5994 case Intrinsic::x86_mmx_pslli_q:
5995 case Intrinsic::x86_mmx_psrli_w:
5996 case Intrinsic::x86_mmx_psrli_d:
5997 case Intrinsic::x86_mmx_psrli_q:
5998 case Intrinsic::x86_mmx_psrai_w:
5999 case Intrinsic::x86_mmx_psrai_d: {
6000 SDValue ShAmt = Op.getOperand(2);
6001 if (isa<ConstantSDNode>(ShAmt))
6004 unsigned NewIntNo = 0;
6005 MVT ShAmtVT = MVT::v4i32;
6007 case Intrinsic::x86_sse2_pslli_w:
6008 NewIntNo = Intrinsic::x86_sse2_psll_w;
6010 case Intrinsic::x86_sse2_pslli_d:
6011 NewIntNo = Intrinsic::x86_sse2_psll_d;
6013 case Intrinsic::x86_sse2_pslli_q:
6014 NewIntNo = Intrinsic::x86_sse2_psll_q;
6016 case Intrinsic::x86_sse2_psrli_w:
6017 NewIntNo = Intrinsic::x86_sse2_psrl_w;
6019 case Intrinsic::x86_sse2_psrli_d:
6020 NewIntNo = Intrinsic::x86_sse2_psrl_d;
6022 case Intrinsic::x86_sse2_psrli_q:
6023 NewIntNo = Intrinsic::x86_sse2_psrl_q;
6025 case Intrinsic::x86_sse2_psrai_w:
6026 NewIntNo = Intrinsic::x86_sse2_psra_w;
6028 case Intrinsic::x86_sse2_psrai_d:
6029 NewIntNo = Intrinsic::x86_sse2_psra_d;
6032 ShAmtVT = MVT::v2i32;
6034 case Intrinsic::x86_mmx_pslli_w:
6035 NewIntNo = Intrinsic::x86_mmx_psll_w;
6037 case Intrinsic::x86_mmx_pslli_d:
6038 NewIntNo = Intrinsic::x86_mmx_psll_d;
6040 case Intrinsic::x86_mmx_pslli_q:
6041 NewIntNo = Intrinsic::x86_mmx_psll_q;
6043 case Intrinsic::x86_mmx_psrli_w:
6044 NewIntNo = Intrinsic::x86_mmx_psrl_w;
6046 case Intrinsic::x86_mmx_psrli_d:
6047 NewIntNo = Intrinsic::x86_mmx_psrl_d;
6049 case Intrinsic::x86_mmx_psrli_q:
6050 NewIntNo = Intrinsic::x86_mmx_psrl_q;
6052 case Intrinsic::x86_mmx_psrai_w:
6053 NewIntNo = Intrinsic::x86_mmx_psra_w;
6055 case Intrinsic::x86_mmx_psrai_d:
6056 NewIntNo = Intrinsic::x86_mmx_psra_d;
6058 default: abort(); // Can't reach here.
6063 MVT VT = Op.getValueType();
6064 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT,
6065 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShAmtVT, ShAmt));
6066 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6067 DAG.getConstant(NewIntNo, MVT::i32),
6068 Op.getOperand(1), ShAmt);
6073 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
6074 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6075 DebugLoc dl = Op.getDebugLoc();
6078 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6080 DAG.getConstant(TD->getPointerSize(),
6081 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6082 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6083 DAG.getNode(ISD::ADD, dl, getPointerTy(),
6088 // Just load the return address.
6089 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6090 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6091 RetAddrFI, NULL, 0);
6094 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
6095 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6096 MFI->setFrameAddressIsTaken(true);
6097 MVT VT = Op.getValueType();
6098 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
6099 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6100 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6101 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6103 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
6107 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6108 SelectionDAG &DAG) {
6109 return DAG.getIntPtrConstant(2*TD->getPointerSize());
6112 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
6114 MachineFunction &MF = DAG.getMachineFunction();
6115 SDValue Chain = Op.getOperand(0);
6116 SDValue Offset = Op.getOperand(1);
6117 SDValue Handler = Op.getOperand(2);
6118 DebugLoc dl = Op.getDebugLoc();
6120 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6122 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6124 SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
6125 DAG.getIntPtrConstant(-TD->getPointerSize()));
6126 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
6127 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0);
6128 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
6129 MF.getRegInfo().addLiveOut(StoreAddrReg);
6131 return DAG.getNode(X86ISD::EH_RETURN, dl,
6133 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6136 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6137 SelectionDAG &DAG) {
6138 SDValue Root = Op.getOperand(0);
6139 SDValue Trmp = Op.getOperand(1); // trampoline
6140 SDValue FPtr = Op.getOperand(2); // nested function
6141 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6142 DebugLoc dl = Op.getDebugLoc();
6144 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6146 const X86InstrInfo *TII =
6147 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
6149 if (Subtarget->is64Bit()) {
6150 SDValue OutChains[6];
6152 // Large code-model.
6154 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
6155 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
6157 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
6158 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
6160 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
6162 // Load the pointer to the nested function into R11.
6163 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
6164 SDValue Addr = Trmp;
6165 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6168 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6169 DAG.getConstant(2, MVT::i64));
6170 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2, false, 2);
6172 // Load the 'nest' parameter value into R10.
6173 // R10 is specified in X86CallingConv.td
6174 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
6175 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6176 DAG.getConstant(10, MVT::i64));
6177 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6178 Addr, TrmpAddr, 10);
6180 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6181 DAG.getConstant(12, MVT::i64));
6182 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12, false, 2);
6184 // Jump to the nested function.
6185 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
6186 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6187 DAG.getConstant(20, MVT::i64));
6188 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6189 Addr, TrmpAddr, 20);
6191 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
6192 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6193 DAG.getConstant(22, MVT::i64));
6194 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
6198 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
6199 return DAG.getMergeValues(Ops, 2, dl);
6201 const Function *Func =
6202 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
6203 unsigned CC = Func->getCallingConv();
6208 assert(0 && "Unsupported calling convention");
6209 case CallingConv::C:
6210 case CallingConv::X86_StdCall: {
6211 // Pass 'nest' parameter in ECX.
6212 // Must be kept in sync with X86CallingConv.td
6215 // Check that ECX wasn't needed by an 'inreg' parameter.
6216 const FunctionType *FTy = Func->getFunctionType();
6217 const AttrListPtr &Attrs = Func->getAttributes();
6219 if (!Attrs.isEmpty() && !Func->isVarArg()) {
6220 unsigned InRegCount = 0;
6223 for (FunctionType::param_iterator I = FTy->param_begin(),
6224 E = FTy->param_end(); I != E; ++I, ++Idx)
6225 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6226 // FIXME: should only count parameters that are lowered to integers.
6227 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6229 if (InRegCount > 2) {
6230 cerr << "Nest register in use - reduce number of inreg parameters!\n";
6236 case CallingConv::X86_FastCall:
6237 case CallingConv::Fast:
6238 // Pass 'nest' parameter in EAX.
6239 // Must be kept in sync with X86CallingConv.td
6244 SDValue OutChains[4];
6247 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6248 DAG.getConstant(10, MVT::i32));
6249 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
6251 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
6252 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
6253 OutChains[0] = DAG.getStore(Root, dl,
6254 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
6257 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6258 DAG.getConstant(1, MVT::i32));
6259 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1, false, 1);
6261 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
6262 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6263 DAG.getConstant(5, MVT::i32));
6264 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
6265 TrmpAddr, 5, false, 1);
6267 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6268 DAG.getConstant(6, MVT::i32));
6269 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6, false, 1);
6272 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
6273 return DAG.getMergeValues(Ops, 2, dl);
6277 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
6279 The rounding mode is in bits 11:10 of FPSR, and has the following
6286 FLT_ROUNDS, on the other hand, expects the following:
6293 To perform the conversion, we do:
6294 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
6297 MachineFunction &MF = DAG.getMachineFunction();
6298 const TargetMachine &TM = MF.getTarget();
6299 const TargetFrameInfo &TFI = *TM.getFrameInfo();
6300 unsigned StackAlignment = TFI.getStackAlignment();
6301 MVT VT = Op.getValueType();
6302 DebugLoc dl = Op.getDebugLoc();
6304 // Save FP Control Word to stack slot
6305 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
6306 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6308 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
6309 DAG.getEntryNode(), StackSlot);
6311 // Load FP Control Word from stack slot
6312 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0);
6314 // Transform as necessary
6316 DAG.getNode(ISD::SRL, dl, MVT::i16,
6317 DAG.getNode(ISD::AND, dl, MVT::i16,
6318 CWD, DAG.getConstant(0x800, MVT::i16)),
6319 DAG.getConstant(11, MVT::i8));
6321 DAG.getNode(ISD::SRL, dl, MVT::i16,
6322 DAG.getNode(ISD::AND, dl, MVT::i16,
6323 CWD, DAG.getConstant(0x400, MVT::i16)),
6324 DAG.getConstant(9, MVT::i8));
6327 DAG.getNode(ISD::AND, dl, MVT::i16,
6328 DAG.getNode(ISD::ADD, dl, MVT::i16,
6329 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
6330 DAG.getConstant(1, MVT::i16)),
6331 DAG.getConstant(3, MVT::i16));
6334 return DAG.getNode((VT.getSizeInBits() < 16 ?
6335 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6338 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
6339 MVT VT = Op.getValueType();
6341 unsigned NumBits = VT.getSizeInBits();
6342 DebugLoc dl = Op.getDebugLoc();
6344 Op = Op.getOperand(0);
6345 if (VT == MVT::i8) {
6346 // Zero extend to i32 since there is not an i8 bsr.
6348 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6351 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
6352 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6353 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
6355 // If src is zero (i.e. bsr sets ZF), returns NumBits.
6356 SmallVector<SDValue, 4> Ops;
6358 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
6359 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6360 Ops.push_back(Op.getValue(1));
6361 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6363 // Finally xor with NumBits-1.
6364 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
6367 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6371 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
6372 MVT VT = Op.getValueType();
6374 unsigned NumBits = VT.getSizeInBits();
6375 DebugLoc dl = Op.getDebugLoc();
6377 Op = Op.getOperand(0);
6378 if (VT == MVT::i8) {
6380 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6383 // Issue a bsf (scan bits forward) which also sets EFLAGS.
6384 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6385 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
6387 // If src is zero (i.e. bsf sets ZF), returns NumBits.
6388 SmallVector<SDValue, 4> Ops;
6390 Ops.push_back(DAG.getConstant(NumBits, OpVT));
6391 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6392 Ops.push_back(Op.getValue(1));
6393 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6396 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6400 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
6401 MVT VT = Op.getValueType();
6402 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
6403 DebugLoc dl = Op.getDebugLoc();
6405 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
6406 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
6407 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
6408 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
6409 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
6411 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
6412 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
6413 // return AloBlo + AloBhi + AhiBlo;
6415 SDValue A = Op.getOperand(0);
6416 SDValue B = Op.getOperand(1);
6418 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6419 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6420 A, DAG.getConstant(32, MVT::i32));
6421 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6422 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6423 B, DAG.getConstant(32, MVT::i32));
6424 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6425 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6427 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6428 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6430 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6431 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6433 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6434 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6435 AloBhi, DAG.getConstant(32, MVT::i32));
6436 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6437 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6438 AhiBlo, DAG.getConstant(32, MVT::i32));
6439 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
6440 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
6445 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
6446 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
6447 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
6448 // looks for this combo and may remove the "setcc" instruction if the "setcc"
6449 // has only one use.
6450 SDNode *N = Op.getNode();
6451 SDValue LHS = N->getOperand(0);
6452 SDValue RHS = N->getOperand(1);
6453 unsigned BaseOp = 0;
6455 DebugLoc dl = Op.getDebugLoc();
6457 switch (Op.getOpcode()) {
6458 default: assert(0 && "Unknown ovf instruction!");
6460 // A subtract of one will be selected as a INC. Note that INC doesn't
6461 // set CF, so we can't do this for UADDO.
6462 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6463 if (C->getAPIntValue() == 1) {
6464 BaseOp = X86ISD::INC;
6468 BaseOp = X86ISD::ADD;
6472 BaseOp = X86ISD::ADD;
6476 // A subtract of one will be selected as a DEC. Note that DEC doesn't
6477 // set CF, so we can't do this for USUBO.
6478 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6479 if (C->getAPIntValue() == 1) {
6480 BaseOp = X86ISD::DEC;
6484 BaseOp = X86ISD::SUB;
6488 BaseOp = X86ISD::SUB;
6492 BaseOp = X86ISD::SMUL;
6496 BaseOp = X86ISD::UMUL;
6501 // Also sets EFLAGS.
6502 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
6503 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
6506 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
6507 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
6509 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
6513 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
6514 MVT T = Op.getValueType();
6515 DebugLoc dl = Op.getDebugLoc();
6518 switch(T.getSimpleVT()) {
6520 assert(false && "Invalid value type!");
6521 case MVT::i8: Reg = X86::AL; size = 1; break;
6522 case MVT::i16: Reg = X86::AX; size = 2; break;
6523 case MVT::i32: Reg = X86::EAX; size = 4; break;
6525 assert(Subtarget->is64Bit() && "Node not type legal!");
6526 Reg = X86::RAX; size = 8;
6529 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
6530 Op.getOperand(2), SDValue());
6531 SDValue Ops[] = { cpIn.getValue(0),
6534 DAG.getTargetConstant(size, MVT::i8),
6536 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6537 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
6539 DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
6543 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
6544 SelectionDAG &DAG) {
6545 assert(Subtarget->is64Bit() && "Result not type legalized?");
6546 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6547 SDValue TheChain = Op.getOperand(0);
6548 DebugLoc dl = Op.getDebugLoc();
6549 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6550 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
6551 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
6553 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
6554 DAG.getConstant(32, MVT::i8));
6556 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
6559 return DAG.getMergeValues(Ops, 2, dl);
6562 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
6563 SDNode *Node = Op.getNode();
6564 DebugLoc dl = Node->getDebugLoc();
6565 MVT T = Node->getValueType(0);
6566 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
6567 DAG.getConstant(0, T), Node->getOperand(2));
6568 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
6569 cast<AtomicSDNode>(Node)->getMemoryVT(),
6570 Node->getOperand(0),
6571 Node->getOperand(1), negOp,
6572 cast<AtomicSDNode>(Node)->getSrcValue(),
6573 cast<AtomicSDNode>(Node)->getAlignment());
6576 /// LowerOperation - Provide custom lowering hooks for some operations.
6578 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
6579 switch (Op.getOpcode()) {
6580 default: assert(0 && "Should not custom lower this!");
6581 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
6582 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
6583 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6584 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6585 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6586 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6587 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6588 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6589 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6590 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6591 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
6592 case ISD::SHL_PARTS:
6593 case ISD::SRA_PARTS:
6594 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
6595 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
6596 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
6597 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
6598 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
6599 case ISD::FABS: return LowerFABS(Op, DAG);
6600 case ISD::FNEG: return LowerFNEG(Op, DAG);
6601 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6602 case ISD::SETCC: return LowerSETCC(Op, DAG);
6603 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
6604 case ISD::SELECT: return LowerSELECT(Op, DAG);
6605 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
6606 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6607 case ISD::CALL: return LowerCALL(Op, DAG);
6608 case ISD::RET: return LowerRET(Op, DAG);
6609 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
6610 case ISD::VASTART: return LowerVASTART(Op, DAG);
6611 case ISD::VAARG: return LowerVAARG(Op, DAG);
6612 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
6613 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6614 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6615 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6616 case ISD::FRAME_TO_ARGS_OFFSET:
6617 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
6618 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
6619 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
6620 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
6621 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6622 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
6623 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
6624 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
6630 case ISD::UMULO: return LowerXALUO(Op, DAG);
6631 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
6635 void X86TargetLowering::
6636 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
6637 SelectionDAG &DAG, unsigned NewOp) {
6638 MVT T = Node->getValueType(0);
6639 DebugLoc dl = Node->getDebugLoc();
6640 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
6642 SDValue Chain = Node->getOperand(0);
6643 SDValue In1 = Node->getOperand(1);
6644 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6645 Node->getOperand(2), DAG.getIntPtrConstant(0));
6646 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6647 Node->getOperand(2), DAG.getIntPtrConstant(1));
6648 // This is a generalized SDNode, not an AtomicSDNode, so it doesn't
6649 // have a MemOperand. Pass the info through as a normal operand.
6650 SDValue LSI = DAG.getMemOperand(cast<MemSDNode>(Node)->getMemOperand());
6651 SDValue Ops[] = { Chain, In1, In2L, In2H, LSI };
6652 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6653 SDValue Result = DAG.getNode(NewOp, dl, Tys, Ops, 5);
6654 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
6655 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6656 Results.push_back(Result.getValue(2));
6659 /// ReplaceNodeResults - Replace a node with an illegal result type
6660 /// with a new node built out of custom code.
6661 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
6662 SmallVectorImpl<SDValue>&Results,
6663 SelectionDAG &DAG) {
6664 DebugLoc dl = N->getDebugLoc();
6665 switch (N->getOpcode()) {
6667 assert(false && "Do not know how to custom type legalize this operation!");
6669 case ISD::FP_TO_SINT: {
6670 std::pair<SDValue,SDValue> Vals =
6671 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
6672 SDValue FIST = Vals.first, StackSlot = Vals.second;
6673 if (FIST.getNode() != 0) {
6674 MVT VT = N->getValueType(0);
6675 // Return a load from the stack slot.
6676 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0));
6680 case ISD::READCYCLECOUNTER: {
6681 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6682 SDValue TheChain = N->getOperand(0);
6683 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6684 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
6686 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
6688 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
6689 SDValue Ops[] = { eax, edx };
6690 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
6691 Results.push_back(edx.getValue(1));
6694 case ISD::ATOMIC_CMP_SWAP: {
6695 MVT T = N->getValueType(0);
6696 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
6697 SDValue cpInL, cpInH;
6698 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
6699 DAG.getConstant(0, MVT::i32));
6700 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
6701 DAG.getConstant(1, MVT::i32));
6702 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
6703 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
6705 SDValue swapInL, swapInH;
6706 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
6707 DAG.getConstant(0, MVT::i32));
6708 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
6709 DAG.getConstant(1, MVT::i32));
6710 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
6712 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
6713 swapInL.getValue(1));
6714 SDValue Ops[] = { swapInH.getValue(0),
6716 swapInH.getValue(1) };
6717 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6718 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
6719 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
6720 MVT::i32, Result.getValue(1));
6721 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
6722 MVT::i32, cpOutL.getValue(2));
6723 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
6724 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6725 Results.push_back(cpOutH.getValue(1));
6728 case ISD::ATOMIC_LOAD_ADD:
6729 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
6731 case ISD::ATOMIC_LOAD_AND:
6732 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
6734 case ISD::ATOMIC_LOAD_NAND:
6735 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
6737 case ISD::ATOMIC_LOAD_OR:
6738 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
6740 case ISD::ATOMIC_LOAD_SUB:
6741 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
6743 case ISD::ATOMIC_LOAD_XOR:
6744 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
6746 case ISD::ATOMIC_SWAP:
6747 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
6752 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
6754 default: return NULL;
6755 case X86ISD::BSF: return "X86ISD::BSF";
6756 case X86ISD::BSR: return "X86ISD::BSR";
6757 case X86ISD::SHLD: return "X86ISD::SHLD";
6758 case X86ISD::SHRD: return "X86ISD::SHRD";
6759 case X86ISD::FAND: return "X86ISD::FAND";
6760 case X86ISD::FOR: return "X86ISD::FOR";
6761 case X86ISD::FXOR: return "X86ISD::FXOR";
6762 case X86ISD::FSRL: return "X86ISD::FSRL";
6763 case X86ISD::FILD: return "X86ISD::FILD";
6764 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
6765 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
6766 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
6767 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
6768 case X86ISD::FLD: return "X86ISD::FLD";
6769 case X86ISD::FST: return "X86ISD::FST";
6770 case X86ISD::CALL: return "X86ISD::CALL";
6771 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
6772 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
6773 case X86ISD::BT: return "X86ISD::BT";
6774 case X86ISD::CMP: return "X86ISD::CMP";
6775 case X86ISD::COMI: return "X86ISD::COMI";
6776 case X86ISD::UCOMI: return "X86ISD::UCOMI";
6777 case X86ISD::SETCC: return "X86ISD::SETCC";
6778 case X86ISD::CMOV: return "X86ISD::CMOV";
6779 case X86ISD::BRCOND: return "X86ISD::BRCOND";
6780 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
6781 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
6782 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
6783 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
6784 case X86ISD::Wrapper: return "X86ISD::Wrapper";
6785 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
6786 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
6787 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
6788 case X86ISD::PINSRB: return "X86ISD::PINSRB";
6789 case X86ISD::PINSRW: return "X86ISD::PINSRW";
6790 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
6791 case X86ISD::FMAX: return "X86ISD::FMAX";
6792 case X86ISD::FMIN: return "X86ISD::FMIN";
6793 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
6794 case X86ISD::FRCP: return "X86ISD::FRCP";
6795 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
6796 case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
6797 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
6798 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
6799 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
6800 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
6801 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
6802 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
6803 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
6804 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
6805 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
6806 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
6807 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
6808 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
6809 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
6810 case X86ISD::VSHL: return "X86ISD::VSHL";
6811 case X86ISD::VSRL: return "X86ISD::VSRL";
6812 case X86ISD::CMPPD: return "X86ISD::CMPPD";
6813 case X86ISD::CMPPS: return "X86ISD::CMPPS";
6814 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
6815 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
6816 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
6817 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
6818 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
6819 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
6820 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
6821 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
6822 case X86ISD::ADD: return "X86ISD::ADD";
6823 case X86ISD::SUB: return "X86ISD::SUB";
6824 case X86ISD::SMUL: return "X86ISD::SMUL";
6825 case X86ISD::UMUL: return "X86ISD::UMUL";
6826 case X86ISD::INC: return "X86ISD::INC";
6827 case X86ISD::DEC: return "X86ISD::DEC";
6828 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
6832 // isLegalAddressingMode - Return true if the addressing mode represented
6833 // by AM is legal for this target, for a load/store of the specified type.
6834 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
6835 const Type *Ty) const {
6836 // X86 supports extremely general addressing modes.
6838 // X86 allows a sign-extended 32-bit immediate field as a displacement.
6839 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
6843 // We can only fold this if we don't need an extra load.
6844 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
6846 // If BaseGV requires a register, we cannot also have a BaseReg.
6847 if (Subtarget->GVRequiresRegister(AM.BaseGV, getTargetMachine(), false) &&
6851 // X86-64 only supports addr of globals in small code model.
6852 if (Subtarget->is64Bit()) {
6853 if (getTargetMachine().getCodeModel() != CodeModel::Small)
6855 // If lower 4G is not available, then we must use rip-relative addressing.
6856 if (AM.BaseOffs || AM.Scale > 1)
6867 // These scales always work.
6872 // These scales are formed with basereg+scalereg. Only accept if there is
6877 default: // Other stuff never works.
6885 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
6886 if (!Ty1->isInteger() || !Ty2->isInteger())
6888 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6889 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6890 if (NumBits1 <= NumBits2)
6892 return Subtarget->is64Bit() || NumBits1 < 64;
6895 bool X86TargetLowering::isTruncateFree(MVT VT1, MVT VT2) const {
6896 if (!VT1.isInteger() || !VT2.isInteger())
6898 unsigned NumBits1 = VT1.getSizeInBits();
6899 unsigned NumBits2 = VT2.getSizeInBits();
6900 if (NumBits1 <= NumBits2)
6902 return Subtarget->is64Bit() || NumBits1 < 64;
6905 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
6906 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
6907 return Ty1 == Type::Int32Ty && Ty2 == Type::Int64Ty && Subtarget->is64Bit();
6910 bool X86TargetLowering::isZExtFree(MVT VT1, MVT VT2) const {
6911 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
6912 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
6915 bool X86TargetLowering::isNarrowingProfitable(MVT VT1, MVT VT2) const {
6916 // i16 instructions are longer (0x66 prefix) and potentially slower.
6917 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
6920 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6921 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6922 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6923 /// are assumed to be legal.
6925 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6927 // Only do shuffles on 128-bit vector types for now.
6928 if (VT.getSizeInBits() == 64)
6931 // FIXME: pshufb, blends, palignr, shifts.
6932 return (VT.getVectorNumElements() == 2 ||
6933 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
6934 isMOVLMask(M, VT) ||
6935 isSHUFPMask(M, VT) ||
6936 isPSHUFDMask(M, VT) ||
6937 isPSHUFHWMask(M, VT) ||
6938 isPSHUFLWMask(M, VT) ||
6939 isUNPCKLMask(M, VT) ||
6940 isUNPCKHMask(M, VT) ||
6941 isUNPCKL_v_undef_Mask(M, VT) ||
6942 isUNPCKH_v_undef_Mask(M, VT));
6946 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
6948 unsigned NumElts = VT.getVectorNumElements();
6949 // FIXME: This collection of masks seems suspect.
6952 if (NumElts == 4 && VT.getSizeInBits() == 128) {
6953 return (isMOVLMask(Mask, VT) ||
6954 isCommutedMOVLMask(Mask, VT, true) ||
6955 isSHUFPMask(Mask, VT) ||
6956 isCommutedSHUFPMask(Mask, VT));
6961 //===----------------------------------------------------------------------===//
6962 // X86 Scheduler Hooks
6963 //===----------------------------------------------------------------------===//
6965 // private utility function
6967 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
6968 MachineBasicBlock *MBB,
6976 TargetRegisterClass *RC,
6977 bool invSrc) const {
6978 // For the atomic bitwise operator, we generate
6981 // ld t1 = [bitinstr.addr]
6982 // op t2 = t1, [bitinstr.val]
6984 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
6986 // fallthrough -->nextMBB
6987 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6988 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6989 MachineFunction::iterator MBBIter = MBB;
6992 /// First build the CFG
6993 MachineFunction *F = MBB->getParent();
6994 MachineBasicBlock *thisMBB = MBB;
6995 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6996 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6997 F->insert(MBBIter, newMBB);
6998 F->insert(MBBIter, nextMBB);
7000 // Move all successors to thisMBB to nextMBB
7001 nextMBB->transferSuccessors(thisMBB);
7003 // Update thisMBB to fall through to newMBB
7004 thisMBB->addSuccessor(newMBB);
7006 // newMBB jumps to itself and fall through to nextMBB
7007 newMBB->addSuccessor(nextMBB);
7008 newMBB->addSuccessor(newMBB);
7010 // Insert instructions into newMBB based on incoming instruction
7011 assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7012 "unexpected number of operands");
7013 DebugLoc dl = bInstr->getDebugLoc();
7014 MachineOperand& destOper = bInstr->getOperand(0);
7015 MachineOperand* argOpers[2 + X86AddrNumOperands];
7016 int numArgs = bInstr->getNumOperands() - 1;
7017 for (int i=0; i < numArgs; ++i)
7018 argOpers[i] = &bInstr->getOperand(i+1);
7020 // x86 address has 4 operands: base, index, scale, and displacement
7021 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7022 int valArgIndx = lastAddrIndx + 1;
7024 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7025 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7026 for (int i=0; i <= lastAddrIndx; ++i)
7027 (*MIB).addOperand(*argOpers[i]);
7029 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7031 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7036 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7037 assert((argOpers[valArgIndx]->isReg() ||
7038 argOpers[valArgIndx]->isImm()) &&
7040 if (argOpers[valArgIndx]->isReg())
7041 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7043 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7045 (*MIB).addOperand(*argOpers[valArgIndx]);
7047 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7050 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7051 for (int i=0; i <= lastAddrIndx; ++i)
7052 (*MIB).addOperand(*argOpers[i]);
7054 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7055 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7057 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7061 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7063 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7067 // private utility function: 64 bit atomics on 32 bit host.
7069 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7070 MachineBasicBlock *MBB,
7075 bool invSrc) const {
7076 // For the atomic bitwise operator, we generate
7077 // thisMBB (instructions are in pairs, except cmpxchg8b)
7078 // ld t1,t2 = [bitinstr.addr]
7080 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7081 // op t5, t6 <- out1, out2, [bitinstr.val]
7082 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
7083 // mov ECX, EBX <- t5, t6
7084 // mov EAX, EDX <- t1, t2
7085 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
7086 // mov t3, t4 <- EAX, EDX
7088 // result in out1, out2
7089 // fallthrough -->nextMBB
7091 const TargetRegisterClass *RC = X86::GR32RegisterClass;
7092 const unsigned LoadOpc = X86::MOV32rm;
7093 const unsigned copyOpc = X86::MOV32rr;
7094 const unsigned NotOpc = X86::NOT32r;
7095 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7096 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7097 MachineFunction::iterator MBBIter = MBB;
7100 /// First build the CFG
7101 MachineFunction *F = MBB->getParent();
7102 MachineBasicBlock *thisMBB = MBB;
7103 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7104 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7105 F->insert(MBBIter, newMBB);
7106 F->insert(MBBIter, nextMBB);
7108 // Move all successors to thisMBB to nextMBB
7109 nextMBB->transferSuccessors(thisMBB);
7111 // Update thisMBB to fall through to newMBB
7112 thisMBB->addSuccessor(newMBB);
7114 // newMBB jumps to itself and fall through to nextMBB
7115 newMBB->addSuccessor(nextMBB);
7116 newMBB->addSuccessor(newMBB);
7118 DebugLoc dl = bInstr->getDebugLoc();
7119 // Insert instructions into newMBB based on incoming instruction
7120 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7121 assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
7122 "unexpected number of operands");
7123 MachineOperand& dest1Oper = bInstr->getOperand(0);
7124 MachineOperand& dest2Oper = bInstr->getOperand(1);
7125 MachineOperand* argOpers[2 + X86AddrNumOperands];
7126 for (int i=0; i < 2 + X86AddrNumOperands; ++i)
7127 argOpers[i] = &bInstr->getOperand(i+2);
7129 // x86 address has 4 operands: base, index, scale, and displacement
7130 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7132 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7133 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
7134 for (int i=0; i <= lastAddrIndx; ++i)
7135 (*MIB).addOperand(*argOpers[i]);
7136 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7137 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
7138 // add 4 to displacement.
7139 for (int i=0; i <= lastAddrIndx-2; ++i)
7140 (*MIB).addOperand(*argOpers[i]);
7141 MachineOperand newOp3 = *(argOpers[3]);
7143 newOp3.setImm(newOp3.getImm()+4);
7145 newOp3.setOffset(newOp3.getOffset()+4);
7146 (*MIB).addOperand(newOp3);
7147 (*MIB).addOperand(*argOpers[lastAddrIndx]);
7149 // t3/4 are defined later, at the bottom of the loop
7150 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
7151 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
7152 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
7153 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
7154 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
7155 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
7157 unsigned tt1 = F->getRegInfo().createVirtualRegister(RC);
7158 unsigned tt2 = F->getRegInfo().createVirtualRegister(RC);
7160 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt1).addReg(t1);
7161 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt2).addReg(t2);
7167 int valArgIndx = lastAddrIndx + 1;
7168 assert((argOpers[valArgIndx]->isReg() ||
7169 argOpers[valArgIndx]->isImm()) &&
7171 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
7172 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
7173 if (argOpers[valArgIndx]->isReg())
7174 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
7176 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
7177 if (regOpcL != X86::MOV32rr)
7179 (*MIB).addOperand(*argOpers[valArgIndx]);
7180 assert(argOpers[valArgIndx + 1]->isReg() ==
7181 argOpers[valArgIndx]->isReg());
7182 assert(argOpers[valArgIndx + 1]->isImm() ==
7183 argOpers[valArgIndx]->isImm());
7184 if (argOpers[valArgIndx + 1]->isReg())
7185 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
7187 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
7188 if (regOpcH != X86::MOV32rr)
7190 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
7192 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
7194 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
7197 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
7199 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
7202 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
7203 for (int i=0; i <= lastAddrIndx; ++i)
7204 (*MIB).addOperand(*argOpers[i]);
7206 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7207 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7209 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
7210 MIB.addReg(X86::EAX);
7211 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
7212 MIB.addReg(X86::EDX);
7215 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7217 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7221 // private utility function
7223 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
7224 MachineBasicBlock *MBB,
7225 unsigned cmovOpc) const {
7226 // For the atomic min/max operator, we generate
7229 // ld t1 = [min/max.addr]
7230 // mov t2 = [min/max.val]
7232 // cmov[cond] t2 = t1
7234 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7236 // fallthrough -->nextMBB
7238 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7239 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7240 MachineFunction::iterator MBBIter = MBB;
7243 /// First build the CFG
7244 MachineFunction *F = MBB->getParent();
7245 MachineBasicBlock *thisMBB = MBB;
7246 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7247 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7248 F->insert(MBBIter, newMBB);
7249 F->insert(MBBIter, nextMBB);
7251 // Move all successors to thisMBB to nextMBB
7252 nextMBB->transferSuccessors(thisMBB);
7254 // Update thisMBB to fall through to newMBB
7255 thisMBB->addSuccessor(newMBB);
7257 // newMBB jumps to newMBB and fall through to nextMBB
7258 newMBB->addSuccessor(nextMBB);
7259 newMBB->addSuccessor(newMBB);
7261 DebugLoc dl = mInstr->getDebugLoc();
7262 // Insert instructions into newMBB based on incoming instruction
7263 assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7264 "unexpected number of operands");
7265 MachineOperand& destOper = mInstr->getOperand(0);
7266 MachineOperand* argOpers[2 + X86AddrNumOperands];
7267 int numArgs = mInstr->getNumOperands() - 1;
7268 for (int i=0; i < numArgs; ++i)
7269 argOpers[i] = &mInstr->getOperand(i+1);
7271 // x86 address has 4 operands: base, index, scale, and displacement
7272 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7273 int valArgIndx = lastAddrIndx + 1;
7275 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7276 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
7277 for (int i=0; i <= lastAddrIndx; ++i)
7278 (*MIB).addOperand(*argOpers[i]);
7280 // We only support register and immediate values
7281 assert((argOpers[valArgIndx]->isReg() ||
7282 argOpers[valArgIndx]->isImm()) &&
7285 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7286 if (argOpers[valArgIndx]->isReg())
7287 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7289 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7290 (*MIB).addOperand(*argOpers[valArgIndx]);
7292 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
7295 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
7300 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7301 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
7305 // Cmp and exchange if none has modified the memory location
7306 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
7307 for (int i=0; i <= lastAddrIndx; ++i)
7308 (*MIB).addOperand(*argOpers[i]);
7310 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7311 (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
7313 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
7314 MIB.addReg(X86::EAX);
7317 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7319 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
7325 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7326 MachineBasicBlock *BB) const {
7327 DebugLoc dl = MI->getDebugLoc();
7328 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7329 switch (MI->getOpcode()) {
7330 default: assert(false && "Unexpected instr type to insert");
7331 case X86::CMOV_V1I64:
7332 case X86::CMOV_FR32:
7333 case X86::CMOV_FR64:
7334 case X86::CMOV_V4F32:
7335 case X86::CMOV_V2F64:
7336 case X86::CMOV_V2I64: {
7337 // To "insert" a SELECT_CC instruction, we actually have to insert the
7338 // diamond control-flow pattern. The incoming instruction knows the
7339 // destination vreg to set, the condition code register to branch on, the
7340 // true/false values to select between, and a branch opcode to use.
7341 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7342 MachineFunction::iterator It = BB;
7348 // cmpTY ccX, r1, r2
7350 // fallthrough --> copy0MBB
7351 MachineBasicBlock *thisMBB = BB;
7352 MachineFunction *F = BB->getParent();
7353 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7354 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7356 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
7357 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
7358 F->insert(It, copy0MBB);
7359 F->insert(It, sinkMBB);
7360 // Update machine-CFG edges by transferring all successors of the current
7361 // block to the new block which will contain the Phi node for the select.
7362 sinkMBB->transferSuccessors(BB);
7364 // Add the true and fallthrough blocks as its successors.
7365 BB->addSuccessor(copy0MBB);
7366 BB->addSuccessor(sinkMBB);
7369 // %FalseValue = ...
7370 // # fallthrough to sinkMBB
7373 // Update machine-CFG edges
7374 BB->addSuccessor(sinkMBB);
7377 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7380 BuildMI(BB, dl, TII->get(X86::PHI), MI->getOperand(0).getReg())
7381 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7382 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7384 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7388 case X86::FP32_TO_INT16_IN_MEM:
7389 case X86::FP32_TO_INT32_IN_MEM:
7390 case X86::FP32_TO_INT64_IN_MEM:
7391 case X86::FP64_TO_INT16_IN_MEM:
7392 case X86::FP64_TO_INT32_IN_MEM:
7393 case X86::FP64_TO_INT64_IN_MEM:
7394 case X86::FP80_TO_INT16_IN_MEM:
7395 case X86::FP80_TO_INT32_IN_MEM:
7396 case X86::FP80_TO_INT64_IN_MEM: {
7397 // Change the floating point control register to use "round towards zero"
7398 // mode when truncating to an integer value.
7399 MachineFunction *F = BB->getParent();
7400 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
7401 addFrameReference(BuildMI(BB, dl, TII->get(X86::FNSTCW16m)), CWFrameIdx);
7403 // Load the old value of the high byte of the control word...
7405 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
7406 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16rm), OldCW),
7409 // Set the high part to be round to zero...
7410 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mi)), CWFrameIdx)
7413 // Reload the modified control word now...
7414 addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7416 // Restore the memory image of control word to original value
7417 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mr)), CWFrameIdx)
7420 // Get the X86 opcode to use.
7422 switch (MI->getOpcode()) {
7423 default: assert(0 && "illegal opcode!");
7424 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
7425 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
7426 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
7427 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
7428 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
7429 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
7430 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
7431 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
7432 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
7436 MachineOperand &Op = MI->getOperand(0);
7438 AM.BaseType = X86AddressMode::RegBase;
7439 AM.Base.Reg = Op.getReg();
7441 AM.BaseType = X86AddressMode::FrameIndexBase;
7442 AM.Base.FrameIndex = Op.getIndex();
7444 Op = MI->getOperand(1);
7446 AM.Scale = Op.getImm();
7447 Op = MI->getOperand(2);
7449 AM.IndexReg = Op.getImm();
7450 Op = MI->getOperand(3);
7451 if (Op.isGlobal()) {
7452 AM.GV = Op.getGlobal();
7454 AM.Disp = Op.getImm();
7456 addFullAddress(BuildMI(BB, dl, TII->get(Opc)), AM)
7457 .addReg(MI->getOperand(X86AddrNumOperands).getReg());
7459 // Reload the original control word now.
7460 addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7462 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7465 case X86::ATOMAND32:
7466 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7467 X86::AND32ri, X86::MOV32rm,
7468 X86::LCMPXCHG32, X86::MOV32rr,
7469 X86::NOT32r, X86::EAX,
7470 X86::GR32RegisterClass);
7472 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
7473 X86::OR32ri, X86::MOV32rm,
7474 X86::LCMPXCHG32, X86::MOV32rr,
7475 X86::NOT32r, X86::EAX,
7476 X86::GR32RegisterClass);
7477 case X86::ATOMXOR32:
7478 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
7479 X86::XOR32ri, X86::MOV32rm,
7480 X86::LCMPXCHG32, X86::MOV32rr,
7481 X86::NOT32r, X86::EAX,
7482 X86::GR32RegisterClass);
7483 case X86::ATOMNAND32:
7484 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7485 X86::AND32ri, X86::MOV32rm,
7486 X86::LCMPXCHG32, X86::MOV32rr,
7487 X86::NOT32r, X86::EAX,
7488 X86::GR32RegisterClass, true);
7489 case X86::ATOMMIN32:
7490 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
7491 case X86::ATOMMAX32:
7492 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
7493 case X86::ATOMUMIN32:
7494 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
7495 case X86::ATOMUMAX32:
7496 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
7498 case X86::ATOMAND16:
7499 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7500 X86::AND16ri, X86::MOV16rm,
7501 X86::LCMPXCHG16, X86::MOV16rr,
7502 X86::NOT16r, X86::AX,
7503 X86::GR16RegisterClass);
7505 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
7506 X86::OR16ri, X86::MOV16rm,
7507 X86::LCMPXCHG16, X86::MOV16rr,
7508 X86::NOT16r, X86::AX,
7509 X86::GR16RegisterClass);
7510 case X86::ATOMXOR16:
7511 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
7512 X86::XOR16ri, X86::MOV16rm,
7513 X86::LCMPXCHG16, X86::MOV16rr,
7514 X86::NOT16r, X86::AX,
7515 X86::GR16RegisterClass);
7516 case X86::ATOMNAND16:
7517 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7518 X86::AND16ri, X86::MOV16rm,
7519 X86::LCMPXCHG16, X86::MOV16rr,
7520 X86::NOT16r, X86::AX,
7521 X86::GR16RegisterClass, true);
7522 case X86::ATOMMIN16:
7523 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
7524 case X86::ATOMMAX16:
7525 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
7526 case X86::ATOMUMIN16:
7527 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
7528 case X86::ATOMUMAX16:
7529 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
7532 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7533 X86::AND8ri, X86::MOV8rm,
7534 X86::LCMPXCHG8, X86::MOV8rr,
7535 X86::NOT8r, X86::AL,
7536 X86::GR8RegisterClass);
7538 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
7539 X86::OR8ri, X86::MOV8rm,
7540 X86::LCMPXCHG8, X86::MOV8rr,
7541 X86::NOT8r, X86::AL,
7542 X86::GR8RegisterClass);
7544 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
7545 X86::XOR8ri, X86::MOV8rm,
7546 X86::LCMPXCHG8, X86::MOV8rr,
7547 X86::NOT8r, X86::AL,
7548 X86::GR8RegisterClass);
7549 case X86::ATOMNAND8:
7550 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7551 X86::AND8ri, X86::MOV8rm,
7552 X86::LCMPXCHG8, X86::MOV8rr,
7553 X86::NOT8r, X86::AL,
7554 X86::GR8RegisterClass, true);
7555 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
7556 // This group is for 64-bit host.
7557 case X86::ATOMAND64:
7558 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7559 X86::AND64ri32, X86::MOV64rm,
7560 X86::LCMPXCHG64, X86::MOV64rr,
7561 X86::NOT64r, X86::RAX,
7562 X86::GR64RegisterClass);
7564 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
7565 X86::OR64ri32, X86::MOV64rm,
7566 X86::LCMPXCHG64, X86::MOV64rr,
7567 X86::NOT64r, X86::RAX,
7568 X86::GR64RegisterClass);
7569 case X86::ATOMXOR64:
7570 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
7571 X86::XOR64ri32, X86::MOV64rm,
7572 X86::LCMPXCHG64, X86::MOV64rr,
7573 X86::NOT64r, X86::RAX,
7574 X86::GR64RegisterClass);
7575 case X86::ATOMNAND64:
7576 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7577 X86::AND64ri32, X86::MOV64rm,
7578 X86::LCMPXCHG64, X86::MOV64rr,
7579 X86::NOT64r, X86::RAX,
7580 X86::GR64RegisterClass, true);
7581 case X86::ATOMMIN64:
7582 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
7583 case X86::ATOMMAX64:
7584 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
7585 case X86::ATOMUMIN64:
7586 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
7587 case X86::ATOMUMAX64:
7588 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
7590 // This group does 64-bit operations on a 32-bit host.
7591 case X86::ATOMAND6432:
7592 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7593 X86::AND32rr, X86::AND32rr,
7594 X86::AND32ri, X86::AND32ri,
7596 case X86::ATOMOR6432:
7597 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7598 X86::OR32rr, X86::OR32rr,
7599 X86::OR32ri, X86::OR32ri,
7601 case X86::ATOMXOR6432:
7602 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7603 X86::XOR32rr, X86::XOR32rr,
7604 X86::XOR32ri, X86::XOR32ri,
7606 case X86::ATOMNAND6432:
7607 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7608 X86::AND32rr, X86::AND32rr,
7609 X86::AND32ri, X86::AND32ri,
7611 case X86::ATOMADD6432:
7612 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7613 X86::ADD32rr, X86::ADC32rr,
7614 X86::ADD32ri, X86::ADC32ri,
7616 case X86::ATOMSUB6432:
7617 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7618 X86::SUB32rr, X86::SBB32rr,
7619 X86::SUB32ri, X86::SBB32ri,
7621 case X86::ATOMSWAP6432:
7622 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7623 X86::MOV32rr, X86::MOV32rr,
7624 X86::MOV32ri, X86::MOV32ri,
7629 //===----------------------------------------------------------------------===//
7630 // X86 Optimization Hooks
7631 //===----------------------------------------------------------------------===//
7633 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
7637 const SelectionDAG &DAG,
7638 unsigned Depth) const {
7639 unsigned Opc = Op.getOpcode();
7640 assert((Opc >= ISD::BUILTIN_OP_END ||
7641 Opc == ISD::INTRINSIC_WO_CHAIN ||
7642 Opc == ISD::INTRINSIC_W_CHAIN ||
7643 Opc == ISD::INTRINSIC_VOID) &&
7644 "Should use MaskedValueIsZero if you don't know whether Op"
7645 " is a target node!");
7647 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
7656 // These nodes' second result is a boolean.
7657 if (Op.getResNo() == 0)
7661 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
7662 Mask.getBitWidth() - 1);
7667 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
7668 /// node is a GlobalAddress + offset.
7669 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
7670 GlobalValue* &GA, int64_t &Offset) const{
7671 if (N->getOpcode() == X86ISD::Wrapper) {
7672 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
7673 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
7674 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
7678 return TargetLowering::isGAPlusOffset(N, GA, Offset);
7681 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
7682 const TargetLowering &TLI) {
7685 if (TLI.isGAPlusOffset(Base, GV, Offset))
7686 return (GV->getAlignment() >= N && (Offset % N) == 0);
7687 // DAG combine handles the stack object case.
7691 static bool EltsFromConsecutiveLoads(ShuffleVectorSDNode *N, unsigned NumElems,
7692 MVT EVT, LoadSDNode *&LDBase,
7693 unsigned &LastLoadedElt,
7694 SelectionDAG &DAG, MachineFrameInfo *MFI,
7695 const TargetLowering &TLI) {
7697 LastLoadedElt = -1U;
7698 for (unsigned i = 0; i < NumElems; ++i) {
7699 if (N->getMaskElt(i) < 0) {
7705 SDValue Elt = DAG.getShuffleScalarElt(N, i);
7706 if (!Elt.getNode() ||
7707 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
7710 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
7712 LDBase = cast<LoadSDNode>(Elt.getNode());
7716 if (Elt.getOpcode() == ISD::UNDEF)
7719 LoadSDNode *LD = cast<LoadSDNode>(Elt);
7720 if (!TLI.isConsecutiveLoad(LD, LDBase, EVT.getSizeInBits()/8, i, MFI))
7727 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
7728 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
7729 /// if the load addresses are consecutive, non-overlapping, and in the right
7730 /// order. In the case of v2i64, it will see if it can rewrite the
7731 /// shuffle to be an appropriate build vector so it can take advantage of
7732 // performBuildVectorCombine.
7733 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
7734 const TargetLowering &TLI) {
7735 DebugLoc dl = N->getDebugLoc();
7736 MVT VT = N->getValueType(0);
7737 MVT EVT = VT.getVectorElementType();
7738 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
7739 unsigned NumElems = VT.getVectorNumElements();
7741 if (VT.getSizeInBits() != 128)
7744 // Try to combine a vector_shuffle into a 128-bit load.
7745 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7746 LoadSDNode *LD = NULL;
7747 unsigned LastLoadedElt;
7748 if (!EltsFromConsecutiveLoads(SVN, NumElems, EVT, LD, LastLoadedElt, DAG,
7752 if (LastLoadedElt == NumElems - 1) {
7753 if (isBaseAlignmentOfN(16, LD->getBasePtr().getNode(), TLI))
7754 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
7755 LD->getSrcValue(), LD->getSrcValueOffset(),
7757 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
7758 LD->getSrcValue(), LD->getSrcValueOffset(),
7759 LD->isVolatile(), LD->getAlignment());
7760 } else if (NumElems == 4 && LastLoadedElt == 1) {
7761 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
7762 SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
7763 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
7764 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
7769 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
7770 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
7771 const X86Subtarget *Subtarget) {
7772 DebugLoc DL = N->getDebugLoc();
7773 SDValue Cond = N->getOperand(0);
7774 // Get the LHS/RHS of the select.
7775 SDValue LHS = N->getOperand(1);
7776 SDValue RHS = N->getOperand(2);
7778 // If we have SSE[12] support, try to form min/max nodes.
7779 if (Subtarget->hasSSE2() &&
7780 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
7781 Cond.getOpcode() == ISD::SETCC) {
7782 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
7784 unsigned Opcode = 0;
7785 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
7788 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
7791 if (!UnsafeFPMath) break;
7793 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
7795 Opcode = X86ISD::FMIN;
7798 case ISD::SETOGT: // (X > Y) ? X : Y -> max
7801 if (!UnsafeFPMath) break;
7803 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
7805 Opcode = X86ISD::FMAX;
7808 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
7811 case ISD::SETOGT: // (X > Y) ? Y : X -> min
7814 if (!UnsafeFPMath) break;
7816 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
7818 Opcode = X86ISD::FMIN;
7821 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
7824 if (!UnsafeFPMath) break;
7826 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
7828 Opcode = X86ISD::FMAX;
7834 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
7837 // If this is a select between two integer constants, try to do some
7839 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
7840 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
7841 // Don't do this for crazy integer types.
7842 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
7843 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
7844 // so that TrueC (the true value) is larger than FalseC.
7845 bool NeedsCondInvert = false;
7847 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
7848 // Efficiently invertible.
7849 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
7850 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
7851 isa<ConstantSDNode>(Cond.getOperand(1))))) {
7852 NeedsCondInvert = true;
7853 std::swap(TrueC, FalseC);
7856 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
7857 if (FalseC->getAPIntValue() == 0 &&
7858 TrueC->getAPIntValue().isPowerOf2()) {
7859 if (NeedsCondInvert) // Invert the condition if needed.
7860 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
7861 DAG.getConstant(1, Cond.getValueType()));
7863 // Zero extend the condition if needed.
7864 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
7866 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
7867 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
7868 DAG.getConstant(ShAmt, MVT::i8));
7871 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
7872 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
7873 if (NeedsCondInvert) // Invert the condition if needed.
7874 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
7875 DAG.getConstant(1, Cond.getValueType()));
7877 // Zero extend the condition if needed.
7878 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
7879 FalseC->getValueType(0), Cond);
7880 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
7881 SDValue(FalseC, 0));
7884 // Optimize cases that will turn into an LEA instruction. This requires
7885 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
7886 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
7887 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
7888 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
7890 bool isFastMultiplier = false;
7892 switch ((unsigned char)Diff) {
7894 case 1: // result = add base, cond
7895 case 2: // result = lea base( , cond*2)
7896 case 3: // result = lea base(cond, cond*2)
7897 case 4: // result = lea base( , cond*4)
7898 case 5: // result = lea base(cond, cond*4)
7899 case 8: // result = lea base( , cond*8)
7900 case 9: // result = lea base(cond, cond*8)
7901 isFastMultiplier = true;
7906 if (isFastMultiplier) {
7907 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
7908 if (NeedsCondInvert) // Invert the condition if needed.
7909 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
7910 DAG.getConstant(1, Cond.getValueType()));
7912 // Zero extend the condition if needed.
7913 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
7915 // Scale the condition by the difference.
7917 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
7918 DAG.getConstant(Diff, Cond.getValueType()));
7920 // Add the base if non-zero.
7921 if (FalseC->getAPIntValue() != 0)
7922 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
7923 SDValue(FalseC, 0));
7933 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
7934 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
7935 TargetLowering::DAGCombinerInfo &DCI) {
7936 DebugLoc DL = N->getDebugLoc();
7938 // If the flag operand isn't dead, don't touch this CMOV.
7939 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
7942 // If this is a select between two integer constants, try to do some
7943 // optimizations. Note that the operands are ordered the opposite of SELECT
7945 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
7946 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
7947 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
7948 // larger than FalseC (the false value).
7949 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
7951 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
7952 CC = X86::GetOppositeBranchCondition(CC);
7953 std::swap(TrueC, FalseC);
7956 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
7957 // This is efficient for any integer data type (including i8/i16) and
7959 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
7960 SDValue Cond = N->getOperand(3);
7961 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
7962 DAG.getConstant(CC, MVT::i8), Cond);
7964 // Zero extend the condition if needed.
7965 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
7967 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
7968 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
7969 DAG.getConstant(ShAmt, MVT::i8));
7970 if (N->getNumValues() == 2) // Dead flag value?
7971 return DCI.CombineTo(N, Cond, SDValue());
7975 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
7976 // for any integer data type, including i8/i16.
7977 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
7978 SDValue Cond = N->getOperand(3);
7979 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
7980 DAG.getConstant(CC, MVT::i8), Cond);
7982 // Zero extend the condition if needed.
7983 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
7984 FalseC->getValueType(0), Cond);
7985 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
7986 SDValue(FalseC, 0));
7988 if (N->getNumValues() == 2) // Dead flag value?
7989 return DCI.CombineTo(N, Cond, SDValue());
7993 // Optimize cases that will turn into an LEA instruction. This requires
7994 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
7995 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
7996 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
7997 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
7999 bool isFastMultiplier = false;
8001 switch ((unsigned char)Diff) {
8003 case 1: // result = add base, cond
8004 case 2: // result = lea base( , cond*2)
8005 case 3: // result = lea base(cond, cond*2)
8006 case 4: // result = lea base( , cond*4)
8007 case 5: // result = lea base(cond, cond*4)
8008 case 8: // result = lea base( , cond*8)
8009 case 9: // result = lea base(cond, cond*8)
8010 isFastMultiplier = true;
8015 if (isFastMultiplier) {
8016 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8017 SDValue Cond = N->getOperand(3);
8018 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8019 DAG.getConstant(CC, MVT::i8), Cond);
8020 // Zero extend the condition if needed.
8021 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8023 // Scale the condition by the difference.
8025 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8026 DAG.getConstant(Diff, Cond.getValueType()));
8028 // Add the base if non-zero.
8029 if (FalseC->getAPIntValue() != 0)
8030 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8031 SDValue(FalseC, 0));
8032 if (N->getNumValues() == 2) // Dead flag value?
8033 return DCI.CombineTo(N, Cond, SDValue());
8043 /// PerformMulCombine - Optimize a single multiply with constant into two
8044 /// in order to implement it with two cheaper instructions, e.g.
8045 /// LEA + SHL, LEA + LEA.
8046 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
8047 TargetLowering::DAGCombinerInfo &DCI) {
8048 if (DAG.getMachineFunction().
8049 getFunction()->hasFnAttr(Attribute::OptimizeForSize))
8052 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8055 MVT VT = N->getValueType(0);
8059 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8062 uint64_t MulAmt = C->getZExtValue();
8063 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
8066 uint64_t MulAmt1 = 0;
8067 uint64_t MulAmt2 = 0;
8068 if ((MulAmt % 9) == 0) {
8070 MulAmt2 = MulAmt / 9;
8071 } else if ((MulAmt % 5) == 0) {
8073 MulAmt2 = MulAmt / 5;
8074 } else if ((MulAmt % 3) == 0) {
8076 MulAmt2 = MulAmt / 3;
8079 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
8080 DebugLoc DL = N->getDebugLoc();
8082 if (isPowerOf2_64(MulAmt2) &&
8083 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
8084 // If second multiplifer is pow2, issue it first. We want the multiply by
8085 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
8087 std::swap(MulAmt1, MulAmt2);
8090 if (isPowerOf2_64(MulAmt1))
8091 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
8092 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
8094 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
8095 DAG.getConstant(MulAmt1, VT));
8097 if (isPowerOf2_64(MulAmt2))
8098 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
8099 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
8101 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
8102 DAG.getConstant(MulAmt2, VT));
8104 // Do not add new nodes to DAG combiner worklist.
8105 DCI.CombineTo(N, NewMul, false);
8111 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
8113 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
8114 const X86Subtarget *Subtarget) {
8115 // On X86 with SSE2 support, we can transform this to a vector shift if
8116 // all elements are shifted by the same amount. We can't do this in legalize
8117 // because the a constant vector is typically transformed to a constant pool
8118 // so we have no knowledge of the shift amount.
8119 if (!Subtarget->hasSSE2())
8122 MVT VT = N->getValueType(0);
8123 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
8126 SDValue ShAmtOp = N->getOperand(1);
8127 MVT EltVT = VT.getVectorElementType();
8128 DebugLoc DL = N->getDebugLoc();
8130 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
8131 unsigned NumElts = VT.getVectorNumElements();
8133 for (; i != NumElts; ++i) {
8134 SDValue Arg = ShAmtOp.getOperand(i);
8135 if (Arg.getOpcode() == ISD::UNDEF) continue;
8139 for (; i != NumElts; ++i) {
8140 SDValue Arg = ShAmtOp.getOperand(i);
8141 if (Arg.getOpcode() == ISD::UNDEF) continue;
8142 if (Arg != BaseShAmt) {
8146 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
8147 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
8148 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
8149 DAG.getIntPtrConstant(0));
8153 if (EltVT.bitsGT(MVT::i32))
8154 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
8155 else if (EltVT.bitsLT(MVT::i32))
8156 BaseShAmt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, BaseShAmt);
8158 // The shift amount is identical so we can do a vector shift.
8159 SDValue ValOp = N->getOperand(0);
8160 switch (N->getOpcode()) {
8162 assert(0 && "Unknown shift opcode!");
8165 if (VT == MVT::v2i64)
8166 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8167 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8169 if (VT == MVT::v4i32)
8170 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8171 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8173 if (VT == MVT::v8i16)
8174 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8175 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8179 if (VT == MVT::v4i32)
8180 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8181 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8183 if (VT == MVT::v8i16)
8184 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8185 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8189 if (VT == MVT::v2i64)
8190 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8191 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8193 if (VT == MVT::v4i32)
8194 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8195 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8197 if (VT == MVT::v8i16)
8198 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8199 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8206 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
8207 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
8208 const X86Subtarget *Subtarget) {
8209 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
8210 // the FP state in cases where an emms may be missing.
8211 // A preferable solution to the general problem is to figure out the right
8212 // places to insert EMMS. This qualifies as a quick hack.
8214 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
8215 StoreSDNode *St = cast<StoreSDNode>(N);
8216 MVT VT = St->getValue().getValueType();
8217 if (VT.getSizeInBits() != 64)
8220 const Function *F = DAG.getMachineFunction().getFunction();
8221 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
8222 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
8223 && Subtarget->hasSSE2();
8224 if ((VT.isVector() ||
8225 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
8226 isa<LoadSDNode>(St->getValue()) &&
8227 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
8228 St->getChain().hasOneUse() && !St->isVolatile()) {
8229 SDNode* LdVal = St->getValue().getNode();
8231 int TokenFactorIndex = -1;
8232 SmallVector<SDValue, 8> Ops;
8233 SDNode* ChainVal = St->getChain().getNode();
8234 // Must be a store of a load. We currently handle two cases: the load
8235 // is a direct child, and it's under an intervening TokenFactor. It is
8236 // possible to dig deeper under nested TokenFactors.
8237 if (ChainVal == LdVal)
8238 Ld = cast<LoadSDNode>(St->getChain());
8239 else if (St->getValue().hasOneUse() &&
8240 ChainVal->getOpcode() == ISD::TokenFactor) {
8241 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
8242 if (ChainVal->getOperand(i).getNode() == LdVal) {
8243 TokenFactorIndex = i;
8244 Ld = cast<LoadSDNode>(St->getValue());
8246 Ops.push_back(ChainVal->getOperand(i));
8250 if (!Ld || !ISD::isNormalLoad(Ld))
8253 // If this is not the MMX case, i.e. we are just turning i64 load/store
8254 // into f64 load/store, avoid the transformation if there are multiple
8255 // uses of the loaded value.
8256 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
8259 DebugLoc LdDL = Ld->getDebugLoc();
8260 DebugLoc StDL = N->getDebugLoc();
8261 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
8262 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
8264 if (Subtarget->is64Bit() || F64IsLegal) {
8265 MVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
8266 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
8267 Ld->getBasePtr(), Ld->getSrcValue(),
8268 Ld->getSrcValueOffset(), Ld->isVolatile(),
8269 Ld->getAlignment());
8270 SDValue NewChain = NewLd.getValue(1);
8271 if (TokenFactorIndex != -1) {
8272 Ops.push_back(NewChain);
8273 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
8276 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
8277 St->getSrcValue(), St->getSrcValueOffset(),
8278 St->isVolatile(), St->getAlignment());
8281 // Otherwise, lower to two pairs of 32-bit loads / stores.
8282 SDValue LoAddr = Ld->getBasePtr();
8283 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
8284 DAG.getConstant(4, MVT::i32));
8286 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
8287 Ld->getSrcValue(), Ld->getSrcValueOffset(),
8288 Ld->isVolatile(), Ld->getAlignment());
8289 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
8290 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
8292 MinAlign(Ld->getAlignment(), 4));
8294 SDValue NewChain = LoLd.getValue(1);
8295 if (TokenFactorIndex != -1) {
8296 Ops.push_back(LoLd);
8297 Ops.push_back(HiLd);
8298 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
8302 LoAddr = St->getBasePtr();
8303 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
8304 DAG.getConstant(4, MVT::i32));
8306 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
8307 St->getSrcValue(), St->getSrcValueOffset(),
8308 St->isVolatile(), St->getAlignment());
8309 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
8311 St->getSrcValueOffset() + 4,
8313 MinAlign(St->getAlignment(), 4));
8314 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
8319 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
8320 /// X86ISD::FXOR nodes.
8321 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
8322 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
8323 // F[X]OR(0.0, x) -> x
8324 // F[X]OR(x, 0.0) -> x
8325 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8326 if (C->getValueAPF().isPosZero())
8327 return N->getOperand(1);
8328 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8329 if (C->getValueAPF().isPosZero())
8330 return N->getOperand(0);
8334 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
8335 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
8336 // FAND(0.0, x) -> 0.0
8337 // FAND(x, 0.0) -> 0.0
8338 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8339 if (C->getValueAPF().isPosZero())
8340 return N->getOperand(0);
8341 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8342 if (C->getValueAPF().isPosZero())
8343 return N->getOperand(1);
8347 static SDValue PerformBTCombine(SDNode *N,
8349 TargetLowering::DAGCombinerInfo &DCI) {
8350 // BT ignores high bits in the bit index operand.
8351 SDValue Op1 = N->getOperand(1);
8352 if (Op1.hasOneUse()) {
8353 unsigned BitWidth = Op1.getValueSizeInBits();
8354 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
8355 APInt KnownZero, KnownOne;
8356 TargetLowering::TargetLoweringOpt TLO(DAG);
8357 TargetLowering &TLI = DAG.getTargetLoweringInfo();
8358 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
8359 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
8360 DCI.CommitTargetLoweringOpt(TLO);
8365 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
8366 SDValue Op = N->getOperand(0);
8367 if (Op.getOpcode() == ISD::BIT_CONVERT)
8368 Op = Op.getOperand(0);
8369 MVT VT = N->getValueType(0), OpVT = Op.getValueType();
8370 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
8371 VT.getVectorElementType().getSizeInBits() ==
8372 OpVT.getVectorElementType().getSizeInBits()) {
8373 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
8378 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
8379 DAGCombinerInfo &DCI) const {
8380 SelectionDAG &DAG = DCI.DAG;
8381 switch (N->getOpcode()) {
8383 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
8384 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
8385 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
8386 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
8389 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
8390 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
8392 case X86ISD::FOR: return PerformFORCombine(N, DAG);
8393 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
8394 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
8395 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
8401 //===----------------------------------------------------------------------===//
8402 // X86 Inline Assembly Support
8403 //===----------------------------------------------------------------------===//
8405 /// getConstraintType - Given a constraint letter, return the type of
8406 /// constraint it is for this target.
8407 X86TargetLowering::ConstraintType
8408 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
8409 if (Constraint.size() == 1) {
8410 switch (Constraint[0]) {
8422 return C_RegisterClass;
8430 return TargetLowering::getConstraintType(Constraint);
8433 /// LowerXConstraint - try to replace an X constraint, which matches anything,
8434 /// with another that has more specific requirements based on the type of the
8435 /// corresponding operand.
8436 const char *X86TargetLowering::
8437 LowerXConstraint(MVT ConstraintVT) const {
8438 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
8439 // 'f' like normal targets.
8440 if (ConstraintVT.isFloatingPoint()) {
8441 if (Subtarget->hasSSE2())
8443 if (Subtarget->hasSSE1())
8447 return TargetLowering::LowerXConstraint(ConstraintVT);
8450 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8451 /// vector. If it is invalid, don't add anything to Ops.
8452 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8455 std::vector<SDValue>&Ops,
8456 SelectionDAG &DAG) const {
8457 SDValue Result(0, 0);
8459 switch (Constraint) {
8462 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8463 if (C->getZExtValue() <= 31) {
8464 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8470 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8471 if (C->getZExtValue() <= 63) {
8472 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8478 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8479 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
8480 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8486 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8487 if (C->getZExtValue() <= 255) {
8488 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8494 // 32-bit signed value
8495 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8496 const ConstantInt *CI = C->getConstantIntValue();
8497 if (CI->isValueValidForType(Type::Int32Ty, C->getSExtValue())) {
8498 // Widen to 64 bits here to get it sign extended.
8499 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
8502 // FIXME gcc accepts some relocatable values here too, but only in certain
8503 // memory models; it's complicated.
8508 // 32-bit unsigned value
8509 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8510 const ConstantInt *CI = C->getConstantIntValue();
8511 if (CI->isValueValidForType(Type::Int32Ty, C->getZExtValue())) {
8512 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8516 // FIXME gcc accepts some relocatable values here too, but only in certain
8517 // memory models; it's complicated.
8521 // Literal immediates are always ok.
8522 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
8523 // Widen to 64 bits here to get it sign extended.
8524 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
8528 // If we are in non-pic codegen mode, we allow the address of a global (with
8529 // an optional displacement) to be used with 'i'.
8530 GlobalAddressSDNode *GA = 0;
8533 // Match either (GA), (GA+C), (GA+C1+C2), etc.
8535 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
8536 Offset += GA->getOffset();
8538 } else if (Op.getOpcode() == ISD::ADD) {
8539 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8540 Offset += C->getZExtValue();
8541 Op = Op.getOperand(0);
8544 } else if (Op.getOpcode() == ISD::SUB) {
8545 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8546 Offset += -C->getZExtValue();
8547 Op = Op.getOperand(0);
8552 // Otherwise, this isn't something we can handle, reject it.
8557 Op = LowerGlobalAddress(GA->getGlobal(), Op.getDebugLoc(), Offset, DAG);
8559 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
8566 if (Result.getNode()) {
8567 Ops.push_back(Result);
8570 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
8574 std::vector<unsigned> X86TargetLowering::
8575 getRegClassForInlineAsmConstraint(const std::string &Constraint,
8577 if (Constraint.size() == 1) {
8578 // FIXME: not handling fp-stack yet!
8579 switch (Constraint[0]) { // GCC X86 Constraint Letters
8580 default: break; // Unknown constraint letter
8581 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
8584 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
8585 else if (VT == MVT::i16)
8586 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
8587 else if (VT == MVT::i8)
8588 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
8589 else if (VT == MVT::i64)
8590 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
8595 return std::vector<unsigned>();
8598 std::pair<unsigned, const TargetRegisterClass*>
8599 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8601 // First, see if this is a constraint that directly corresponds to an LLVM
8603 if (Constraint.size() == 1) {
8604 // GCC Constraint Letters
8605 switch (Constraint[0]) {
8607 case 'r': // GENERAL_REGS
8608 case 'R': // LEGACY_REGS
8609 case 'l': // INDEX_REGS
8611 return std::make_pair(0U, X86::GR8RegisterClass);
8613 return std::make_pair(0U, X86::GR16RegisterClass);
8614 if (VT == MVT::i32 || !Subtarget->is64Bit())
8615 return std::make_pair(0U, X86::GR32RegisterClass);
8616 return std::make_pair(0U, X86::GR64RegisterClass);
8617 case 'f': // FP Stack registers.
8618 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
8619 // value to the correct fpstack register class.
8620 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
8621 return std::make_pair(0U, X86::RFP32RegisterClass);
8622 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
8623 return std::make_pair(0U, X86::RFP64RegisterClass);
8624 return std::make_pair(0U, X86::RFP80RegisterClass);
8625 case 'y': // MMX_REGS if MMX allowed.
8626 if (!Subtarget->hasMMX()) break;
8627 return std::make_pair(0U, X86::VR64RegisterClass);
8628 case 'Y': // SSE_REGS if SSE2 allowed
8629 if (!Subtarget->hasSSE2()) break;
8631 case 'x': // SSE_REGS if SSE1 allowed
8632 if (!Subtarget->hasSSE1()) break;
8634 switch (VT.getSimpleVT()) {
8636 // Scalar SSE types.
8639 return std::make_pair(0U, X86::FR32RegisterClass);
8642 return std::make_pair(0U, X86::FR64RegisterClass);
8650 return std::make_pair(0U, X86::VR128RegisterClass);
8656 // Use the default implementation in TargetLowering to convert the register
8657 // constraint into a member of a register class.
8658 std::pair<unsigned, const TargetRegisterClass*> Res;
8659 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8661 // Not found as a standard register?
8662 if (Res.second == 0) {
8663 // GCC calls "st(0)" just plain "st".
8664 if (StringsEqualNoCase("{st}", Constraint)) {
8665 Res.first = X86::ST0;
8666 Res.second = X86::RFP80RegisterClass;
8668 // 'A' means EAX + EDX.
8669 if (Constraint == "A") {
8670 Res.first = X86::EAX;
8671 Res.second = X86::GRADRegisterClass;
8676 // Otherwise, check to see if this is a register class of the wrong value
8677 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
8678 // turn into {ax},{dx}.
8679 if (Res.second->hasType(VT))
8680 return Res; // Correct type already, nothing to do.
8682 // All of the single-register GCC register classes map their values onto
8683 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
8684 // really want an 8-bit or 32-bit register, map to the appropriate register
8685 // class and return the appropriate register.
8686 if (Res.second == X86::GR16RegisterClass) {
8687 if (VT == MVT::i8) {
8688 unsigned DestReg = 0;
8689 switch (Res.first) {
8691 case X86::AX: DestReg = X86::AL; break;
8692 case X86::DX: DestReg = X86::DL; break;
8693 case X86::CX: DestReg = X86::CL; break;
8694 case X86::BX: DestReg = X86::BL; break;
8697 Res.first = DestReg;
8698 Res.second = X86::GR8RegisterClass;
8700 } else if (VT == MVT::i32) {
8701 unsigned DestReg = 0;
8702 switch (Res.first) {
8704 case X86::AX: DestReg = X86::EAX; break;
8705 case X86::DX: DestReg = X86::EDX; break;
8706 case X86::CX: DestReg = X86::ECX; break;
8707 case X86::BX: DestReg = X86::EBX; break;
8708 case X86::SI: DestReg = X86::ESI; break;
8709 case X86::DI: DestReg = X86::EDI; break;
8710 case X86::BP: DestReg = X86::EBP; break;
8711 case X86::SP: DestReg = X86::ESP; break;
8714 Res.first = DestReg;
8715 Res.second = X86::GR32RegisterClass;
8717 } else if (VT == MVT::i64) {
8718 unsigned DestReg = 0;
8719 switch (Res.first) {
8721 case X86::AX: DestReg = X86::RAX; break;
8722 case X86::DX: DestReg = X86::RDX; break;
8723 case X86::CX: DestReg = X86::RCX; break;
8724 case X86::BX: DestReg = X86::RBX; break;
8725 case X86::SI: DestReg = X86::RSI; break;
8726 case X86::DI: DestReg = X86::RDI; break;
8727 case X86::BP: DestReg = X86::RBP; break;
8728 case X86::SP: DestReg = X86::RSP; break;
8731 Res.first = DestReg;
8732 Res.second = X86::GR64RegisterClass;
8735 } else if (Res.second == X86::FR32RegisterClass ||
8736 Res.second == X86::FR64RegisterClass ||
8737 Res.second == X86::VR128RegisterClass) {
8738 // Handle references to XMM physical registers that got mapped into the
8739 // wrong class. This can happen with constraints like {xmm0} where the
8740 // target independent register mapper will just pick the first match it can
8741 // find, ignoring the required type.
8743 Res.second = X86::FR32RegisterClass;
8744 else if (VT == MVT::f64)
8745 Res.second = X86::FR64RegisterClass;
8746 else if (X86::VR128RegisterClass->hasType(VT))
8747 Res.second = X86::VR128RegisterClass;
8753 //===----------------------------------------------------------------------===//
8754 // X86 Widen vector type
8755 //===----------------------------------------------------------------------===//
8757 /// getWidenVectorType: given a vector type, returns the type to widen
8758 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
8759 /// If there is no vector type that we want to widen to, returns MVT::Other
8760 /// When and where to widen is target dependent based on the cost of
8761 /// scalarizing vs using the wider vector type.
8763 MVT X86TargetLowering::getWidenVectorType(MVT VT) const {
8764 assert(VT.isVector());
8765 if (isTypeLegal(VT))
8768 // TODO: In computeRegisterProperty, we can compute the list of legal vector
8769 // type based on element type. This would speed up our search (though
8770 // it may not be worth it since the size of the list is relatively
8772 MVT EltVT = VT.getVectorElementType();
8773 unsigned NElts = VT.getVectorNumElements();
8775 // On X86, it make sense to widen any vector wider than 1
8779 for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
8780 nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
8781 MVT SVT = (MVT::SimpleValueType)nVT;
8783 if (isTypeLegal(SVT) &&
8784 SVT.getVectorElementType() == EltVT &&
8785 SVT.getVectorNumElements() > NElts)