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 "X86MachineFunctionInfo.h"
19 #include "X86TargetMachine.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Function.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/ADT/BitVector.h"
27 #include "llvm/ADT/VectorExtras.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/PseudoSourceValue.h"
35 #include "llvm/CodeGen/SelectionDAG.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/ADT/SmallSet.h"
40 #include "llvm/ADT/StringExtras.h"
41 #include "llvm/Support/CommandLine.h"
45 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
47 // Forward declarations.
48 static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG, DebugLoc dl);
50 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
51 : TargetLowering(TM) {
52 Subtarget = &TM.getSubtarget<X86Subtarget>();
53 X86ScalarSSEf64 = Subtarget->hasSSE2();
54 X86ScalarSSEf32 = Subtarget->hasSSE1();
55 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
59 RegInfo = TM.getRegisterInfo();
62 // Set up the TargetLowering object.
64 // X86 is weird, it always uses i8 for shift amounts and setcc results.
65 setShiftAmountType(MVT::i8);
66 setBooleanContents(ZeroOrOneBooleanContent);
67 setSchedulingPreference(SchedulingForRegPressure);
68 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
69 setStackPointerRegisterToSaveRestore(X86StackPtr);
71 if (Subtarget->isTargetDarwin()) {
72 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
73 setUseUnderscoreSetJmp(false);
74 setUseUnderscoreLongJmp(false);
75 } else if (Subtarget->isTargetMingw()) {
76 // MS runtime is weird: it exports _setjmp, but longjmp!
77 setUseUnderscoreSetJmp(true);
78 setUseUnderscoreLongJmp(false);
80 setUseUnderscoreSetJmp(true);
81 setUseUnderscoreLongJmp(true);
84 // Set up the register classes.
85 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
86 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
87 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
88 if (Subtarget->is64Bit())
89 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
91 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
93 // We don't accept any truncstore of integer registers.
94 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
95 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
96 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
97 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
98 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
99 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
101 // SETOEQ and SETUNE require checking two conditions.
102 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
103 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
104 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
105 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
106 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
107 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
109 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
111 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
112 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
113 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
115 if (Subtarget->is64Bit()) {
116 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
117 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
119 if (X86ScalarSSEf64) {
120 // We have an impenetrably clever algorithm for ui64->double only.
121 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
123 // We have faster algorithm for ui32->single only.
124 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
126 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
129 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
131 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
132 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
133 // SSE has no i16 to fp conversion, only i32
134 if (X86ScalarSSEf32) {
135 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
136 // f32 and f64 cases are Legal, f80 case is not
137 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
139 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
140 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
143 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
144 // are Legal, f80 is custom lowered.
145 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
146 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
148 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
150 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
151 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
153 if (X86ScalarSSEf32) {
154 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
155 // f32 and f64 cases are Legal, f80 case is not
156 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
158 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
159 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
162 // Handle FP_TO_UINT by promoting the destination to a larger signed
164 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
165 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
166 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
168 if (Subtarget->is64Bit()) {
169 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
170 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
172 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
173 // Expand FP_TO_UINT into a select.
174 // FIXME: We would like to use a Custom expander here eventually to do
175 // the optimal thing for SSE vs. the default expansion in the legalizer.
176 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
178 // With SSE3 we can use fisttpll to convert to a signed i64.
179 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
182 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
183 if (!X86ScalarSSEf64) {
184 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
185 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
188 // Scalar integer divide and remainder are lowered to use operations that
189 // produce two results, to match the available instructions. This exposes
190 // the two-result form to trivial CSE, which is able to combine x/y and x%y
191 // into a single instruction.
193 // Scalar integer multiply-high is also lowered to use two-result
194 // operations, to match the available instructions. However, plain multiply
195 // (low) operations are left as Legal, as there are single-result
196 // instructions for this in x86. Using the two-result multiply instructions
197 // when both high and low results are needed must be arranged by dagcombine.
198 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
199 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
200 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
201 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
202 setOperationAction(ISD::SREM , MVT::i8 , Expand);
203 setOperationAction(ISD::UREM , MVT::i8 , Expand);
204 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
205 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
206 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
207 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
208 setOperationAction(ISD::SREM , MVT::i16 , Expand);
209 setOperationAction(ISD::UREM , MVT::i16 , Expand);
210 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
211 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
212 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
213 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
214 setOperationAction(ISD::SREM , MVT::i32 , Expand);
215 setOperationAction(ISD::UREM , MVT::i32 , Expand);
216 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
217 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
218 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
219 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
220 setOperationAction(ISD::SREM , MVT::i64 , Expand);
221 setOperationAction(ISD::UREM , MVT::i64 , Expand);
223 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
224 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
225 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
226 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
227 if (Subtarget->is64Bit())
228 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
229 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
230 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
231 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
232 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
233 setOperationAction(ISD::FREM , MVT::f32 , Expand);
234 setOperationAction(ISD::FREM , MVT::f64 , Expand);
235 setOperationAction(ISD::FREM , MVT::f80 , Expand);
236 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
238 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
239 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
240 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
241 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
242 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
243 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
244 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
245 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
246 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
247 if (Subtarget->is64Bit()) {
248 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
249 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
250 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
253 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
254 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
256 // These should be promoted to a larger select which is supported.
257 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
258 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
259 // X86 wants to expand cmov itself.
260 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
261 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
262 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
263 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
264 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
265 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
266 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
267 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
268 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
269 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
270 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
271 if (Subtarget->is64Bit()) {
272 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
273 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
275 // X86 ret instruction may pop stack.
276 setOperationAction(ISD::RET , MVT::Other, Custom);
277 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
280 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
281 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
282 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
283 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
284 if (Subtarget->is64Bit())
285 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
286 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
287 if (Subtarget->is64Bit()) {
288 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
289 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
290 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
291 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
293 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
294 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
295 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
296 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
297 if (Subtarget->is64Bit()) {
298 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
299 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
300 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
303 if (Subtarget->hasSSE1())
304 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
306 if (!Subtarget->hasSSE2())
307 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
309 // Expand certain atomics
310 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
311 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
312 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
313 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
315 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
316 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
317 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
318 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
320 if (!Subtarget->is64Bit()) {
321 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
322 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
323 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
324 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
325 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
326 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
327 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
330 // Use the default ISD::DBG_STOPPOINT, ISD::DECLARE expansion.
331 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
332 // FIXME - use subtarget debug flags
333 if (!Subtarget->isTargetDarwin() &&
334 !Subtarget->isTargetELF() &&
335 !Subtarget->isTargetCygMing()) {
336 setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
337 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
340 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
341 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
342 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
343 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
344 if (Subtarget->is64Bit()) {
345 setExceptionPointerRegister(X86::RAX);
346 setExceptionSelectorRegister(X86::RDX);
348 setExceptionPointerRegister(X86::EAX);
349 setExceptionSelectorRegister(X86::EDX);
351 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
352 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
354 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
356 setOperationAction(ISD::TRAP, MVT::Other, Legal);
358 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
359 setOperationAction(ISD::VASTART , MVT::Other, Custom);
360 setOperationAction(ISD::VAEND , MVT::Other, Expand);
361 if (Subtarget->is64Bit()) {
362 setOperationAction(ISD::VAARG , MVT::Other, Custom);
363 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
365 setOperationAction(ISD::VAARG , MVT::Other, Expand);
366 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
369 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
370 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
371 if (Subtarget->is64Bit())
372 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
373 if (Subtarget->isTargetCygMing())
374 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
376 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
378 if (X86ScalarSSEf64) {
379 // f32 and f64 use SSE.
380 // Set up the FP register classes.
381 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
382 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
384 // Use ANDPD to simulate FABS.
385 setOperationAction(ISD::FABS , MVT::f64, Custom);
386 setOperationAction(ISD::FABS , MVT::f32, Custom);
388 // Use XORP to simulate FNEG.
389 setOperationAction(ISD::FNEG , MVT::f64, Custom);
390 setOperationAction(ISD::FNEG , MVT::f32, Custom);
392 // Use ANDPD and ORPD to simulate FCOPYSIGN.
393 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
394 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
396 // We don't support sin/cos/fmod
397 setOperationAction(ISD::FSIN , MVT::f64, Expand);
398 setOperationAction(ISD::FCOS , MVT::f64, Expand);
399 setOperationAction(ISD::FSIN , MVT::f32, Expand);
400 setOperationAction(ISD::FCOS , MVT::f32, Expand);
402 // Expand FP immediates into loads from the stack, except for the special
404 addLegalFPImmediate(APFloat(+0.0)); // xorpd
405 addLegalFPImmediate(APFloat(+0.0f)); // xorps
407 // Floating truncations from f80 and extensions to f80 go through memory.
408 // If optimizing, we lie about this though and handle it in
409 // InstructionSelectPreprocess so that dagcombine2 can hack on these.
411 setConvertAction(MVT::f32, MVT::f80, Expand);
412 setConvertAction(MVT::f64, MVT::f80, Expand);
413 setConvertAction(MVT::f80, MVT::f32, Expand);
414 setConvertAction(MVT::f80, MVT::f64, Expand);
416 } else if (X86ScalarSSEf32) {
417 // Use SSE for f32, x87 for f64.
418 // Set up the FP register classes.
419 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
420 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
422 // Use ANDPS to simulate FABS.
423 setOperationAction(ISD::FABS , MVT::f32, Custom);
425 // Use XORP to simulate FNEG.
426 setOperationAction(ISD::FNEG , MVT::f32, Custom);
428 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
430 // Use ANDPS and ORPS to simulate FCOPYSIGN.
431 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
432 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
434 // We don't support sin/cos/fmod
435 setOperationAction(ISD::FSIN , MVT::f32, Expand);
436 setOperationAction(ISD::FCOS , MVT::f32, Expand);
438 // Special cases we handle for FP constants.
439 addLegalFPImmediate(APFloat(+0.0f)); // xorps
440 addLegalFPImmediate(APFloat(+0.0)); // FLD0
441 addLegalFPImmediate(APFloat(+1.0)); // FLD1
442 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
443 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
445 // SSE <-> X87 conversions go through memory. If optimizing, we lie about
446 // this though and handle it in InstructionSelectPreprocess so that
447 // dagcombine2 can hack on these.
449 setConvertAction(MVT::f32, MVT::f64, Expand);
450 setConvertAction(MVT::f32, MVT::f80, Expand);
451 setConvertAction(MVT::f80, MVT::f32, Expand);
452 setConvertAction(MVT::f64, MVT::f32, Expand);
453 // And x87->x87 truncations also.
454 setConvertAction(MVT::f80, MVT::f64, Expand);
458 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
459 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
462 // f32 and f64 in x87.
463 // Set up the FP register classes.
464 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
465 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
467 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
468 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
469 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
470 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
472 // Floating truncations go through memory. If optimizing, we lie about
473 // this though and handle it in InstructionSelectPreprocess so that
474 // dagcombine2 can hack on these.
476 setConvertAction(MVT::f80, MVT::f32, Expand);
477 setConvertAction(MVT::f64, MVT::f32, Expand);
478 setConvertAction(MVT::f80, MVT::f64, Expand);
482 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
483 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
485 addLegalFPImmediate(APFloat(+0.0)); // FLD0
486 addLegalFPImmediate(APFloat(+1.0)); // FLD1
487 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
488 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
489 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
490 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
491 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
492 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
495 // Long double always uses X87.
496 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
497 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
498 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
501 APFloat TmpFlt(+0.0);
502 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
504 addLegalFPImmediate(TmpFlt); // FLD0
506 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
507 APFloat TmpFlt2(+1.0);
508 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
510 addLegalFPImmediate(TmpFlt2); // FLD1
511 TmpFlt2.changeSign();
512 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
516 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
517 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
520 // Always use a library call for pow.
521 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
522 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
523 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
525 setOperationAction(ISD::FLOG, MVT::f80, Expand);
526 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
527 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
528 setOperationAction(ISD::FEXP, MVT::f80, Expand);
529 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
531 // First set operation action for all vector types to either promote
532 // (for widening) or expand (for scalarization). Then we will selectively
533 // turn on ones that can be effectively codegen'd.
534 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
535 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
536 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
537 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
538 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
539 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
540 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
541 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
542 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
543 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
544 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
545 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
546 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
547 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
548 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
549 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
550 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
551 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
552 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
553 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
554 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
555 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
556 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
557 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
558 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
559 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
560 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
561 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
562 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
563 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
564 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
565 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
566 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
567 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
568 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
569 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
570 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
571 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
572 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
573 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
574 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
575 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
576 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
577 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
578 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
581 if (!DisableMMX && Subtarget->hasMMX()) {
582 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
583 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
584 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
585 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
586 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
588 // FIXME: add MMX packed arithmetics
590 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
591 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
592 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
593 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
595 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
596 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
597 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
598 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
600 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
601 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
603 setOperationAction(ISD::AND, MVT::v8i8, Promote);
604 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
605 setOperationAction(ISD::AND, MVT::v4i16, Promote);
606 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
607 setOperationAction(ISD::AND, MVT::v2i32, Promote);
608 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
609 setOperationAction(ISD::AND, MVT::v1i64, Legal);
611 setOperationAction(ISD::OR, MVT::v8i8, Promote);
612 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
613 setOperationAction(ISD::OR, MVT::v4i16, Promote);
614 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
615 setOperationAction(ISD::OR, MVT::v2i32, Promote);
616 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
617 setOperationAction(ISD::OR, MVT::v1i64, Legal);
619 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
620 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
621 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
622 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
623 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
624 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
625 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
627 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
628 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
629 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
630 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
631 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
632 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
633 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
634 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
635 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
637 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
638 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
639 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
640 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
641 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
643 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
644 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
645 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
646 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
648 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
649 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
650 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
651 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
653 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
655 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
656 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Expand);
657 setOperationAction(ISD::SELECT, MVT::v8i8, Promote);
658 setOperationAction(ISD::SELECT, MVT::v4i16, Promote);
659 setOperationAction(ISD::SELECT, MVT::v2i32, Promote);
660 setOperationAction(ISD::SELECT, MVT::v1i64, Custom);
663 if (Subtarget->hasSSE1()) {
664 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
666 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
667 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
668 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
669 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
670 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
671 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
672 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
673 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
674 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
675 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
676 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
677 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
680 if (Subtarget->hasSSE2()) {
681 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
682 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
683 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
684 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
685 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
687 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
688 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
689 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
690 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
691 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
692 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
693 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
694 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
695 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
696 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
697 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
698 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
699 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
700 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
701 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
702 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
704 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
705 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
706 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
707 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
709 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
710 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
711 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
712 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
713 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
715 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
716 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
717 MVT VT = (MVT::SimpleValueType)i;
718 // Do not attempt to custom lower non-power-of-2 vectors
719 if (!isPowerOf2_32(VT.getVectorNumElements()))
721 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
722 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
723 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
725 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
726 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
727 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
728 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
729 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
730 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
731 if (Subtarget->is64Bit()) {
732 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
733 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
736 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
737 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
738 setOperationAction(ISD::AND, (MVT::SimpleValueType)VT, Promote);
739 AddPromotedToType (ISD::AND, (MVT::SimpleValueType)VT, MVT::v2i64);
740 setOperationAction(ISD::OR, (MVT::SimpleValueType)VT, Promote);
741 AddPromotedToType (ISD::OR, (MVT::SimpleValueType)VT, MVT::v2i64);
742 setOperationAction(ISD::XOR, (MVT::SimpleValueType)VT, Promote);
743 AddPromotedToType (ISD::XOR, (MVT::SimpleValueType)VT, MVT::v2i64);
744 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Promote);
745 AddPromotedToType (ISD::LOAD, (MVT::SimpleValueType)VT, MVT::v2i64);
746 setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
747 AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v2i64);
750 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
752 // Custom lower v2i64 and v2f64 selects.
753 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
754 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
755 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
756 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
760 if (Subtarget->hasSSE41()) {
761 // FIXME: Do we need to handle scalar-to-vector here?
762 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
764 // i8 and i16 vectors are custom , because the source register and source
765 // source memory operand types are not the same width. f32 vectors are
766 // custom since the immediate controlling the insert encodes additional
768 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
769 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
770 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
771 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
773 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
774 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
775 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
776 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
778 if (Subtarget->is64Bit()) {
779 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
780 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
784 if (Subtarget->hasSSE42()) {
785 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
788 // We want to custom lower some of our intrinsics.
789 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
791 // Add/Sub/Mul with overflow operations are custom lowered.
792 setOperationAction(ISD::SADDO, MVT::i32, Custom);
793 setOperationAction(ISD::SADDO, MVT::i64, Custom);
794 setOperationAction(ISD::UADDO, MVT::i32, Custom);
795 setOperationAction(ISD::UADDO, MVT::i64, Custom);
796 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
797 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
798 setOperationAction(ISD::USUBO, MVT::i32, Custom);
799 setOperationAction(ISD::USUBO, MVT::i64, Custom);
800 setOperationAction(ISD::SMULO, MVT::i32, Custom);
801 setOperationAction(ISD::SMULO, MVT::i64, Custom);
802 setOperationAction(ISD::UMULO, MVT::i32, Custom);
803 setOperationAction(ISD::UMULO, MVT::i64, Custom);
805 // We have target-specific dag combine patterns for the following nodes:
806 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
807 setTargetDAGCombine(ISD::BUILD_VECTOR);
808 setTargetDAGCombine(ISD::SELECT);
809 setTargetDAGCombine(ISD::SHL);
810 setTargetDAGCombine(ISD::SRA);
811 setTargetDAGCombine(ISD::SRL);
812 setTargetDAGCombine(ISD::STORE);
814 computeRegisterProperties();
816 // FIXME: These should be based on subtarget info. Plus, the values should
817 // be smaller when we are in optimizing for size mode.
818 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
819 maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
820 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
821 allowUnalignedMemoryAccesses = true; // x86 supports it!
822 setPrefLoopAlignment(16);
826 MVT X86TargetLowering::getSetCCResultType(MVT VT) const {
831 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
832 /// the desired ByVal argument alignment.
833 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
836 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
837 if (VTy->getBitWidth() == 128)
839 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
840 unsigned EltAlign = 0;
841 getMaxByValAlign(ATy->getElementType(), EltAlign);
842 if (EltAlign > MaxAlign)
844 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
845 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
846 unsigned EltAlign = 0;
847 getMaxByValAlign(STy->getElementType(i), EltAlign);
848 if (EltAlign > MaxAlign)
857 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
858 /// function arguments in the caller parameter area. For X86, aggregates
859 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
860 /// are at 4-byte boundaries.
861 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
862 if (Subtarget->is64Bit()) {
863 // Max of 8 and alignment of type.
864 unsigned TyAlign = TD->getABITypeAlignment(Ty);
871 if (Subtarget->hasSSE1())
872 getMaxByValAlign(Ty, Align);
876 /// getOptimalMemOpType - Returns the target specific optimal type for load
877 /// and store operations as a result of memset, memcpy, and memmove
878 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
881 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
882 bool isSrcConst, bool isSrcStr) 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 if (Subtarget->getStackAlignment() >= 16) {
887 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
889 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
892 if (Subtarget->is64Bit() && Size >= 8)
898 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
900 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
901 SelectionDAG &DAG) const {
902 if (usesGlobalOffsetTable())
903 return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
904 if (!Subtarget->isPICStyleRIPRel())
905 return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
909 //===----------------------------------------------------------------------===//
910 // Return Value Calling Convention Implementation
911 //===----------------------------------------------------------------------===//
913 #include "X86GenCallingConv.inc"
915 /// LowerRET - Lower an ISD::RET node.
916 SDValue X86TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
917 DebugLoc dl = Op.getNode()->getDebugLoc();
918 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
920 SmallVector<CCValAssign, 16> RVLocs;
921 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
922 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
923 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
924 CCInfo.AnalyzeReturn(Op.getNode(), RetCC_X86);
926 // If this is the first return lowered for this function, add the regs to the
927 // liveout set for the function.
928 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
929 for (unsigned i = 0; i != RVLocs.size(); ++i)
930 if (RVLocs[i].isRegLoc())
931 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
933 SDValue Chain = Op.getOperand(0);
935 // Handle tail call return.
936 Chain = GetPossiblePreceedingTailCall(Chain, X86ISD::TAILCALL);
937 if (Chain.getOpcode() == X86ISD::TAILCALL) {
938 SDValue TailCall = Chain;
939 SDValue TargetAddress = TailCall.getOperand(1);
940 SDValue StackAdjustment = TailCall.getOperand(2);
941 assert(((TargetAddress.getOpcode() == ISD::Register &&
942 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::EAX ||
943 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
944 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
945 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
946 "Expecting an global address, external symbol, or register");
947 assert(StackAdjustment.getOpcode() == ISD::Constant &&
948 "Expecting a const value");
950 SmallVector<SDValue,8> Operands;
951 Operands.push_back(Chain.getOperand(0));
952 Operands.push_back(TargetAddress);
953 Operands.push_back(StackAdjustment);
954 // Copy registers used by the call. Last operand is a flag so it is not
956 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
957 Operands.push_back(Chain.getOperand(i));
959 return DAG.getNode(X86ISD::TC_RETURN, dl, MVT::Other, &Operands[0],
966 SmallVector<SDValue, 6> RetOps;
967 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
968 // Operand #1 = Bytes To Pop
969 RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
971 // Copy the result values into the output registers.
972 for (unsigned i = 0; i != RVLocs.size(); ++i) {
973 CCValAssign &VA = RVLocs[i];
974 assert(VA.isRegLoc() && "Can only return in registers!");
975 SDValue ValToCopy = Op.getOperand(i*2+1);
977 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
978 // the RET instruction and handled by the FP Stackifier.
979 if (VA.getLocReg() == X86::ST0 ||
980 VA.getLocReg() == X86::ST1) {
981 // If this is a copy from an xmm register to ST(0), use an FPExtend to
982 // change the value to the FP stack register class.
983 if (isScalarFPTypeInSSEReg(VA.getValVT()))
984 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
985 RetOps.push_back(ValToCopy);
986 // Don't emit a copytoreg.
990 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
991 Flag = Chain.getValue(1);
994 // The x86-64 ABI for returning structs by value requires that we copy
995 // the sret argument into %rax for the return. We saved the argument into
996 // a virtual register in the entry block, so now we copy the value out
998 if (Subtarget->is64Bit() &&
999 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1000 MachineFunction &MF = DAG.getMachineFunction();
1001 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1002 unsigned Reg = FuncInfo->getSRetReturnReg();
1004 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1005 FuncInfo->setSRetReturnReg(Reg);
1007 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1009 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1010 Flag = Chain.getValue(1);
1013 RetOps[0] = Chain; // Update chain.
1015 // Add the flag if we have it.
1017 RetOps.push_back(Flag);
1019 return DAG.getNode(X86ISD::RET_FLAG, dl,
1020 MVT::Other, &RetOps[0], RetOps.size());
1024 /// LowerCallResult - Lower the result values of an ISD::CALL into the
1025 /// appropriate copies out of appropriate physical registers. This assumes that
1026 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
1027 /// being lowered. The returns a SDNode with the same number of values as the
1029 SDNode *X86TargetLowering::
1030 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall,
1031 unsigned CallingConv, SelectionDAG &DAG) {
1033 DebugLoc dl = TheCall->getDebugLoc();
1034 // Assign locations to each value returned by this call.
1035 SmallVector<CCValAssign, 16> RVLocs;
1036 bool isVarArg = TheCall->isVarArg();
1037 bool Is64Bit = Subtarget->is64Bit();
1038 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
1039 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
1041 SmallVector<SDValue, 8> ResultVals;
1043 // Copy all of the result registers out of their specified physreg.
1044 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1045 CCValAssign &VA = RVLocs[i];
1046 MVT CopyVT = VA.getValVT();
1048 // If this is x86-64, and we disabled SSE, we can't return FP values
1049 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1050 ((Is64Bit || TheCall->isInreg()) && !Subtarget->hasSSE1())) {
1051 cerr << "SSE register return with SSE disabled\n";
1055 // If this is a call to a function that returns an fp value on the floating
1056 // point stack, but where we prefer to use the value in xmm registers, copy
1057 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1058 if ((VA.getLocReg() == X86::ST0 ||
1059 VA.getLocReg() == X86::ST1) &&
1060 isScalarFPTypeInSSEReg(VA.getValVT())) {
1064 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1065 CopyVT, InFlag).getValue(1);
1066 SDValue Val = Chain.getValue(0);
1067 InFlag = Chain.getValue(2);
1069 if (CopyVT != VA.getValVT()) {
1070 // Round the F80 the right size, which also moves to the appropriate xmm
1072 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1073 // This truncation won't change the value.
1074 DAG.getIntPtrConstant(1));
1077 ResultVals.push_back(Val);
1080 // Merge everything together with a MERGE_VALUES node.
1081 ResultVals.push_back(Chain);
1082 return DAG.getNode(ISD::MERGE_VALUES, dl, TheCall->getVTList(),
1083 &ResultVals[0], ResultVals.size()).getNode();
1087 //===----------------------------------------------------------------------===//
1088 // C & StdCall & Fast Calling Convention implementation
1089 //===----------------------------------------------------------------------===//
1090 // StdCall calling convention seems to be standard for many Windows' API
1091 // routines and around. It differs from C calling convention just a little:
1092 // callee should clean up the stack, not caller. Symbols should be also
1093 // decorated in some fancy way :) It doesn't support any vector arguments.
1094 // For info on fast calling convention see Fast Calling Convention (tail call)
1095 // implementation LowerX86_32FastCCCallTo.
1097 /// AddLiveIn - This helper function adds the specified physical register to the
1098 /// MachineFunction as a live in value. It also creates a corresponding virtual
1099 /// register for it.
1100 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
1101 const TargetRegisterClass *RC) {
1102 assert(RC->contains(PReg) && "Not the correct regclass!");
1103 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
1104 MF.getRegInfo().addLiveIn(PReg, VReg);
1108 /// CallIsStructReturn - Determines whether a CALL node uses struct return
1110 static bool CallIsStructReturn(CallSDNode *TheCall) {
1111 unsigned NumOps = TheCall->getNumArgs();
1115 return TheCall->getArgFlags(0).isSRet();
1118 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
1119 /// return semantics.
1120 static bool ArgsAreStructReturn(SDValue Op) {
1121 unsigned NumArgs = Op.getNode()->getNumValues() - 1;
1125 return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
1128 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
1129 /// the callee to pop its own arguments. Callee pop is necessary to support tail
1131 bool X86TargetLowering::IsCalleePop(bool IsVarArg, unsigned CallingConv) {
1135 switch (CallingConv) {
1138 case CallingConv::X86_StdCall:
1139 return !Subtarget->is64Bit();
1140 case CallingConv::X86_FastCall:
1141 return !Subtarget->is64Bit();
1142 case CallingConv::Fast:
1143 return PerformTailCallOpt;
1147 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1148 /// given CallingConvention value.
1149 CCAssignFn *X86TargetLowering::CCAssignFnForNode(unsigned CC) const {
1150 if (Subtarget->is64Bit()) {
1151 if (Subtarget->isTargetWin64())
1152 return CC_X86_Win64_C;
1153 else if (CC == CallingConv::Fast && PerformTailCallOpt)
1154 return CC_X86_64_TailCall;
1159 if (CC == CallingConv::X86_FastCall)
1160 return CC_X86_32_FastCall;
1161 else if (CC == CallingConv::Fast)
1162 return CC_X86_32_FastCC;
1167 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1168 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1170 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDValue Op) {
1171 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1172 if (CC == CallingConv::X86_FastCall)
1174 else if (CC == CallingConv::X86_StdCall)
1180 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1181 /// in a register before calling.
1182 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1183 return !IsTailCall && !Is64Bit &&
1184 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1185 Subtarget->isPICStyleGOT();
1188 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1189 /// address to be loaded in a register.
1191 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1192 return !Is64Bit && IsTailCall &&
1193 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1194 Subtarget->isPICStyleGOT();
1197 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1198 /// by "Src" to address "Dst" with size and alignment information specified by
1199 /// the specific parameter attribute. The copy will be passed as a byval
1200 /// function parameter.
1202 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1203 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1205 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1206 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1207 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1210 SDValue X86TargetLowering::LowerMemArgument(SDValue Op, SelectionDAG &DAG,
1211 const CCValAssign &VA,
1212 MachineFrameInfo *MFI,
1214 SDValue Root, unsigned i) {
1215 // Create the nodes corresponding to a load from this parameter slot.
1216 ISD::ArgFlagsTy Flags =
1217 cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1218 bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1219 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1221 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1222 // changed with more analysis.
1223 // In case of tail call optimization mark all arguments mutable. Since they
1224 // could be overwritten by lowering of arguments in case of a tail call.
1225 int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1226 VA.getLocMemOffset(), isImmutable);
1227 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1228 if (Flags.isByVal())
1230 return DAG.getLoad(VA.getValVT(), Op.getNode()->getDebugLoc(), Root, FIN,
1231 PseudoSourceValue::getFixedStack(FI), 0);
1235 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) {
1236 MachineFunction &MF = DAG.getMachineFunction();
1237 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1238 DebugLoc dl = Op.getNode()->getDebugLoc();
1240 const Function* Fn = MF.getFunction();
1241 if (Fn->hasExternalLinkage() &&
1242 Subtarget->isTargetCygMing() &&
1243 Fn->getName() == "main")
1244 FuncInfo->setForceFramePointer(true);
1246 // Decorate the function name.
1247 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1249 MachineFrameInfo *MFI = MF.getFrameInfo();
1250 SDValue Root = Op.getOperand(0);
1251 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
1252 unsigned CC = MF.getFunction()->getCallingConv();
1253 bool Is64Bit = Subtarget->is64Bit();
1254 bool IsWin64 = Subtarget->isTargetWin64();
1256 assert(!(isVarArg && CC == CallingConv::Fast) &&
1257 "Var args not supported with calling convention fastcc");
1259 // Assign locations to all of the incoming arguments.
1260 SmallVector<CCValAssign, 16> ArgLocs;
1261 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1262 CCInfo.AnalyzeFormalArguments(Op.getNode(), CCAssignFnForNode(CC));
1264 SmallVector<SDValue, 8> ArgValues;
1265 unsigned LastVal = ~0U;
1266 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1267 CCValAssign &VA = ArgLocs[i];
1268 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1270 assert(VA.getValNo() != LastVal &&
1271 "Don't support value assigned to multiple locs yet");
1272 LastVal = VA.getValNo();
1274 if (VA.isRegLoc()) {
1275 MVT RegVT = VA.getLocVT();
1276 TargetRegisterClass *RC = NULL;
1277 if (RegVT == MVT::i32)
1278 RC = X86::GR32RegisterClass;
1279 else if (Is64Bit && RegVT == MVT::i64)
1280 RC = X86::GR64RegisterClass;
1281 else if (RegVT == MVT::f32)
1282 RC = X86::FR32RegisterClass;
1283 else if (RegVT == MVT::f64)
1284 RC = X86::FR64RegisterClass;
1285 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1286 RC = X86::VR128RegisterClass;
1287 else if (RegVT.isVector()) {
1288 assert(RegVT.getSizeInBits() == 64);
1290 RC = X86::VR64RegisterClass; // MMX values are passed in MMXs.
1292 // Darwin calling convention passes MMX values in either GPRs or
1293 // XMMs in x86-64. Other targets pass them in memory.
1294 if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1295 RC = X86::VR128RegisterClass; // MMX values are passed in XMMs.
1298 RC = X86::GR64RegisterClass; // v1i64 values are passed in GPRs.
1303 assert(0 && "Unknown argument type!");
1306 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1307 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, RegVT);
1309 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1310 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1312 if (VA.getLocInfo() == CCValAssign::SExt)
1313 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1314 DAG.getValueType(VA.getValVT()));
1315 else if (VA.getLocInfo() == CCValAssign::ZExt)
1316 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1317 DAG.getValueType(VA.getValVT()));
1319 if (VA.getLocInfo() != CCValAssign::Full)
1320 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1322 // Handle MMX values passed in GPRs.
1323 if (Is64Bit && RegVT != VA.getLocVT()) {
1324 if (RegVT.getSizeInBits() == 64 && RC == X86::GR64RegisterClass)
1325 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1326 else if (RC == X86::VR128RegisterClass) {
1327 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1328 ArgValue, DAG.getConstant(0, MVT::i64));
1329 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1333 ArgValues.push_back(ArgValue);
1335 assert(VA.isMemLoc());
1336 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1340 // The x86-64 ABI for returning structs by value requires that we copy
1341 // the sret argument into %rax for the return. Save the argument into
1342 // a virtual register so that we can access it from the return points.
1343 if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1344 MachineFunction &MF = DAG.getMachineFunction();
1345 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1346 unsigned Reg = FuncInfo->getSRetReturnReg();
1348 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1349 FuncInfo->setSRetReturnReg(Reg);
1351 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, ArgValues[0]);
1352 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Root);
1355 unsigned StackSize = CCInfo.getNextStackOffset();
1356 // align stack specially for tail calls
1357 if (PerformTailCallOpt && CC == CallingConv::Fast)
1358 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1360 // If the function takes variable number of arguments, make a frame index for
1361 // the start of the first vararg value... for expansion of llvm.va_start.
1363 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1364 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1367 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1369 // FIXME: We should really autogenerate these arrays
1370 static const unsigned GPR64ArgRegsWin64[] = {
1371 X86::RCX, X86::RDX, X86::R8, X86::R9
1373 static const unsigned XMMArgRegsWin64[] = {
1374 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1376 static const unsigned GPR64ArgRegs64Bit[] = {
1377 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1379 static const unsigned XMMArgRegs64Bit[] = {
1380 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1381 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1383 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1386 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1387 GPR64ArgRegs = GPR64ArgRegsWin64;
1388 XMMArgRegs = XMMArgRegsWin64;
1390 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1391 GPR64ArgRegs = GPR64ArgRegs64Bit;
1392 XMMArgRegs = XMMArgRegs64Bit;
1394 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1396 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1399 assert((Subtarget->hasSSE1() || !NumXMMRegs) &&
1400 "SSE register cannot be used when SSE is disabled!");
1401 if (!Subtarget->hasSSE1()) {
1402 // Kernel mode asks for SSE to be disabled, so don't push them
1404 TotalNumXMMRegs = 0;
1406 // For X86-64, if there are vararg parameters that are passed via
1407 // registers, then we must store them to their spots on the stack so they
1408 // may be loaded by deferencing the result of va_next.
1409 VarArgsGPOffset = NumIntRegs * 8;
1410 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1411 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1412 TotalNumXMMRegs * 16, 16);
1414 // Store the integer parameter registers.
1415 SmallVector<SDValue, 8> MemOps;
1416 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1417 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1418 DAG.getIntPtrConstant(VarArgsGPOffset));
1419 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1420 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1421 X86::GR64RegisterClass);
1422 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::i64);
1424 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1425 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1426 MemOps.push_back(Store);
1427 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1428 DAG.getIntPtrConstant(8));
1431 // Now store the XMM (fp + vector) parameter registers.
1432 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1433 DAG.getIntPtrConstant(VarArgsFPOffset));
1434 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1435 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1436 X86::VR128RegisterClass);
1437 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::v4f32);
1439 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1440 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1441 MemOps.push_back(Store);
1442 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1443 DAG.getIntPtrConstant(16));
1445 if (!MemOps.empty())
1446 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1447 &MemOps[0], MemOps.size());
1451 ArgValues.push_back(Root);
1453 // Some CCs need callee pop.
1454 if (IsCalleePop(isVarArg, CC)) {
1455 BytesToPopOnReturn = StackSize; // Callee pops everything.
1456 BytesCallerReserves = 0;
1458 BytesToPopOnReturn = 0; // Callee pops nothing.
1459 // If this is an sret function, the return should pop the hidden pointer.
1460 if (!Is64Bit && CC != CallingConv::Fast && ArgsAreStructReturn(Op))
1461 BytesToPopOnReturn = 4;
1462 BytesCallerReserves = StackSize;
1466 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1467 if (CC == CallingConv::X86_FastCall)
1468 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1471 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1473 // Return the new list of results.
1474 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(),
1475 &ArgValues[0], ArgValues.size()).getValue(Op.getResNo());
1479 X86TargetLowering::LowerMemOpCallTo(CallSDNode *TheCall, SelectionDAG &DAG,
1480 const SDValue &StackPtr,
1481 const CCValAssign &VA,
1483 SDValue Arg, ISD::ArgFlagsTy Flags) {
1484 DebugLoc dl = TheCall->getDebugLoc();
1485 unsigned LocMemOffset = VA.getLocMemOffset();
1486 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1487 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1488 if (Flags.isByVal()) {
1489 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1491 return DAG.getStore(Chain, dl, Arg, PtrOff,
1492 PseudoSourceValue::getStack(), LocMemOffset);
1495 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1496 /// optimization is performed and it is required.
1498 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1499 SDValue &OutRetAddr,
1505 if (!IsTailCall || FPDiff==0) return Chain;
1507 // Adjust the Return address stack slot.
1508 MVT VT = getPointerTy();
1509 OutRetAddr = getReturnAddressFrameIndex(DAG);
1511 // Load the "old" Return address.
1512 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0);
1513 return SDValue(OutRetAddr.getNode(), 1);
1516 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1517 /// optimization is performed and it is required (FPDiff!=0).
1519 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1520 SDValue Chain, SDValue RetAddrFrIdx,
1521 bool Is64Bit, int FPDiff, DebugLoc dl) {
1522 // Store the return address to the appropriate stack slot.
1523 if (!FPDiff) return Chain;
1524 // Calculate the new stack slot for the return address.
1525 int SlotSize = Is64Bit ? 8 : 4;
1526 int NewReturnAddrFI =
1527 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1528 MVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1529 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1530 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1531 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1535 SDValue X86TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1536 MachineFunction &MF = DAG.getMachineFunction();
1537 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
1538 SDValue Chain = TheCall->getChain();
1539 unsigned CC = TheCall->getCallingConv();
1540 bool isVarArg = TheCall->isVarArg();
1541 bool IsTailCall = TheCall->isTailCall() &&
1542 CC == CallingConv::Fast && PerformTailCallOpt;
1543 SDValue Callee = TheCall->getCallee();
1544 bool Is64Bit = Subtarget->is64Bit();
1545 bool IsStructRet = CallIsStructReturn(TheCall);
1546 DebugLoc dl = TheCall->getDebugLoc();
1548 assert(!(isVarArg && CC == CallingConv::Fast) &&
1549 "Var args not supported with calling convention fastcc");
1551 // Analyze operands of the call, assigning locations to each operand.
1552 SmallVector<CCValAssign, 16> ArgLocs;
1553 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1554 CCInfo.AnalyzeCallOperands(TheCall, CCAssignFnForNode(CC));
1556 // Get a count of how many bytes are to be pushed on the stack.
1557 unsigned NumBytes = CCInfo.getNextStackOffset();
1558 if (PerformTailCallOpt && CC == CallingConv::Fast)
1559 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1563 // Lower arguments at fp - stackoffset + fpdiff.
1564 unsigned NumBytesCallerPushed =
1565 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1566 FPDiff = NumBytesCallerPushed - NumBytes;
1568 // Set the delta of movement of the returnaddr stackslot.
1569 // But only set if delta is greater than previous delta.
1570 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1571 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1574 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1576 SDValue RetAddrFrIdx;
1577 // Load return adress for tail calls.
1578 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1581 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1582 SmallVector<SDValue, 8> MemOpChains;
1585 // Walk the register/memloc assignments, inserting copies/loads. In the case
1586 // of tail call optimization arguments are handle later.
1587 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1588 CCValAssign &VA = ArgLocs[i];
1589 SDValue Arg = TheCall->getArg(i);
1590 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1591 bool isByVal = Flags.isByVal();
1593 // Promote the value if needed.
1594 switch (VA.getLocInfo()) {
1595 default: assert(0 && "Unknown loc info!");
1596 case CCValAssign::Full: break;
1597 case CCValAssign::SExt:
1598 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1600 case CCValAssign::ZExt:
1601 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1603 case CCValAssign::AExt:
1604 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1608 if (VA.isRegLoc()) {
1610 MVT RegVT = VA.getLocVT();
1611 if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1612 switch (VA.getLocReg()) {
1615 case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1617 // Special case: passing MMX values in GPR registers.
1618 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1621 case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1622 case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1623 // Special case: passing MMX values in XMM registers.
1624 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1625 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1626 Arg = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v2i64,
1627 DAG.getNode(ISD::UNDEF, dl, MVT::v2i64), Arg,
1628 getMOVLMask(2, DAG, dl));
1633 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1635 if (!IsTailCall || (IsTailCall && isByVal)) {
1636 assert(VA.isMemLoc());
1637 if (StackPtr.getNode() == 0)
1638 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1640 MemOpChains.push_back(LowerMemOpCallTo(TheCall, DAG, StackPtr, VA,
1641 Chain, Arg, Flags));
1646 if (!MemOpChains.empty())
1647 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1648 &MemOpChains[0], MemOpChains.size());
1650 // Build a sequence of copy-to-reg nodes chained together with token chain
1651 // and flag operands which copy the outgoing args into registers.
1653 // Tail call byval lowering might overwrite argument registers so in case of
1654 // tail call optimization the copies to registers are lowered later.
1656 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1657 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1658 RegsToPass[i].second, InFlag);
1659 InFlag = Chain.getValue(1);
1662 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1664 if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1665 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1666 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1668 InFlag = Chain.getValue(1);
1670 // If we are tail calling and generating PIC/GOT style code load the address
1671 // of the callee into ecx. The value in ecx is used as target of the tail
1672 // jump. This is done to circumvent the ebx/callee-saved problem for tail
1673 // calls on PIC/GOT architectures. Normally we would just put the address of
1674 // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1675 // restored (since ebx is callee saved) before jumping to the target@PLT.
1676 if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1677 // Note: The actual moving to ecx is done further down.
1678 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1679 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1680 !G->getGlobal()->hasProtectedVisibility())
1681 Callee = LowerGlobalAddress(Callee, DAG);
1682 else if (isa<ExternalSymbolSDNode>(Callee))
1683 Callee = LowerExternalSymbol(Callee,DAG);
1686 if (Is64Bit && isVarArg) {
1687 // From AMD64 ABI document:
1688 // For calls that may call functions that use varargs or stdargs
1689 // (prototype-less calls or calls to functions containing ellipsis (...) in
1690 // the declaration) %al is used as hidden argument to specify the number
1691 // of SSE registers used. The contents of %al do not need to match exactly
1692 // the number of registers, but must be an ubound on the number of SSE
1693 // registers used and is in the range 0 - 8 inclusive.
1695 // FIXME: Verify this on Win64
1696 // Count the number of XMM registers allocated.
1697 static const unsigned XMMArgRegs[] = {
1698 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1699 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1701 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1702 assert((Subtarget->hasSSE1() || !NumXMMRegs)
1703 && "SSE registers cannot be used when SSE is disabled");
1705 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1706 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1707 InFlag = Chain.getValue(1);
1711 // For tail calls lower the arguments to the 'real' stack slot.
1713 SmallVector<SDValue, 8> MemOpChains2;
1716 // Do not flag preceeding copytoreg stuff together with the following stuff.
1718 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1719 CCValAssign &VA = ArgLocs[i];
1720 if (!VA.isRegLoc()) {
1721 assert(VA.isMemLoc());
1722 SDValue Arg = TheCall->getArg(i);
1723 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1724 // Create frame index.
1725 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1726 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1727 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1728 FIN = DAG.getFrameIndex(FI, getPointerTy());
1730 if (Flags.isByVal()) {
1731 // Copy relative to framepointer.
1732 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1733 if (StackPtr.getNode() == 0)
1734 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
1736 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
1738 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1741 // Store relative to framepointer.
1742 MemOpChains2.push_back(
1743 DAG.getStore(Chain, dl, Arg, FIN,
1744 PseudoSourceValue::getFixedStack(FI), 0));
1749 if (!MemOpChains2.empty())
1750 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1751 &MemOpChains2[0], MemOpChains2.size());
1753 // Copy arguments to their registers.
1754 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1755 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1756 RegsToPass[i].second, InFlag);
1757 InFlag = Chain.getValue(1);
1761 // Store the return address to the appropriate stack slot.
1762 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1766 // If the callee is a GlobalAddress node (quite common, every direct call is)
1767 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1768 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1769 // We should use extra load for direct calls to dllimported functions in
1771 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1772 getTargetMachine(), true))
1773 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy(),
1775 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1776 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1777 } else if (IsTailCall) {
1778 unsigned Opc = Is64Bit ? X86::R9 : X86::EAX;
1780 Chain = DAG.getCopyToReg(Chain, dl,
1781 DAG.getRegister(Opc, getPointerTy()),
1783 Callee = DAG.getRegister(Opc, getPointerTy());
1784 // Add register as live out.
1785 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1788 // Returns a chain & a flag for retval copy to use.
1789 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1790 SmallVector<SDValue, 8> Ops;
1793 Ops.push_back(Chain);
1794 Ops.push_back(DAG.getIntPtrConstant(NumBytes, true));
1795 Ops.push_back(DAG.getIntPtrConstant(0, true));
1796 if (InFlag.getNode())
1797 Ops.push_back(InFlag);
1798 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1799 InFlag = Chain.getValue(1);
1801 // Returns a chain & a flag for retval copy to use.
1802 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1806 Ops.push_back(Chain);
1807 Ops.push_back(Callee);
1810 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1812 // Add argument registers to the end of the list so that they are known live
1814 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1815 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1816 RegsToPass[i].second.getValueType()));
1818 // Add an implicit use GOT pointer in EBX.
1819 if (!IsTailCall && !Is64Bit &&
1820 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1821 Subtarget->isPICStyleGOT())
1822 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1824 // Add an implicit use of AL for x86 vararg functions.
1825 if (Is64Bit && isVarArg)
1826 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1828 if (InFlag.getNode())
1829 Ops.push_back(InFlag);
1832 assert(InFlag.getNode() &&
1833 "Flag must be set. Depend on flag being set in LowerRET");
1834 Chain = DAG.getNode(X86ISD::TAILCALL, dl,
1835 TheCall->getVTList(), &Ops[0], Ops.size());
1837 return SDValue(Chain.getNode(), Op.getResNo());
1840 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
1841 InFlag = Chain.getValue(1);
1843 // Create the CALLSEQ_END node.
1844 unsigned NumBytesForCalleeToPush;
1845 if (IsCalleePop(isVarArg, CC))
1846 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1847 else if (!Is64Bit && CC != CallingConv::Fast && IsStructRet)
1848 // If this is is a call to a struct-return function, the callee
1849 // pops the hidden struct pointer, so we have to push it back.
1850 // This is common for Darwin/X86, Linux & Mingw32 targets.
1851 NumBytesForCalleeToPush = 4;
1853 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1855 // Returns a flag for retval copy to use.
1856 Chain = DAG.getCALLSEQ_END(Chain,
1857 DAG.getIntPtrConstant(NumBytes, true),
1858 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
1861 InFlag = Chain.getValue(1);
1863 // Handle result values, copying them out of physregs into vregs that we
1865 return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
1870 //===----------------------------------------------------------------------===//
1871 // Fast Calling Convention (tail call) implementation
1872 //===----------------------------------------------------------------------===//
1874 // Like std call, callee cleans arguments, convention except that ECX is
1875 // reserved for storing the tail called function address. Only 2 registers are
1876 // free for argument passing (inreg). Tail call optimization is performed
1878 // * tailcallopt is enabled
1879 // * caller/callee are fastcc
1880 // On X86_64 architecture with GOT-style position independent code only local
1881 // (within module) calls are supported at the moment.
1882 // To keep the stack aligned according to platform abi the function
1883 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1884 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1885 // If a tail called function callee has more arguments than the caller the
1886 // caller needs to make sure that there is room to move the RETADDR to. This is
1887 // achieved by reserving an area the size of the argument delta right after the
1888 // original REtADDR, but before the saved framepointer or the spilled registers
1889 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1901 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1902 /// for a 16 byte align requirement.
1903 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1904 SelectionDAG& DAG) {
1905 MachineFunction &MF = DAG.getMachineFunction();
1906 const TargetMachine &TM = MF.getTarget();
1907 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1908 unsigned StackAlignment = TFI.getStackAlignment();
1909 uint64_t AlignMask = StackAlignment - 1;
1910 int64_t Offset = StackSize;
1911 uint64_t SlotSize = TD->getPointerSize();
1912 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1913 // Number smaller than 12 so just add the difference.
1914 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1916 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1917 Offset = ((~AlignMask) & Offset) + StackAlignment +
1918 (StackAlignment-SlotSize);
1923 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1924 /// following the call is a return. A function is eligible if caller/callee
1925 /// calling conventions match, currently only fastcc supports tail calls, and
1926 /// the function CALL is immediatly followed by a RET.
1927 bool X86TargetLowering::IsEligibleForTailCallOptimization(CallSDNode *TheCall,
1929 SelectionDAG& DAG) const {
1930 if (!PerformTailCallOpt)
1933 if (CheckTailCallReturnConstraints(TheCall, Ret)) {
1934 MachineFunction &MF = DAG.getMachineFunction();
1935 unsigned CallerCC = MF.getFunction()->getCallingConv();
1936 unsigned CalleeCC= TheCall->getCallingConv();
1937 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1938 SDValue Callee = TheCall->getCallee();
1939 // On x86/32Bit PIC/GOT tail calls are supported.
1940 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1941 !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1944 // Can only do local tail calls (in same module, hidden or protected) on
1945 // x86_64 PIC/GOT at the moment.
1946 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1947 return G->getGlobal()->hasHiddenVisibility()
1948 || G->getGlobal()->hasProtectedVisibility();
1956 X86TargetLowering::createFastISel(MachineFunction &mf,
1957 MachineModuleInfo *mmo,
1959 DenseMap<const Value *, unsigned> &vm,
1960 DenseMap<const BasicBlock *,
1961 MachineBasicBlock *> &bm,
1962 DenseMap<const AllocaInst *, int> &am
1964 , SmallSet<Instruction*, 8> &cil
1967 return X86::createFastISel(mf, mmo, dw, vm, bm, am
1975 //===----------------------------------------------------------------------===//
1976 // Other Lowering Hooks
1977 //===----------------------------------------------------------------------===//
1980 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1981 MachineFunction &MF = DAG.getMachineFunction();
1982 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1983 int ReturnAddrIndex = FuncInfo->getRAIndex();
1985 if (ReturnAddrIndex == 0) {
1986 // Set up a frame object for the return address.
1987 uint64_t SlotSize = TD->getPointerSize();
1988 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize);
1989 FuncInfo->setRAIndex(ReturnAddrIndex);
1992 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1996 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
1997 /// specific condition code, returning the condition code and the LHS/RHS of the
1998 /// comparison to make.
1999 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2000 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2002 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2003 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2004 // X > -1 -> X == 0, jump !sign.
2005 RHS = DAG.getConstant(0, RHS.getValueType());
2006 return X86::COND_NS;
2007 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2008 // X < 0 -> X == 0, jump on sign.
2010 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2012 RHS = DAG.getConstant(0, RHS.getValueType());
2013 return X86::COND_LE;
2017 switch (SetCCOpcode) {
2018 default: assert(0 && "Invalid integer condition!");
2019 case ISD::SETEQ: return X86::COND_E;
2020 case ISD::SETGT: return X86::COND_G;
2021 case ISD::SETGE: return X86::COND_GE;
2022 case ISD::SETLT: return X86::COND_L;
2023 case ISD::SETLE: return X86::COND_LE;
2024 case ISD::SETNE: return X86::COND_NE;
2025 case ISD::SETULT: return X86::COND_B;
2026 case ISD::SETUGT: return X86::COND_A;
2027 case ISD::SETULE: return X86::COND_BE;
2028 case ISD::SETUGE: return X86::COND_AE;
2032 // First determine if it is required or is profitable to flip the operands.
2034 // If LHS is a foldable load, but RHS is not, flip the condition.
2035 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2036 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2037 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2038 std::swap(LHS, RHS);
2041 switch (SetCCOpcode) {
2047 std::swap(LHS, RHS);
2051 // On a floating point condition, the flags are set as follows:
2053 // 0 | 0 | 0 | X > Y
2054 // 0 | 0 | 1 | X < Y
2055 // 1 | 0 | 0 | X == Y
2056 // 1 | 1 | 1 | unordered
2057 switch (SetCCOpcode) {
2058 default: assert(0 && "Condcode should be pre-legalized away");
2060 case ISD::SETEQ: return X86::COND_E;
2061 case ISD::SETOLT: // flipped
2063 case ISD::SETGT: return X86::COND_A;
2064 case ISD::SETOLE: // flipped
2066 case ISD::SETGE: return X86::COND_AE;
2067 case ISD::SETUGT: // flipped
2069 case ISD::SETLT: return X86::COND_B;
2070 case ISD::SETUGE: // flipped
2072 case ISD::SETLE: return X86::COND_BE;
2074 case ISD::SETNE: return X86::COND_NE;
2075 case ISD::SETUO: return X86::COND_P;
2076 case ISD::SETO: return X86::COND_NP;
2080 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2081 /// code. Current x86 isa includes the following FP cmov instructions:
2082 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2083 static bool hasFPCMov(unsigned X86CC) {
2099 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
2100 /// true if Op is undef or if its value falls within the specified range (L, H].
2101 static bool isUndefOrInRange(SDValue Op, unsigned Low, unsigned Hi) {
2102 if (Op.getOpcode() == ISD::UNDEF)
2105 unsigned Val = cast<ConstantSDNode>(Op)->getZExtValue();
2106 return (Val >= Low && Val < Hi);
2109 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
2110 /// true if Op is undef or if its value equal to the specified value.
2111 static bool isUndefOrEqual(SDValue Op, unsigned Val) {
2112 if (Op.getOpcode() == ISD::UNDEF)
2114 return cast<ConstantSDNode>(Op)->getZExtValue() == Val;
2117 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2118 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
2119 bool X86::isPSHUFDMask(SDNode *N) {
2120 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2122 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
2125 // Check if the value doesn't reference the second vector.
2126 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2127 SDValue Arg = N->getOperand(i);
2128 if (Arg.getOpcode() == ISD::UNDEF) continue;
2129 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2130 if (cast<ConstantSDNode>(Arg)->getZExtValue() >= e)
2137 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2138 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2139 bool X86::isPSHUFHWMask(SDNode *N) {
2140 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2142 if (N->getNumOperands() != 8)
2145 // Lower quadword copied in order.
2146 for (unsigned i = 0; i != 4; ++i) {
2147 SDValue Arg = N->getOperand(i);
2148 if (Arg.getOpcode() == ISD::UNDEF) continue;
2149 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2150 if (cast<ConstantSDNode>(Arg)->getZExtValue() != i)
2154 // Upper quadword shuffled.
2155 for (unsigned i = 4; i != 8; ++i) {
2156 SDValue Arg = N->getOperand(i);
2157 if (Arg.getOpcode() == ISD::UNDEF) continue;
2158 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2159 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2160 if (Val < 4 || Val > 7)
2167 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2168 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2169 bool X86::isPSHUFLWMask(SDNode *N) {
2170 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2172 if (N->getNumOperands() != 8)
2175 // Upper quadword copied in order.
2176 for (unsigned i = 4; i != 8; ++i)
2177 if (!isUndefOrEqual(N->getOperand(i), i))
2180 // Lower quadword shuffled.
2181 for (unsigned i = 0; i != 4; ++i)
2182 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2188 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2189 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2190 template<class SDOperand>
2191 static bool isSHUFPMask(SDOperand *Elems, unsigned NumElems) {
2192 if (NumElems != 2 && NumElems != 4) return false;
2194 unsigned Half = NumElems / 2;
2195 for (unsigned i = 0; i < Half; ++i)
2196 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2198 for (unsigned i = Half; i < NumElems; ++i)
2199 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2205 bool X86::isSHUFPMask(SDNode *N) {
2206 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2207 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2210 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2211 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2212 /// half elements to come from vector 1 (which would equal the dest.) and
2213 /// the upper half to come from vector 2.
2214 template<class SDOperand>
2215 static bool isCommutedSHUFP(SDOperand *Ops, unsigned NumOps) {
2216 if (NumOps != 2 && NumOps != 4) return false;
2218 unsigned Half = NumOps / 2;
2219 for (unsigned i = 0; i < Half; ++i)
2220 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2222 for (unsigned i = Half; i < NumOps; ++i)
2223 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2228 static bool isCommutedSHUFP(SDNode *N) {
2229 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2230 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2233 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2234 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2235 bool X86::isMOVHLPSMask(SDNode *N) {
2236 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2238 if (N->getNumOperands() != 4)
2241 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2242 return isUndefOrEqual(N->getOperand(0), 6) &&
2243 isUndefOrEqual(N->getOperand(1), 7) &&
2244 isUndefOrEqual(N->getOperand(2), 2) &&
2245 isUndefOrEqual(N->getOperand(3), 3);
2248 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2249 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2251 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2252 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2254 if (N->getNumOperands() != 4)
2257 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2258 return isUndefOrEqual(N->getOperand(0), 2) &&
2259 isUndefOrEqual(N->getOperand(1), 3) &&
2260 isUndefOrEqual(N->getOperand(2), 2) &&
2261 isUndefOrEqual(N->getOperand(3), 3);
2264 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2265 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2266 bool X86::isMOVLPMask(SDNode *N) {
2267 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2269 unsigned NumElems = N->getNumOperands();
2270 if (NumElems != 2 && NumElems != 4)
2273 for (unsigned i = 0; i < NumElems/2; ++i)
2274 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2277 for (unsigned i = NumElems/2; i < NumElems; ++i)
2278 if (!isUndefOrEqual(N->getOperand(i), i))
2284 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2285 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2287 bool X86::isMOVHPMask(SDNode *N) {
2288 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2290 unsigned NumElems = N->getNumOperands();
2291 if (NumElems != 2 && NumElems != 4)
2294 for (unsigned i = 0; i < NumElems/2; ++i)
2295 if (!isUndefOrEqual(N->getOperand(i), i))
2298 for (unsigned i = 0; i < NumElems/2; ++i) {
2299 SDValue Arg = N->getOperand(i + NumElems/2);
2300 if (!isUndefOrEqual(Arg, i + NumElems))
2307 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2308 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2309 template<class SDOperand>
2310 bool static isUNPCKLMask(SDOperand *Elts, unsigned NumElts,
2311 bool V2IsSplat = false) {
2312 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2315 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2316 SDValue BitI = Elts[i];
2317 SDValue BitI1 = Elts[i+1];
2318 if (!isUndefOrEqual(BitI, j))
2321 if (!isUndefOrEqual(BitI1, NumElts))
2324 if (!isUndefOrEqual(BitI1, j + NumElts))
2332 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2333 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2334 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2337 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2338 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2339 template<class SDOperand>
2340 bool static isUNPCKHMask(SDOperand *Elts, unsigned NumElts,
2341 bool V2IsSplat = false) {
2342 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2345 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2346 SDValue BitI = Elts[i];
2347 SDValue BitI1 = Elts[i+1];
2348 if (!isUndefOrEqual(BitI, j + NumElts/2))
2351 if (isUndefOrEqual(BitI1, NumElts))
2354 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2362 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2363 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2364 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2367 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2368 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2370 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2371 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2373 unsigned NumElems = N->getNumOperands();
2374 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2377 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2378 SDValue BitI = N->getOperand(i);
2379 SDValue BitI1 = N->getOperand(i+1);
2381 if (!isUndefOrEqual(BitI, j))
2383 if (!isUndefOrEqual(BitI1, j))
2390 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2391 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2393 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2394 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2396 unsigned NumElems = N->getNumOperands();
2397 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2400 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2401 SDValue BitI = N->getOperand(i);
2402 SDValue BitI1 = N->getOperand(i + 1);
2404 if (!isUndefOrEqual(BitI, j))
2406 if (!isUndefOrEqual(BitI1, j))
2413 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2414 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2415 /// MOVSD, and MOVD, i.e. setting the lowest element.
2416 template<class SDOperand>
2417 static bool isMOVLMask(SDOperand *Elts, unsigned NumElts) {
2418 if (NumElts != 2 && NumElts != 4)
2421 if (!isUndefOrEqual(Elts[0], NumElts))
2424 for (unsigned i = 1; i < NumElts; ++i) {
2425 if (!isUndefOrEqual(Elts[i], i))
2432 bool X86::isMOVLMask(SDNode *N) {
2433 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2434 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2437 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2438 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2439 /// element of vector 2 and the other elements to come from vector 1 in order.
2440 template<class SDOperand>
2441 static bool isCommutedMOVL(SDOperand *Ops, unsigned NumOps,
2442 bool V2IsSplat = false,
2443 bool V2IsUndef = false) {
2444 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2447 if (!isUndefOrEqual(Ops[0], 0))
2450 for (unsigned i = 1; i < NumOps; ++i) {
2451 SDValue Arg = Ops[i];
2452 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2453 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2454 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2461 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2462 bool V2IsUndef = false) {
2463 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2464 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2465 V2IsSplat, V2IsUndef);
2468 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2469 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2470 bool X86::isMOVSHDUPMask(SDNode *N) {
2471 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2473 if (N->getNumOperands() != 4)
2476 // Expect 1, 1, 3, 3
2477 for (unsigned i = 0; i < 2; ++i) {
2478 SDValue Arg = N->getOperand(i);
2479 if (Arg.getOpcode() == ISD::UNDEF) continue;
2480 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2481 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2482 if (Val != 1) return false;
2486 for (unsigned i = 2; i < 4; ++i) {
2487 SDValue Arg = N->getOperand(i);
2488 if (Arg.getOpcode() == ISD::UNDEF) continue;
2489 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2490 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2491 if (Val != 3) return false;
2495 // Don't use movshdup if it can be done with a shufps.
2499 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2500 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2501 bool X86::isMOVSLDUPMask(SDNode *N) {
2502 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2504 if (N->getNumOperands() != 4)
2507 // Expect 0, 0, 2, 2
2508 for (unsigned i = 0; i < 2; ++i) {
2509 SDValue Arg = N->getOperand(i);
2510 if (Arg.getOpcode() == ISD::UNDEF) continue;
2511 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2512 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2513 if (Val != 0) return false;
2517 for (unsigned i = 2; i < 4; ++i) {
2518 SDValue Arg = N->getOperand(i);
2519 if (Arg.getOpcode() == ISD::UNDEF) continue;
2520 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2521 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2522 if (Val != 2) return false;
2526 // Don't use movshdup if it can be done with a shufps.
2530 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2531 /// specifies a identity operation on the LHS or RHS.
2532 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2533 unsigned NumElems = N->getNumOperands();
2534 for (unsigned i = 0; i < NumElems; ++i)
2535 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2540 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2541 /// a splat of a single element.
2542 static bool isSplatMask(SDNode *N) {
2543 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2545 // This is a splat operation if each element of the permute is the same, and
2546 // if the value doesn't reference the second vector.
2547 unsigned NumElems = N->getNumOperands();
2548 SDValue ElementBase;
2550 for (; i != NumElems; ++i) {
2551 SDValue Elt = N->getOperand(i);
2552 if (isa<ConstantSDNode>(Elt)) {
2558 if (!ElementBase.getNode())
2561 for (; i != NumElems; ++i) {
2562 SDValue Arg = N->getOperand(i);
2563 if (Arg.getOpcode() == ISD::UNDEF) continue;
2564 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2565 if (Arg != ElementBase) return false;
2568 // Make sure it is a splat of the first vector operand.
2569 return cast<ConstantSDNode>(ElementBase)->getZExtValue() < NumElems;
2572 /// getSplatMaskEltNo - Given a splat mask, return the index to the element
2573 /// we want to splat.
2574 static SDValue getSplatMaskEltNo(SDNode *N) {
2575 assert(isSplatMask(N) && "Not a splat mask");
2576 unsigned NumElems = N->getNumOperands();
2577 SDValue ElementBase;
2579 for (; i != NumElems; ++i) {
2580 SDValue Elt = N->getOperand(i);
2581 if (isa<ConstantSDNode>(Elt))
2584 assert(0 && " No splat value found!");
2589 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2590 /// a splat of a single element and it's a 2 or 4 element mask.
2591 bool X86::isSplatMask(SDNode *N) {
2592 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2594 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2595 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2597 return ::isSplatMask(N);
2600 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2601 /// specifies a splat of zero element.
2602 bool X86::isSplatLoMask(SDNode *N) {
2603 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2605 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2606 if (!isUndefOrEqual(N->getOperand(i), 0))
2611 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2612 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2613 bool X86::isMOVDDUPMask(SDNode *N) {
2614 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2616 unsigned e = N->getNumOperands() / 2;
2617 for (unsigned i = 0; i < e; ++i)
2618 if (!isUndefOrEqual(N->getOperand(i), i))
2620 for (unsigned i = 0; i < e; ++i)
2621 if (!isUndefOrEqual(N->getOperand(e+i), i))
2626 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2627 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2629 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2630 unsigned NumOperands = N->getNumOperands();
2631 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2633 for (unsigned i = 0; i < NumOperands; ++i) {
2635 SDValue Arg = N->getOperand(NumOperands-i-1);
2636 if (Arg.getOpcode() != ISD::UNDEF)
2637 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2638 if (Val >= NumOperands) Val -= NumOperands;
2640 if (i != NumOperands - 1)
2647 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2648 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2650 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2652 // 8 nodes, but we only care about the last 4.
2653 for (unsigned i = 7; i >= 4; --i) {
2655 SDValue Arg = N->getOperand(i);
2656 if (Arg.getOpcode() != ISD::UNDEF) {
2657 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2667 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2668 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2670 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2672 // 8 nodes, but we only care about the first 4.
2673 for (int i = 3; i >= 0; --i) {
2675 SDValue Arg = N->getOperand(i);
2676 if (Arg.getOpcode() != ISD::UNDEF)
2677 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2686 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2687 /// specifies a 8 element shuffle that can be broken into a pair of
2688 /// PSHUFHW and PSHUFLW.
2689 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2690 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2692 if (N->getNumOperands() != 8)
2695 // Lower quadword shuffled.
2696 for (unsigned i = 0; i != 4; ++i) {
2697 SDValue Arg = N->getOperand(i);
2698 if (Arg.getOpcode() == ISD::UNDEF) continue;
2699 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2700 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2705 // Upper quadword shuffled.
2706 for (unsigned i = 4; i != 8; ++i) {
2707 SDValue Arg = N->getOperand(i);
2708 if (Arg.getOpcode() == ISD::UNDEF) continue;
2709 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2710 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2711 if (Val < 4 || Val > 7)
2718 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2719 /// values in ther permute mask.
2720 static SDValue CommuteVectorShuffle(SDValue Op, SDValue &V1,
2721 SDValue &V2, SDValue &Mask,
2722 SelectionDAG &DAG) {
2723 MVT VT = Op.getValueType();
2724 MVT MaskVT = Mask.getValueType();
2725 MVT EltVT = MaskVT.getVectorElementType();
2726 unsigned NumElems = Mask.getNumOperands();
2727 SmallVector<SDValue, 8> MaskVec;
2728 DebugLoc dl = Op.getNode()->getDebugLoc();
2730 for (unsigned i = 0; i != NumElems; ++i) {
2731 SDValue Arg = Mask.getOperand(i);
2732 if (Arg.getOpcode() == ISD::UNDEF) {
2733 MaskVec.push_back(DAG.getNode(ISD::UNDEF, dl, EltVT));
2736 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2737 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2739 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2741 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2745 Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT, &MaskVec[0], NumElems);
2746 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, Mask);
2749 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2750 /// the two vector operands have swapped position.
2752 SDValue CommuteVectorShuffleMask(SDValue Mask, SelectionDAG &DAG, DebugLoc dl) {
2753 MVT MaskVT = Mask.getValueType();
2754 MVT EltVT = MaskVT.getVectorElementType();
2755 unsigned NumElems = Mask.getNumOperands();
2756 SmallVector<SDValue, 8> MaskVec;
2757 for (unsigned i = 0; i != NumElems; ++i) {
2758 SDValue Arg = Mask.getOperand(i);
2759 if (Arg.getOpcode() == ISD::UNDEF) {
2760 MaskVec.push_back(DAG.getNode(ISD::UNDEF, dl, EltVT));
2763 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2764 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2766 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2768 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2770 return DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT, &MaskVec[0], NumElems);
2774 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2775 /// match movhlps. The lower half elements should come from upper half of
2776 /// V1 (and in order), and the upper half elements should come from the upper
2777 /// half of V2 (and in order).
2778 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2779 unsigned NumElems = Mask->getNumOperands();
2782 for (unsigned i = 0, e = 2; i != e; ++i)
2783 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2785 for (unsigned i = 2; i != 4; ++i)
2786 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2791 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2792 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2794 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2795 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
2797 N = N->getOperand(0).getNode();
2798 if (!ISD::isNON_EXTLoad(N))
2801 *LD = cast<LoadSDNode>(N);
2805 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2806 /// match movlp{s|d}. The lower half elements should come from lower half of
2807 /// V1 (and in order), and the upper half elements should come from the upper
2808 /// half of V2 (and in order). And since V1 will become the source of the
2809 /// MOVLP, it must be either a vector load or a scalar load to vector.
2810 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2811 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2813 // Is V2 is a vector load, don't do this transformation. We will try to use
2814 // load folding shufps op.
2815 if (ISD::isNON_EXTLoad(V2))
2818 unsigned NumElems = Mask->getNumOperands();
2819 if (NumElems != 2 && NumElems != 4)
2821 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2822 if (!isUndefOrEqual(Mask->getOperand(i), i))
2824 for (unsigned i = NumElems/2; i != NumElems; ++i)
2825 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2830 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2832 static bool isSplatVector(SDNode *N) {
2833 if (N->getOpcode() != ISD::BUILD_VECTOR)
2836 SDValue SplatValue = N->getOperand(0);
2837 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2838 if (N->getOperand(i) != SplatValue)
2843 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2845 static bool isUndefShuffle(SDNode *N) {
2846 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2849 SDValue V1 = N->getOperand(0);
2850 SDValue V2 = N->getOperand(1);
2851 SDValue Mask = N->getOperand(2);
2852 unsigned NumElems = Mask.getNumOperands();
2853 for (unsigned i = 0; i != NumElems; ++i) {
2854 SDValue Arg = Mask.getOperand(i);
2855 if (Arg.getOpcode() != ISD::UNDEF) {
2856 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2857 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2859 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2866 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2868 static inline bool isZeroNode(SDValue Elt) {
2869 return ((isa<ConstantSDNode>(Elt) &&
2870 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2871 (isa<ConstantFPSDNode>(Elt) &&
2872 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2875 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2876 /// to an zero vector.
2877 static bool isZeroShuffle(SDNode *N) {
2878 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2881 SDValue V1 = N->getOperand(0);
2882 SDValue V2 = N->getOperand(1);
2883 SDValue Mask = N->getOperand(2);
2884 unsigned NumElems = Mask.getNumOperands();
2885 for (unsigned i = 0; i != NumElems; ++i) {
2886 SDValue Arg = Mask.getOperand(i);
2887 if (Arg.getOpcode() == ISD::UNDEF)
2890 unsigned Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2891 if (Idx < NumElems) {
2892 unsigned Opc = V1.getNode()->getOpcode();
2893 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
2895 if (Opc != ISD::BUILD_VECTOR ||
2896 !isZeroNode(V1.getNode()->getOperand(Idx)))
2898 } else if (Idx >= NumElems) {
2899 unsigned Opc = V2.getNode()->getOpcode();
2900 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
2902 if (Opc != ISD::BUILD_VECTOR ||
2903 !isZeroNode(V2.getNode()->getOperand(Idx - NumElems)))
2910 /// getZeroVector - Returns a vector of specified type with all zero elements.
2912 static SDValue getZeroVector(MVT VT, bool HasSSE2, SelectionDAG &DAG,
2914 assert(VT.isVector() && "Expected a vector type");
2916 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2917 // type. This ensures they get CSE'd.
2919 if (VT.getSizeInBits() == 64) { // MMX
2920 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2921 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2922 } else if (HasSSE2) { // SSE2
2923 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2924 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2926 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2927 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
2929 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2932 /// getOnesVector - Returns a vector of specified type with all bits set.
2934 static SDValue getOnesVector(MVT VT, SelectionDAG &DAG, DebugLoc dl) {
2935 assert(VT.isVector() && "Expected a vector type");
2937 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2938 // type. This ensures they get CSE'd.
2939 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2941 if (VT.getSizeInBits() == 64) // MMX
2942 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2944 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2945 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2949 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2950 /// that point to V2 points to its first element.
2951 static SDValue NormalizeMask(SDValue Mask, SelectionDAG &DAG) {
2952 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2954 bool Changed = false;
2955 SmallVector<SDValue, 8> MaskVec;
2956 unsigned NumElems = Mask.getNumOperands();
2957 for (unsigned i = 0; i != NumElems; ++i) {
2958 SDValue Arg = Mask.getOperand(i);
2959 if (Arg.getOpcode() != ISD::UNDEF) {
2960 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2961 if (Val > NumElems) {
2962 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2966 MaskVec.push_back(Arg);
2970 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getNode()->getDebugLoc(),
2971 Mask.getValueType(),
2972 &MaskVec[0], MaskVec.size());
2976 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2977 /// operation of specified width.
2978 static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG, DebugLoc dl) {
2979 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2980 MVT BaseVT = MaskVT.getVectorElementType();
2982 SmallVector<SDValue, 8> MaskVec;
2983 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2984 for (unsigned i = 1; i != NumElems; ++i)
2985 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2986 return DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
2987 &MaskVec[0], MaskVec.size());
2990 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2991 /// of specified width.
2992 static SDValue getUnpacklMask(unsigned NumElems, SelectionDAG &DAG,
2994 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2995 MVT BaseVT = MaskVT.getVectorElementType();
2996 SmallVector<SDValue, 8> MaskVec;
2997 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2998 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2999 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
3001 return DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3002 &MaskVec[0], MaskVec.size());
3005 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
3006 /// of specified width.
3007 static SDValue getUnpackhMask(unsigned NumElems, SelectionDAG &DAG,
3009 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3010 MVT BaseVT = MaskVT.getVectorElementType();
3011 unsigned Half = NumElems/2;
3012 SmallVector<SDValue, 8> MaskVec;
3013 for (unsigned i = 0; i != Half; ++i) {
3014 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
3015 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
3017 return DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3018 &MaskVec[0], MaskVec.size());
3021 /// getSwapEltZeroMask - Returns a vector_shuffle mask for a shuffle that swaps
3022 /// element #0 of a vector with the specified index, leaving the rest of the
3023 /// elements in place.
3024 static SDValue getSwapEltZeroMask(unsigned NumElems, unsigned DestElt,
3025 SelectionDAG &DAG, DebugLoc dl) {
3026 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3027 MVT BaseVT = MaskVT.getVectorElementType();
3028 SmallVector<SDValue, 8> MaskVec;
3029 // Element #0 of the result gets the elt we are replacing.
3030 MaskVec.push_back(DAG.getConstant(DestElt, BaseVT));
3031 for (unsigned i = 1; i != NumElems; ++i)
3032 MaskVec.push_back(DAG.getConstant(i == DestElt ? 0 : i, BaseVT));
3033 return DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3034 &MaskVec[0], MaskVec.size());
3037 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3038 static SDValue PromoteSplat(SDValue Op, SelectionDAG &DAG, bool HasSSE2) {
3039 MVT PVT = HasSSE2 ? MVT::v4i32 : MVT::v4f32;
3040 MVT VT = Op.getValueType();
3043 SDValue V1 = Op.getOperand(0);
3044 SDValue Mask = Op.getOperand(2);
3045 unsigned MaskNumElems = Mask.getNumOperands();
3046 unsigned NumElems = MaskNumElems;
3047 DebugLoc dl = Op.getNode()->getDebugLoc();
3048 // Special handling of v4f32 -> v4i32.
3049 if (VT != MVT::v4f32) {
3050 // Find which element we want to splat.
3051 SDNode* EltNoNode = getSplatMaskEltNo(Mask.getNode()).getNode();
3052 unsigned EltNo = cast<ConstantSDNode>(EltNoNode)->getZExtValue();
3053 // unpack elements to the correct location
3054 while (NumElems > 4) {
3055 if (EltNo < NumElems/2) {
3056 Mask = getUnpacklMask(MaskNumElems, DAG, dl);
3058 Mask = getUnpackhMask(MaskNumElems, DAG, dl);
3059 EltNo -= NumElems/2;
3061 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V1, Mask);
3064 SDValue Cst = DAG.getConstant(EltNo, MVT::i32);
3065 Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3068 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3069 SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, PVT, V1,
3070 DAG.getNode(ISD::UNDEF, PVT), Mask);
3071 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Shuffle);
3074 /// isVectorLoad - Returns true if the node is a vector load, a scalar
3075 /// load that's promoted to vector, or a load bitcasted.
3076 static bool isVectorLoad(SDValue Op) {
3077 assert(Op.getValueType().isVector() && "Expected a vector type");
3078 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR ||
3079 Op.getOpcode() == ISD::BIT_CONVERT) {
3080 return isa<LoadSDNode>(Op.getOperand(0));
3082 return isa<LoadSDNode>(Op);
3086 /// CanonicalizeMovddup - Cannonicalize movddup shuffle to v2f64.
3088 static SDValue CanonicalizeMovddup(SDValue Op, SDValue V1, SDValue Mask,
3089 SelectionDAG &DAG, bool HasSSE3) {
3090 // If we have sse3 and shuffle has more than one use or input is a load, then
3091 // use movddup. Otherwise, use movlhps.
3092 bool UseMovddup = HasSSE3 && (!Op.hasOneUse() || isVectorLoad(V1));
3093 MVT PVT = UseMovddup ? MVT::v2f64 : MVT::v4f32;
3094 MVT VT = Op.getValueType();
3097 DebugLoc dl = Op.getNode()->getDebugLoc();
3098 unsigned NumElems = PVT.getVectorNumElements();
3099 if (NumElems == 2) {
3100 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3101 Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3103 assert(NumElems == 4);
3104 SDValue Cst0 = DAG.getTargetConstant(0, MVT::i32);
3105 SDValue Cst1 = DAG.getTargetConstant(1, MVT::i32);
3106 Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
3107 Cst0, Cst1, Cst0, Cst1);
3110 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3111 SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, PVT, V1,
3112 DAG.getNode(ISD::UNDEF, dl, PVT), Mask);
3113 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Shuffle);
3116 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3117 /// vector of zero or undef vector. This produces a shuffle where the low
3118 /// element of V2 is swizzled into the zero/undef vector, landing at element
3119 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3120 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3121 bool isZero, bool HasSSE2,
3122 SelectionDAG &DAG) {
3123 DebugLoc dl = V2.getNode()->getDebugLoc();
3124 MVT VT = V2.getValueType();
3126 ? getZeroVector(VT, HasSSE2, DAG, dl) : DAG.getNode(ISD::UNDEF, dl, VT);
3127 unsigned NumElems = V2.getValueType().getVectorNumElements();
3128 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3129 MVT EVT = MaskVT.getVectorElementType();
3130 SmallVector<SDValue, 16> MaskVec;
3131 for (unsigned i = 0; i != NumElems; ++i)
3132 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
3133 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
3135 MaskVec.push_back(DAG.getConstant(i, EVT));
3136 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3137 &MaskVec[0], MaskVec.size());
3138 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, Mask);
3141 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3142 /// a shuffle that is zero.
3144 unsigned getNumOfConsecutiveZeros(SDValue Op, SDValue Mask,
3145 unsigned NumElems, bool Low,
3146 SelectionDAG &DAG) {
3147 unsigned NumZeros = 0;
3148 for (unsigned i = 0; i < NumElems; ++i) {
3149 unsigned Index = Low ? i : NumElems-i-1;
3150 SDValue Idx = Mask.getOperand(Index);
3151 if (Idx.getOpcode() == ISD::UNDEF) {
3155 SDValue Elt = DAG.getShuffleScalarElt(Op.getNode(), Index);
3156 if (Elt.getNode() && isZeroNode(Elt))
3164 /// isVectorShift - Returns true if the shuffle can be implemented as a
3165 /// logical left or right shift of a vector.
3166 static bool isVectorShift(SDValue Op, SDValue Mask, SelectionDAG &DAG,
3167 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3168 unsigned NumElems = Mask.getNumOperands();
3171 unsigned NumZeros= getNumOfConsecutiveZeros(Op, Mask, NumElems, true, DAG);
3174 NumZeros = getNumOfConsecutiveZeros(Op, Mask, NumElems, false, DAG);
3179 bool SeenV1 = false;
3180 bool SeenV2 = false;
3181 for (unsigned i = NumZeros; i < NumElems; ++i) {
3182 unsigned Val = isLeft ? (i - NumZeros) : i;
3183 SDValue Idx = Mask.getOperand(isLeft ? i : (i - NumZeros));
3184 if (Idx.getOpcode() == ISD::UNDEF)
3186 unsigned Index = cast<ConstantSDNode>(Idx)->getZExtValue();
3187 if (Index < NumElems)
3196 if (SeenV1 && SeenV2)
3199 ShVal = SeenV1 ? Op.getOperand(0) : Op.getOperand(1);
3205 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3207 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3208 unsigned NumNonZero, unsigned NumZero,
3209 SelectionDAG &DAG, TargetLowering &TLI) {
3213 DebugLoc dl = Op.getNode()->getDebugLoc();
3216 for (unsigned i = 0; i < 16; ++i) {
3217 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3218 if (ThisIsNonZero && First) {
3220 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3222 V = DAG.getNode(ISD::UNDEF, dl, MVT::v8i16);
3227 SDValue ThisElt(0, 0), LastElt(0, 0);
3228 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3229 if (LastIsNonZero) {
3230 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3231 MVT::i16, Op.getOperand(i-1));
3233 if (ThisIsNonZero) {
3234 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3235 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3236 ThisElt, DAG.getConstant(8, MVT::i8));
3238 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3242 if (ThisElt.getNode())
3243 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3244 DAG.getIntPtrConstant(i/2));
3248 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3251 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3253 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3254 unsigned NumNonZero, unsigned NumZero,
3255 SelectionDAG &DAG, TargetLowering &TLI) {
3259 DebugLoc dl = Op.getNode()->getDebugLoc();
3262 for (unsigned i = 0; i < 8; ++i) {
3263 bool isNonZero = (NonZeros & (1 << i)) != 0;
3267 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3269 V = DAG.getNode(ISD::UNDEF, dl, MVT::v8i16);
3272 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3273 MVT::v8i16, V, Op.getOperand(i),
3274 DAG.getIntPtrConstant(i));
3281 /// getVShift - Return a vector logical shift node.
3283 static SDValue getVShift(bool isLeft, MVT VT, SDValue SrcOp,
3284 unsigned NumBits, SelectionDAG &DAG,
3285 const TargetLowering &TLI, DebugLoc dl) {
3286 bool isMMX = VT.getSizeInBits() == 64;
3287 MVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3288 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3289 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3290 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3291 DAG.getNode(Opc, dl, ShVT, SrcOp,
3292 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3296 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3297 DebugLoc dl = Op.getNode()->getDebugLoc();
3298 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3299 if (ISD::isBuildVectorAllZeros(Op.getNode())
3300 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3301 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3302 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3303 // eliminated on x86-32 hosts.
3304 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3307 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3308 return getOnesVector(Op.getValueType(), DAG, dl);
3309 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3312 MVT VT = Op.getValueType();
3313 MVT EVT = VT.getVectorElementType();
3314 unsigned EVTBits = EVT.getSizeInBits();
3316 unsigned NumElems = Op.getNumOperands();
3317 unsigned NumZero = 0;
3318 unsigned NumNonZero = 0;
3319 unsigned NonZeros = 0;
3320 bool IsAllConstants = true;
3321 SmallSet<SDValue, 8> Values;
3322 for (unsigned i = 0; i < NumElems; ++i) {
3323 SDValue Elt = Op.getOperand(i);
3324 if (Elt.getOpcode() == ISD::UNDEF)
3327 if (Elt.getOpcode() != ISD::Constant &&
3328 Elt.getOpcode() != ISD::ConstantFP)
3329 IsAllConstants = false;
3330 if (isZeroNode(Elt))
3333 NonZeros |= (1 << i);
3338 if (NumNonZero == 0) {
3339 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3340 return DAG.getNode(ISD::UNDEF, dl, VT);
3343 // Special case for single non-zero, non-undef, element.
3344 if (NumNonZero == 1 && NumElems <= 4) {
3345 unsigned Idx = CountTrailingZeros_32(NonZeros);
3346 SDValue Item = Op.getOperand(Idx);
3348 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3349 // the value are obviously zero, truncate the value to i32 and do the
3350 // insertion that way. Only do this if the value is non-constant or if the
3351 // value is a constant being inserted into element 0. It is cheaper to do
3352 // a constant pool load than it is to do a movd + shuffle.
3353 if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3354 (!IsAllConstants || Idx == 0)) {
3355 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3356 // Handle MMX and SSE both.
3357 MVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3358 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3360 // Truncate the value (which may itself be a constant) to i32, and
3361 // convert it to a vector with movd (S2V+shuffle to zero extend).
3362 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3363 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3364 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3365 Subtarget->hasSSE2(), DAG);
3367 // Now we have our 32-bit value zero extended in the low element of
3368 // a vector. If Idx != 0, swizzle it into place.
3371 Item, DAG.getNode(ISD::UNDEF, dl, Item.getValueType()),
3372 getSwapEltZeroMask(VecElts, Idx, DAG, dl)
3374 Item = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VecVT, Ops, 3);
3376 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3380 // If we have a constant or non-constant insertion into the low element of
3381 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3382 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3383 // depending on what the source datatype is. Because we can only get here
3384 // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3386 // Don't do this for i64 values on x86-32.
3387 (EVT != MVT::i64 || Subtarget->is64Bit())) {
3388 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3389 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3390 return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3391 Subtarget->hasSSE2(), DAG);
3394 // Is it a vector logical left shift?
3395 if (NumElems == 2 && Idx == 1 &&
3396 isZeroNode(Op.getOperand(0)) && !isZeroNode(Op.getOperand(1))) {
3397 unsigned NumBits = VT.getSizeInBits();
3398 return getVShift(true, VT,
3399 DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(1)),
3400 NumBits/2, DAG, *this, dl);
3403 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3406 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3407 // is a non-constant being inserted into an element other than the low one,
3408 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3409 // movd/movss) to move this into the low element, then shuffle it into
3411 if (EVTBits == 32) {
3412 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3414 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3415 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3416 Subtarget->hasSSE2(), DAG);
3417 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3418 MVT MaskEVT = MaskVT.getVectorElementType();
3419 SmallVector<SDValue, 8> MaskVec;
3420 for (unsigned i = 0; i < NumElems; i++)
3421 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3422 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3423 &MaskVec[0], MaskVec.size());
3424 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, Item,
3425 DAG.getNode(ISD::UNDEF, VT), Mask);
3429 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3430 if (Values.size() == 1)
3433 // A vector full of immediates; various special cases are already
3434 // handled, so this is best done with a single constant-pool load.
3438 // Let legalizer expand 2-wide build_vectors.
3439 if (EVTBits == 64) {
3440 if (NumNonZero == 1) {
3441 // One half is zero or undef.
3442 unsigned Idx = CountTrailingZeros_32(NonZeros);
3443 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3444 Op.getOperand(Idx));
3445 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3446 Subtarget->hasSSE2(), DAG);
3451 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3452 if (EVTBits == 8 && NumElems == 16) {
3453 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3455 if (V.getNode()) return V;
3458 if (EVTBits == 16 && NumElems == 8) {
3459 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3461 if (V.getNode()) return V;
3464 // If element VT is == 32 bits, turn it into a number of shuffles.
3465 SmallVector<SDValue, 8> V;
3467 if (NumElems == 4 && NumZero > 0) {
3468 for (unsigned i = 0; i < 4; ++i) {
3469 bool isZero = !(NonZeros & (1 << i));
3471 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3473 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3476 for (unsigned i = 0; i < 2; ++i) {
3477 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3480 V[i] = V[i*2]; // Must be a zero vector.
3483 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[i*2+1], V[i*2],
3484 getMOVLMask(NumElems, DAG, dl));
3487 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[i*2], V[i*2+1],
3488 getMOVLMask(NumElems, DAG, dl));
3491 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[i*2], V[i*2+1],
3492 getUnpacklMask(NumElems, DAG, dl));
3497 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3498 MVT EVT = MaskVT.getVectorElementType();
3499 SmallVector<SDValue, 8> MaskVec;
3500 bool Reverse = (NonZeros & 0x3) == 2;
3501 for (unsigned i = 0; i < 2; ++i)
3503 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3505 MaskVec.push_back(DAG.getConstant(i, EVT));
3506 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3507 for (unsigned i = 0; i < 2; ++i)
3509 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3511 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3512 SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3513 &MaskVec[0], MaskVec.size());
3514 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[0], V[1], ShufMask);
3517 if (Values.size() > 2) {
3518 // Expand into a number of unpckl*.
3520 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3521 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3522 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3523 SDValue UnpckMask = getUnpacklMask(NumElems, DAG, dl);
3524 for (unsigned i = 0; i < NumElems; ++i)
3525 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3527 while (NumElems != 0) {
3528 for (unsigned i = 0; i < NumElems; ++i)
3529 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[i], V[i + NumElems],
3540 SDValue LowerVECTOR_SHUFFLEv8i16(SDValue V1, SDValue V2,
3541 SDValue PermMask, SelectionDAG &DAG,
3542 TargetLowering &TLI, DebugLoc dl) {
3544 MVT MaskVT = MVT::getIntVectorWithNumElements(8);
3545 MVT MaskEVT = MaskVT.getVectorElementType();
3546 MVT PtrVT = TLI.getPointerTy();
3547 SmallVector<SDValue, 8> MaskElts(PermMask.getNode()->op_begin(),
3548 PermMask.getNode()->op_end());
3550 // First record which half of which vector the low elements come from.
3551 SmallVector<unsigned, 4> LowQuad(4);
3552 for (unsigned i = 0; i < 4; ++i) {
3553 SDValue Elt = MaskElts[i];
3554 if (Elt.getOpcode() == ISD::UNDEF)
3556 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3557 int QuadIdx = EltIdx / 4;
3561 int BestLowQuad = -1;
3562 unsigned MaxQuad = 1;
3563 for (unsigned i = 0; i < 4; ++i) {
3564 if (LowQuad[i] > MaxQuad) {
3566 MaxQuad = LowQuad[i];
3570 // Record which half of which vector the high elements come from.
3571 SmallVector<unsigned, 4> HighQuad(4);
3572 for (unsigned i = 4; i < 8; ++i) {
3573 SDValue Elt = MaskElts[i];
3574 if (Elt.getOpcode() == ISD::UNDEF)
3576 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3577 int QuadIdx = EltIdx / 4;
3578 ++HighQuad[QuadIdx];
3581 int BestHighQuad = -1;
3583 for (unsigned i = 0; i < 4; ++i) {
3584 if (HighQuad[i] > MaxQuad) {
3586 MaxQuad = HighQuad[i];
3590 // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3591 if (BestLowQuad != -1 || BestHighQuad != -1) {
3592 // First sort the 4 chunks in order using shufpd.
3593 SmallVector<SDValue, 8> MaskVec;
3595 if (BestLowQuad != -1)
3596 MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3598 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3600 if (BestHighQuad != -1)
3601 MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3603 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3605 SDValue Mask= DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, &MaskVec[0],2);
3606 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v2i64,
3607 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
3608 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), Mask);
3609 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
3611 // Now sort high and low parts separately.
3612 BitVector InOrder(8);
3613 if (BestLowQuad != -1) {
3614 // Sort lower half in order using PSHUFLW.
3616 bool AnyOutOrder = false;
3618 for (unsigned i = 0; i != 4; ++i) {
3619 SDValue Elt = MaskElts[i];
3620 if (Elt.getOpcode() == ISD::UNDEF) {
3621 MaskVec.push_back(Elt);
3624 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3628 MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3630 // If this element is in the right place after this shuffle, then
3632 if ((int)(EltIdx / 4) == BestLowQuad)
3637 for (unsigned i = 4; i != 8; ++i)
3638 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3639 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3641 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v8i16,
3646 if (BestHighQuad != -1) {
3647 // Sort high half in order using PSHUFHW if possible.
3650 for (unsigned i = 0; i != 4; ++i)
3651 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3653 bool AnyOutOrder = false;
3654 for (unsigned i = 4; i != 8; ++i) {
3655 SDValue Elt = MaskElts[i];
3656 if (Elt.getOpcode() == ISD::UNDEF) {
3657 MaskVec.push_back(Elt);
3660 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3664 MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3666 // If this element is in the right place after this shuffle, then
3668 if ((int)(EltIdx / 4) == BestHighQuad)
3674 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl,
3675 MaskVT, &MaskVec[0], 8);
3676 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v8i16,
3681 // The other elements are put in the right place using pextrw and pinsrw.
3682 for (unsigned i = 0; i != 8; ++i) {
3685 SDValue Elt = MaskElts[i];
3686 if (Elt.getOpcode() == ISD::UNDEF)
3688 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3689 SDValue ExtOp = (EltIdx < 8)
3690 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
3691 DAG.getConstant(EltIdx, PtrVT))
3692 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
3693 DAG.getConstant(EltIdx - 8, PtrVT));
3694 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3695 DAG.getConstant(i, PtrVT));
3701 // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use as
3702 // few as possible. First, let's find out how many elements are already in the
3704 unsigned V1InOrder = 0;
3705 unsigned V1FromV1 = 0;
3706 unsigned V2InOrder = 0;
3707 unsigned V2FromV2 = 0;
3708 SmallVector<SDValue, 8> V1Elts;
3709 SmallVector<SDValue, 8> V2Elts;
3710 for (unsigned i = 0; i < 8; ++i) {
3711 SDValue Elt = MaskElts[i];
3712 if (Elt.getOpcode() == ISD::UNDEF) {
3713 V1Elts.push_back(Elt);
3714 V2Elts.push_back(Elt);
3719 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3721 V1Elts.push_back(Elt);
3722 V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3724 } else if (EltIdx == i+8) {
3725 V1Elts.push_back(Elt);
3726 V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3728 } else if (EltIdx < 8) {
3729 V1Elts.push_back(Elt);
3730 V2Elts.push_back(DAG.getConstant(EltIdx+8, MaskEVT));
3733 V1Elts.push_back(Elt);
3734 V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3739 if (V2InOrder > V1InOrder) {
3740 PermMask = CommuteVectorShuffleMask(PermMask, DAG, dl);
3742 std::swap(V1Elts, V2Elts);
3743 std::swap(V1FromV1, V2FromV2);
3746 if ((V1FromV1 + V1InOrder) != 8) {
3747 // Some elements are from V2.
3749 // If there are elements that are from V1 but out of place,
3750 // then first sort them in place
3751 SmallVector<SDValue, 8> MaskVec;
3752 for (unsigned i = 0; i < 8; ++i) {
3753 SDValue Elt = V1Elts[i];
3754 if (Elt.getOpcode() == ISD::UNDEF) {
3755 MaskVec.push_back(DAG.getNode(ISD::UNDEF, dl, MaskEVT));
3758 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3760 MaskVec.push_back(DAG.getNode(ISD::UNDEF, dl, MaskEVT));
3762 MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3764 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT, &MaskVec[0], 8);
3765 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v8i16, V1, V1, Mask);
3769 for (unsigned i = 0; i < 8; ++i) {
3770 SDValue Elt = V1Elts[i];
3771 if (Elt.getOpcode() == ISD::UNDEF)
3773 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3776 SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
3777 DAG.getConstant(EltIdx - 8, PtrVT));
3778 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3779 DAG.getConstant(i, PtrVT));
3783 // All elements are from V1.
3785 for (unsigned i = 0; i < 8; ++i) {
3786 SDValue Elt = V1Elts[i];
3787 if (Elt.getOpcode() == ISD::UNDEF)
3789 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3790 SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
3791 DAG.getConstant(EltIdx, PtrVT));
3792 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3793 DAG.getConstant(i, PtrVT));
3799 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3800 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3801 /// done when every pair / quad of shuffle mask elements point to elements in
3802 /// the right sequence. e.g.
3803 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3805 SDValue RewriteAsNarrowerShuffle(SDValue V1, SDValue V2,
3807 SDValue PermMask, SelectionDAG &DAG,
3808 TargetLowering &TLI, DebugLoc dl) {
3809 unsigned NumElems = PermMask.getNumOperands();
3810 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3811 MVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3812 MVT MaskEltVT = MaskVT.getVectorElementType();
3814 switch (VT.getSimpleVT()) {
3815 default: assert(false && "Unexpected!");
3816 case MVT::v4f32: NewVT = MVT::v2f64; break;
3817 case MVT::v4i32: NewVT = MVT::v2i64; break;
3818 case MVT::v8i16: NewVT = MVT::v4i32; break;
3819 case MVT::v16i8: NewVT = MVT::v4i32; break;
3822 if (NewWidth == 2) {
3828 unsigned Scale = NumElems / NewWidth;
3829 SmallVector<SDValue, 8> MaskVec;
3830 for (unsigned i = 0; i < NumElems; i += Scale) {
3831 unsigned StartIdx = ~0U;
3832 for (unsigned j = 0; j < Scale; ++j) {
3833 SDValue Elt = PermMask.getOperand(i+j);
3834 if (Elt.getOpcode() == ISD::UNDEF)
3836 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3837 if (StartIdx == ~0U)
3838 StartIdx = EltIdx - (EltIdx % Scale);
3839 if (EltIdx != StartIdx + j)
3842 if (StartIdx == ~0U)
3843 MaskVec.push_back(DAG.getNode(ISD::UNDEF, dl, MaskEltVT));
3845 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MaskEltVT));
3848 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
3849 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
3850 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, NewVT, V1, V2,
3851 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3852 &MaskVec[0], MaskVec.size()));
3855 /// getVZextMovL - Return a zero-extending vector move low node.
3857 static SDValue getVZextMovL(MVT VT, MVT OpVT,
3858 SDValue SrcOp, SelectionDAG &DAG,
3859 const X86Subtarget *Subtarget, DebugLoc dl) {
3860 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3861 LoadSDNode *LD = NULL;
3862 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
3863 LD = dyn_cast<LoadSDNode>(SrcOp);
3865 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3867 MVT EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3868 if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
3869 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3870 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3871 SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
3873 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3874 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3875 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3876 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3884 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3885 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3886 DAG.getNode(ISD::BIT_CONVERT, dl,
3890 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
3893 LowerVECTOR_SHUFFLE_4wide(SDValue V1, SDValue V2,
3894 SDValue PermMask, MVT VT, SelectionDAG &DAG,
3896 MVT MaskVT = PermMask.getValueType();
3897 MVT MaskEVT = MaskVT.getVectorElementType();
3898 SmallVector<std::pair<int, int>, 8> Locs;
3900 SmallVector<SDValue, 8> Mask1(4, DAG.getNode(ISD::UNDEF, dl, MaskEVT));
3903 for (unsigned i = 0; i != 4; ++i) {
3904 SDValue Elt = PermMask.getOperand(i);
3905 if (Elt.getOpcode() == ISD::UNDEF) {
3906 Locs[i] = std::make_pair(-1, -1);
3908 unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
3909 assert(Val < 8 && "Invalid VECTOR_SHUFFLE index!");
3911 Locs[i] = std::make_pair(0, NumLo);
3915 Locs[i] = std::make_pair(1, NumHi);
3917 Mask1[2+NumHi] = Elt;
3923 if (NumLo <= 2 && NumHi <= 2) {
3924 // If no more than two elements come from either vector. This can be
3925 // implemented with two shuffles. First shuffle gather the elements.
3926 // The second shuffle, which takes the first shuffle as both of its
3927 // vector operands, put the elements into the right order.
3928 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
3929 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3930 &Mask1[0], Mask1.size()));
3932 SmallVector<SDValue, 8> Mask2(4, DAG.getNode(ISD::UNDEF, dl, MaskEVT));
3933 for (unsigned i = 0; i != 4; ++i) {
3934 if (Locs[i].first == -1)
3937 unsigned Idx = (i < 2) ? 0 : 4;
3938 Idx += Locs[i].first * 2 + Locs[i].second;
3939 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3943 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V1,
3944 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3945 &Mask2[0], Mask2.size()));
3946 } else if (NumLo == 3 || NumHi == 3) {
3947 // Otherwise, we must have three elements from one vector, call it X, and
3948 // one element from the other, call it Y. First, use a shufps to build an
3949 // intermediate vector with the one element from Y and the element from X
3950 // that will be in the same half in the final destination (the indexes don't
3951 // matter). Then, use a shufps to build the final vector, taking the half
3952 // containing the element from Y from the intermediate, and the other half
3955 // Normalize it so the 3 elements come from V1.
3956 PermMask = CommuteVectorShuffleMask(PermMask, DAG, dl);
3960 // Find the element from V2.
3962 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
3963 SDValue Elt = PermMask.getOperand(HiIndex);
3964 if (Elt.getOpcode() == ISD::UNDEF)
3966 unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
3971 Mask1[0] = PermMask.getOperand(HiIndex);
3972 Mask1[1] = DAG.getNode(ISD::UNDEF, dl, MaskEVT);
3973 Mask1[2] = PermMask.getOperand(HiIndex^1);
3974 Mask1[3] = DAG.getNode(ISD::UNDEF, dl, MaskEVT);
3975 V2 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
3976 DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3979 Mask1[0] = PermMask.getOperand(0);
3980 Mask1[1] = PermMask.getOperand(1);
3981 Mask1[2] = DAG.getConstant(HiIndex & 1 ? 6 : 4, MaskEVT);
3982 Mask1[3] = DAG.getConstant(HiIndex & 1 ? 4 : 6, MaskEVT);
3983 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
3984 DAG.getNode(ISD::BUILD_VECTOR, dl,
3985 MaskVT, &Mask1[0], 4));
3987 Mask1[0] = DAG.getConstant(HiIndex & 1 ? 2 : 0, MaskEVT);
3988 Mask1[1] = DAG.getConstant(HiIndex & 1 ? 0 : 2, MaskEVT);
3989 Mask1[2] = PermMask.getOperand(2);
3990 Mask1[3] = PermMask.getOperand(3);
3991 if (Mask1[2].getOpcode() != ISD::UNDEF)
3993 DAG.getConstant(cast<ConstantSDNode>(Mask1[2])->getZExtValue()+4,
3995 if (Mask1[3].getOpcode() != ISD::UNDEF)
3997 DAG.getConstant(cast<ConstantSDNode>(Mask1[3])->getZExtValue()+4,
3999 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V2, V1,
4000 DAG.getNode(ISD::BUILD_VECTOR, dl,
4001 MaskVT, &Mask1[0], 4));
4005 // Break it into (shuffle shuffle_hi, shuffle_lo).
4007 SmallVector<SDValue,8> LoMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
4008 SmallVector<SDValue,8> HiMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
4009 SmallVector<SDValue,8> *MaskPtr = &LoMask;
4010 unsigned MaskIdx = 0;
4013 for (unsigned i = 0; i != 4; ++i) {
4020 SDValue Elt = PermMask.getOperand(i);
4021 if (Elt.getOpcode() == ISD::UNDEF) {
4022 Locs[i] = std::make_pair(-1, -1);
4023 } else if (cast<ConstantSDNode>(Elt)->getZExtValue() < 4) {
4024 Locs[i] = std::make_pair(MaskIdx, LoIdx);
4025 (*MaskPtr)[LoIdx] = Elt;
4028 Locs[i] = std::make_pair(MaskIdx, HiIdx);
4029 (*MaskPtr)[HiIdx] = Elt;
4034 SDValue LoShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
4035 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4036 &LoMask[0], LoMask.size()));
4037 SDValue HiShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
4038 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4039 &HiMask[0], HiMask.size()));
4040 SmallVector<SDValue, 8> MaskOps;
4041 for (unsigned i = 0; i != 4; ++i) {
4042 if (Locs[i].first == -1) {
4043 MaskOps.push_back(DAG.getNode(ISD::UNDEF, dl, MaskEVT));
4045 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4046 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
4049 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, LoShuffle, HiShuffle,
4050 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4051 &MaskOps[0], MaskOps.size()));
4055 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4056 SDValue V1 = Op.getOperand(0);
4057 SDValue V2 = Op.getOperand(1);
4058 SDValue PermMask = Op.getOperand(2);
4059 MVT VT = Op.getValueType();
4060 DebugLoc dl = Op.getNode()->getDebugLoc();
4061 unsigned NumElems = PermMask.getNumOperands();
4062 bool isMMX = VT.getSizeInBits() == 64;
4063 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4064 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4065 bool V1IsSplat = false;
4066 bool V2IsSplat = false;
4068 if (isUndefShuffle(Op.getNode()))
4069 return DAG.getNode(ISD::UNDEF, dl, VT);
4071 if (isZeroShuffle(Op.getNode()))
4072 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4074 if (isIdentityMask(PermMask.getNode()))
4076 else if (isIdentityMask(PermMask.getNode(), true))
4079 // Canonicalize movddup shuffles.
4080 if (V2IsUndef && Subtarget->hasSSE2() &&
4081 VT.getSizeInBits() == 128 &&
4082 X86::isMOVDDUPMask(PermMask.getNode()))
4083 return CanonicalizeMovddup(Op, V1, PermMask, DAG, Subtarget->hasSSE3());
4085 if (isSplatMask(PermMask.getNode())) {
4086 if (isMMX || NumElems < 4) return Op;
4087 // Promote it to a v4{if}32 splat.
4088 return PromoteSplat(Op, DAG, Subtarget->hasSSE2());
4091 // If the shuffle can be profitably rewritten as a narrower shuffle, then
4093 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4094 SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG,
4096 if (NewOp.getNode())
4097 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4098 LowerVECTOR_SHUFFLE(NewOp, DAG));
4099 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4100 // FIXME: Figure out a cleaner way to do this.
4101 // Try to make use of movq to zero out the top part.
4102 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4103 SDValue NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
4105 if (NewOp.getNode()) {
4106 SDValue NewV1 = NewOp.getOperand(0);
4107 SDValue NewV2 = NewOp.getOperand(1);
4108 SDValue NewMask = NewOp.getOperand(2);
4109 if (isCommutedMOVL(NewMask.getNode(), true, false)) {
4110 NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
4111 return getVZextMovL(VT, NewOp.getValueType(), NewV2, DAG, Subtarget,
4115 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4116 SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
4118 if (NewOp.getNode() && X86::isMOVLMask(NewOp.getOperand(2).getNode()))
4119 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4120 DAG, Subtarget, dl);
4124 // Check if this can be converted into a logical shift.
4125 bool isLeft = false;
4128 bool isShift = isVectorShift(Op, PermMask, DAG, isLeft, ShVal, ShAmt);
4129 if (isShift && ShVal.hasOneUse()) {
4130 // If the shifted value has multiple uses, it may be cheaper to use
4131 // v_set0 + movlhps or movhlps, etc.
4132 MVT EVT = VT.getVectorElementType();
4133 ShAmt *= EVT.getSizeInBits();
4134 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4137 if (X86::isMOVLMask(PermMask.getNode())) {
4140 if (ISD::isBuildVectorAllZeros(V1.getNode()))
4141 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4146 if (!isMMX && (X86::isMOVSHDUPMask(PermMask.getNode()) ||
4147 X86::isMOVSLDUPMask(PermMask.getNode()) ||
4148 X86::isMOVHLPSMask(PermMask.getNode()) ||
4149 X86::isMOVHPMask(PermMask.getNode()) ||
4150 X86::isMOVLPMask(PermMask.getNode())))
4153 if (ShouldXformToMOVHLPS(PermMask.getNode()) ||
4154 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), PermMask.getNode()))
4155 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4158 // No better options. Use a vshl / vsrl.
4159 MVT EVT = VT.getVectorElementType();
4160 ShAmt *= EVT.getSizeInBits();
4161 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4164 bool Commuted = false;
4165 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4166 // 1,1,1,1 -> v8i16 though.
4167 V1IsSplat = isSplatVector(V1.getNode());
4168 V2IsSplat = isSplatVector(V2.getNode());
4170 // Canonicalize the splat or undef, if present, to be on the RHS.
4171 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4172 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4173 std::swap(V1IsSplat, V2IsSplat);
4174 std::swap(V1IsUndef, V2IsUndef);
4178 // FIXME: Figure out a cleaner way to do this.
4179 if (isCommutedMOVL(PermMask.getNode(), V2IsSplat, V2IsUndef)) {
4180 if (V2IsUndef) return V1;
4181 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4183 // V2 is a splat, so the mask may be malformed. That is, it may point
4184 // to any V2 element. The instruction selectior won't like this. Get
4185 // a corrected mask and commute to form a proper MOVS{S|D}.
4186 SDValue NewMask = getMOVLMask(NumElems, DAG, dl);
4187 if (NewMask.getNode() != PermMask.getNode())
4188 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, NewMask);
4193 if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
4194 X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
4195 X86::isUNPCKLMask(PermMask.getNode()) ||
4196 X86::isUNPCKHMask(PermMask.getNode()))
4200 // Normalize mask so all entries that point to V2 points to its first
4201 // element then try to match unpck{h|l} again. If match, return a
4202 // new vector_shuffle with the corrected mask.
4203 SDValue NewMask = NormalizeMask(PermMask, DAG);
4204 if (NewMask.getNode() != PermMask.getNode()) {
4205 if (X86::isUNPCKLMask(NewMask.getNode(), true)) {
4206 SDValue NewMask = getUnpacklMask(NumElems, DAG, dl);
4207 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, NewMask);
4208 } else if (X86::isUNPCKHMask(NewMask.getNode(), true)) {
4209 SDValue NewMask = getUnpackhMask(NumElems, DAG, dl);
4210 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, NewMask);
4215 // Normalize the node to match x86 shuffle ops if needed
4216 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.getNode()))
4217 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4220 // Commute is back and try unpck* again.
4221 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4222 if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
4223 X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
4224 X86::isUNPCKLMask(PermMask.getNode()) ||
4225 X86::isUNPCKHMask(PermMask.getNode()))
4229 // Try PSHUF* first, then SHUFP*.
4230 // MMX doesn't have PSHUFD but it does have PSHUFW. While it's theoretically
4231 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
4232 if (isMMX && NumElems == 4 && X86::isPSHUFDMask(PermMask.getNode())) {
4233 if (V2.getOpcode() != ISD::UNDEF)
4234 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1,
4235 DAG.getNode(ISD::UNDEF, VT), PermMask);
4240 if (Subtarget->hasSSE2() &&
4241 (X86::isPSHUFDMask(PermMask.getNode()) ||
4242 X86::isPSHUFHWMask(PermMask.getNode()) ||
4243 X86::isPSHUFLWMask(PermMask.getNode()))) {
4245 if (VT == MVT::v4f32) {
4247 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, RVT,
4248 DAG.getNode(ISD::BIT_CONVERT, dl, RVT, V1),
4249 DAG.getNode(ISD::UNDEF, dl, RVT), PermMask);
4250 } else if (V2.getOpcode() != ISD::UNDEF)
4251 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, RVT, V1,
4252 DAG.getNode(ISD::UNDEF, dl, RVT), PermMask);
4254 Op = DAG.getNode(ISD::BIT_CONVERT, dl, VT, Op);
4258 // Binary or unary shufps.
4259 if (X86::isSHUFPMask(PermMask.getNode()) ||
4260 (V2.getOpcode() == ISD::UNDEF && X86::isPSHUFDMask(PermMask.getNode())))
4264 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4265 if (VT == MVT::v8i16) {
4266 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this, dl);
4267 if (NewOp.getNode())
4271 // Handle all 4 wide cases with a number of shuffles except for MMX.
4272 if (NumElems == 4 && !isMMX)
4273 return LowerVECTOR_SHUFFLE_4wide(V1, V2, PermMask, VT, DAG, dl);
4279 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4280 SelectionDAG &DAG) {
4281 MVT VT = Op.getValueType();
4282 DebugLoc dl = Op.getNode()->getDebugLoc();
4283 if (VT.getSizeInBits() == 8) {
4284 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4285 Op.getOperand(0), Op.getOperand(1));
4286 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4287 DAG.getValueType(VT));
4288 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4289 } else if (VT.getSizeInBits() == 16) {
4290 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4291 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4293 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4294 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4295 DAG.getNode(ISD::BIT_CONVERT, dl,
4299 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4300 Op.getOperand(0), Op.getOperand(1));
4301 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4302 DAG.getValueType(VT));
4303 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4304 } else if (VT == MVT::f32) {
4305 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4306 // the result back to FR32 register. It's only worth matching if the
4307 // result has a single use which is a store or a bitcast to i32. And in
4308 // the case of a store, it's not worth it if the index is a constant 0,
4309 // because a MOVSSmr can be used instead, which is smaller and faster.
4310 if (!Op.hasOneUse())
4312 SDNode *User = *Op.getNode()->use_begin();
4313 if ((User->getOpcode() != ISD::STORE ||
4314 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4315 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4316 (User->getOpcode() != ISD::BIT_CONVERT ||
4317 User->getValueType(0) != MVT::i32))
4319 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4320 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4323 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4324 } else if (VT == MVT::i32) {
4325 // ExtractPS works with constant index.
4326 if (isa<ConstantSDNode>(Op.getOperand(1)))
4334 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4335 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4338 if (Subtarget->hasSSE41()) {
4339 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4344 MVT VT = Op.getValueType();
4345 DebugLoc dl = Op.getNode()->getDebugLoc();
4346 // TODO: handle v16i8.
4347 if (VT.getSizeInBits() == 16) {
4348 SDValue Vec = Op.getOperand(0);
4349 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4351 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4352 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4353 DAG.getNode(ISD::BIT_CONVERT, dl,
4356 // Transform it so it match pextrw which produces a 32-bit result.
4357 MVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT()+1);
4358 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EVT,
4359 Op.getOperand(0), Op.getOperand(1));
4360 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EVT, Extract,
4361 DAG.getValueType(VT));
4362 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4363 } else if (VT.getSizeInBits() == 32) {
4364 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4367 // SHUFPS the element to the lowest double word, then movss.
4368 MVT MaskVT = MVT::getIntVectorWithNumElements(4);
4369 SmallVector<SDValue, 8> IdxVec;
4371 push_back(DAG.getConstant(Idx, MaskVT.getVectorElementType()));
4373 push_back(DAG.getNode(ISD::UNDEF, dl, MaskVT.getVectorElementType()));
4375 push_back(DAG.getNode(ISD::UNDEF, dl, MaskVT.getVectorElementType()));
4377 push_back(DAG.getNode(ISD::UNDEF, dl, MaskVT.getVectorElementType()));
4378 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4379 &IdxVec[0], IdxVec.size());
4380 SDValue Vec = Op.getOperand(0);
4381 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, Vec.getValueType(),
4382 Vec, DAG.getNode(ISD::UNDEF, dl, Vec.getValueType()),
4384 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4385 DAG.getIntPtrConstant(0));
4386 } else if (VT.getSizeInBits() == 64) {
4387 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4388 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4389 // to match extract_elt for f64.
4390 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4394 // UNPCKHPD the element to the lowest double word, then movsd.
4395 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4396 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4397 MVT MaskVT = MVT::getIntVectorWithNumElements(2);
4398 SmallVector<SDValue, 8> IdxVec;
4399 IdxVec.push_back(DAG.getConstant(1, MaskVT.getVectorElementType()));
4401 push_back(DAG.getNode(ISD::UNDEF, dl, MaskVT.getVectorElementType()));
4402 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4403 &IdxVec[0], IdxVec.size());
4404 SDValue Vec = Op.getOperand(0);
4405 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, Vec.getValueType(),
4406 Vec, DAG.getNode(ISD::UNDEF, dl, Vec.getValueType()),
4408 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4409 DAG.getIntPtrConstant(0));
4416 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4417 MVT VT = Op.getValueType();
4418 MVT EVT = VT.getVectorElementType();
4419 DebugLoc dl = Op.getNode()->getDebugLoc();
4421 SDValue N0 = Op.getOperand(0);
4422 SDValue N1 = Op.getOperand(1);
4423 SDValue N2 = Op.getOperand(2);
4425 if ((EVT.getSizeInBits() == 8 || EVT.getSizeInBits() == 16) &&
4426 isa<ConstantSDNode>(N2)) {
4427 unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4429 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4431 if (N1.getValueType() != MVT::i32)
4432 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4433 if (N2.getValueType() != MVT::i32)
4434 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4435 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4436 } else if (EVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4437 // Bits [7:6] of the constant are the source select. This will always be
4438 // zero here. The DAG Combiner may combine an extract_elt index into these
4439 // bits. For example (insert (extract, 3), 2) could be matched by putting
4440 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4441 // Bits [5:4] of the constant are the destination select. This is the
4442 // value of the incoming immediate.
4443 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4444 // combine either bitwise AND or insert of float 0.0 to set these bits.
4445 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4446 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4447 } else if (EVT == MVT::i32) {
4448 // InsertPS works with constant index.
4449 if (isa<ConstantSDNode>(N2))
4456 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4457 MVT VT = Op.getValueType();
4458 MVT EVT = VT.getVectorElementType();
4460 if (Subtarget->hasSSE41())
4461 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4466 DebugLoc dl = Op.getNode()->getDebugLoc();
4467 SDValue N0 = Op.getOperand(0);
4468 SDValue N1 = Op.getOperand(1);
4469 SDValue N2 = Op.getOperand(2);
4471 if (EVT.getSizeInBits() == 16) {
4472 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4473 // as its second argument.
4474 if (N1.getValueType() != MVT::i32)
4475 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4476 if (N2.getValueType() != MVT::i32)
4477 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4478 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
4484 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4485 DebugLoc dl = Op.getNode()->getDebugLoc();
4486 if (Op.getValueType() == MVT::v2f32)
4487 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4488 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4489 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4490 Op.getOperand(0))));
4492 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4493 MVT VT = MVT::v2i32;
4494 switch (Op.getValueType().getSimpleVT()) {
4501 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4502 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4505 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4506 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4507 // one of the above mentioned nodes. It has to be wrapped because otherwise
4508 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4509 // be used to form addressing mode. These wrapped nodes will be selected
4512 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4513 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4514 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(),
4516 CP->getAlignment());
4517 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4518 // With PIC, the address is actually $g + Offset.
4519 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4520 !Subtarget->isPICStyleRIPRel()) {
4521 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4522 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4530 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV,
4532 SelectionDAG &DAG) const {
4533 bool IsPic = getTargetMachine().getRelocationModel() == Reloc::PIC_;
4534 bool ExtraLoadRequired =
4535 Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false);
4537 // Create the TargetGlobalAddress node, folding in the constant
4538 // offset if it is legal.
4540 if (!IsPic && !ExtraLoadRequired && isInt32(Offset)) {
4541 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4544 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0);
4545 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4547 // With PIC, the address is actually $g + Offset.
4548 if (IsPic && !Subtarget->isPICStyleRIPRel()) {
4549 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4550 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4554 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4555 // load the value at address GV, not the value of GV itself. This means that
4556 // the GlobalAddress must be in the base or index register of the address, not
4557 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4558 // The same applies for external symbols during PIC codegen
4559 if (ExtraLoadRequired)
4560 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
4561 PseudoSourceValue::getGOT(), 0);
4563 // If there was a non-zero offset that we didn't fold, create an explicit
4566 Result = DAG.getNode(ISD::ADD, getPointerTy(), Result,
4567 DAG.getConstant(Offset, getPointerTy()));
4573 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4574 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4575 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4576 return LowerGlobalAddress(GV, Offset, DAG);
4579 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4581 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4584 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
4585 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
4586 DAG.getNode(X86ISD::GlobalBaseReg,
4588 InFlag = Chain.getValue(1);
4590 // emit leal symbol@TLSGD(,%ebx,1), %eax
4591 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4592 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4593 GA->getValueType(0),
4595 SDValue Ops[] = { Chain, TGA, InFlag };
4596 SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
4597 InFlag = Result.getValue(2);
4598 Chain = Result.getValue(1);
4600 // call ___tls_get_addr. This function receives its argument in
4601 // the register EAX.
4602 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Result, InFlag);
4603 InFlag = Chain.getValue(1);
4605 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4606 SDValue Ops1[] = { Chain,
4607 DAG.getTargetExternalSymbol("___tls_get_addr",
4609 DAG.getRegister(X86::EAX, PtrVT),
4610 DAG.getRegister(X86::EBX, PtrVT),
4612 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
4613 InFlag = Chain.getValue(1);
4615 return DAG.getCopyFromReg(Chain, dl, X86::EAX, PtrVT, InFlag);
4618 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4620 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4622 SDValue InFlag, Chain;
4623 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
4625 // emit leaq symbol@TLSGD(%rip), %rdi
4626 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4627 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4628 GA->getValueType(0),
4630 SDValue Ops[] = { DAG.getEntryNode(), TGA};
4631 SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 2);
4632 Chain = Result.getValue(1);
4633 InFlag = Result.getValue(2);
4635 // call __tls_get_addr. This function receives its argument in
4636 // the register RDI.
4637 Chain = DAG.getCopyToReg(Chain, dl, X86::RDI, Result, InFlag);
4638 InFlag = Chain.getValue(1);
4640 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4641 SDValue Ops1[] = { Chain,
4642 DAG.getTargetExternalSymbol("__tls_get_addr",
4644 DAG.getRegister(X86::RDI, PtrVT),
4646 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 4);
4647 InFlag = Chain.getValue(1);
4649 return DAG.getCopyFromReg(Chain, dl, X86::RAX, PtrVT, InFlag);
4652 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4653 // "local exec" model.
4654 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4656 // Get the Thread Pointer
4657 SDValue ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4658 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4660 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4661 GA->getValueType(0),
4663 SDValue Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4665 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4666 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
4667 PseudoSourceValue::getGOT(), 0);
4669 // The address of the thread local variable is the add of the thread
4670 // pointer with the offset of the variable.
4671 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4675 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4676 // TODO: implement the "local dynamic" model
4677 // TODO: implement the "initial exec"model for pic executables
4678 assert(Subtarget->isTargetELF() &&
4679 "TLS not implemented for non-ELF targets");
4680 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4681 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4682 // otherwise use the "Local Exec"TLS Model
4683 if (Subtarget->is64Bit()) {
4684 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4686 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4687 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4689 return LowerToTLSExecModel(GA, DAG, getPointerTy());
4694 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4695 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4696 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4697 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4698 // With PIC, the address is actually $g + Offset.
4699 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4700 !Subtarget->isPICStyleRIPRel()) {
4701 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4702 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4709 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4710 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4711 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4712 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4713 // With PIC, the address is actually $g + Offset.
4714 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4715 !Subtarget->isPICStyleRIPRel()) {
4716 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4717 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4724 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4725 /// take a 2 x i32 value to shift plus a shift amount.
4726 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4727 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4728 MVT VT = Op.getValueType();
4729 unsigned VTBits = VT.getSizeInBits();
4730 DebugLoc dl = Op.getNode()->getDebugLoc();
4731 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4732 SDValue ShOpLo = Op.getOperand(0);
4733 SDValue ShOpHi = Op.getOperand(1);
4734 SDValue ShAmt = Op.getOperand(2);
4735 SDValue Tmp1 = isSRA ?
4736 DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
4737 DAG.getConstant(VTBits - 1, MVT::i8)) :
4738 DAG.getConstant(0, VT);
4741 if (Op.getOpcode() == ISD::SHL_PARTS) {
4742 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
4743 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4745 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
4746 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
4749 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
4750 DAG.getConstant(VTBits, MVT::i8));
4751 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, VT,
4752 AndNode, DAG.getConstant(0, MVT::i8));
4755 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4756 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4757 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4759 if (Op.getOpcode() == ISD::SHL_PARTS) {
4760 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4761 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4763 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4764 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4767 SDValue Ops[2] = { Lo, Hi };
4768 return DAG.getMergeValues(Ops, 2, dl);
4771 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4772 MVT SrcVT = Op.getOperand(0).getValueType();
4773 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4774 "Unknown SINT_TO_FP to lower!");
4776 // These are really Legal; caller falls through into that case.
4777 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4779 if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 &&
4780 Subtarget->is64Bit())
4783 DebugLoc dl = Op.getNode()->getDebugLoc();
4784 unsigned Size = SrcVT.getSizeInBits()/8;
4785 MachineFunction &MF = DAG.getMachineFunction();
4786 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4787 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4788 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
4790 PseudoSourceValue::getFixedStack(SSFI), 0);
4794 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4796 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4798 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4799 SmallVector<SDValue, 8> Ops;
4800 Ops.push_back(Chain);
4801 Ops.push_back(StackSlot);
4802 Ops.push_back(DAG.getValueType(SrcVT));
4803 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
4804 Tys, &Ops[0], Ops.size());
4807 Chain = Result.getValue(1);
4808 SDValue InFlag = Result.getValue(2);
4810 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4811 // shouldn't be necessary except that RFP cannot be live across
4812 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4813 MachineFunction &MF = DAG.getMachineFunction();
4814 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4815 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4816 Tys = DAG.getVTList(MVT::Other);
4817 SmallVector<SDValue, 8> Ops;
4818 Ops.push_back(Chain);
4819 Ops.push_back(Result);
4820 Ops.push_back(StackSlot);
4821 Ops.push_back(DAG.getValueType(Op.getValueType()));
4822 Ops.push_back(InFlag);
4823 Chain = DAG.getNode(X86ISD::FST, dl, Tys, &Ops[0], Ops.size());
4824 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
4825 PseudoSourceValue::getFixedStack(SSFI), 0);
4831 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
4832 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
4833 // This algorithm is not obvious. Here it is in C code, more or less:
4835 double uint64_to_double( uint32_t hi, uint32_t lo ) {
4836 static const __m128i exp = { 0x4330000045300000ULL, 0 };
4837 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
4839 // Copy ints to xmm registers.
4840 __m128i xh = _mm_cvtsi32_si128( hi );
4841 __m128i xl = _mm_cvtsi32_si128( lo );
4843 // Combine into low half of a single xmm register.
4844 __m128i x = _mm_unpacklo_epi32( xh, xl );
4848 // Merge in appropriate exponents to give the integer bits the right
4850 x = _mm_unpacklo_epi32( x, exp );
4852 // Subtract away the biases to deal with the IEEE-754 double precision
4854 d = _mm_sub_pd( (__m128d) x, bias );
4856 // All conversions up to here are exact. The correctly rounded result is
4857 // calculated using the current rounding mode using the following
4859 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
4860 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
4861 // store doesn't really need to be here (except
4862 // maybe to zero the other double)
4867 DebugLoc dl = Op.getNode()->getDebugLoc();
4869 // Build some magic constants.
4870 std::vector<Constant*> CV0;
4871 CV0.push_back(ConstantInt::get(APInt(32, 0x45300000)));
4872 CV0.push_back(ConstantInt::get(APInt(32, 0x43300000)));
4873 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4874 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4875 Constant *C0 = ConstantVector::get(CV0);
4876 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 4);
4878 std::vector<Constant*> CV1;
4879 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4530000000000000ULL))));
4880 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4330000000000000ULL))));
4881 Constant *C1 = ConstantVector::get(CV1);
4882 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 4);
4884 SmallVector<SDValue, 4> MaskVec;
4885 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
4886 MaskVec.push_back(DAG.getConstant(4, MVT::i32));
4887 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
4888 MaskVec.push_back(DAG.getConstant(5, MVT::i32));
4889 SDValue UnpcklMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
4890 &MaskVec[0], MaskVec.size());
4891 SmallVector<SDValue, 4> MaskVec2;
4892 MaskVec2.push_back(DAG.getConstant(1, MVT::i32));
4893 MaskVec2.push_back(DAG.getConstant(0, MVT::i32));
4894 SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32,
4895 &MaskVec2[0], MaskVec2.size());
4897 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4898 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4900 DAG.getIntPtrConstant(1)));
4901 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4902 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4904 DAG.getIntPtrConstant(0)));
4905 SDValue Unpck1 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v4i32,
4906 XR1, XR2, UnpcklMask);
4907 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
4908 PseudoSourceValue::getConstantPool(), 0,
4910 SDValue Unpck2 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v4i32,
4911 Unpck1, CLod0, UnpcklMask);
4912 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
4913 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
4914 PseudoSourceValue::getConstantPool(), 0,
4916 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
4918 // Add the halves; easiest way is to swap them into another reg first.
4919 SDValue Shuf = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v2f64,
4920 Sub, Sub, ShufMask);
4921 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
4922 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
4923 DAG.getIntPtrConstant(0));
4926 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
4927 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
4928 DebugLoc dl = Op.getNode()->getDebugLoc();
4929 // FP constant to bias correct the final result.
4930 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
4933 // Load the 32-bit value into an XMM register.
4934 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4935 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4937 DAG.getIntPtrConstant(0)));
4939 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
4940 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
4941 DAG.getIntPtrConstant(0));
4943 // Or the load with the bias.
4944 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
4945 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4946 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4948 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4949 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4950 MVT::v2f64, Bias)));
4951 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
4952 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
4953 DAG.getIntPtrConstant(0));
4955 // Subtract the bias.
4956 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
4958 // Handle final rounding.
4959 MVT DestVT = Op.getValueType();
4961 if (DestVT.bitsLT(MVT::f64)) {
4962 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
4963 DAG.getIntPtrConstant(0));
4964 } else if (DestVT.bitsGT(MVT::f64)) {
4965 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
4968 // Handle final rounding.
4972 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4973 SDValue N0 = Op.getOperand(0);
4974 DebugLoc dl = Op.getNode()->getDebugLoc();
4976 // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
4977 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
4978 // the optimization here.
4979 if (DAG.SignBitIsZero(N0))
4980 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
4982 MVT SrcVT = N0.getValueType();
4983 if (SrcVT == MVT::i64) {
4984 // We only handle SSE2 f64 target here; caller can handle the rest.
4985 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
4988 return LowerUINT_TO_FP_i64(Op, DAG);
4989 } else if (SrcVT == MVT::i32) {
4990 return LowerUINT_TO_FP_i32(Op, DAG);
4993 assert(0 && "Unknown UINT_TO_FP to lower!");
4997 std::pair<SDValue,SDValue> X86TargetLowering::
4998 FP_TO_SINTHelper(SDValue Op, SelectionDAG &DAG) {
4999 DebugLoc dl = Op.getNode()->getDebugLoc();
5000 assert(Op.getValueType().getSimpleVT() <= MVT::i64 &&
5001 Op.getValueType().getSimpleVT() >= MVT::i16 &&
5002 "Unknown FP_TO_SINT to lower!");
5004 // These are really Legal.
5005 if (Op.getValueType() == MVT::i32 &&
5006 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5007 return std::make_pair(SDValue(), SDValue());
5008 if (Subtarget->is64Bit() &&
5009 Op.getValueType() == MVT::i64 &&
5010 Op.getOperand(0).getValueType() != MVT::f80)
5011 return std::make_pair(SDValue(), SDValue());
5013 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5015 MachineFunction &MF = DAG.getMachineFunction();
5016 unsigned MemSize = Op.getValueType().getSizeInBits()/8;
5017 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
5018 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5020 switch (Op.getValueType().getSimpleVT()) {
5021 default: assert(0 && "Invalid FP_TO_SINT to lower!");
5022 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5023 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5024 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5027 SDValue Chain = DAG.getEntryNode();
5028 SDValue Value = Op.getOperand(0);
5029 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5030 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5031 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5032 PseudoSourceValue::getFixedStack(SSFI), 0);
5033 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5035 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5037 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5038 Chain = Value.getValue(1);
5039 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
5040 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5043 // Build the FP_TO_INT*_IN_MEM
5044 SDValue Ops[] = { Chain, Value, StackSlot };
5045 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5047 return std::make_pair(FIST, StackSlot);
5050 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
5051 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(Op, DAG);
5052 SDValue FIST = Vals.first, StackSlot = Vals.second;
5053 if (FIST.getNode() == 0) return SDValue();
5056 return DAG.getLoad(Op.getValueType(), Op.getNode()->getDebugLoc(),
5057 FIST, StackSlot, NULL, 0);
5060 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
5061 DebugLoc dl = Op.getNode()->getDebugLoc();
5062 MVT VT = Op.getValueType();
5065 EltVT = VT.getVectorElementType();
5066 std::vector<Constant*> CV;
5067 if (EltVT == MVT::f64) {
5068 Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
5072 Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
5078 Constant *C = ConstantVector::get(CV);
5079 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
5080 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5081 PseudoSourceValue::getConstantPool(), 0,
5083 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5086 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
5087 DebugLoc dl = Op.getNode()->getDebugLoc();
5088 MVT VT = Op.getValueType();
5090 unsigned EltNum = 1;
5091 if (VT.isVector()) {
5092 EltVT = VT.getVectorElementType();
5093 EltNum = VT.getVectorNumElements();
5095 std::vector<Constant*> CV;
5096 if (EltVT == MVT::f64) {
5097 Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
5101 Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
5107 Constant *C = ConstantVector::get(CV);
5108 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
5109 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5110 PseudoSourceValue::getConstantPool(), 0,
5112 if (VT.isVector()) {
5113 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5114 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5115 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5117 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5119 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5123 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5124 SDValue Op0 = Op.getOperand(0);
5125 SDValue Op1 = Op.getOperand(1);
5126 DebugLoc dl = Op.getNode()->getDebugLoc();
5127 MVT VT = Op.getValueType();
5128 MVT SrcVT = Op1.getValueType();
5130 // If second operand is smaller, extend it first.
5131 if (SrcVT.bitsLT(VT)) {
5132 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5135 // And if it is bigger, shrink it first.
5136 if (SrcVT.bitsGT(VT)) {
5137 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5141 // At this point the operands and the result should have the same
5142 // type, and that won't be f80 since that is not custom lowered.
5144 // First get the sign bit of second operand.
5145 std::vector<Constant*> CV;
5146 if (SrcVT == MVT::f64) {
5147 CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
5148 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
5150 CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
5151 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5152 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5153 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5155 Constant *C = ConstantVector::get(CV);
5156 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
5157 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5158 PseudoSourceValue::getConstantPool(), 0,
5160 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5162 // Shift sign bit right or left if the two operands have different types.
5163 if (SrcVT.bitsGT(VT)) {
5164 // Op0 is MVT::f32, Op1 is MVT::f64.
5165 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5166 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5167 DAG.getConstant(32, MVT::i32));
5168 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5169 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5170 DAG.getIntPtrConstant(0));
5173 // Clear first operand sign bit.
5175 if (VT == MVT::f64) {
5176 CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
5177 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
5179 CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
5180 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5181 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5182 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5184 C = ConstantVector::get(CV);
5185 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
5186 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5187 PseudoSourceValue::getConstantPool(), 0,
5189 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5191 // Or the value with the sign bit.
5192 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5195 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5196 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5197 SDValue Op0 = Op.getOperand(0);
5198 SDValue Op1 = Op.getOperand(1);
5199 DebugLoc dl = Op.getNode()->getDebugLoc();
5200 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5202 // Lower (X & (1 << N)) == 0 to BT(X, N).
5203 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5204 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5205 if (Op0.getOpcode() == ISD::AND &&
5207 Op1.getOpcode() == ISD::Constant &&
5208 cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5209 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5211 if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
5212 if (ConstantSDNode *Op010C =
5213 dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
5214 if (Op010C->getZExtValue() == 1) {
5215 LHS = Op0.getOperand(0);
5216 RHS = Op0.getOperand(1).getOperand(1);
5218 } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
5219 if (ConstantSDNode *Op000C =
5220 dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
5221 if (Op000C->getZExtValue() == 1) {
5222 LHS = Op0.getOperand(1);
5223 RHS = Op0.getOperand(0).getOperand(1);
5225 } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
5226 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5227 SDValue AndLHS = Op0.getOperand(0);
5228 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5229 LHS = AndLHS.getOperand(0);
5230 RHS = AndLHS.getOperand(1);
5234 if (LHS.getNode()) {
5235 // If LHS is i8, promote it to i16 with any_extend. There is no i8 BT
5236 // instruction. Since the shift amount is in-range-or-undefined, we know
5237 // that doing a bittest on the i16 value is ok. We extend to i32 because
5238 // the encoding for the i16 version is larger than the i32 version.
5239 if (LHS.getValueType() == MVT::i8)
5240 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5242 // If the operand types disagree, extend the shift amount to match. Since
5243 // BT ignores high bits (like shifts) we can use anyextend.
5244 if (LHS.getValueType() != RHS.getValueType())
5245 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5247 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5248 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5249 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5250 DAG.getConstant(Cond, MVT::i8), BT);
5254 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5255 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5257 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5258 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5259 DAG.getConstant(X86CC, MVT::i8), Cond);
5262 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5264 SDValue Op0 = Op.getOperand(0);
5265 SDValue Op1 = Op.getOperand(1);
5266 SDValue CC = Op.getOperand(2);
5267 MVT VT = Op.getValueType();
5268 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5269 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5270 DebugLoc dl = Op.getNode()->getDebugLoc();
5274 MVT VT0 = Op0.getValueType();
5275 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5276 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5279 switch (SetCCOpcode) {
5282 case ISD::SETEQ: SSECC = 0; break;
5284 case ISD::SETGT: Swap = true; // Fallthrough
5286 case ISD::SETOLT: SSECC = 1; break;
5288 case ISD::SETGE: Swap = true; // Fallthrough
5290 case ISD::SETOLE: SSECC = 2; break;
5291 case ISD::SETUO: SSECC = 3; break;
5293 case ISD::SETNE: SSECC = 4; break;
5294 case ISD::SETULE: Swap = true;
5295 case ISD::SETUGE: SSECC = 5; break;
5296 case ISD::SETULT: Swap = true;
5297 case ISD::SETUGT: SSECC = 6; break;
5298 case ISD::SETO: SSECC = 7; break;
5301 std::swap(Op0, Op1);
5303 // In the two special cases we can't handle, emit two comparisons.
5305 if (SetCCOpcode == ISD::SETUEQ) {
5307 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5308 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5309 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
5311 else if (SetCCOpcode == ISD::SETONE) {
5313 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5314 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5315 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
5317 assert(0 && "Illegal FP comparison");
5319 // Handle all other FP comparisons here.
5320 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5323 // We are handling one of the integer comparisons here. Since SSE only has
5324 // GT and EQ comparisons for integer, swapping operands and multiple
5325 // operations may be required for some comparisons.
5326 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5327 bool Swap = false, Invert = false, FlipSigns = false;
5329 switch (VT.getSimpleVT()) {
5331 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5332 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5333 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5334 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5337 switch (SetCCOpcode) {
5339 case ISD::SETNE: Invert = true;
5340 case ISD::SETEQ: Opc = EQOpc; break;
5341 case ISD::SETLT: Swap = true;
5342 case ISD::SETGT: Opc = GTOpc; break;
5343 case ISD::SETGE: Swap = true;
5344 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
5345 case ISD::SETULT: Swap = true;
5346 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5347 case ISD::SETUGE: Swap = true;
5348 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5351 std::swap(Op0, Op1);
5353 // Since SSE has no unsigned integer comparisons, we need to flip the sign
5354 // bits of the inputs before performing those operations.
5356 MVT EltVT = VT.getVectorElementType();
5357 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
5359 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5360 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
5362 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
5363 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
5366 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
5368 // If the logical-not of the result is required, perform that now.
5370 Result = DAG.getNOT(dl, Result, VT);
5375 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5376 static bool isX86LogicalCmp(unsigned Opc) {
5377 return Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI;
5380 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5381 bool addTest = true;
5382 SDValue Cond = Op.getOperand(0);
5383 DebugLoc dl = Op.getNode()->getDebugLoc();
5386 if (Cond.getOpcode() == ISD::SETCC)
5387 Cond = LowerSETCC(Cond, DAG);
5389 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5390 // setting operand in place of the X86ISD::SETCC.
5391 if (Cond.getOpcode() == X86ISD::SETCC) {
5392 CC = Cond.getOperand(0);
5394 SDValue Cmp = Cond.getOperand(1);
5395 unsigned Opc = Cmp.getOpcode();
5396 MVT VT = Op.getValueType();
5398 bool IllegalFPCMov = false;
5399 if (VT.isFloatingPoint() && !VT.isVector() &&
5400 !isScalarFPTypeInSSEReg(VT)) // FPStack?
5401 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
5403 if ((isX86LogicalCmp(Opc) && !IllegalFPCMov) || Opc == X86ISD::BT) { // FIXME
5410 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5411 Cond= DAG.getNode(X86ISD::CMP, dl, MVT::i32, Cond,
5412 DAG.getConstant(0, MVT::i8));
5415 const MVT *VTs = DAG.getNodeValueTypes(Op.getValueType(),
5417 SmallVector<SDValue, 4> Ops;
5418 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
5419 // condition is true.
5420 Ops.push_back(Op.getOperand(2));
5421 Ops.push_back(Op.getOperand(1));
5423 Ops.push_back(Cond);
5424 return DAG.getNode(X86ISD::CMOV, dl, VTs, 2, &Ops[0], Ops.size());
5427 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
5428 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
5429 // from the AND / OR.
5430 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
5431 Opc = Op.getOpcode();
5432 if (Opc != ISD::OR && Opc != ISD::AND)
5434 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5435 Op.getOperand(0).hasOneUse() &&
5436 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
5437 Op.getOperand(1).hasOneUse());
5440 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
5441 // 1 and that the SETCC node has a single use.
5442 static bool isXor1OfSetCC(SDValue Op) {
5443 if (Op.getOpcode() != ISD::XOR)
5445 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5446 if (N1C && N1C->getAPIntValue() == 1) {
5447 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5448 Op.getOperand(0).hasOneUse();
5453 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
5454 bool addTest = true;
5455 SDValue Chain = Op.getOperand(0);
5456 SDValue Cond = Op.getOperand(1);
5457 SDValue Dest = Op.getOperand(2);
5458 DebugLoc dl = Op.getNode()->getDebugLoc();
5461 if (Cond.getOpcode() == ISD::SETCC)
5462 Cond = LowerSETCC(Cond, DAG);
5464 // FIXME: LowerXALUO doesn't handle these!!
5465 else if (Cond.getOpcode() == X86ISD::ADD ||
5466 Cond.getOpcode() == X86ISD::SUB ||
5467 Cond.getOpcode() == X86ISD::SMUL ||
5468 Cond.getOpcode() == X86ISD::UMUL)
5469 Cond = LowerXALUO(Cond, DAG);
5472 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5473 // setting operand in place of the X86ISD::SETCC.
5474 if (Cond.getOpcode() == X86ISD::SETCC) {
5475 CC = Cond.getOperand(0);
5477 SDValue Cmp = Cond.getOperand(1);
5478 unsigned Opc = Cmp.getOpcode();
5479 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
5480 if (isX86LogicalCmp(Opc) || Opc == X86ISD::BT) {
5484 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
5488 // These can only come from an arithmetic instruction with overflow,
5489 // e.g. SADDO, UADDO.
5490 Cond = Cond.getNode()->getOperand(1);
5497 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
5498 SDValue Cmp = Cond.getOperand(0).getOperand(1);
5499 unsigned Opc = Cmp.getOpcode();
5500 if (CondOpc == ISD::OR) {
5501 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
5502 // two branches instead of an explicit OR instruction with a
5504 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5505 isX86LogicalCmp(Opc)) {
5506 CC = Cond.getOperand(0).getOperand(0);
5507 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5508 Chain, Dest, CC, Cmp);
5509 CC = Cond.getOperand(1).getOperand(0);
5513 } else { // ISD::AND
5514 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
5515 // two branches instead of an explicit AND instruction with a
5516 // separate test. However, we only do this if this block doesn't
5517 // have a fall-through edge, because this requires an explicit
5518 // jmp when the condition is false.
5519 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5520 isX86LogicalCmp(Opc) &&
5521 Op.getNode()->hasOneUse()) {
5522 X86::CondCode CCode =
5523 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5524 CCode = X86::GetOppositeBranchCondition(CCode);
5525 CC = DAG.getConstant(CCode, MVT::i8);
5526 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
5527 // Look for an unconditional branch following this conditional branch.
5528 // We need this because we need to reverse the successors in order
5529 // to implement FCMP_OEQ.
5530 if (User.getOpcode() == ISD::BR) {
5531 SDValue FalseBB = User.getOperand(1);
5533 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
5534 assert(NewBR == User);
5537 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5538 Chain, Dest, CC, Cmp);
5539 X86::CondCode CCode =
5540 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
5541 CCode = X86::GetOppositeBranchCondition(CCode);
5542 CC = DAG.getConstant(CCode, MVT::i8);
5548 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
5549 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
5550 // It should be transformed during dag combiner except when the condition
5551 // is set by a arithmetics with overflow node.
5552 X86::CondCode CCode =
5553 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5554 CCode = X86::GetOppositeBranchCondition(CCode);
5555 CC = DAG.getConstant(CCode, MVT::i8);
5556 Cond = Cond.getOperand(0).getOperand(1);
5562 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5563 Cond= DAG.getNode(X86ISD::CMP, dl, MVT::i32, Cond,
5564 DAG.getConstant(0, MVT::i8));
5566 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5567 Chain, Dest, CC, Cond);
5571 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
5572 // Calls to _alloca is needed to probe the stack when allocating more than 4k
5573 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
5574 // that the guard pages used by the OS virtual memory manager are allocated in
5575 // correct sequence.
5577 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5578 SelectionDAG &DAG) {
5579 assert(Subtarget->isTargetCygMing() &&
5580 "This should be used only on Cygwin/Mingw targets");
5581 DebugLoc dl = Op.getNode()->getDebugLoc();
5584 SDValue Chain = Op.getOperand(0);
5585 SDValue Size = Op.getOperand(1);
5586 // FIXME: Ensure alignment here
5590 MVT IntPtr = getPointerTy();
5591 MVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
5593 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
5595 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
5596 Flag = Chain.getValue(1);
5598 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5599 SDValue Ops[] = { Chain,
5600 DAG.getTargetExternalSymbol("_alloca", IntPtr),
5601 DAG.getRegister(X86::EAX, IntPtr),
5602 DAG.getRegister(X86StackPtr, SPTy),
5604 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops, 5);
5605 Flag = Chain.getValue(1);
5607 Chain = DAG.getCALLSEQ_END(Chain,
5608 DAG.getIntPtrConstant(0, true),
5609 DAG.getIntPtrConstant(0, true),
5612 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
5614 SDValue Ops1[2] = { Chain.getValue(0), Chain };
5615 return DAG.getMergeValues(Ops1, 2, dl);
5619 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
5621 SDValue Dst, SDValue Src,
5622 SDValue Size, unsigned Align,
5624 uint64_t DstSVOff) {
5625 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5627 // If not DWORD aligned or size is more than the threshold, call the library.
5628 // The libc version is likely to be faster for these cases. It can use the
5629 // address value and run time information about the CPU.
5630 if ((Align & 3) != 0 ||
5632 ConstantSize->getZExtValue() >
5633 getSubtarget()->getMaxInlineSizeThreshold()) {
5634 SDValue InFlag(0, 0);
5636 // Check to see if there is a specialized entry-point for memory zeroing.
5637 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
5639 if (const char *bzeroEntry = V &&
5640 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
5641 MVT IntPtr = getPointerTy();
5642 const Type *IntPtrTy = TD->getIntPtrType();
5643 TargetLowering::ArgListTy Args;
5644 TargetLowering::ArgListEntry Entry;
5646 Entry.Ty = IntPtrTy;
5647 Args.push_back(Entry);
5649 Args.push_back(Entry);
5650 std::pair<SDValue,SDValue> CallResult =
5651 LowerCallTo(Chain, Type::VoidTy, false, false, false, false,
5652 CallingConv::C, false,
5653 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl);
5654 return CallResult.second;
5657 // Otherwise have the target-independent code call memset.
5661 uint64_t SizeVal = ConstantSize->getZExtValue();
5662 SDValue InFlag(0, 0);
5665 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
5666 unsigned BytesLeft = 0;
5667 bool TwoRepStos = false;
5670 uint64_t Val = ValC->getZExtValue() & 255;
5672 // If the value is a constant, then we can potentially use larger sets.
5673 switch (Align & 3) {
5674 case 2: // WORD aligned
5677 Val = (Val << 8) | Val;
5679 case 0: // DWORD aligned
5682 Val = (Val << 8) | Val;
5683 Val = (Val << 16) | Val;
5684 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
5687 Val = (Val << 32) | Val;
5690 default: // Byte aligned
5693 Count = DAG.getIntPtrConstant(SizeVal);
5697 if (AVT.bitsGT(MVT::i8)) {
5698 unsigned UBytes = AVT.getSizeInBits() / 8;
5699 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
5700 BytesLeft = SizeVal % UBytes;
5703 Chain = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
5705 InFlag = Chain.getValue(1);
5708 Count = DAG.getIntPtrConstant(SizeVal);
5709 Chain = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
5710 InFlag = Chain.getValue(1);
5713 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
5716 InFlag = Chain.getValue(1);
5717 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
5720 InFlag = Chain.getValue(1);
5722 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5723 SmallVector<SDValue, 8> Ops;
5724 Ops.push_back(Chain);
5725 Ops.push_back(DAG.getValueType(AVT));
5726 Ops.push_back(InFlag);
5727 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
5730 InFlag = Chain.getValue(1);
5732 MVT CVT = Count.getValueType();
5733 SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
5734 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
5735 Chain = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
5738 InFlag = Chain.getValue(1);
5739 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5741 Ops.push_back(Chain);
5742 Ops.push_back(DAG.getValueType(MVT::i8));
5743 Ops.push_back(InFlag);
5744 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
5745 } else if (BytesLeft) {
5746 // Handle the last 1 - 7 bytes.
5747 unsigned Offset = SizeVal - BytesLeft;
5748 MVT AddrVT = Dst.getValueType();
5749 MVT SizeVT = Size.getValueType();
5751 Chain = DAG.getMemset(Chain, dl,
5752 DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
5753 DAG.getConstant(Offset, AddrVT)),
5755 DAG.getConstant(BytesLeft, SizeVT),
5756 Align, DstSV, DstSVOff + Offset);
5759 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
5764 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
5765 SDValue Chain, SDValue Dst, SDValue Src,
5766 SDValue Size, unsigned Align,
5768 const Value *DstSV, uint64_t DstSVOff,
5769 const Value *SrcSV, uint64_t SrcSVOff) {
5770 // This requires the copy size to be a constant, preferrably
5771 // within a subtarget-specific limit.
5772 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5775 uint64_t SizeVal = ConstantSize->getZExtValue();
5776 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
5779 /// If not DWORD aligned, call the library.
5780 if ((Align & 3) != 0)
5785 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
5788 unsigned UBytes = AVT.getSizeInBits() / 8;
5789 unsigned CountVal = SizeVal / UBytes;
5790 SDValue Count = DAG.getIntPtrConstant(CountVal);
5791 unsigned BytesLeft = SizeVal % UBytes;
5793 SDValue InFlag(0, 0);
5794 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
5797 InFlag = Chain.getValue(1);
5798 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
5801 InFlag = Chain.getValue(1);
5802 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
5805 InFlag = Chain.getValue(1);
5807 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5808 SmallVector<SDValue, 8> Ops;
5809 Ops.push_back(Chain);
5810 Ops.push_back(DAG.getValueType(AVT));
5811 Ops.push_back(InFlag);
5812 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, &Ops[0], Ops.size());
5814 SmallVector<SDValue, 4> Results;
5815 Results.push_back(RepMovs);
5817 // Handle the last 1 - 7 bytes.
5818 unsigned Offset = SizeVal - BytesLeft;
5819 MVT DstVT = Dst.getValueType();
5820 MVT SrcVT = Src.getValueType();
5821 MVT SizeVT = Size.getValueType();
5822 Results.push_back(DAG.getMemcpy(Chain, dl,
5823 DAG.getNode(ISD::ADD, dl, DstVT, Dst,
5824 DAG.getConstant(Offset, DstVT)),
5825 DAG.getNode(ISD::ADD, dl, SrcVT, Src,
5826 DAG.getConstant(Offset, SrcVT)),
5827 DAG.getConstant(BytesLeft, SizeVT),
5828 Align, AlwaysInline,
5829 DstSV, DstSVOff + Offset,
5830 SrcSV, SrcSVOff + Offset));
5833 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5834 &Results[0], Results.size());
5837 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
5838 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5839 DebugLoc dl = Op.getNode()->getDebugLoc();
5841 if (!Subtarget->is64Bit()) {
5842 // vastart just stores the address of the VarArgsFrameIndex slot into the
5843 // memory location argument.
5844 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5845 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
5849 // gp_offset (0 - 6 * 8)
5850 // fp_offset (48 - 48 + 8 * 16)
5851 // overflow_arg_area (point to parameters coming in memory).
5853 SmallVector<SDValue, 8> MemOps;
5854 SDValue FIN = Op.getOperand(1);
5856 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
5857 DAG.getConstant(VarArgsGPOffset, MVT::i32),
5859 MemOps.push_back(Store);
5862 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5863 FIN, DAG.getIntPtrConstant(4));
5864 Store = DAG.getStore(Op.getOperand(0), dl,
5865 DAG.getConstant(VarArgsFPOffset, MVT::i32),
5867 MemOps.push_back(Store);
5869 // Store ptr to overflow_arg_area
5870 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5871 FIN, DAG.getIntPtrConstant(4));
5872 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5873 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0);
5874 MemOps.push_back(Store);
5876 // Store ptr to reg_save_area.
5877 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5878 FIN, DAG.getIntPtrConstant(8));
5879 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
5880 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0);
5881 MemOps.push_back(Store);
5882 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5883 &MemOps[0], MemOps.size());
5886 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
5887 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5888 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
5889 SDValue Chain = Op.getOperand(0);
5890 SDValue SrcPtr = Op.getOperand(1);
5891 SDValue SrcSV = Op.getOperand(2);
5893 assert(0 && "VAArgInst is not yet implemented for x86-64!");
5898 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
5899 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5900 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
5901 SDValue Chain = Op.getOperand(0);
5902 SDValue DstPtr = Op.getOperand(1);
5903 SDValue SrcPtr = Op.getOperand(2);
5904 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5905 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5906 DebugLoc dl = Op.getNode()->getDebugLoc();
5908 return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
5909 DAG.getIntPtrConstant(24), 8, false,
5910 DstSV, 0, SrcSV, 0);
5914 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
5915 DebugLoc dl = Op.getNode()->getDebugLoc();
5916 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5918 default: return SDValue(); // Don't custom lower most intrinsics.
5919 // Comparison intrinsics.
5920 case Intrinsic::x86_sse_comieq_ss:
5921 case Intrinsic::x86_sse_comilt_ss:
5922 case Intrinsic::x86_sse_comile_ss:
5923 case Intrinsic::x86_sse_comigt_ss:
5924 case Intrinsic::x86_sse_comige_ss:
5925 case Intrinsic::x86_sse_comineq_ss:
5926 case Intrinsic::x86_sse_ucomieq_ss:
5927 case Intrinsic::x86_sse_ucomilt_ss:
5928 case Intrinsic::x86_sse_ucomile_ss:
5929 case Intrinsic::x86_sse_ucomigt_ss:
5930 case Intrinsic::x86_sse_ucomige_ss:
5931 case Intrinsic::x86_sse_ucomineq_ss:
5932 case Intrinsic::x86_sse2_comieq_sd:
5933 case Intrinsic::x86_sse2_comilt_sd:
5934 case Intrinsic::x86_sse2_comile_sd:
5935 case Intrinsic::x86_sse2_comigt_sd:
5936 case Intrinsic::x86_sse2_comige_sd:
5937 case Intrinsic::x86_sse2_comineq_sd:
5938 case Intrinsic::x86_sse2_ucomieq_sd:
5939 case Intrinsic::x86_sse2_ucomilt_sd:
5940 case Intrinsic::x86_sse2_ucomile_sd:
5941 case Intrinsic::x86_sse2_ucomigt_sd:
5942 case Intrinsic::x86_sse2_ucomige_sd:
5943 case Intrinsic::x86_sse2_ucomineq_sd: {
5945 ISD::CondCode CC = ISD::SETCC_INVALID;
5948 case Intrinsic::x86_sse_comieq_ss:
5949 case Intrinsic::x86_sse2_comieq_sd:
5953 case Intrinsic::x86_sse_comilt_ss:
5954 case Intrinsic::x86_sse2_comilt_sd:
5958 case Intrinsic::x86_sse_comile_ss:
5959 case Intrinsic::x86_sse2_comile_sd:
5963 case Intrinsic::x86_sse_comigt_ss:
5964 case Intrinsic::x86_sse2_comigt_sd:
5968 case Intrinsic::x86_sse_comige_ss:
5969 case Intrinsic::x86_sse2_comige_sd:
5973 case Intrinsic::x86_sse_comineq_ss:
5974 case Intrinsic::x86_sse2_comineq_sd:
5978 case Intrinsic::x86_sse_ucomieq_ss:
5979 case Intrinsic::x86_sse2_ucomieq_sd:
5980 Opc = X86ISD::UCOMI;
5983 case Intrinsic::x86_sse_ucomilt_ss:
5984 case Intrinsic::x86_sse2_ucomilt_sd:
5985 Opc = X86ISD::UCOMI;
5988 case Intrinsic::x86_sse_ucomile_ss:
5989 case Intrinsic::x86_sse2_ucomile_sd:
5990 Opc = X86ISD::UCOMI;
5993 case Intrinsic::x86_sse_ucomigt_ss:
5994 case Intrinsic::x86_sse2_ucomigt_sd:
5995 Opc = X86ISD::UCOMI;
5998 case Intrinsic::x86_sse_ucomige_ss:
5999 case Intrinsic::x86_sse2_ucomige_sd:
6000 Opc = X86ISD::UCOMI;
6003 case Intrinsic::x86_sse_ucomineq_ss:
6004 case Intrinsic::x86_sse2_ucomineq_sd:
6005 Opc = X86ISD::UCOMI;
6010 SDValue LHS = Op.getOperand(1);
6011 SDValue RHS = Op.getOperand(2);
6012 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6013 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6014 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6015 DAG.getConstant(X86CC, MVT::i8), Cond);
6016 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6019 // Fix vector shift instructions where the last operand is a non-immediate
6021 case Intrinsic::x86_sse2_pslli_w:
6022 case Intrinsic::x86_sse2_pslli_d:
6023 case Intrinsic::x86_sse2_pslli_q:
6024 case Intrinsic::x86_sse2_psrli_w:
6025 case Intrinsic::x86_sse2_psrli_d:
6026 case Intrinsic::x86_sse2_psrli_q:
6027 case Intrinsic::x86_sse2_psrai_w:
6028 case Intrinsic::x86_sse2_psrai_d:
6029 case Intrinsic::x86_mmx_pslli_w:
6030 case Intrinsic::x86_mmx_pslli_d:
6031 case Intrinsic::x86_mmx_pslli_q:
6032 case Intrinsic::x86_mmx_psrli_w:
6033 case Intrinsic::x86_mmx_psrli_d:
6034 case Intrinsic::x86_mmx_psrli_q:
6035 case Intrinsic::x86_mmx_psrai_w:
6036 case Intrinsic::x86_mmx_psrai_d: {
6037 SDValue ShAmt = Op.getOperand(2);
6038 if (isa<ConstantSDNode>(ShAmt))
6041 unsigned NewIntNo = 0;
6042 MVT ShAmtVT = MVT::v4i32;
6044 case Intrinsic::x86_sse2_pslli_w:
6045 NewIntNo = Intrinsic::x86_sse2_psll_w;
6047 case Intrinsic::x86_sse2_pslli_d:
6048 NewIntNo = Intrinsic::x86_sse2_psll_d;
6050 case Intrinsic::x86_sse2_pslli_q:
6051 NewIntNo = Intrinsic::x86_sse2_psll_q;
6053 case Intrinsic::x86_sse2_psrli_w:
6054 NewIntNo = Intrinsic::x86_sse2_psrl_w;
6056 case Intrinsic::x86_sse2_psrli_d:
6057 NewIntNo = Intrinsic::x86_sse2_psrl_d;
6059 case Intrinsic::x86_sse2_psrli_q:
6060 NewIntNo = Intrinsic::x86_sse2_psrl_q;
6062 case Intrinsic::x86_sse2_psrai_w:
6063 NewIntNo = Intrinsic::x86_sse2_psra_w;
6065 case Intrinsic::x86_sse2_psrai_d:
6066 NewIntNo = Intrinsic::x86_sse2_psra_d;
6069 ShAmtVT = MVT::v2i32;
6071 case Intrinsic::x86_mmx_pslli_w:
6072 NewIntNo = Intrinsic::x86_mmx_psll_w;
6074 case Intrinsic::x86_mmx_pslli_d:
6075 NewIntNo = Intrinsic::x86_mmx_psll_d;
6077 case Intrinsic::x86_mmx_pslli_q:
6078 NewIntNo = Intrinsic::x86_mmx_psll_q;
6080 case Intrinsic::x86_mmx_psrli_w:
6081 NewIntNo = Intrinsic::x86_mmx_psrl_w;
6083 case Intrinsic::x86_mmx_psrli_d:
6084 NewIntNo = Intrinsic::x86_mmx_psrl_d;
6086 case Intrinsic::x86_mmx_psrli_q:
6087 NewIntNo = Intrinsic::x86_mmx_psrl_q;
6089 case Intrinsic::x86_mmx_psrai_w:
6090 NewIntNo = Intrinsic::x86_mmx_psra_w;
6092 case Intrinsic::x86_mmx_psrai_d:
6093 NewIntNo = Intrinsic::x86_mmx_psra_d;
6095 default: abort(); // Can't reach here.
6100 MVT VT = Op.getValueType();
6101 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT,
6102 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShAmtVT, ShAmt));
6103 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6104 DAG.getConstant(NewIntNo, MVT::i32),
6105 Op.getOperand(1), ShAmt);
6110 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
6111 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6112 DebugLoc dl = Op.getNode()->getDebugLoc();
6115 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6117 DAG.getConstant(TD->getPointerSize(),
6118 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6119 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6120 DAG.getNode(ISD::ADD, dl, getPointerTy(),
6125 // Just load the return address.
6126 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6127 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6128 RetAddrFI, NULL, 0);
6131 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
6132 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6133 MFI->setFrameAddressIsTaken(true);
6134 MVT VT = Op.getValueType();
6135 DebugLoc dl = Op.getNode()->getDebugLoc(); // FIXME probably not meaningful
6136 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6137 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6138 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6140 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
6144 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6145 SelectionDAG &DAG) {
6146 return DAG.getIntPtrConstant(2*TD->getPointerSize());
6149 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
6151 MachineFunction &MF = DAG.getMachineFunction();
6152 SDValue Chain = Op.getOperand(0);
6153 SDValue Offset = Op.getOperand(1);
6154 SDValue Handler = Op.getOperand(2);
6155 DebugLoc dl = Op.getNode()->getDebugLoc();
6157 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6159 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6161 SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
6162 DAG.getIntPtrConstant(-TD->getPointerSize()));
6163 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
6164 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0);
6165 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
6166 MF.getRegInfo().addLiveOut(StoreAddrReg);
6168 return DAG.getNode(X86ISD::EH_RETURN, dl,
6170 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6173 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6174 SelectionDAG &DAG) {
6175 SDValue Root = Op.getOperand(0);
6176 SDValue Trmp = Op.getOperand(1); // trampoline
6177 SDValue FPtr = Op.getOperand(2); // nested function
6178 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6179 DebugLoc dl = Op.getNode()->getDebugLoc();
6181 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6183 const X86InstrInfo *TII =
6184 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
6186 if (Subtarget->is64Bit()) {
6187 SDValue OutChains[6];
6189 // Large code-model.
6191 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
6192 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
6194 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
6195 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
6197 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
6199 // Load the pointer to the nested function into R11.
6200 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
6201 SDValue Addr = Trmp;
6202 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6205 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6206 DAG.getConstant(2, MVT::i64));
6207 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2, false, 2);
6209 // Load the 'nest' parameter value into R10.
6210 // R10 is specified in X86CallingConv.td
6211 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
6212 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6213 DAG.getConstant(10, MVT::i64));
6214 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6215 Addr, TrmpAddr, 10);
6217 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6218 DAG.getConstant(12, MVT::i64));
6219 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12, false, 2);
6221 // Jump to the nested function.
6222 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
6223 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6224 DAG.getConstant(20, MVT::i64));
6225 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6226 Addr, TrmpAddr, 20);
6228 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
6229 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6230 DAG.getConstant(22, MVT::i64));
6231 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
6235 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
6236 return DAG.getMergeValues(Ops, 2, dl);
6238 const Function *Func =
6239 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
6240 unsigned CC = Func->getCallingConv();
6245 assert(0 && "Unsupported calling convention");
6246 case CallingConv::C:
6247 case CallingConv::X86_StdCall: {
6248 // Pass 'nest' parameter in ECX.
6249 // Must be kept in sync with X86CallingConv.td
6252 // Check that ECX wasn't needed by an 'inreg' parameter.
6253 const FunctionType *FTy = Func->getFunctionType();
6254 const AttrListPtr &Attrs = Func->getAttributes();
6256 if (!Attrs.isEmpty() && !Func->isVarArg()) {
6257 unsigned InRegCount = 0;
6260 for (FunctionType::param_iterator I = FTy->param_begin(),
6261 E = FTy->param_end(); I != E; ++I, ++Idx)
6262 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6263 // FIXME: should only count parameters that are lowered to integers.
6264 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6266 if (InRegCount > 2) {
6267 cerr << "Nest register in use - reduce number of inreg parameters!\n";
6273 case CallingConv::X86_FastCall:
6274 case CallingConv::Fast:
6275 // Pass 'nest' parameter in EAX.
6276 // Must be kept in sync with X86CallingConv.td
6281 SDValue OutChains[4];
6284 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6285 DAG.getConstant(10, MVT::i32));
6286 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
6288 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
6289 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
6290 OutChains[0] = DAG.getStore(Root, dl,
6291 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
6294 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6295 DAG.getConstant(1, MVT::i32));
6296 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1, false, 1);
6298 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
6299 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6300 DAG.getConstant(5, MVT::i32));
6301 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
6302 TrmpAddr, 5, false, 1);
6304 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6305 DAG.getConstant(6, MVT::i32));
6306 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6, false, 1);
6309 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
6310 return DAG.getMergeValues(Ops, 2, dl);
6314 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
6316 The rounding mode is in bits 11:10 of FPSR, and has the following
6323 FLT_ROUNDS, on the other hand, expects the following:
6330 To perform the conversion, we do:
6331 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
6334 MachineFunction &MF = DAG.getMachineFunction();
6335 const TargetMachine &TM = MF.getTarget();
6336 const TargetFrameInfo &TFI = *TM.getFrameInfo();
6337 unsigned StackAlignment = TFI.getStackAlignment();
6338 MVT VT = Op.getValueType();
6339 DebugLoc dl = Op.getNode()->getDebugLoc();
6341 // Save FP Control Word to stack slot
6342 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
6343 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6345 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
6346 DAG.getEntryNode(), StackSlot);
6348 // Load FP Control Word from stack slot
6349 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0);
6351 // Transform as necessary
6353 DAG.getNode(ISD::SRL, dl, MVT::i16,
6354 DAG.getNode(ISD::AND, dl, MVT::i16,
6355 CWD, DAG.getConstant(0x800, MVT::i16)),
6356 DAG.getConstant(11, MVT::i8));
6358 DAG.getNode(ISD::SRL, dl, MVT::i16,
6359 DAG.getNode(ISD::AND, dl, MVT::i16,
6360 CWD, DAG.getConstant(0x400, MVT::i16)),
6361 DAG.getConstant(9, MVT::i8));
6364 DAG.getNode(ISD::AND, dl, MVT::i16,
6365 DAG.getNode(ISD::ADD, dl, MVT::i16,
6366 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
6367 DAG.getConstant(1, MVT::i16)),
6368 DAG.getConstant(3, MVT::i16));
6371 return DAG.getNode((VT.getSizeInBits() < 16 ?
6372 ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
6375 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
6376 MVT VT = Op.getValueType();
6378 unsigned NumBits = VT.getSizeInBits();
6379 DebugLoc dl = Op.getNode()->getDebugLoc();
6381 Op = Op.getOperand(0);
6382 if (VT == MVT::i8) {
6383 // Zero extend to i32 since there is not an i8 bsr.
6385 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6388 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
6389 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6390 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
6392 // If src is zero (i.e. bsr sets ZF), returns NumBits.
6393 SmallVector<SDValue, 4> Ops;
6395 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
6396 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6397 Ops.push_back(Op.getValue(1));
6398 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6400 // Finally xor with NumBits-1.
6401 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
6404 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6408 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
6409 MVT VT = Op.getValueType();
6411 unsigned NumBits = VT.getSizeInBits();
6412 DebugLoc dl = Op.getNode()->getDebugLoc();
6414 Op = Op.getOperand(0);
6415 if (VT == MVT::i8) {
6417 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6420 // Issue a bsf (scan bits forward) which also sets EFLAGS.
6421 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6422 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
6424 // If src is zero (i.e. bsf sets ZF), returns NumBits.
6425 SmallVector<SDValue, 4> Ops;
6427 Ops.push_back(DAG.getConstant(NumBits, OpVT));
6428 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6429 Ops.push_back(Op.getValue(1));
6430 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6433 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6437 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
6438 MVT VT = Op.getValueType();
6439 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
6440 DebugLoc dl = Op.getNode()->getDebugLoc();
6442 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
6443 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
6444 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
6445 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
6446 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
6448 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
6449 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
6450 // return AloBlo + AloBhi + AhiBlo;
6452 SDValue A = Op.getOperand(0);
6453 SDValue B = Op.getOperand(1);
6455 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6456 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6457 A, DAG.getConstant(32, MVT::i32));
6458 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6459 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6460 B, DAG.getConstant(32, MVT::i32));
6461 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6462 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6464 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6465 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6467 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6468 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6470 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6471 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6472 AloBhi, DAG.getConstant(32, MVT::i32));
6473 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6474 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6475 AhiBlo, DAG.getConstant(32, MVT::i32));
6476 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
6477 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
6482 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
6483 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
6484 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
6485 // looks for this combo and may remove the "setcc" instruction if the "setcc"
6486 // has only one use.
6487 SDNode *N = Op.getNode();
6488 SDValue LHS = N->getOperand(0);
6489 SDValue RHS = N->getOperand(1);
6490 unsigned BaseOp = 0;
6492 DebugLoc dl = Op.getNode()->getDebugLoc();
6494 switch (Op.getOpcode()) {
6495 default: assert(0 && "Unknown ovf instruction!");
6497 BaseOp = X86ISD::ADD;
6501 BaseOp = X86ISD::ADD;
6505 BaseOp = X86ISD::SUB;
6509 BaseOp = X86ISD::SUB;
6513 BaseOp = X86ISD::SMUL;
6517 BaseOp = X86ISD::UMUL;
6522 // Also sets EFLAGS.
6523 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
6524 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
6527 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
6528 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
6530 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
6534 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
6535 MVT T = Op.getValueType();
6536 DebugLoc dl = Op.getNode()->getDebugLoc();
6539 switch(T.getSimpleVT()) {
6541 assert(false && "Invalid value type!");
6542 case MVT::i8: Reg = X86::AL; size = 1; break;
6543 case MVT::i16: Reg = X86::AX; size = 2; break;
6544 case MVT::i32: Reg = X86::EAX; size = 4; break;
6546 assert(Subtarget->is64Bit() && "Node not type legal!");
6547 Reg = X86::RAX; size = 8;
6550 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
6551 Op.getOperand(2), SDValue());
6552 SDValue Ops[] = { cpIn.getValue(0),
6555 DAG.getTargetConstant(size, MVT::i8),
6557 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6558 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
6560 DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
6564 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
6565 SelectionDAG &DAG) {
6566 assert(Subtarget->is64Bit() && "Result not type legalized?");
6567 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6568 SDValue TheChain = Op.getOperand(0);
6569 DebugLoc dl = Op.getNode()->getDebugLoc();
6570 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6571 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
6572 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
6574 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
6575 DAG.getConstant(32, MVT::i8));
6577 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
6580 return DAG.getMergeValues(Ops, 2, dl);
6583 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
6584 SDNode *Node = Op.getNode();
6585 DebugLoc dl = Node->getDebugLoc();
6586 MVT T = Node->getValueType(0);
6587 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
6588 DAG.getConstant(0, T), Node->getOperand(2));
6589 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
6590 cast<AtomicSDNode>(Node)->getMemoryVT(),
6591 Node->getOperand(0),
6592 Node->getOperand(1), negOp,
6593 cast<AtomicSDNode>(Node)->getSrcValue(),
6594 cast<AtomicSDNode>(Node)->getAlignment());
6597 /// LowerOperation - Provide custom lowering hooks for some operations.
6599 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
6600 switch (Op.getOpcode()) {
6601 default: assert(0 && "Should not custom lower this!");
6602 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
6603 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
6604 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6605 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6606 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6607 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6608 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6609 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6610 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6611 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6612 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
6613 case ISD::SHL_PARTS:
6614 case ISD::SRA_PARTS:
6615 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
6616 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
6617 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
6618 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
6619 case ISD::FABS: return LowerFABS(Op, DAG);
6620 case ISD::FNEG: return LowerFNEG(Op, DAG);
6621 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6622 case ISD::SETCC: return LowerSETCC(Op, DAG);
6623 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
6624 case ISD::SELECT: return LowerSELECT(Op, DAG);
6625 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
6626 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6627 case ISD::CALL: return LowerCALL(Op, DAG);
6628 case ISD::RET: return LowerRET(Op, DAG);
6629 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
6630 case ISD::VASTART: return LowerVASTART(Op, DAG);
6631 case ISD::VAARG: return LowerVAARG(Op, DAG);
6632 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
6633 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6634 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6635 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6636 case ISD::FRAME_TO_ARGS_OFFSET:
6637 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
6638 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
6639 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
6640 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
6641 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6642 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
6643 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
6644 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
6650 case ISD::UMULO: return LowerXALUO(Op, DAG);
6651 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
6655 void X86TargetLowering::
6656 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
6657 SelectionDAG &DAG, unsigned NewOp) {
6658 MVT T = Node->getValueType(0);
6659 DebugLoc dl = Node->getDebugLoc();
6660 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
6662 SDValue Chain = Node->getOperand(0);
6663 SDValue In1 = Node->getOperand(1);
6664 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6665 Node->getOperand(2), DAG.getIntPtrConstant(0));
6666 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6667 Node->getOperand(2), DAG.getIntPtrConstant(1));
6668 // This is a generalized SDNode, not an AtomicSDNode, so it doesn't
6669 // have a MemOperand. Pass the info through as a normal operand.
6670 SDValue LSI = DAG.getMemOperand(cast<MemSDNode>(Node)->getMemOperand());
6671 SDValue Ops[] = { Chain, In1, In2L, In2H, LSI };
6672 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6673 SDValue Result = DAG.getNode(NewOp, dl, Tys, Ops, 5);
6674 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
6675 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6676 Results.push_back(Result.getValue(2));
6679 /// ReplaceNodeResults - Replace a node with an illegal result type
6680 /// with a new node built out of custom code.
6681 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
6682 SmallVectorImpl<SDValue>&Results,
6683 SelectionDAG &DAG) {
6684 DebugLoc dl = N->getDebugLoc();
6685 switch (N->getOpcode()) {
6687 assert(false && "Do not know how to custom type legalize this operation!");
6689 case ISD::FP_TO_SINT: {
6690 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(SDValue(N, 0), DAG);
6691 SDValue FIST = Vals.first, StackSlot = Vals.second;
6692 if (FIST.getNode() != 0) {
6693 MVT VT = N->getValueType(0);
6694 // Return a load from the stack slot.
6695 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0));
6699 case ISD::READCYCLECOUNTER: {
6700 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6701 SDValue TheChain = N->getOperand(0);
6702 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6703 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
6705 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
6707 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
6708 SDValue Ops[] = { eax, edx };
6709 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
6710 Results.push_back(edx.getValue(1));
6713 case ISD::ATOMIC_CMP_SWAP: {
6714 MVT T = N->getValueType(0);
6715 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
6716 SDValue cpInL, cpInH;
6717 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
6718 DAG.getConstant(0, MVT::i32));
6719 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
6720 DAG.getConstant(1, MVT::i32));
6721 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
6722 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
6724 SDValue swapInL, swapInH;
6725 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
6726 DAG.getConstant(0, MVT::i32));
6727 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
6728 DAG.getConstant(1, MVT::i32));
6729 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
6731 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
6732 swapInL.getValue(1));
6733 SDValue Ops[] = { swapInH.getValue(0),
6735 swapInH.getValue(1) };
6736 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6737 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
6738 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
6739 MVT::i32, Result.getValue(1));
6740 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
6741 MVT::i32, cpOutL.getValue(2));
6742 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
6743 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6744 Results.push_back(cpOutH.getValue(1));
6747 case ISD::ATOMIC_LOAD_ADD:
6748 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
6750 case ISD::ATOMIC_LOAD_AND:
6751 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
6753 case ISD::ATOMIC_LOAD_NAND:
6754 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
6756 case ISD::ATOMIC_LOAD_OR:
6757 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
6759 case ISD::ATOMIC_LOAD_SUB:
6760 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
6762 case ISD::ATOMIC_LOAD_XOR:
6763 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
6765 case ISD::ATOMIC_SWAP:
6766 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
6771 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
6773 default: return NULL;
6774 case X86ISD::BSF: return "X86ISD::BSF";
6775 case X86ISD::BSR: return "X86ISD::BSR";
6776 case X86ISD::SHLD: return "X86ISD::SHLD";
6777 case X86ISD::SHRD: return "X86ISD::SHRD";
6778 case X86ISD::FAND: return "X86ISD::FAND";
6779 case X86ISD::FOR: return "X86ISD::FOR";
6780 case X86ISD::FXOR: return "X86ISD::FXOR";
6781 case X86ISD::FSRL: return "X86ISD::FSRL";
6782 case X86ISD::FILD: return "X86ISD::FILD";
6783 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
6784 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
6785 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
6786 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
6787 case X86ISD::FLD: return "X86ISD::FLD";
6788 case X86ISD::FST: return "X86ISD::FST";
6789 case X86ISD::CALL: return "X86ISD::CALL";
6790 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
6791 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
6792 case X86ISD::BT: return "X86ISD::BT";
6793 case X86ISD::CMP: return "X86ISD::CMP";
6794 case X86ISD::COMI: return "X86ISD::COMI";
6795 case X86ISD::UCOMI: return "X86ISD::UCOMI";
6796 case X86ISD::SETCC: return "X86ISD::SETCC";
6797 case X86ISD::CMOV: return "X86ISD::CMOV";
6798 case X86ISD::BRCOND: return "X86ISD::BRCOND";
6799 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
6800 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
6801 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
6802 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
6803 case X86ISD::Wrapper: return "X86ISD::Wrapper";
6804 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
6805 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
6806 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
6807 case X86ISD::PINSRB: return "X86ISD::PINSRB";
6808 case X86ISD::PINSRW: return "X86ISD::PINSRW";
6809 case X86ISD::FMAX: return "X86ISD::FMAX";
6810 case X86ISD::FMIN: return "X86ISD::FMIN";
6811 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
6812 case X86ISD::FRCP: return "X86ISD::FRCP";
6813 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
6814 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
6815 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
6816 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
6817 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
6818 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
6819 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
6820 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
6821 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
6822 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
6823 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
6824 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
6825 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
6826 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
6827 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
6828 case X86ISD::VSHL: return "X86ISD::VSHL";
6829 case X86ISD::VSRL: return "X86ISD::VSRL";
6830 case X86ISD::CMPPD: return "X86ISD::CMPPD";
6831 case X86ISD::CMPPS: return "X86ISD::CMPPS";
6832 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
6833 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
6834 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
6835 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
6836 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
6837 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
6838 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
6839 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
6840 case X86ISD::ADD: return "X86ISD::ADD";
6841 case X86ISD::SUB: return "X86ISD::SUB";
6842 case X86ISD::SMUL: return "X86ISD::SMUL";
6843 case X86ISD::UMUL: return "X86ISD::UMUL";
6847 // isLegalAddressingMode - Return true if the addressing mode represented
6848 // by AM is legal for this target, for a load/store of the specified type.
6849 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
6850 const Type *Ty) const {
6851 // X86 supports extremely general addressing modes.
6853 // X86 allows a sign-extended 32-bit immediate field as a displacement.
6854 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
6858 // We can only fold this if we don't need an extra load.
6859 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
6861 // If BaseGV requires a register, we cannot also have a BaseReg.
6862 if (Subtarget->GVRequiresRegister(AM.BaseGV, getTargetMachine(), false) &&
6866 // X86-64 only supports addr of globals in small code model.
6867 if (Subtarget->is64Bit()) {
6868 if (getTargetMachine().getCodeModel() != CodeModel::Small)
6870 // If lower 4G is not available, then we must use rip-relative addressing.
6871 if (AM.BaseOffs || AM.Scale > 1)
6882 // These scales always work.
6887 // These scales are formed with basereg+scalereg. Only accept if there is
6892 default: // Other stuff never works.
6900 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
6901 if (!Ty1->isInteger() || !Ty2->isInteger())
6903 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6904 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6905 if (NumBits1 <= NumBits2)
6907 return Subtarget->is64Bit() || NumBits1 < 64;
6910 bool X86TargetLowering::isTruncateFree(MVT VT1, MVT VT2) const {
6911 if (!VT1.isInteger() || !VT2.isInteger())
6913 unsigned NumBits1 = VT1.getSizeInBits();
6914 unsigned NumBits2 = VT2.getSizeInBits();
6915 if (NumBits1 <= NumBits2)
6917 return Subtarget->is64Bit() || NumBits1 < 64;
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(SDValue Mask, MVT VT) const {
6926 // Only do shuffles on 128-bit vector types for now.
6927 if (VT.getSizeInBits() == 64) return false;
6928 return (Mask.getNode()->getNumOperands() <= 4 ||
6929 isIdentityMask(Mask.getNode()) ||
6930 isIdentityMask(Mask.getNode(), true) ||
6931 isSplatMask(Mask.getNode()) ||
6932 isPSHUFHW_PSHUFLWMask(Mask.getNode()) ||
6933 X86::isUNPCKLMask(Mask.getNode()) ||
6934 X86::isUNPCKHMask(Mask.getNode()) ||
6935 X86::isUNPCKL_v_undef_Mask(Mask.getNode()) ||
6936 X86::isUNPCKH_v_undef_Mask(Mask.getNode()));
6940 X86TargetLowering::isVectorClearMaskLegal(const std::vector<SDValue> &BVOps,
6941 MVT EVT, SelectionDAG &DAG) const {
6942 unsigned NumElts = BVOps.size();
6943 // Only do shuffles on 128-bit vector types for now.
6944 if (EVT.getSizeInBits() * NumElts == 64) return false;
6945 if (NumElts == 2) return true;
6947 return (isMOVLMask(&BVOps[0], 4) ||
6948 isCommutedMOVL(&BVOps[0], 4, true) ||
6949 isSHUFPMask(&BVOps[0], 4) ||
6950 isCommutedSHUFP(&BVOps[0], 4));
6955 //===----------------------------------------------------------------------===//
6956 // X86 Scheduler Hooks
6957 //===----------------------------------------------------------------------===//
6959 // private utility function
6961 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
6962 MachineBasicBlock *MBB,
6970 TargetRegisterClass *RC,
6972 // For the atomic bitwise operator, we generate
6975 // ld t1 = [bitinstr.addr]
6976 // op t2 = t1, [bitinstr.val]
6978 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
6980 // fallthrough -->nextMBB
6981 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6982 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6983 MachineFunction::iterator MBBIter = MBB;
6986 /// First build the CFG
6987 MachineFunction *F = MBB->getParent();
6988 MachineBasicBlock *thisMBB = MBB;
6989 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6990 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6991 F->insert(MBBIter, newMBB);
6992 F->insert(MBBIter, nextMBB);
6994 // Move all successors to thisMBB to nextMBB
6995 nextMBB->transferSuccessors(thisMBB);
6997 // Update thisMBB to fall through to newMBB
6998 thisMBB->addSuccessor(newMBB);
7000 // newMBB jumps to itself and fall through to nextMBB
7001 newMBB->addSuccessor(nextMBB);
7002 newMBB->addSuccessor(newMBB);
7004 // Insert instructions into newMBB based on incoming instruction
7005 assert(bInstr->getNumOperands() < 8 && "unexpected number of operands");
7006 DebugLoc dl = bInstr->getDebugLoc();
7007 MachineOperand& destOper = bInstr->getOperand(0);
7008 MachineOperand* argOpers[6];
7009 int numArgs = bInstr->getNumOperands() - 1;
7010 for (int i=0; i < numArgs; ++i)
7011 argOpers[i] = &bInstr->getOperand(i+1);
7013 // x86 address has 4 operands: base, index, scale, and displacement
7014 int lastAddrIndx = 3; // [0,3]
7017 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7018 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7019 for (int i=0; i <= lastAddrIndx; ++i)
7020 (*MIB).addOperand(*argOpers[i]);
7022 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7024 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7029 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7030 assert((argOpers[valArgIndx]->isReg() ||
7031 argOpers[valArgIndx]->isImm()) &&
7033 if (argOpers[valArgIndx]->isReg())
7034 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7036 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7038 (*MIB).addOperand(*argOpers[valArgIndx]);
7040 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7043 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7044 for (int i=0; i <= lastAddrIndx; ++i)
7045 (*MIB).addOperand(*argOpers[i]);
7047 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7048 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7050 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7054 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7056 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7060 // private utility function: 64 bit atomics on 32 bit host.
7062 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7063 MachineBasicBlock *MBB,
7069 // For the atomic bitwise operator, we generate
7070 // thisMBB (instructions are in pairs, except cmpxchg8b)
7071 // ld t1,t2 = [bitinstr.addr]
7073 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7074 // op t5, t6 <- out1, out2, [bitinstr.val]
7075 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
7076 // mov ECX, EBX <- t5, t6
7077 // mov EAX, EDX <- t1, t2
7078 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
7079 // mov t3, t4 <- EAX, EDX
7081 // result in out1, out2
7082 // fallthrough -->nextMBB
7084 const TargetRegisterClass *RC = X86::GR32RegisterClass;
7085 const unsigned LoadOpc = X86::MOV32rm;
7086 const unsigned copyOpc = X86::MOV32rr;
7087 const unsigned NotOpc = X86::NOT32r;
7088 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7089 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7090 MachineFunction::iterator MBBIter = MBB;
7093 /// First build the CFG
7094 MachineFunction *F = MBB->getParent();
7095 MachineBasicBlock *thisMBB = MBB;
7096 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7097 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7098 F->insert(MBBIter, newMBB);
7099 F->insert(MBBIter, nextMBB);
7101 // Move all successors to thisMBB to nextMBB
7102 nextMBB->transferSuccessors(thisMBB);
7104 // Update thisMBB to fall through to newMBB
7105 thisMBB->addSuccessor(newMBB);
7107 // newMBB jumps to itself and fall through to nextMBB
7108 newMBB->addSuccessor(nextMBB);
7109 newMBB->addSuccessor(newMBB);
7111 DebugLoc dl = bInstr->getDebugLoc();
7112 // Insert instructions into newMBB based on incoming instruction
7113 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7114 assert(bInstr->getNumOperands() < 18 && "unexpected number of operands");
7115 MachineOperand& dest1Oper = bInstr->getOperand(0);
7116 MachineOperand& dest2Oper = bInstr->getOperand(1);
7117 MachineOperand* argOpers[6];
7118 for (int i=0; i < 6; ++i)
7119 argOpers[i] = &bInstr->getOperand(i+2);
7121 // x86 address has 4 operands: base, index, scale, and displacement
7122 int lastAddrIndx = 3; // [0,3]
7124 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7125 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
7126 for (int i=0; i <= lastAddrIndx; ++i)
7127 (*MIB).addOperand(*argOpers[i]);
7128 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7129 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
7130 // add 4 to displacement.
7131 for (int i=0; i <= lastAddrIndx-1; ++i)
7132 (*MIB).addOperand(*argOpers[i]);
7133 MachineOperand newOp3 = *(argOpers[3]);
7135 newOp3.setImm(newOp3.getImm()+4);
7137 newOp3.setOffset(newOp3.getOffset()+4);
7138 (*MIB).addOperand(newOp3);
7140 // t3/4 are defined later, at the bottom of the loop
7141 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
7142 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
7143 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
7144 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
7145 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
7146 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
7148 unsigned tt1 = F->getRegInfo().createVirtualRegister(RC);
7149 unsigned tt2 = F->getRegInfo().createVirtualRegister(RC);
7151 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt1).addReg(t1);
7152 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt2).addReg(t2);
7158 assert((argOpers[4]->isReg() || argOpers[4]->isImm()) &&
7160 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
7161 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
7162 if (argOpers[4]->isReg())
7163 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
7165 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
7166 if (regOpcL != X86::MOV32rr)
7168 (*MIB).addOperand(*argOpers[4]);
7169 assert(argOpers[5]->isReg() == argOpers[4]->isReg());
7170 assert(argOpers[5]->isImm() == argOpers[4]->isImm());
7171 if (argOpers[5]->isReg())
7172 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
7174 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
7175 if (regOpcH != X86::MOV32rr)
7177 (*MIB).addOperand(*argOpers[5]);
7179 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
7181 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
7184 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
7186 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
7189 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
7190 for (int i=0; i <= lastAddrIndx; ++i)
7191 (*MIB).addOperand(*argOpers[i]);
7193 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7194 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7196 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
7197 MIB.addReg(X86::EAX);
7198 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
7199 MIB.addReg(X86::EDX);
7202 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7204 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7208 // private utility function
7210 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
7211 MachineBasicBlock *MBB,
7213 // For the atomic min/max operator, we generate
7216 // ld t1 = [min/max.addr]
7217 // mov t2 = [min/max.val]
7219 // cmov[cond] t2 = t1
7221 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7223 // fallthrough -->nextMBB
7225 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7226 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7227 MachineFunction::iterator MBBIter = MBB;
7230 /// First build the CFG
7231 MachineFunction *F = MBB->getParent();
7232 MachineBasicBlock *thisMBB = MBB;
7233 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7234 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7235 F->insert(MBBIter, newMBB);
7236 F->insert(MBBIter, nextMBB);
7238 // Move all successors to thisMBB to nextMBB
7239 nextMBB->transferSuccessors(thisMBB);
7241 // Update thisMBB to fall through to newMBB
7242 thisMBB->addSuccessor(newMBB);
7244 // newMBB jumps to newMBB and fall through to nextMBB
7245 newMBB->addSuccessor(nextMBB);
7246 newMBB->addSuccessor(newMBB);
7248 DebugLoc dl = mInstr->getDebugLoc();
7249 // Insert instructions into newMBB based on incoming instruction
7250 assert(mInstr->getNumOperands() < 8 && "unexpected number of operands");
7251 MachineOperand& destOper = mInstr->getOperand(0);
7252 MachineOperand* argOpers[6];
7253 int numArgs = mInstr->getNumOperands() - 1;
7254 for (int i=0; i < numArgs; ++i)
7255 argOpers[i] = &mInstr->getOperand(i+1);
7257 // x86 address has 4 operands: base, index, scale, and displacement
7258 int lastAddrIndx = 3; // [0,3]
7261 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7262 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
7263 for (int i=0; i <= lastAddrIndx; ++i)
7264 (*MIB).addOperand(*argOpers[i]);
7266 // We only support register and immediate values
7267 assert((argOpers[valArgIndx]->isReg() ||
7268 argOpers[valArgIndx]->isImm()) &&
7271 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7272 if (argOpers[valArgIndx]->isReg())
7273 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7275 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7276 (*MIB).addOperand(*argOpers[valArgIndx]);
7278 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
7281 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
7286 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7287 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
7291 // Cmp and exchange if none has modified the memory location
7292 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
7293 for (int i=0; i <= lastAddrIndx; ++i)
7294 (*MIB).addOperand(*argOpers[i]);
7296 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7297 (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
7299 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
7300 MIB.addReg(X86::EAX);
7303 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7305 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
7311 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7312 MachineBasicBlock *BB) {
7313 DebugLoc dl = MI->getDebugLoc();
7314 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7315 switch (MI->getOpcode()) {
7316 default: assert(false && "Unexpected instr type to insert");
7317 case X86::CMOV_V1I64:
7318 case X86::CMOV_FR32:
7319 case X86::CMOV_FR64:
7320 case X86::CMOV_V4F32:
7321 case X86::CMOV_V2F64:
7322 case X86::CMOV_V2I64: {
7323 // To "insert" a SELECT_CC instruction, we actually have to insert the
7324 // diamond control-flow pattern. The incoming instruction knows the
7325 // destination vreg to set, the condition code register to branch on, the
7326 // true/false values to select between, and a branch opcode to use.
7327 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7328 MachineFunction::iterator It = BB;
7334 // cmpTY ccX, r1, r2
7336 // fallthrough --> copy0MBB
7337 MachineBasicBlock *thisMBB = BB;
7338 MachineFunction *F = BB->getParent();
7339 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7340 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7342 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
7343 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
7344 F->insert(It, copy0MBB);
7345 F->insert(It, sinkMBB);
7346 // Update machine-CFG edges by transferring all successors of the current
7347 // block to the new block which will contain the Phi node for the select.
7348 sinkMBB->transferSuccessors(BB);
7350 // Add the true and fallthrough blocks as its successors.
7351 BB->addSuccessor(copy0MBB);
7352 BB->addSuccessor(sinkMBB);
7355 // %FalseValue = ...
7356 // # fallthrough to sinkMBB
7359 // Update machine-CFG edges
7360 BB->addSuccessor(sinkMBB);
7363 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7366 BuildMI(BB, dl, TII->get(X86::PHI), MI->getOperand(0).getReg())
7367 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7368 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7370 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7374 case X86::FP32_TO_INT16_IN_MEM:
7375 case X86::FP32_TO_INT32_IN_MEM:
7376 case X86::FP32_TO_INT64_IN_MEM:
7377 case X86::FP64_TO_INT16_IN_MEM:
7378 case X86::FP64_TO_INT32_IN_MEM:
7379 case X86::FP64_TO_INT64_IN_MEM:
7380 case X86::FP80_TO_INT16_IN_MEM:
7381 case X86::FP80_TO_INT32_IN_MEM:
7382 case X86::FP80_TO_INT64_IN_MEM: {
7383 // Change the floating point control register to use "round towards zero"
7384 // mode when truncating to an integer value.
7385 MachineFunction *F = BB->getParent();
7386 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
7387 addFrameReference(BuildMI(BB, dl, TII->get(X86::FNSTCW16m)), CWFrameIdx);
7389 // Load the old value of the high byte of the control word...
7391 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
7392 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16rm), OldCW),
7395 // Set the high part to be round to zero...
7396 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mi)), CWFrameIdx)
7399 // Reload the modified control word now...
7400 addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7402 // Restore the memory image of control word to original value
7403 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mr)), CWFrameIdx)
7406 // Get the X86 opcode to use.
7408 switch (MI->getOpcode()) {
7409 default: assert(0 && "illegal opcode!");
7410 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
7411 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
7412 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
7413 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
7414 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
7415 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
7416 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
7417 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
7418 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
7422 MachineOperand &Op = MI->getOperand(0);
7424 AM.BaseType = X86AddressMode::RegBase;
7425 AM.Base.Reg = Op.getReg();
7427 AM.BaseType = X86AddressMode::FrameIndexBase;
7428 AM.Base.FrameIndex = Op.getIndex();
7430 Op = MI->getOperand(1);
7432 AM.Scale = Op.getImm();
7433 Op = MI->getOperand(2);
7435 AM.IndexReg = Op.getImm();
7436 Op = MI->getOperand(3);
7437 if (Op.isGlobal()) {
7438 AM.GV = Op.getGlobal();
7440 AM.Disp = Op.getImm();
7442 addFullAddress(BuildMI(BB, dl, TII->get(Opc)), AM)
7443 .addReg(MI->getOperand(4).getReg());
7445 // Reload the original control word now.
7446 addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7448 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7451 case X86::ATOMAND32:
7452 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7453 X86::AND32ri, X86::MOV32rm,
7454 X86::LCMPXCHG32, X86::MOV32rr,
7455 X86::NOT32r, X86::EAX,
7456 X86::GR32RegisterClass);
7458 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
7459 X86::OR32ri, X86::MOV32rm,
7460 X86::LCMPXCHG32, X86::MOV32rr,
7461 X86::NOT32r, X86::EAX,
7462 X86::GR32RegisterClass);
7463 case X86::ATOMXOR32:
7464 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
7465 X86::XOR32ri, X86::MOV32rm,
7466 X86::LCMPXCHG32, X86::MOV32rr,
7467 X86::NOT32r, X86::EAX,
7468 X86::GR32RegisterClass);
7469 case X86::ATOMNAND32:
7470 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7471 X86::AND32ri, X86::MOV32rm,
7472 X86::LCMPXCHG32, X86::MOV32rr,
7473 X86::NOT32r, X86::EAX,
7474 X86::GR32RegisterClass, true);
7475 case X86::ATOMMIN32:
7476 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
7477 case X86::ATOMMAX32:
7478 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
7479 case X86::ATOMUMIN32:
7480 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
7481 case X86::ATOMUMAX32:
7482 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
7484 case X86::ATOMAND16:
7485 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7486 X86::AND16ri, X86::MOV16rm,
7487 X86::LCMPXCHG16, X86::MOV16rr,
7488 X86::NOT16r, X86::AX,
7489 X86::GR16RegisterClass);
7491 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
7492 X86::OR16ri, X86::MOV16rm,
7493 X86::LCMPXCHG16, X86::MOV16rr,
7494 X86::NOT16r, X86::AX,
7495 X86::GR16RegisterClass);
7496 case X86::ATOMXOR16:
7497 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
7498 X86::XOR16ri, X86::MOV16rm,
7499 X86::LCMPXCHG16, X86::MOV16rr,
7500 X86::NOT16r, X86::AX,
7501 X86::GR16RegisterClass);
7502 case X86::ATOMNAND16:
7503 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7504 X86::AND16ri, X86::MOV16rm,
7505 X86::LCMPXCHG16, X86::MOV16rr,
7506 X86::NOT16r, X86::AX,
7507 X86::GR16RegisterClass, true);
7508 case X86::ATOMMIN16:
7509 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
7510 case X86::ATOMMAX16:
7511 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
7512 case X86::ATOMUMIN16:
7513 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
7514 case X86::ATOMUMAX16:
7515 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
7518 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7519 X86::AND8ri, X86::MOV8rm,
7520 X86::LCMPXCHG8, X86::MOV8rr,
7521 X86::NOT8r, X86::AL,
7522 X86::GR8RegisterClass);
7524 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
7525 X86::OR8ri, X86::MOV8rm,
7526 X86::LCMPXCHG8, X86::MOV8rr,
7527 X86::NOT8r, X86::AL,
7528 X86::GR8RegisterClass);
7530 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
7531 X86::XOR8ri, X86::MOV8rm,
7532 X86::LCMPXCHG8, X86::MOV8rr,
7533 X86::NOT8r, X86::AL,
7534 X86::GR8RegisterClass);
7535 case X86::ATOMNAND8:
7536 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7537 X86::AND8ri, X86::MOV8rm,
7538 X86::LCMPXCHG8, X86::MOV8rr,
7539 X86::NOT8r, X86::AL,
7540 X86::GR8RegisterClass, true);
7541 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
7542 // This group is for 64-bit host.
7543 case X86::ATOMAND64:
7544 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7545 X86::AND64ri32, X86::MOV64rm,
7546 X86::LCMPXCHG64, X86::MOV64rr,
7547 X86::NOT64r, X86::RAX,
7548 X86::GR64RegisterClass);
7550 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
7551 X86::OR64ri32, X86::MOV64rm,
7552 X86::LCMPXCHG64, X86::MOV64rr,
7553 X86::NOT64r, X86::RAX,
7554 X86::GR64RegisterClass);
7555 case X86::ATOMXOR64:
7556 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
7557 X86::XOR64ri32, X86::MOV64rm,
7558 X86::LCMPXCHG64, X86::MOV64rr,
7559 X86::NOT64r, X86::RAX,
7560 X86::GR64RegisterClass);
7561 case X86::ATOMNAND64:
7562 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7563 X86::AND64ri32, X86::MOV64rm,
7564 X86::LCMPXCHG64, X86::MOV64rr,
7565 X86::NOT64r, X86::RAX,
7566 X86::GR64RegisterClass, true);
7567 case X86::ATOMMIN64:
7568 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
7569 case X86::ATOMMAX64:
7570 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
7571 case X86::ATOMUMIN64:
7572 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
7573 case X86::ATOMUMAX64:
7574 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
7576 // This group does 64-bit operations on a 32-bit host.
7577 case X86::ATOMAND6432:
7578 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7579 X86::AND32rr, X86::AND32rr,
7580 X86::AND32ri, X86::AND32ri,
7582 case X86::ATOMOR6432:
7583 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7584 X86::OR32rr, X86::OR32rr,
7585 X86::OR32ri, X86::OR32ri,
7587 case X86::ATOMXOR6432:
7588 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7589 X86::XOR32rr, X86::XOR32rr,
7590 X86::XOR32ri, X86::XOR32ri,
7592 case X86::ATOMNAND6432:
7593 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7594 X86::AND32rr, X86::AND32rr,
7595 X86::AND32ri, X86::AND32ri,
7597 case X86::ATOMADD6432:
7598 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7599 X86::ADD32rr, X86::ADC32rr,
7600 X86::ADD32ri, X86::ADC32ri,
7602 case X86::ATOMSUB6432:
7603 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7604 X86::SUB32rr, X86::SBB32rr,
7605 X86::SUB32ri, X86::SBB32ri,
7607 case X86::ATOMSWAP6432:
7608 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7609 X86::MOV32rr, X86::MOV32rr,
7610 X86::MOV32ri, X86::MOV32ri,
7615 //===----------------------------------------------------------------------===//
7616 // X86 Optimization Hooks
7617 //===----------------------------------------------------------------------===//
7619 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
7623 const SelectionDAG &DAG,
7624 unsigned Depth) const {
7625 unsigned Opc = Op.getOpcode();
7626 assert((Opc >= ISD::BUILTIN_OP_END ||
7627 Opc == ISD::INTRINSIC_WO_CHAIN ||
7628 Opc == ISD::INTRINSIC_W_CHAIN ||
7629 Opc == ISD::INTRINSIC_VOID) &&
7630 "Should use MaskedValueIsZero if you don't know whether Op"
7631 " is a target node!");
7633 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
7640 // These nodes' second result is a boolean.
7641 if (Op.getResNo() == 0)
7645 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
7646 Mask.getBitWidth() - 1);
7651 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
7652 /// node is a GlobalAddress + offset.
7653 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
7654 GlobalValue* &GA, int64_t &Offset) const{
7655 if (N->getOpcode() == X86ISD::Wrapper) {
7656 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
7657 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
7658 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
7662 return TargetLowering::isGAPlusOffset(N, GA, Offset);
7665 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
7666 const TargetLowering &TLI) {
7669 if (TLI.isGAPlusOffset(Base, GV, Offset))
7670 return (GV->getAlignment() >= N && (Offset % N) == 0);
7671 // DAG combine handles the stack object case.
7675 static bool EltsFromConsecutiveLoads(SDNode *N, SDValue PermMask,
7676 unsigned NumElems, MVT EVT,
7678 SelectionDAG &DAG, MachineFrameInfo *MFI,
7679 const TargetLowering &TLI) {
7681 for (unsigned i = 0; i < NumElems; ++i) {
7682 SDValue Idx = PermMask.getOperand(i);
7683 if (Idx.getOpcode() == ISD::UNDEF) {
7689 SDValue Elt = DAG.getShuffleScalarElt(N, i);
7690 if (!Elt.getNode() ||
7691 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
7694 Base = Elt.getNode();
7695 if (Base->getOpcode() == ISD::UNDEF)
7699 if (Elt.getOpcode() == ISD::UNDEF)
7702 if (!TLI.isConsecutiveLoad(Elt.getNode(), Base,
7703 EVT.getSizeInBits()/8, i, MFI))
7709 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
7710 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
7711 /// if the load addresses are consecutive, non-overlapping, and in the right
7713 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
7714 const TargetLowering &TLI) {
7715 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7716 DebugLoc dl = N->getDebugLoc();
7717 MVT VT = N->getValueType(0);
7718 MVT EVT = VT.getVectorElementType();
7719 SDValue PermMask = N->getOperand(2);
7720 unsigned NumElems = PermMask.getNumOperands();
7721 SDNode *Base = NULL;
7722 if (!EltsFromConsecutiveLoads(N, PermMask, NumElems, EVT, Base,
7726 LoadSDNode *LD = cast<LoadSDNode>(Base);
7727 if (isBaseAlignmentOfN(16, Base->getOperand(1).getNode(), TLI))
7728 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
7729 LD->getSrcValue(), LD->getSrcValueOffset(),
7731 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
7732 LD->getSrcValue(), LD->getSrcValueOffset(),
7733 LD->isVolatile(), LD->getAlignment());
7736 /// PerformBuildVectorCombine - build_vector 0,(load i64 / f64) -> movq / movsd.
7737 static SDValue PerformBuildVectorCombine(SDNode *N, SelectionDAG &DAG,
7738 TargetLowering::DAGCombinerInfo &DCI,
7739 const X86Subtarget *Subtarget,
7740 const TargetLowering &TLI) {
7741 unsigned NumOps = N->getNumOperands();
7742 DebugLoc dl = N->getDebugLoc();
7744 // Ignore single operand BUILD_VECTOR.
7748 MVT VT = N->getValueType(0);
7749 MVT EVT = VT.getVectorElementType();
7750 if ((EVT != MVT::i64 && EVT != MVT::f64) || Subtarget->is64Bit())
7751 // We are looking for load i64 and zero extend. We want to transform
7752 // it before legalizer has a chance to expand it. Also look for i64
7753 // BUILD_PAIR bit casted to f64.
7755 // This must be an insertion into a zero vector.
7756 SDValue HighElt = N->getOperand(1);
7757 if (!isZeroNode(HighElt))
7760 // Value must be a load.
7761 SDNode *Base = N->getOperand(0).getNode();
7762 if (!isa<LoadSDNode>(Base)) {
7763 if (Base->getOpcode() != ISD::BIT_CONVERT)
7765 Base = Base->getOperand(0).getNode();
7766 if (!isa<LoadSDNode>(Base))
7770 // Transform it into VZEXT_LOAD addr.
7771 LoadSDNode *LD = cast<LoadSDNode>(Base);
7773 // Load must not be an extload.
7774 if (LD->getExtensionType() != ISD::NON_EXTLOAD)
7777 // Load type should legal type so we don't have to legalize it.
7778 if (!TLI.isTypeLegal(VT))
7781 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
7782 SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
7783 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
7784 TargetLowering::TargetLoweringOpt TLO(DAG);
7785 TLO.CombineTo(SDValue(Base, 1), ResNode.getValue(1));
7786 DCI.CommitTargetLoweringOpt(TLO);
7790 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
7791 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
7792 const X86Subtarget *Subtarget) {
7793 DebugLoc dl = N->getDebugLoc();
7794 SDValue Cond = N->getOperand(0);
7796 // If we have SSE[12] support, try to form min/max nodes.
7797 if (Subtarget->hasSSE2() &&
7798 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
7799 if (Cond.getOpcode() == ISD::SETCC) {
7800 // Get the LHS/RHS of the select.
7801 SDValue LHS = N->getOperand(1);
7802 SDValue RHS = N->getOperand(2);
7803 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
7805 unsigned Opcode = 0;
7806 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
7809 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
7812 if (!UnsafeFPMath) break;
7814 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
7816 Opcode = X86ISD::FMIN;
7819 case ISD::SETOGT: // (X > Y) ? X : Y -> max
7822 if (!UnsafeFPMath) break;
7824 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
7826 Opcode = X86ISD::FMAX;
7829 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
7832 case ISD::SETOGT: // (X > Y) ? Y : X -> min
7835 if (!UnsafeFPMath) break;
7837 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
7839 Opcode = X86ISD::FMIN;
7842 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
7845 if (!UnsafeFPMath) break;
7847 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
7849 Opcode = X86ISD::FMAX;
7855 return DAG.getNode(Opcode, dl, N->getValueType(0), LHS, RHS);
7863 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
7865 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
7866 const X86Subtarget *Subtarget) {
7867 // On X86 with SSE2 support, we can transform this to a vector shift if
7868 // all elements are shifted by the same amount. We can't do this in legalize
7869 // because the a constant vector is typically transformed to a constant pool
7870 // so we have no knowledge of the shift amount.
7871 if (!Subtarget->hasSSE2())
7874 MVT VT = N->getValueType(0);
7875 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
7878 SDValue ShAmtOp = N->getOperand(1);
7879 MVT EltVT = VT.getVectorElementType();
7880 DebugLoc dl = N->getDebugLoc();
7882 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
7883 unsigned NumElts = VT.getVectorNumElements();
7885 for (; i != NumElts; ++i) {
7886 SDValue Arg = ShAmtOp.getOperand(i);
7887 if (Arg.getOpcode() == ISD::UNDEF) continue;
7891 for (; i != NumElts; ++i) {
7892 SDValue Arg = ShAmtOp.getOperand(i);
7893 if (Arg.getOpcode() == ISD::UNDEF) continue;
7894 if (Arg != BaseShAmt) {
7898 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
7899 isSplatMask(ShAmtOp.getOperand(2).getNode())) {
7900 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, ShAmtOp,
7901 DAG.getIntPtrConstant(0));
7905 if (EltVT.bitsGT(MVT::i32))
7906 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
7907 else if (EltVT.bitsLT(MVT::i32))
7908 BaseShAmt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BaseShAmt);
7910 // The shift amount is identical so we can do a vector shift.
7911 SDValue ValOp = N->getOperand(0);
7912 switch (N->getOpcode()) {
7914 assert(0 && "Unknown shift opcode!");
7917 if (VT == MVT::v2i64)
7918 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7919 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7921 if (VT == MVT::v4i32)
7922 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7923 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
7925 if (VT == MVT::v8i16)
7926 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7927 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
7931 if (VT == MVT::v4i32)
7932 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7933 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
7935 if (VT == MVT::v8i16)
7936 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7937 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
7941 if (VT == MVT::v2i64)
7942 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7943 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7945 if (VT == MVT::v4i32)
7946 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7947 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
7949 if (VT == MVT::v8i16)
7950 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7951 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
7958 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
7959 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
7960 const X86Subtarget *Subtarget) {
7961 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
7962 // the FP state in cases where an emms may be missing.
7963 // A preferable solution to the general problem is to figure out the right
7964 // places to insert EMMS. This qualifies as a quick hack.
7965 StoreSDNode *St = cast<StoreSDNode>(N);
7966 if (St->getValue().getValueType().isVector() &&
7967 St->getValue().getValueType().getSizeInBits() == 64 &&
7968 isa<LoadSDNode>(St->getValue()) &&
7969 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
7970 St->getChain().hasOneUse() && !St->isVolatile()) {
7971 SDNode* LdVal = St->getValue().getNode();
7973 int TokenFactorIndex = -1;
7974 SmallVector<SDValue, 8> Ops;
7975 SDNode* ChainVal = St->getChain().getNode();
7976 // Must be a store of a load. We currently handle two cases: the load
7977 // is a direct child, and it's under an intervening TokenFactor. It is
7978 // possible to dig deeper under nested TokenFactors.
7979 if (ChainVal == LdVal)
7980 Ld = cast<LoadSDNode>(St->getChain());
7981 else if (St->getValue().hasOneUse() &&
7982 ChainVal->getOpcode() == ISD::TokenFactor) {
7983 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
7984 if (ChainVal->getOperand(i).getNode() == LdVal) {
7985 TokenFactorIndex = i;
7986 Ld = cast<LoadSDNode>(St->getValue());
7988 Ops.push_back(ChainVal->getOperand(i));
7992 DebugLoc dl = N->getDebugLoc();
7993 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
7994 if (Subtarget->is64Bit()) {
7995 SDValue NewLd = DAG.getLoad(MVT::i64, dl, Ld->getChain(),
7996 Ld->getBasePtr(), Ld->getSrcValue(),
7997 Ld->getSrcValueOffset(), Ld->isVolatile(),
7998 Ld->getAlignment());
7999 SDValue NewChain = NewLd.getValue(1);
8000 if (TokenFactorIndex != -1) {
8001 Ops.push_back(NewChain);
8002 NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Ops[0],
8005 return DAG.getStore(NewChain, dl, NewLd, St->getBasePtr(),
8006 St->getSrcValue(), St->getSrcValueOffset(),
8007 St->isVolatile(), St->getAlignment());
8010 // Otherwise, lower to two 32-bit copies.
8011 SDValue LoAddr = Ld->getBasePtr();
8012 SDValue HiAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, LoAddr,
8013 DAG.getConstant(4, MVT::i32));
8015 SDValue LoLd = DAG.getLoad(MVT::i32, dl, Ld->getChain(), LoAddr,
8016 Ld->getSrcValue(), Ld->getSrcValueOffset(),
8017 Ld->isVolatile(), Ld->getAlignment());
8018 SDValue HiLd = DAG.getLoad(MVT::i32, dl, Ld->getChain(), HiAddr,
8019 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
8021 MinAlign(Ld->getAlignment(), 4));
8023 SDValue NewChain = LoLd.getValue(1);
8024 if (TokenFactorIndex != -1) {
8025 Ops.push_back(LoLd);
8026 Ops.push_back(HiLd);
8027 NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Ops[0],
8031 LoAddr = St->getBasePtr();
8032 HiAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, LoAddr,
8033 DAG.getConstant(4, MVT::i32));
8035 SDValue LoSt = DAG.getStore(NewChain, dl, LoLd, LoAddr,
8036 St->getSrcValue(), St->getSrcValueOffset(),
8037 St->isVolatile(), St->getAlignment());
8038 SDValue HiSt = DAG.getStore(NewChain, dl, HiLd, HiAddr,
8040 St->getSrcValueOffset() + 4,
8042 MinAlign(St->getAlignment(), 4));
8043 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoSt, HiSt);
8049 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
8050 /// X86ISD::FXOR nodes.
8051 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
8052 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
8053 // F[X]OR(0.0, x) -> x
8054 // F[X]OR(x, 0.0) -> x
8055 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8056 if (C->getValueAPF().isPosZero())
8057 return N->getOperand(1);
8058 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8059 if (C->getValueAPF().isPosZero())
8060 return N->getOperand(0);
8064 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
8065 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
8066 // FAND(0.0, x) -> 0.0
8067 // FAND(x, 0.0) -> 0.0
8068 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8069 if (C->getValueAPF().isPosZero())
8070 return N->getOperand(0);
8071 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8072 if (C->getValueAPF().isPosZero())
8073 return N->getOperand(1);
8077 static SDValue PerformBTCombine(SDNode *N,
8079 TargetLowering::DAGCombinerInfo &DCI) {
8080 // BT ignores high bits in the bit index operand.
8081 SDValue Op1 = N->getOperand(1);
8082 if (Op1.hasOneUse()) {
8083 unsigned BitWidth = Op1.getValueSizeInBits();
8084 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
8085 APInt KnownZero, KnownOne;
8086 TargetLowering::TargetLoweringOpt TLO(DAG);
8087 TargetLowering &TLI = DAG.getTargetLoweringInfo();
8088 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
8089 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
8090 DCI.CommitTargetLoweringOpt(TLO);
8095 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
8096 DAGCombinerInfo &DCI) const {
8097 SelectionDAG &DAG = DCI.DAG;
8098 switch (N->getOpcode()) {
8100 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
8101 case ISD::BUILD_VECTOR:
8102 return PerformBuildVectorCombine(N, DAG, DCI, Subtarget, *this);
8103 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
8106 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
8107 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
8109 case X86ISD::FOR: return PerformFORCombine(N, DAG);
8110 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
8111 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
8117 //===----------------------------------------------------------------------===//
8118 // X86 Inline Assembly Support
8119 //===----------------------------------------------------------------------===//
8121 /// getConstraintType - Given a constraint letter, return the type of
8122 /// constraint it is for this target.
8123 X86TargetLowering::ConstraintType
8124 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
8125 if (Constraint.size() == 1) {
8126 switch (Constraint[0]) {
8138 return C_RegisterClass;
8143 return TargetLowering::getConstraintType(Constraint);
8146 /// LowerXConstraint - try to replace an X constraint, which matches anything,
8147 /// with another that has more specific requirements based on the type of the
8148 /// corresponding operand.
8149 const char *X86TargetLowering::
8150 LowerXConstraint(MVT ConstraintVT) const {
8151 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
8152 // 'f' like normal targets.
8153 if (ConstraintVT.isFloatingPoint()) {
8154 if (Subtarget->hasSSE2())
8156 if (Subtarget->hasSSE1())
8160 return TargetLowering::LowerXConstraint(ConstraintVT);
8163 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8164 /// vector. If it is invalid, don't add anything to Ops.
8165 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8168 std::vector<SDValue>&Ops,
8169 SelectionDAG &DAG) const {
8170 SDValue Result(0, 0);
8172 switch (Constraint) {
8175 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8176 if (C->getZExtValue() <= 31) {
8177 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8183 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8184 if (C->getZExtValue() <= 63) {
8185 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8191 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8192 if (C->getZExtValue() <= 255) {
8193 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8199 // Literal immediates are always ok.
8200 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
8201 Result = DAG.getTargetConstant(CST->getZExtValue(), Op.getValueType());
8205 // If we are in non-pic codegen mode, we allow the address of a global (with
8206 // an optional displacement) to be used with 'i'.
8207 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
8210 // Match either (GA) or (GA+C)
8212 Offset = GA->getOffset();
8213 } else if (Op.getOpcode() == ISD::ADD) {
8214 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8215 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
8217 Offset = GA->getOffset()+C->getZExtValue();
8219 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8220 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
8222 Offset = GA->getOffset()+C->getZExtValue();
8230 Op = LowerGlobalAddress(GA->getGlobal(), Offset, DAG);
8232 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
8238 // Otherwise, not valid for this mode.
8243 if (Result.getNode()) {
8244 Ops.push_back(Result);
8247 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
8251 std::vector<unsigned> X86TargetLowering::
8252 getRegClassForInlineAsmConstraint(const std::string &Constraint,
8254 if (Constraint.size() == 1) {
8255 // FIXME: not handling fp-stack yet!
8256 switch (Constraint[0]) { // GCC X86 Constraint Letters
8257 default: break; // Unknown constraint letter
8258 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
8261 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
8262 else if (VT == MVT::i16)
8263 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
8264 else if (VT == MVT::i8)
8265 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
8266 else if (VT == MVT::i64)
8267 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
8272 return std::vector<unsigned>();
8275 std::pair<unsigned, const TargetRegisterClass*>
8276 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8278 // First, see if this is a constraint that directly corresponds to an LLVM
8280 if (Constraint.size() == 1) {
8281 // GCC Constraint Letters
8282 switch (Constraint[0]) {
8284 case 'r': // GENERAL_REGS
8285 case 'R': // LEGACY_REGS
8286 case 'l': // INDEX_REGS
8288 return std::make_pair(0U, X86::GR8RegisterClass);
8290 return std::make_pair(0U, X86::GR16RegisterClass);
8291 if (VT == MVT::i32 || !Subtarget->is64Bit())
8292 return std::make_pair(0U, X86::GR32RegisterClass);
8293 return std::make_pair(0U, X86::GR64RegisterClass);
8294 case 'f': // FP Stack registers.
8295 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
8296 // value to the correct fpstack register class.
8297 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
8298 return std::make_pair(0U, X86::RFP32RegisterClass);
8299 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
8300 return std::make_pair(0U, X86::RFP64RegisterClass);
8301 return std::make_pair(0U, X86::RFP80RegisterClass);
8302 case 'y': // MMX_REGS if MMX allowed.
8303 if (!Subtarget->hasMMX()) break;
8304 return std::make_pair(0U, X86::VR64RegisterClass);
8305 case 'Y': // SSE_REGS if SSE2 allowed
8306 if (!Subtarget->hasSSE2()) break;
8308 case 'x': // SSE_REGS if SSE1 allowed
8309 if (!Subtarget->hasSSE1()) break;
8311 switch (VT.getSimpleVT()) {
8313 // Scalar SSE types.
8316 return std::make_pair(0U, X86::FR32RegisterClass);
8319 return std::make_pair(0U, X86::FR64RegisterClass);
8327 return std::make_pair(0U, X86::VR128RegisterClass);
8333 // Use the default implementation in TargetLowering to convert the register
8334 // constraint into a member of a register class.
8335 std::pair<unsigned, const TargetRegisterClass*> Res;
8336 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8338 // Not found as a standard register?
8339 if (Res.second == 0) {
8340 // GCC calls "st(0)" just plain "st".
8341 if (StringsEqualNoCase("{st}", Constraint)) {
8342 Res.first = X86::ST0;
8343 Res.second = X86::RFP80RegisterClass;
8345 // 'A' means EAX + EDX.
8346 if (Constraint == "A") {
8347 Res.first = X86::EAX;
8348 Res.second = X86::GRADRegisterClass;
8353 // Otherwise, check to see if this is a register class of the wrong value
8354 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
8355 // turn into {ax},{dx}.
8356 if (Res.second->hasType(VT))
8357 return Res; // Correct type already, nothing to do.
8359 // All of the single-register GCC register classes map their values onto
8360 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
8361 // really want an 8-bit or 32-bit register, map to the appropriate register
8362 // class and return the appropriate register.
8363 if (Res.second == X86::GR16RegisterClass) {
8364 if (VT == MVT::i8) {
8365 unsigned DestReg = 0;
8366 switch (Res.first) {
8368 case X86::AX: DestReg = X86::AL; break;
8369 case X86::DX: DestReg = X86::DL; break;
8370 case X86::CX: DestReg = X86::CL; break;
8371 case X86::BX: DestReg = X86::BL; break;
8374 Res.first = DestReg;
8375 Res.second = Res.second = X86::GR8RegisterClass;
8377 } else if (VT == MVT::i32) {
8378 unsigned DestReg = 0;
8379 switch (Res.first) {
8381 case X86::AX: DestReg = X86::EAX; break;
8382 case X86::DX: DestReg = X86::EDX; break;
8383 case X86::CX: DestReg = X86::ECX; break;
8384 case X86::BX: DestReg = X86::EBX; break;
8385 case X86::SI: DestReg = X86::ESI; break;
8386 case X86::DI: DestReg = X86::EDI; break;
8387 case X86::BP: DestReg = X86::EBP; break;
8388 case X86::SP: DestReg = X86::ESP; break;
8391 Res.first = DestReg;
8392 Res.second = Res.second = X86::GR32RegisterClass;
8394 } else if (VT == MVT::i64) {
8395 unsigned DestReg = 0;
8396 switch (Res.first) {
8398 case X86::AX: DestReg = X86::RAX; break;
8399 case X86::DX: DestReg = X86::RDX; break;
8400 case X86::CX: DestReg = X86::RCX; break;
8401 case X86::BX: DestReg = X86::RBX; break;
8402 case X86::SI: DestReg = X86::RSI; break;
8403 case X86::DI: DestReg = X86::RDI; break;
8404 case X86::BP: DestReg = X86::RBP; break;
8405 case X86::SP: DestReg = X86::RSP; break;
8408 Res.first = DestReg;
8409 Res.second = Res.second = X86::GR64RegisterClass;
8412 } else if (Res.second == X86::FR32RegisterClass ||
8413 Res.second == X86::FR64RegisterClass ||
8414 Res.second == X86::VR128RegisterClass) {
8415 // Handle references to XMM physical registers that got mapped into the
8416 // wrong class. This can happen with constraints like {xmm0} where the
8417 // target independent register mapper will just pick the first match it can
8418 // find, ignoring the required type.
8420 Res.second = X86::FR32RegisterClass;
8421 else if (VT == MVT::f64)
8422 Res.second = X86::FR64RegisterClass;
8423 else if (X86::VR128RegisterClass->hasType(VT))
8424 Res.second = X86::VR128RegisterClass;
8430 //===----------------------------------------------------------------------===//
8431 // X86 Widen vector type
8432 //===----------------------------------------------------------------------===//
8434 /// getWidenVectorType: given a vector type, returns the type to widen
8435 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
8436 /// If there is no vector type that we want to widen to, returns MVT::Other
8437 /// When and where to widen is target dependent based on the cost of
8438 /// scalarizing vs using the wider vector type.
8440 MVT X86TargetLowering::getWidenVectorType(MVT VT) const {
8441 assert(VT.isVector());
8442 if (isTypeLegal(VT))
8445 // TODO: In computeRegisterProperty, we can compute the list of legal vector
8446 // type based on element type. This would speed up our search (though
8447 // it may not be worth it since the size of the list is relatively
8449 MVT EltVT = VT.getVectorElementType();
8450 unsigned NElts = VT.getVectorNumElements();
8452 // On X86, it make sense to widen any vector wider than 1
8456 for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
8457 nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
8458 MVT SVT = (MVT::SimpleValueType)nVT;
8460 if (isTypeLegal(SVT) &&
8461 SVT.getVectorElementType() == EltVT &&
8462 SVT.getVectorNumElements() > NElts)