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 (RVLocs[i].getLocReg() == X86::ST0 ||
980 RVLocs[i].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(RVLocs[i].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 MVT CopyVT = RVLocs[i].getValVT();
1047 // If this is x86-64, and we disabled SSE, we can't return FP values
1048 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1049 ((Is64Bit || TheCall->isInreg()) && !Subtarget->hasSSE1())) {
1050 cerr << "SSE register return with SSE disabled\n";
1054 // If this is a call to a function that returns an fp value on the floating
1055 // point stack, but where we prefer to use the value in xmm registers, copy
1056 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1057 if ((RVLocs[i].getLocReg() == X86::ST0 ||
1058 RVLocs[i].getLocReg() == X86::ST1) &&
1059 isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
1063 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
1064 CopyVT, InFlag).getValue(1);
1065 SDValue Val = Chain.getValue(0);
1066 InFlag = Chain.getValue(2);
1068 if (CopyVT != RVLocs[i].getValVT()) {
1069 // Round the F80 the right size, which also moves to the appropriate xmm
1071 Val = DAG.getNode(ISD::FP_ROUND, dl, RVLocs[i].getValVT(), Val,
1072 // This truncation won't change the value.
1073 DAG.getIntPtrConstant(1));
1076 ResultVals.push_back(Val);
1079 // Merge everything together with a MERGE_VALUES node.
1080 ResultVals.push_back(Chain);
1081 return DAG.getNode(ISD::MERGE_VALUES, dl, TheCall->getVTList(),
1082 &ResultVals[0], ResultVals.size()).getNode();
1086 //===----------------------------------------------------------------------===//
1087 // C & StdCall & Fast Calling Convention implementation
1088 //===----------------------------------------------------------------------===//
1089 // StdCall calling convention seems to be standard for many Windows' API
1090 // routines and around. It differs from C calling convention just a little:
1091 // callee should clean up the stack, not caller. Symbols should be also
1092 // decorated in some fancy way :) It doesn't support any vector arguments.
1093 // For info on fast calling convention see Fast Calling Convention (tail call)
1094 // implementation LowerX86_32FastCCCallTo.
1096 /// AddLiveIn - This helper function adds the specified physical register to the
1097 /// MachineFunction as a live in value. It also creates a corresponding virtual
1098 /// register for it.
1099 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
1100 const TargetRegisterClass *RC) {
1101 assert(RC->contains(PReg) && "Not the correct regclass!");
1102 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
1103 MF.getRegInfo().addLiveIn(PReg, VReg);
1107 /// CallIsStructReturn - Determines whether a CALL node uses struct return
1109 static bool CallIsStructReturn(CallSDNode *TheCall) {
1110 unsigned NumOps = TheCall->getNumArgs();
1114 return TheCall->getArgFlags(0).isSRet();
1117 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
1118 /// return semantics.
1119 static bool ArgsAreStructReturn(SDValue Op) {
1120 unsigned NumArgs = Op.getNode()->getNumValues() - 1;
1124 return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
1127 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
1128 /// the callee to pop its own arguments. Callee pop is necessary to support tail
1130 bool X86TargetLowering::IsCalleePop(bool IsVarArg, unsigned CallingConv) {
1134 switch (CallingConv) {
1137 case CallingConv::X86_StdCall:
1138 return !Subtarget->is64Bit();
1139 case CallingConv::X86_FastCall:
1140 return !Subtarget->is64Bit();
1141 case CallingConv::Fast:
1142 return PerformTailCallOpt;
1146 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1147 /// given CallingConvention value.
1148 CCAssignFn *X86TargetLowering::CCAssignFnForNode(unsigned CC) const {
1149 if (Subtarget->is64Bit()) {
1150 if (Subtarget->isTargetWin64())
1151 return CC_X86_Win64_C;
1152 else if (CC == CallingConv::Fast && PerformTailCallOpt)
1153 return CC_X86_64_TailCall;
1158 if (CC == CallingConv::X86_FastCall)
1159 return CC_X86_32_FastCall;
1160 else if (CC == CallingConv::Fast)
1161 return CC_X86_32_FastCC;
1166 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1167 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1169 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDValue Op) {
1170 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1171 if (CC == CallingConv::X86_FastCall)
1173 else if (CC == CallingConv::X86_StdCall)
1179 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1180 /// in a register before calling.
1181 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1182 return !IsTailCall && !Is64Bit &&
1183 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1184 Subtarget->isPICStyleGOT();
1187 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1188 /// address to be loaded in a register.
1190 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1191 return !Is64Bit && IsTailCall &&
1192 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1193 Subtarget->isPICStyleGOT();
1196 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1197 /// by "Src" to address "Dst" with size and alignment information specified by
1198 /// the specific parameter attribute. The copy will be passed as a byval
1199 /// function parameter.
1201 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1202 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1204 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1205 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1206 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1209 SDValue X86TargetLowering::LowerMemArgument(SDValue Op, SelectionDAG &DAG,
1210 const CCValAssign &VA,
1211 MachineFrameInfo *MFI,
1213 SDValue Root, unsigned i) {
1214 // Create the nodes corresponding to a load from this parameter slot.
1215 ISD::ArgFlagsTy Flags =
1216 cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1217 bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1218 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1220 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1221 // changed with more analysis.
1222 // In case of tail call optimization mark all arguments mutable. Since they
1223 // could be overwritten by lowering of arguments in case of a tail call.
1224 int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1225 VA.getLocMemOffset(), isImmutable);
1226 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1227 if (Flags.isByVal())
1229 return DAG.getLoad(VA.getValVT(), Op.getNode()->getDebugLoc(), Root, FIN,
1230 PseudoSourceValue::getFixedStack(FI), 0);
1234 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) {
1235 MachineFunction &MF = DAG.getMachineFunction();
1236 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1237 DebugLoc dl = Op.getNode()->getDebugLoc();
1239 const Function* Fn = MF.getFunction();
1240 if (Fn->hasExternalLinkage() &&
1241 Subtarget->isTargetCygMing() &&
1242 Fn->getName() == "main")
1243 FuncInfo->setForceFramePointer(true);
1245 // Decorate the function name.
1246 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1248 MachineFrameInfo *MFI = MF.getFrameInfo();
1249 SDValue Root = Op.getOperand(0);
1250 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
1251 unsigned CC = MF.getFunction()->getCallingConv();
1252 bool Is64Bit = Subtarget->is64Bit();
1253 bool IsWin64 = Subtarget->isTargetWin64();
1255 assert(!(isVarArg && CC == CallingConv::Fast) &&
1256 "Var args not supported with calling convention fastcc");
1258 // Assign locations to all of the incoming arguments.
1259 SmallVector<CCValAssign, 16> ArgLocs;
1260 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1261 CCInfo.AnalyzeFormalArguments(Op.getNode(), CCAssignFnForNode(CC));
1263 SmallVector<SDValue, 8> ArgValues;
1264 unsigned LastVal = ~0U;
1265 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1266 CCValAssign &VA = ArgLocs[i];
1267 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1269 assert(VA.getValNo() != LastVal &&
1270 "Don't support value assigned to multiple locs yet");
1271 LastVal = VA.getValNo();
1273 if (VA.isRegLoc()) {
1274 MVT RegVT = VA.getLocVT();
1275 TargetRegisterClass *RC = NULL;
1276 if (RegVT == MVT::i32)
1277 RC = X86::GR32RegisterClass;
1278 else if (Is64Bit && RegVT == MVT::i64)
1279 RC = X86::GR64RegisterClass;
1280 else if (RegVT == MVT::f32)
1281 RC = X86::FR32RegisterClass;
1282 else if (RegVT == MVT::f64)
1283 RC = X86::FR64RegisterClass;
1284 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1285 RC = X86::VR128RegisterClass;
1286 else if (RegVT.isVector()) {
1287 assert(RegVT.getSizeInBits() == 64);
1289 RC = X86::VR64RegisterClass; // MMX values are passed in MMXs.
1291 // Darwin calling convention passes MMX values in either GPRs or
1292 // XMMs in x86-64. Other targets pass them in memory.
1293 if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1294 RC = X86::VR128RegisterClass; // MMX values are passed in XMMs.
1297 RC = X86::GR64RegisterClass; // v1i64 values are passed in GPRs.
1302 assert(0 && "Unknown argument type!");
1305 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1306 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, RegVT);
1308 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1309 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1311 if (VA.getLocInfo() == CCValAssign::SExt)
1312 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1313 DAG.getValueType(VA.getValVT()));
1314 else if (VA.getLocInfo() == CCValAssign::ZExt)
1315 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1316 DAG.getValueType(VA.getValVT()));
1318 if (VA.getLocInfo() != CCValAssign::Full)
1319 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1321 // Handle MMX values passed in GPRs.
1322 if (Is64Bit && RegVT != VA.getLocVT()) {
1323 if (RegVT.getSizeInBits() == 64 && RC == X86::GR64RegisterClass)
1324 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1325 else if (RC == X86::VR128RegisterClass) {
1326 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1327 ArgValue, DAG.getConstant(0, MVT::i64));
1328 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1332 ArgValues.push_back(ArgValue);
1334 assert(VA.isMemLoc());
1335 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1339 // The x86-64 ABI for returning structs by value requires that we copy
1340 // the sret argument into %rax for the return. Save the argument into
1341 // a virtual register so that we can access it from the return points.
1342 if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1343 MachineFunction &MF = DAG.getMachineFunction();
1344 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1345 unsigned Reg = FuncInfo->getSRetReturnReg();
1347 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1348 FuncInfo->setSRetReturnReg(Reg);
1350 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, ArgValues[0]);
1351 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Root);
1354 unsigned StackSize = CCInfo.getNextStackOffset();
1355 // align stack specially for tail calls
1356 if (PerformTailCallOpt && CC == CallingConv::Fast)
1357 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1359 // If the function takes variable number of arguments, make a frame index for
1360 // the start of the first vararg value... for expansion of llvm.va_start.
1362 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1363 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1366 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1368 // FIXME: We should really autogenerate these arrays
1369 static const unsigned GPR64ArgRegsWin64[] = {
1370 X86::RCX, X86::RDX, X86::R8, X86::R9
1372 static const unsigned XMMArgRegsWin64[] = {
1373 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1375 static const unsigned GPR64ArgRegs64Bit[] = {
1376 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1378 static const unsigned XMMArgRegs64Bit[] = {
1379 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1380 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1382 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1385 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1386 GPR64ArgRegs = GPR64ArgRegsWin64;
1387 XMMArgRegs = XMMArgRegsWin64;
1389 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1390 GPR64ArgRegs = GPR64ArgRegs64Bit;
1391 XMMArgRegs = XMMArgRegs64Bit;
1393 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1395 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1398 assert((Subtarget->hasSSE1() || !NumXMMRegs) &&
1399 "SSE register cannot be used when SSE is disabled!");
1400 if (!Subtarget->hasSSE1()) {
1401 // Kernel mode asks for SSE to be disabled, so don't push them
1403 TotalNumXMMRegs = 0;
1405 // For X86-64, if there are vararg parameters that are passed via
1406 // registers, then we must store them to their spots on the stack so they
1407 // may be loaded by deferencing the result of va_next.
1408 VarArgsGPOffset = NumIntRegs * 8;
1409 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1410 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1411 TotalNumXMMRegs * 16, 16);
1413 // Store the integer parameter registers.
1414 SmallVector<SDValue, 8> MemOps;
1415 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1416 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1417 DAG.getIntPtrConstant(VarArgsGPOffset));
1418 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1419 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1420 X86::GR64RegisterClass);
1421 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::i64);
1423 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1424 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1425 MemOps.push_back(Store);
1426 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1427 DAG.getIntPtrConstant(8));
1430 // Now store the XMM (fp + vector) parameter registers.
1431 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1432 DAG.getIntPtrConstant(VarArgsFPOffset));
1433 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1434 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1435 X86::VR128RegisterClass);
1436 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::v4f32);
1438 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1439 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1440 MemOps.push_back(Store);
1441 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1442 DAG.getIntPtrConstant(16));
1444 if (!MemOps.empty())
1445 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1446 &MemOps[0], MemOps.size());
1450 ArgValues.push_back(Root);
1452 // Some CCs need callee pop.
1453 if (IsCalleePop(isVarArg, CC)) {
1454 BytesToPopOnReturn = StackSize; // Callee pops everything.
1455 BytesCallerReserves = 0;
1457 BytesToPopOnReturn = 0; // Callee pops nothing.
1458 // If this is an sret function, the return should pop the hidden pointer.
1459 if (!Is64Bit && CC != CallingConv::Fast && ArgsAreStructReturn(Op))
1460 BytesToPopOnReturn = 4;
1461 BytesCallerReserves = StackSize;
1465 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1466 if (CC == CallingConv::X86_FastCall)
1467 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1470 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1472 // Return the new list of results.
1473 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(),
1474 &ArgValues[0], ArgValues.size()).getValue(Op.getResNo());
1478 X86TargetLowering::LowerMemOpCallTo(CallSDNode *TheCall, SelectionDAG &DAG,
1479 const SDValue &StackPtr,
1480 const CCValAssign &VA,
1482 SDValue Arg, ISD::ArgFlagsTy Flags) {
1483 DebugLoc dl = TheCall->getDebugLoc();
1484 unsigned LocMemOffset = VA.getLocMemOffset();
1485 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1486 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1487 if (Flags.isByVal()) {
1488 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1490 return DAG.getStore(Chain, dl, Arg, PtrOff,
1491 PseudoSourceValue::getStack(), LocMemOffset);
1494 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1495 /// optimization is performed and it is required.
1497 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1498 SDValue &OutRetAddr,
1504 if (!IsTailCall || FPDiff==0) return Chain;
1506 // Adjust the Return address stack slot.
1507 MVT VT = getPointerTy();
1508 OutRetAddr = getReturnAddressFrameIndex(DAG);
1510 // Load the "old" Return address.
1511 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0);
1512 return SDValue(OutRetAddr.getNode(), 1);
1515 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1516 /// optimization is performed and it is required (FPDiff!=0).
1518 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1519 SDValue Chain, SDValue RetAddrFrIdx,
1520 bool Is64Bit, int FPDiff, DebugLoc dl) {
1521 // Store the return address to the appropriate stack slot.
1522 if (!FPDiff) return Chain;
1523 // Calculate the new stack slot for the return address.
1524 int SlotSize = Is64Bit ? 8 : 4;
1525 int NewReturnAddrFI =
1526 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1527 MVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1528 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1529 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1530 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1534 SDValue X86TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1535 MachineFunction &MF = DAG.getMachineFunction();
1536 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
1537 SDValue Chain = TheCall->getChain();
1538 unsigned CC = TheCall->getCallingConv();
1539 bool isVarArg = TheCall->isVarArg();
1540 bool IsTailCall = TheCall->isTailCall() &&
1541 CC == CallingConv::Fast && PerformTailCallOpt;
1542 SDValue Callee = TheCall->getCallee();
1543 bool Is64Bit = Subtarget->is64Bit();
1544 bool IsStructRet = CallIsStructReturn(TheCall);
1545 DebugLoc dl = TheCall->getDebugLoc();
1547 assert(!(isVarArg && CC == CallingConv::Fast) &&
1548 "Var args not supported with calling convention fastcc");
1550 // Analyze operands of the call, assigning locations to each operand.
1551 SmallVector<CCValAssign, 16> ArgLocs;
1552 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1553 CCInfo.AnalyzeCallOperands(TheCall, CCAssignFnForNode(CC));
1555 // Get a count of how many bytes are to be pushed on the stack.
1556 unsigned NumBytes = CCInfo.getNextStackOffset();
1557 if (PerformTailCallOpt && CC == CallingConv::Fast)
1558 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1562 // Lower arguments at fp - stackoffset + fpdiff.
1563 unsigned NumBytesCallerPushed =
1564 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1565 FPDiff = NumBytesCallerPushed - NumBytes;
1567 // Set the delta of movement of the returnaddr stackslot.
1568 // But only set if delta is greater than previous delta.
1569 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1570 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1573 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1575 SDValue RetAddrFrIdx;
1576 // Load return adress for tail calls.
1577 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1580 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1581 SmallVector<SDValue, 8> MemOpChains;
1584 // Walk the register/memloc assignments, inserting copies/loads. In the case
1585 // of tail call optimization arguments are handle later.
1586 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1587 CCValAssign &VA = ArgLocs[i];
1588 SDValue Arg = TheCall->getArg(i);
1589 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1590 bool isByVal = Flags.isByVal();
1592 // Promote the value if needed.
1593 switch (VA.getLocInfo()) {
1594 default: assert(0 && "Unknown loc info!");
1595 case CCValAssign::Full: break;
1596 case CCValAssign::SExt:
1597 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1599 case CCValAssign::ZExt:
1600 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1602 case CCValAssign::AExt:
1603 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1607 if (VA.isRegLoc()) {
1609 MVT RegVT = VA.getLocVT();
1610 if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1611 switch (VA.getLocReg()) {
1614 case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1616 // Special case: passing MMX values in GPR registers.
1617 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1620 case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1621 case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1622 // Special case: passing MMX values in XMM registers.
1623 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1624 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1625 Arg = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v2i64,
1626 DAG.getNode(ISD::UNDEF, dl, MVT::v2i64), Arg,
1627 getMOVLMask(2, DAG, dl));
1632 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1634 if (!IsTailCall || (IsTailCall && isByVal)) {
1635 assert(VA.isMemLoc());
1636 if (StackPtr.getNode() == 0)
1637 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1639 MemOpChains.push_back(LowerMemOpCallTo(TheCall, DAG, StackPtr, VA,
1640 Chain, Arg, Flags));
1645 if (!MemOpChains.empty())
1646 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1647 &MemOpChains[0], MemOpChains.size());
1649 // Build a sequence of copy-to-reg nodes chained together with token chain
1650 // and flag operands which copy the outgoing args into registers.
1652 // Tail call byval lowering might overwrite argument registers so in case of
1653 // tail call optimization the copies to registers are lowered later.
1655 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1656 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1657 RegsToPass[i].second, InFlag);
1658 InFlag = Chain.getValue(1);
1661 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1663 if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1664 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1665 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1667 InFlag = Chain.getValue(1);
1669 // If we are tail calling and generating PIC/GOT style code load the address
1670 // of the callee into ecx. The value in ecx is used as target of the tail
1671 // jump. This is done to circumvent the ebx/callee-saved problem for tail
1672 // calls on PIC/GOT architectures. Normally we would just put the address of
1673 // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1674 // restored (since ebx is callee saved) before jumping to the target@PLT.
1675 if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1676 // Note: The actual moving to ecx is done further down.
1677 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1678 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1679 !G->getGlobal()->hasProtectedVisibility())
1680 Callee = LowerGlobalAddress(Callee, DAG);
1681 else if (isa<ExternalSymbolSDNode>(Callee))
1682 Callee = LowerExternalSymbol(Callee,DAG);
1685 if (Is64Bit && isVarArg) {
1686 // From AMD64 ABI document:
1687 // For calls that may call functions that use varargs or stdargs
1688 // (prototype-less calls or calls to functions containing ellipsis (...) in
1689 // the declaration) %al is used as hidden argument to specify the number
1690 // of SSE registers used. The contents of %al do not need to match exactly
1691 // the number of registers, but must be an ubound on the number of SSE
1692 // registers used and is in the range 0 - 8 inclusive.
1694 // FIXME: Verify this on Win64
1695 // Count the number of XMM registers allocated.
1696 static const unsigned XMMArgRegs[] = {
1697 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1698 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1700 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1701 assert((Subtarget->hasSSE1() || !NumXMMRegs)
1702 && "SSE registers cannot be used when SSE is disabled");
1704 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1705 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1706 InFlag = Chain.getValue(1);
1710 // For tail calls lower the arguments to the 'real' stack slot.
1712 SmallVector<SDValue, 8> MemOpChains2;
1715 // Do not flag preceeding copytoreg stuff together with the following stuff.
1717 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1718 CCValAssign &VA = ArgLocs[i];
1719 if (!VA.isRegLoc()) {
1720 assert(VA.isMemLoc());
1721 SDValue Arg = TheCall->getArg(i);
1722 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1723 // Create frame index.
1724 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1725 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1726 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1727 FIN = DAG.getFrameIndex(FI, getPointerTy());
1729 if (Flags.isByVal()) {
1730 // Copy relative to framepointer.
1731 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1732 if (StackPtr.getNode() == 0)
1733 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
1735 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
1737 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1740 // Store relative to framepointer.
1741 MemOpChains2.push_back(
1742 DAG.getStore(Chain, dl, Arg, FIN,
1743 PseudoSourceValue::getFixedStack(FI), 0));
1748 if (!MemOpChains2.empty())
1749 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1750 &MemOpChains2[0], MemOpChains2.size());
1752 // Copy arguments to their registers.
1753 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1754 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1755 RegsToPass[i].second, InFlag);
1756 InFlag = Chain.getValue(1);
1760 // Store the return address to the appropriate stack slot.
1761 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1765 // If the callee is a GlobalAddress node (quite common, every direct call is)
1766 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1767 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1768 // We should use extra load for direct calls to dllimported functions in
1770 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1771 getTargetMachine(), true))
1772 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy(),
1774 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1775 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1776 } else if (IsTailCall) {
1777 unsigned Opc = Is64Bit ? X86::R9 : X86::EAX;
1779 Chain = DAG.getCopyToReg(Chain, dl,
1780 DAG.getRegister(Opc, getPointerTy()),
1782 Callee = DAG.getRegister(Opc, getPointerTy());
1783 // Add register as live out.
1784 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1787 // Returns a chain & a flag for retval copy to use.
1788 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1789 SmallVector<SDValue, 8> Ops;
1792 Ops.push_back(Chain);
1793 Ops.push_back(DAG.getIntPtrConstant(NumBytes, true));
1794 Ops.push_back(DAG.getIntPtrConstant(0, true));
1795 if (InFlag.getNode())
1796 Ops.push_back(InFlag);
1797 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1798 InFlag = Chain.getValue(1);
1800 // Returns a chain & a flag for retval copy to use.
1801 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1805 Ops.push_back(Chain);
1806 Ops.push_back(Callee);
1809 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1811 // Add argument registers to the end of the list so that they are known live
1813 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1814 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1815 RegsToPass[i].second.getValueType()));
1817 // Add an implicit use GOT pointer in EBX.
1818 if (!IsTailCall && !Is64Bit &&
1819 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1820 Subtarget->isPICStyleGOT())
1821 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1823 // Add an implicit use of AL for x86 vararg functions.
1824 if (Is64Bit && isVarArg)
1825 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1827 if (InFlag.getNode())
1828 Ops.push_back(InFlag);
1831 assert(InFlag.getNode() &&
1832 "Flag must be set. Depend on flag being set in LowerRET");
1833 Chain = DAG.getNode(X86ISD::TAILCALL, dl,
1834 TheCall->getVTList(), &Ops[0], Ops.size());
1836 return SDValue(Chain.getNode(), Op.getResNo());
1839 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
1840 InFlag = Chain.getValue(1);
1842 // Create the CALLSEQ_END node.
1843 unsigned NumBytesForCalleeToPush;
1844 if (IsCalleePop(isVarArg, CC))
1845 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1846 else if (!Is64Bit && CC != CallingConv::Fast && IsStructRet)
1847 // If this is is a call to a struct-return function, the callee
1848 // pops the hidden struct pointer, so we have to push it back.
1849 // This is common for Darwin/X86, Linux & Mingw32 targets.
1850 NumBytesForCalleeToPush = 4;
1852 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1854 // Returns a flag for retval copy to use.
1855 Chain = DAG.getCALLSEQ_END(Chain,
1856 DAG.getIntPtrConstant(NumBytes, true),
1857 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
1860 InFlag = Chain.getValue(1);
1862 // Handle result values, copying them out of physregs into vregs that we
1864 return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
1869 //===----------------------------------------------------------------------===//
1870 // Fast Calling Convention (tail call) implementation
1871 //===----------------------------------------------------------------------===//
1873 // Like std call, callee cleans arguments, convention except that ECX is
1874 // reserved for storing the tail called function address. Only 2 registers are
1875 // free for argument passing (inreg). Tail call optimization is performed
1877 // * tailcallopt is enabled
1878 // * caller/callee are fastcc
1879 // On X86_64 architecture with GOT-style position independent code only local
1880 // (within module) calls are supported at the moment.
1881 // To keep the stack aligned according to platform abi the function
1882 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1883 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1884 // If a tail called function callee has more arguments than the caller the
1885 // caller needs to make sure that there is room to move the RETADDR to. This is
1886 // achieved by reserving an area the size of the argument delta right after the
1887 // original REtADDR, but before the saved framepointer or the spilled registers
1888 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1900 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1901 /// for a 16 byte align requirement.
1902 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1903 SelectionDAG& DAG) {
1904 MachineFunction &MF = DAG.getMachineFunction();
1905 const TargetMachine &TM = MF.getTarget();
1906 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1907 unsigned StackAlignment = TFI.getStackAlignment();
1908 uint64_t AlignMask = StackAlignment - 1;
1909 int64_t Offset = StackSize;
1910 uint64_t SlotSize = TD->getPointerSize();
1911 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1912 // Number smaller than 12 so just add the difference.
1913 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1915 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1916 Offset = ((~AlignMask) & Offset) + StackAlignment +
1917 (StackAlignment-SlotSize);
1922 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1923 /// following the call is a return. A function is eligible if caller/callee
1924 /// calling conventions match, currently only fastcc supports tail calls, and
1925 /// the function CALL is immediatly followed by a RET.
1926 bool X86TargetLowering::IsEligibleForTailCallOptimization(CallSDNode *TheCall,
1928 SelectionDAG& DAG) const {
1929 if (!PerformTailCallOpt)
1932 if (CheckTailCallReturnConstraints(TheCall, Ret)) {
1933 MachineFunction &MF = DAG.getMachineFunction();
1934 unsigned CallerCC = MF.getFunction()->getCallingConv();
1935 unsigned CalleeCC= TheCall->getCallingConv();
1936 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1937 SDValue Callee = TheCall->getCallee();
1938 // On x86/32Bit PIC/GOT tail calls are supported.
1939 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1940 !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1943 // Can only do local tail calls (in same module, hidden or protected) on
1944 // x86_64 PIC/GOT at the moment.
1945 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1946 return G->getGlobal()->hasHiddenVisibility()
1947 || G->getGlobal()->hasProtectedVisibility();
1955 X86TargetLowering::createFastISel(MachineFunction &mf,
1956 MachineModuleInfo *mmo,
1958 DenseMap<const Value *, unsigned> &vm,
1959 DenseMap<const BasicBlock *,
1960 MachineBasicBlock *> &bm,
1961 DenseMap<const AllocaInst *, int> &am
1963 , SmallSet<Instruction*, 8> &cil
1966 return X86::createFastISel(mf, mmo, dw, vm, bm, am
1974 //===----------------------------------------------------------------------===//
1975 // Other Lowering Hooks
1976 //===----------------------------------------------------------------------===//
1979 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1980 MachineFunction &MF = DAG.getMachineFunction();
1981 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1982 int ReturnAddrIndex = FuncInfo->getRAIndex();
1984 if (ReturnAddrIndex == 0) {
1985 // Set up a frame object for the return address.
1986 uint64_t SlotSize = TD->getPointerSize();
1987 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize);
1988 FuncInfo->setRAIndex(ReturnAddrIndex);
1991 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1995 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
1996 /// specific condition code, returning the condition code and the LHS/RHS of the
1997 /// comparison to make.
1998 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1999 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2001 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2002 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2003 // X > -1 -> X == 0, jump !sign.
2004 RHS = DAG.getConstant(0, RHS.getValueType());
2005 return X86::COND_NS;
2006 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2007 // X < 0 -> X == 0, jump on sign.
2009 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2011 RHS = DAG.getConstant(0, RHS.getValueType());
2012 return X86::COND_LE;
2016 switch (SetCCOpcode) {
2017 default: assert(0 && "Invalid integer condition!");
2018 case ISD::SETEQ: return X86::COND_E;
2019 case ISD::SETGT: return X86::COND_G;
2020 case ISD::SETGE: return X86::COND_GE;
2021 case ISD::SETLT: return X86::COND_L;
2022 case ISD::SETLE: return X86::COND_LE;
2023 case ISD::SETNE: return X86::COND_NE;
2024 case ISD::SETULT: return X86::COND_B;
2025 case ISD::SETUGT: return X86::COND_A;
2026 case ISD::SETULE: return X86::COND_BE;
2027 case ISD::SETUGE: return X86::COND_AE;
2031 // First determine if it is required or is profitable to flip the operands.
2033 // If LHS is a foldable load, but RHS is not, flip the condition.
2034 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2035 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2036 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2037 std::swap(LHS, RHS);
2040 switch (SetCCOpcode) {
2046 std::swap(LHS, RHS);
2050 // On a floating point condition, the flags are set as follows:
2052 // 0 | 0 | 0 | X > Y
2053 // 0 | 0 | 1 | X < Y
2054 // 1 | 0 | 0 | X == Y
2055 // 1 | 1 | 1 | unordered
2056 switch (SetCCOpcode) {
2057 default: assert(0 && "Condcode should be pre-legalized away");
2059 case ISD::SETEQ: return X86::COND_E;
2060 case ISD::SETOLT: // flipped
2062 case ISD::SETGT: return X86::COND_A;
2063 case ISD::SETOLE: // flipped
2065 case ISD::SETGE: return X86::COND_AE;
2066 case ISD::SETUGT: // flipped
2068 case ISD::SETLT: return X86::COND_B;
2069 case ISD::SETUGE: // flipped
2071 case ISD::SETLE: return X86::COND_BE;
2073 case ISD::SETNE: return X86::COND_NE;
2074 case ISD::SETUO: return X86::COND_P;
2075 case ISD::SETO: return X86::COND_NP;
2079 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2080 /// code. Current x86 isa includes the following FP cmov instructions:
2081 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2082 static bool hasFPCMov(unsigned X86CC) {
2098 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
2099 /// true if Op is undef or if its value falls within the specified range (L, H].
2100 static bool isUndefOrInRange(SDValue Op, unsigned Low, unsigned Hi) {
2101 if (Op.getOpcode() == ISD::UNDEF)
2104 unsigned Val = cast<ConstantSDNode>(Op)->getZExtValue();
2105 return (Val >= Low && Val < Hi);
2108 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
2109 /// true if Op is undef or if its value equal to the specified value.
2110 static bool isUndefOrEqual(SDValue Op, unsigned Val) {
2111 if (Op.getOpcode() == ISD::UNDEF)
2113 return cast<ConstantSDNode>(Op)->getZExtValue() == Val;
2116 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2117 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
2118 bool X86::isPSHUFDMask(SDNode *N) {
2119 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2121 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
2124 // Check if the value doesn't reference the second vector.
2125 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2126 SDValue Arg = N->getOperand(i);
2127 if (Arg.getOpcode() == ISD::UNDEF) continue;
2128 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2129 if (cast<ConstantSDNode>(Arg)->getZExtValue() >= e)
2136 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2137 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2138 bool X86::isPSHUFHWMask(SDNode *N) {
2139 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2141 if (N->getNumOperands() != 8)
2144 // Lower quadword copied in order.
2145 for (unsigned i = 0; i != 4; ++i) {
2146 SDValue Arg = N->getOperand(i);
2147 if (Arg.getOpcode() == ISD::UNDEF) continue;
2148 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2149 if (cast<ConstantSDNode>(Arg)->getZExtValue() != i)
2153 // Upper quadword shuffled.
2154 for (unsigned i = 4; i != 8; ++i) {
2155 SDValue Arg = N->getOperand(i);
2156 if (Arg.getOpcode() == ISD::UNDEF) continue;
2157 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2158 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2159 if (Val < 4 || Val > 7)
2166 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2167 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2168 bool X86::isPSHUFLWMask(SDNode *N) {
2169 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2171 if (N->getNumOperands() != 8)
2174 // Upper quadword copied in order.
2175 for (unsigned i = 4; i != 8; ++i)
2176 if (!isUndefOrEqual(N->getOperand(i), i))
2179 // Lower quadword shuffled.
2180 for (unsigned i = 0; i != 4; ++i)
2181 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2187 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2188 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2189 template<class SDOperand>
2190 static bool isSHUFPMask(SDOperand *Elems, unsigned NumElems) {
2191 if (NumElems != 2 && NumElems != 4) return false;
2193 unsigned Half = NumElems / 2;
2194 for (unsigned i = 0; i < Half; ++i)
2195 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2197 for (unsigned i = Half; i < NumElems; ++i)
2198 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2204 bool X86::isSHUFPMask(SDNode *N) {
2205 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2206 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2209 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2210 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2211 /// half elements to come from vector 1 (which would equal the dest.) and
2212 /// the upper half to come from vector 2.
2213 template<class SDOperand>
2214 static bool isCommutedSHUFP(SDOperand *Ops, unsigned NumOps) {
2215 if (NumOps != 2 && NumOps != 4) return false;
2217 unsigned Half = NumOps / 2;
2218 for (unsigned i = 0; i < Half; ++i)
2219 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2221 for (unsigned i = Half; i < NumOps; ++i)
2222 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2227 static bool isCommutedSHUFP(SDNode *N) {
2228 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2229 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2232 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2233 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2234 bool X86::isMOVHLPSMask(SDNode *N) {
2235 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2237 if (N->getNumOperands() != 4)
2240 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2241 return isUndefOrEqual(N->getOperand(0), 6) &&
2242 isUndefOrEqual(N->getOperand(1), 7) &&
2243 isUndefOrEqual(N->getOperand(2), 2) &&
2244 isUndefOrEqual(N->getOperand(3), 3);
2247 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2248 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2250 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2251 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2253 if (N->getNumOperands() != 4)
2256 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2257 return isUndefOrEqual(N->getOperand(0), 2) &&
2258 isUndefOrEqual(N->getOperand(1), 3) &&
2259 isUndefOrEqual(N->getOperand(2), 2) &&
2260 isUndefOrEqual(N->getOperand(3), 3);
2263 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2264 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2265 bool X86::isMOVLPMask(SDNode *N) {
2266 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2268 unsigned NumElems = N->getNumOperands();
2269 if (NumElems != 2 && NumElems != 4)
2272 for (unsigned i = 0; i < NumElems/2; ++i)
2273 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2276 for (unsigned i = NumElems/2; i < NumElems; ++i)
2277 if (!isUndefOrEqual(N->getOperand(i), i))
2283 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2284 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2286 bool X86::isMOVHPMask(SDNode *N) {
2287 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2289 unsigned NumElems = N->getNumOperands();
2290 if (NumElems != 2 && NumElems != 4)
2293 for (unsigned i = 0; i < NumElems/2; ++i)
2294 if (!isUndefOrEqual(N->getOperand(i), i))
2297 for (unsigned i = 0; i < NumElems/2; ++i) {
2298 SDValue Arg = N->getOperand(i + NumElems/2);
2299 if (!isUndefOrEqual(Arg, i + NumElems))
2306 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2307 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2308 template<class SDOperand>
2309 bool static isUNPCKLMask(SDOperand *Elts, unsigned NumElts,
2310 bool V2IsSplat = false) {
2311 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2314 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2315 SDValue BitI = Elts[i];
2316 SDValue BitI1 = Elts[i+1];
2317 if (!isUndefOrEqual(BitI, j))
2320 if (isUndefOrEqual(BitI1, NumElts))
2323 if (!isUndefOrEqual(BitI1, j + NumElts))
2331 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2332 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2333 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2336 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2337 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2338 template<class SDOperand>
2339 bool static isUNPCKHMask(SDOperand *Elts, unsigned NumElts,
2340 bool V2IsSplat = false) {
2341 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2344 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2345 SDValue BitI = Elts[i];
2346 SDValue BitI1 = Elts[i+1];
2347 if (!isUndefOrEqual(BitI, j + NumElts/2))
2350 if (isUndefOrEqual(BitI1, NumElts))
2353 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2361 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2362 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2363 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2366 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2367 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2369 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2370 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2372 unsigned NumElems = N->getNumOperands();
2373 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2376 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2377 SDValue BitI = N->getOperand(i);
2378 SDValue BitI1 = N->getOperand(i+1);
2380 if (!isUndefOrEqual(BitI, j))
2382 if (!isUndefOrEqual(BitI1, j))
2389 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2390 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2392 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2393 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2395 unsigned NumElems = N->getNumOperands();
2396 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2399 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2400 SDValue BitI = N->getOperand(i);
2401 SDValue BitI1 = N->getOperand(i + 1);
2403 if (!isUndefOrEqual(BitI, j))
2405 if (!isUndefOrEqual(BitI1, j))
2412 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2413 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2414 /// MOVSD, and MOVD, i.e. setting the lowest element.
2415 template<class SDOperand>
2416 static bool isMOVLMask(SDOperand *Elts, unsigned NumElts) {
2417 if (NumElts != 2 && NumElts != 4)
2420 if (!isUndefOrEqual(Elts[0], NumElts))
2423 for (unsigned i = 1; i < NumElts; ++i) {
2424 if (!isUndefOrEqual(Elts[i], i))
2431 bool X86::isMOVLMask(SDNode *N) {
2432 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2433 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2436 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2437 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2438 /// element of vector 2 and the other elements to come from vector 1 in order.
2439 template<class SDOperand>
2440 static bool isCommutedMOVL(SDOperand *Ops, unsigned NumOps,
2441 bool V2IsSplat = false,
2442 bool V2IsUndef = false) {
2443 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2446 if (!isUndefOrEqual(Ops[0], 0))
2449 for (unsigned i = 1; i < NumOps; ++i) {
2450 SDValue Arg = Ops[i];
2451 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2452 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2453 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2460 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2461 bool V2IsUndef = false) {
2462 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2463 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2464 V2IsSplat, V2IsUndef);
2467 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2468 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2469 bool X86::isMOVSHDUPMask(SDNode *N) {
2470 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2472 if (N->getNumOperands() != 4)
2475 // Expect 1, 1, 3, 3
2476 for (unsigned i = 0; i < 2; ++i) {
2477 SDValue Arg = N->getOperand(i);
2478 if (Arg.getOpcode() == ISD::UNDEF) continue;
2479 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2480 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2481 if (Val != 1) return false;
2485 for (unsigned i = 2; i < 4; ++i) {
2486 SDValue Arg = N->getOperand(i);
2487 if (Arg.getOpcode() == ISD::UNDEF) continue;
2488 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2489 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2490 if (Val != 3) return false;
2494 // Don't use movshdup if it can be done with a shufps.
2498 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2499 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2500 bool X86::isMOVSLDUPMask(SDNode *N) {
2501 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2503 if (N->getNumOperands() != 4)
2506 // Expect 0, 0, 2, 2
2507 for (unsigned i = 0; i < 2; ++i) {
2508 SDValue Arg = N->getOperand(i);
2509 if (Arg.getOpcode() == ISD::UNDEF) continue;
2510 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2511 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2512 if (Val != 0) return false;
2516 for (unsigned i = 2; i < 4; ++i) {
2517 SDValue Arg = N->getOperand(i);
2518 if (Arg.getOpcode() == ISD::UNDEF) continue;
2519 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2520 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2521 if (Val != 2) return false;
2525 // Don't use movshdup if it can be done with a shufps.
2529 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2530 /// specifies a identity operation on the LHS or RHS.
2531 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2532 unsigned NumElems = N->getNumOperands();
2533 for (unsigned i = 0; i < NumElems; ++i)
2534 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2539 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2540 /// a splat of a single element.
2541 static bool isSplatMask(SDNode *N) {
2542 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2544 // This is a splat operation if each element of the permute is the same, and
2545 // if the value doesn't reference the second vector.
2546 unsigned NumElems = N->getNumOperands();
2547 SDValue ElementBase;
2549 for (; i != NumElems; ++i) {
2550 SDValue Elt = N->getOperand(i);
2551 if (isa<ConstantSDNode>(Elt)) {
2557 if (!ElementBase.getNode())
2560 for (; i != NumElems; ++i) {
2561 SDValue Arg = N->getOperand(i);
2562 if (Arg.getOpcode() == ISD::UNDEF) continue;
2563 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2564 if (Arg != ElementBase) return false;
2567 // Make sure it is a splat of the first vector operand.
2568 return cast<ConstantSDNode>(ElementBase)->getZExtValue() < NumElems;
2571 /// getSplatMaskEltNo - Given a splat mask, return the index to the element
2572 /// we want to splat.
2573 static SDValue getSplatMaskEltNo(SDNode *N) {
2574 assert(isSplatMask(N) && "Not a splat mask");
2575 unsigned NumElems = N->getNumOperands();
2576 SDValue ElementBase;
2578 for (; i != NumElems; ++i) {
2579 SDValue Elt = N->getOperand(i);
2580 if (isa<ConstantSDNode>(Elt))
2583 assert(0 && " No splat value found!");
2588 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2589 /// a splat of a single element and it's a 2 or 4 element mask.
2590 bool X86::isSplatMask(SDNode *N) {
2591 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2593 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2594 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2596 return ::isSplatMask(N);
2599 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2600 /// specifies a splat of zero element.
2601 bool X86::isSplatLoMask(SDNode *N) {
2602 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2604 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2605 if (!isUndefOrEqual(N->getOperand(i), 0))
2610 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2611 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2612 bool X86::isMOVDDUPMask(SDNode *N) {
2613 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2615 unsigned e = N->getNumOperands() / 2;
2616 for (unsigned i = 0; i < e; ++i)
2617 if (!isUndefOrEqual(N->getOperand(i), i))
2619 for (unsigned i = 0; i < e; ++i)
2620 if (!isUndefOrEqual(N->getOperand(e+i), i))
2625 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2626 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2628 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2629 unsigned NumOperands = N->getNumOperands();
2630 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2632 for (unsigned i = 0; i < NumOperands; ++i) {
2634 SDValue Arg = N->getOperand(NumOperands-i-1);
2635 if (Arg.getOpcode() != ISD::UNDEF)
2636 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2637 if (Val >= NumOperands) Val -= NumOperands;
2639 if (i != NumOperands - 1)
2646 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2647 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2649 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2651 // 8 nodes, but we only care about the last 4.
2652 for (unsigned i = 7; i >= 4; --i) {
2654 SDValue Arg = N->getOperand(i);
2655 if (Arg.getOpcode() != ISD::UNDEF)
2656 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2665 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2666 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2668 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2670 // 8 nodes, but we only care about the first 4.
2671 for (int i = 3; i >= 0; --i) {
2673 SDValue Arg = N->getOperand(i);
2674 if (Arg.getOpcode() != ISD::UNDEF)
2675 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2684 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2685 /// specifies a 8 element shuffle that can be broken into a pair of
2686 /// PSHUFHW and PSHUFLW.
2687 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2688 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2690 if (N->getNumOperands() != 8)
2693 // Lower quadword shuffled.
2694 for (unsigned i = 0; i != 4; ++i) {
2695 SDValue Arg = N->getOperand(i);
2696 if (Arg.getOpcode() == ISD::UNDEF) continue;
2697 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2698 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2703 // Upper quadword shuffled.
2704 for (unsigned i = 4; i != 8; ++i) {
2705 SDValue Arg = N->getOperand(i);
2706 if (Arg.getOpcode() == ISD::UNDEF) continue;
2707 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2708 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2709 if (Val < 4 || Val > 7)
2716 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2717 /// values in ther permute mask.
2718 static SDValue CommuteVectorShuffle(SDValue Op, SDValue &V1,
2719 SDValue &V2, SDValue &Mask,
2720 SelectionDAG &DAG) {
2721 MVT VT = Op.getValueType();
2722 MVT MaskVT = Mask.getValueType();
2723 MVT EltVT = MaskVT.getVectorElementType();
2724 unsigned NumElems = Mask.getNumOperands();
2725 SmallVector<SDValue, 8> MaskVec;
2726 DebugLoc dl = Op.getNode()->getDebugLoc();
2728 for (unsigned i = 0; i != NumElems; ++i) {
2729 SDValue Arg = Mask.getOperand(i);
2730 if (Arg.getOpcode() == ISD::UNDEF) {
2731 MaskVec.push_back(DAG.getNode(ISD::UNDEF, dl, EltVT));
2734 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2735 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2737 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2739 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2743 Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT, &MaskVec[0], NumElems);
2744 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, Mask);
2747 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2748 /// the two vector operands have swapped position.
2750 SDValue CommuteVectorShuffleMask(SDValue Mask, SelectionDAG &DAG, DebugLoc dl) {
2751 MVT MaskVT = Mask.getValueType();
2752 MVT EltVT = MaskVT.getVectorElementType();
2753 unsigned NumElems = Mask.getNumOperands();
2754 SmallVector<SDValue, 8> MaskVec;
2755 for (unsigned i = 0; i != NumElems; ++i) {
2756 SDValue Arg = Mask.getOperand(i);
2757 if (Arg.getOpcode() == ISD::UNDEF) {
2758 MaskVec.push_back(DAG.getNode(ISD::UNDEF, dl, EltVT));
2761 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2762 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2764 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2766 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2768 return DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT, &MaskVec[0], NumElems);
2772 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2773 /// match movhlps. The lower half elements should come from upper half of
2774 /// V1 (and in order), and the upper half elements should come from the upper
2775 /// half of V2 (and in order).
2776 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2777 unsigned NumElems = Mask->getNumOperands();
2780 for (unsigned i = 0, e = 2; i != e; ++i)
2781 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2783 for (unsigned i = 2; i != 4; ++i)
2784 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2789 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2790 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2792 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2793 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
2795 N = N->getOperand(0).getNode();
2796 if (!ISD::isNON_EXTLoad(N))
2799 *LD = cast<LoadSDNode>(N);
2803 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2804 /// match movlp{s|d}. The lower half elements should come from lower half of
2805 /// V1 (and in order), and the upper half elements should come from the upper
2806 /// half of V2 (and in order). And since V1 will become the source of the
2807 /// MOVLP, it must be either a vector load or a scalar load to vector.
2808 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2809 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2811 // Is V2 is a vector load, don't do this transformation. We will try to use
2812 // load folding shufps op.
2813 if (ISD::isNON_EXTLoad(V2))
2816 unsigned NumElems = Mask->getNumOperands();
2817 if (NumElems != 2 && NumElems != 4)
2819 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2820 if (!isUndefOrEqual(Mask->getOperand(i), i))
2822 for (unsigned i = NumElems/2; i != NumElems; ++i)
2823 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2828 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2830 static bool isSplatVector(SDNode *N) {
2831 if (N->getOpcode() != ISD::BUILD_VECTOR)
2834 SDValue SplatValue = N->getOperand(0);
2835 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2836 if (N->getOperand(i) != SplatValue)
2841 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2843 static bool isUndefShuffle(SDNode *N) {
2844 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2847 SDValue V1 = N->getOperand(0);
2848 SDValue V2 = N->getOperand(1);
2849 SDValue Mask = N->getOperand(2);
2850 unsigned NumElems = Mask.getNumOperands();
2851 for (unsigned i = 0; i != NumElems; ++i) {
2852 SDValue Arg = Mask.getOperand(i);
2853 if (Arg.getOpcode() != ISD::UNDEF) {
2854 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2855 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2857 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2864 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2866 static inline bool isZeroNode(SDValue Elt) {
2867 return ((isa<ConstantSDNode>(Elt) &&
2868 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2869 (isa<ConstantFPSDNode>(Elt) &&
2870 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2873 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2874 /// to an zero vector.
2875 static bool isZeroShuffle(SDNode *N) {
2876 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2879 SDValue V1 = N->getOperand(0);
2880 SDValue V2 = N->getOperand(1);
2881 SDValue Mask = N->getOperand(2);
2882 unsigned NumElems = Mask.getNumOperands();
2883 for (unsigned i = 0; i != NumElems; ++i) {
2884 SDValue Arg = Mask.getOperand(i);
2885 if (Arg.getOpcode() == ISD::UNDEF)
2888 unsigned Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2889 if (Idx < NumElems) {
2890 unsigned Opc = V1.getNode()->getOpcode();
2891 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
2893 if (Opc != ISD::BUILD_VECTOR ||
2894 !isZeroNode(V1.getNode()->getOperand(Idx)))
2896 } else if (Idx >= NumElems) {
2897 unsigned Opc = V2.getNode()->getOpcode();
2898 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
2900 if (Opc != ISD::BUILD_VECTOR ||
2901 !isZeroNode(V2.getNode()->getOperand(Idx - NumElems)))
2908 /// getZeroVector - Returns a vector of specified type with all zero elements.
2910 static SDValue getZeroVector(MVT VT, bool HasSSE2, SelectionDAG &DAG,
2912 assert(VT.isVector() && "Expected a vector type");
2914 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2915 // type. This ensures they get CSE'd.
2917 if (VT.getSizeInBits() == 64) { // MMX
2918 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2919 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2920 } else if (HasSSE2) { // SSE2
2921 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2922 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2924 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2925 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
2927 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2930 /// getOnesVector - Returns a vector of specified type with all bits set.
2932 static SDValue getOnesVector(MVT VT, SelectionDAG &DAG, DebugLoc dl) {
2933 assert(VT.isVector() && "Expected a vector type");
2935 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2936 // type. This ensures they get CSE'd.
2937 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2939 if (VT.getSizeInBits() == 64) // MMX
2940 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2942 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2943 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2947 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2948 /// that point to V2 points to its first element.
2949 static SDValue NormalizeMask(SDValue Mask, SelectionDAG &DAG) {
2950 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2952 bool Changed = false;
2953 SmallVector<SDValue, 8> MaskVec;
2954 unsigned NumElems = Mask.getNumOperands();
2955 for (unsigned i = 0; i != NumElems; ++i) {
2956 SDValue Arg = Mask.getOperand(i);
2957 if (Arg.getOpcode() != ISD::UNDEF) {
2958 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2959 if (Val > NumElems) {
2960 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2964 MaskVec.push_back(Arg);
2968 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getNode()->getDebugLoc(),
2969 Mask.getValueType(),
2970 &MaskVec[0], MaskVec.size());
2974 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2975 /// operation of specified width.
2976 static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG, DebugLoc dl) {
2977 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2978 MVT BaseVT = MaskVT.getVectorElementType();
2980 SmallVector<SDValue, 8> MaskVec;
2981 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2982 for (unsigned i = 1; i != NumElems; ++i)
2983 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2984 return DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
2985 &MaskVec[0], MaskVec.size());
2988 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2989 /// of specified width.
2990 static SDValue getUnpacklMask(unsigned NumElems, SelectionDAG &DAG,
2992 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2993 MVT BaseVT = MaskVT.getVectorElementType();
2994 SmallVector<SDValue, 8> MaskVec;
2995 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2996 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2997 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2999 return DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3000 &MaskVec[0], MaskVec.size());
3003 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
3004 /// of specified width.
3005 static SDValue getUnpackhMask(unsigned NumElems, SelectionDAG &DAG,
3007 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3008 MVT BaseVT = MaskVT.getVectorElementType();
3009 unsigned Half = NumElems/2;
3010 SmallVector<SDValue, 8> MaskVec;
3011 for (unsigned i = 0; i != Half; ++i) {
3012 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
3013 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
3015 return DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3016 &MaskVec[0], MaskVec.size());
3019 /// getSwapEltZeroMask - Returns a vector_shuffle mask for a shuffle that swaps
3020 /// element #0 of a vector with the specified index, leaving the rest of the
3021 /// elements in place.
3022 static SDValue getSwapEltZeroMask(unsigned NumElems, unsigned DestElt,
3023 SelectionDAG &DAG, DebugLoc dl) {
3024 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3025 MVT BaseVT = MaskVT.getVectorElementType();
3026 SmallVector<SDValue, 8> MaskVec;
3027 // Element #0 of the result gets the elt we are replacing.
3028 MaskVec.push_back(DAG.getConstant(DestElt, BaseVT));
3029 for (unsigned i = 1; i != NumElems; ++i)
3030 MaskVec.push_back(DAG.getConstant(i == DestElt ? 0 : i, BaseVT));
3031 return DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3032 &MaskVec[0], MaskVec.size());
3035 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3036 static SDValue PromoteSplat(SDValue Op, SelectionDAG &DAG, bool HasSSE2) {
3037 MVT PVT = HasSSE2 ? MVT::v4i32 : MVT::v4f32;
3038 MVT VT = Op.getValueType();
3041 SDValue V1 = Op.getOperand(0);
3042 SDValue Mask = Op.getOperand(2);
3043 unsigned MaskNumElems = Mask.getNumOperands();
3044 unsigned NumElems = MaskNumElems;
3045 DebugLoc dl = Op.getNode()->getDebugLoc();
3046 // Special handling of v4f32 -> v4i32.
3047 if (VT != MVT::v4f32) {
3048 // Find which element we want to splat.
3049 SDNode* EltNoNode = getSplatMaskEltNo(Mask.getNode()).getNode();
3050 unsigned EltNo = cast<ConstantSDNode>(EltNoNode)->getZExtValue();
3051 // unpack elements to the correct location
3052 while (NumElems > 4) {
3053 if (EltNo < NumElems/2) {
3054 Mask = getUnpacklMask(MaskNumElems, DAG, dl);
3056 Mask = getUnpackhMask(MaskNumElems, DAG, dl);
3057 EltNo -= NumElems/2;
3059 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V1, Mask);
3062 SDValue Cst = DAG.getConstant(EltNo, MVT::i32);
3063 Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3066 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3067 SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, PVT, V1,
3068 DAG.getNode(ISD::UNDEF, PVT), Mask);
3069 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Shuffle);
3072 /// isVectorLoad - Returns true if the node is a vector load, a scalar
3073 /// load that's promoted to vector, or a load bitcasted.
3074 static bool isVectorLoad(SDValue Op) {
3075 assert(Op.getValueType().isVector() && "Expected a vector type");
3076 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR ||
3077 Op.getOpcode() == ISD::BIT_CONVERT) {
3078 return isa<LoadSDNode>(Op.getOperand(0));
3080 return isa<LoadSDNode>(Op);
3084 /// CanonicalizeMovddup - Cannonicalize movddup shuffle to v2f64.
3086 static SDValue CanonicalizeMovddup(SDValue Op, SDValue V1, SDValue Mask,
3087 SelectionDAG &DAG, bool HasSSE3) {
3088 // If we have sse3 and shuffle has more than one use or input is a load, then
3089 // use movddup. Otherwise, use movlhps.
3090 bool UseMovddup = HasSSE3 && (!Op.hasOneUse() || isVectorLoad(V1));
3091 MVT PVT = UseMovddup ? MVT::v2f64 : MVT::v4f32;
3092 MVT VT = Op.getValueType();
3095 DebugLoc dl = Op.getNode()->getDebugLoc();
3096 unsigned NumElems = PVT.getVectorNumElements();
3097 if (NumElems == 2) {
3098 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3099 Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3101 assert(NumElems == 4);
3102 SDValue Cst0 = DAG.getTargetConstant(0, MVT::i32);
3103 SDValue Cst1 = DAG.getTargetConstant(1, MVT::i32);
3104 Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
3105 Cst0, Cst1, Cst0, Cst1);
3108 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3109 SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, PVT, V1,
3110 DAG.getNode(ISD::UNDEF, dl, PVT), Mask);
3111 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Shuffle);
3114 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3115 /// vector of zero or undef vector. This produces a shuffle where the low
3116 /// element of V2 is swizzled into the zero/undef vector, landing at element
3117 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3118 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3119 bool isZero, bool HasSSE2,
3120 SelectionDAG &DAG) {
3121 DebugLoc dl = V2.getNode()->getDebugLoc();
3122 MVT VT = V2.getValueType();
3124 ? getZeroVector(VT, HasSSE2, DAG, dl) : DAG.getNode(ISD::UNDEF, dl, VT);
3125 unsigned NumElems = V2.getValueType().getVectorNumElements();
3126 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3127 MVT EVT = MaskVT.getVectorElementType();
3128 SmallVector<SDValue, 16> MaskVec;
3129 for (unsigned i = 0; i != NumElems; ++i)
3130 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
3131 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
3133 MaskVec.push_back(DAG.getConstant(i, EVT));
3134 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3135 &MaskVec[0], MaskVec.size());
3136 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, Mask);
3139 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3140 /// a shuffle that is zero.
3142 unsigned getNumOfConsecutiveZeros(SDValue Op, SDValue Mask,
3143 unsigned NumElems, bool Low,
3144 SelectionDAG &DAG) {
3145 unsigned NumZeros = 0;
3146 for (unsigned i = 0; i < NumElems; ++i) {
3147 unsigned Index = Low ? i : NumElems-i-1;
3148 SDValue Idx = Mask.getOperand(Index);
3149 if (Idx.getOpcode() == ISD::UNDEF) {
3153 SDValue Elt = DAG.getShuffleScalarElt(Op.getNode(), Index);
3154 if (Elt.getNode() && isZeroNode(Elt))
3162 /// isVectorShift - Returns true if the shuffle can be implemented as a
3163 /// logical left or right shift of a vector.
3164 static bool isVectorShift(SDValue Op, SDValue Mask, SelectionDAG &DAG,
3165 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3166 unsigned NumElems = Mask.getNumOperands();
3169 unsigned NumZeros= getNumOfConsecutiveZeros(Op, Mask, NumElems, true, DAG);
3172 NumZeros = getNumOfConsecutiveZeros(Op, Mask, NumElems, false, DAG);
3177 bool SeenV1 = false;
3178 bool SeenV2 = false;
3179 for (unsigned i = NumZeros; i < NumElems; ++i) {
3180 unsigned Val = isLeft ? (i - NumZeros) : i;
3181 SDValue Idx = Mask.getOperand(isLeft ? i : (i - NumZeros));
3182 if (Idx.getOpcode() == ISD::UNDEF)
3184 unsigned Index = cast<ConstantSDNode>(Idx)->getZExtValue();
3185 if (Index < NumElems)
3194 if (SeenV1 && SeenV2)
3197 ShVal = SeenV1 ? Op.getOperand(0) : Op.getOperand(1);
3203 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3205 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3206 unsigned NumNonZero, unsigned NumZero,
3207 SelectionDAG &DAG, TargetLowering &TLI) {
3211 DebugLoc dl = Op.getNode()->getDebugLoc();
3214 for (unsigned i = 0; i < 16; ++i) {
3215 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3216 if (ThisIsNonZero && First) {
3218 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3220 V = DAG.getNode(ISD::UNDEF, dl, MVT::v8i16);
3225 SDValue ThisElt(0, 0), LastElt(0, 0);
3226 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3227 if (LastIsNonZero) {
3228 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3229 MVT::i16, Op.getOperand(i-1));
3231 if (ThisIsNonZero) {
3232 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3233 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3234 ThisElt, DAG.getConstant(8, MVT::i8));
3236 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3240 if (ThisElt.getNode())
3241 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3242 DAG.getIntPtrConstant(i/2));
3246 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3249 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3251 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3252 unsigned NumNonZero, unsigned NumZero,
3253 SelectionDAG &DAG, TargetLowering &TLI) {
3257 DebugLoc dl = Op.getNode()->getDebugLoc();
3260 for (unsigned i = 0; i < 8; ++i) {
3261 bool isNonZero = (NonZeros & (1 << i)) != 0;
3265 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3267 V = DAG.getNode(ISD::UNDEF, dl, MVT::v8i16);
3270 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3271 MVT::v8i16, V, Op.getOperand(i),
3272 DAG.getIntPtrConstant(i));
3279 /// getVShift - Return a vector logical shift node.
3281 static SDValue getVShift(bool isLeft, MVT VT, SDValue SrcOp,
3282 unsigned NumBits, SelectionDAG &DAG,
3283 const TargetLowering &TLI, DebugLoc dl) {
3284 bool isMMX = VT.getSizeInBits() == 64;
3285 MVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3286 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3287 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3288 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3289 DAG.getNode(Opc, dl, ShVT, SrcOp,
3290 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3294 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3295 DebugLoc dl = Op.getNode()->getDebugLoc();
3296 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3297 if (ISD::isBuildVectorAllZeros(Op.getNode())
3298 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3299 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3300 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3301 // eliminated on x86-32 hosts.
3302 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3305 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3306 return getOnesVector(Op.getValueType(), DAG, dl);
3307 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3310 MVT VT = Op.getValueType();
3311 MVT EVT = VT.getVectorElementType();
3312 unsigned EVTBits = EVT.getSizeInBits();
3314 unsigned NumElems = Op.getNumOperands();
3315 unsigned NumZero = 0;
3316 unsigned NumNonZero = 0;
3317 unsigned NonZeros = 0;
3318 bool IsAllConstants = true;
3319 SmallSet<SDValue, 8> Values;
3320 for (unsigned i = 0; i < NumElems; ++i) {
3321 SDValue Elt = Op.getOperand(i);
3322 if (Elt.getOpcode() == ISD::UNDEF)
3325 if (Elt.getOpcode() != ISD::Constant &&
3326 Elt.getOpcode() != ISD::ConstantFP)
3327 IsAllConstants = false;
3328 if (isZeroNode(Elt))
3331 NonZeros |= (1 << i);
3336 if (NumNonZero == 0) {
3337 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3338 return DAG.getNode(ISD::UNDEF, dl, VT);
3341 // Special case for single non-zero, non-undef, element.
3342 if (NumNonZero == 1 && NumElems <= 4) {
3343 unsigned Idx = CountTrailingZeros_32(NonZeros);
3344 SDValue Item = Op.getOperand(Idx);
3346 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3347 // the value are obviously zero, truncate the value to i32 and do the
3348 // insertion that way. Only do this if the value is non-constant or if the
3349 // value is a constant being inserted into element 0. It is cheaper to do
3350 // a constant pool load than it is to do a movd + shuffle.
3351 if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3352 (!IsAllConstants || Idx == 0)) {
3353 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3354 // Handle MMX and SSE both.
3355 MVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3356 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3358 // Truncate the value (which may itself be a constant) to i32, and
3359 // convert it to a vector with movd (S2V+shuffle to zero extend).
3360 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3361 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3362 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3363 Subtarget->hasSSE2(), DAG);
3365 // Now we have our 32-bit value zero extended in the low element of
3366 // a vector. If Idx != 0, swizzle it into place.
3369 Item, DAG.getNode(ISD::UNDEF, dl, Item.getValueType()),
3370 getSwapEltZeroMask(VecElts, Idx, DAG, dl)
3372 Item = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VecVT, Ops, 3);
3374 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3378 // If we have a constant or non-constant insertion into the low element of
3379 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3380 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3381 // depending on what the source datatype is. Because we can only get here
3382 // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3384 // Don't do this for i64 values on x86-32.
3385 (EVT != MVT::i64 || Subtarget->is64Bit())) {
3386 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3387 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3388 return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3389 Subtarget->hasSSE2(), DAG);
3392 // Is it a vector logical left shift?
3393 if (NumElems == 2 && Idx == 1 &&
3394 isZeroNode(Op.getOperand(0)) && !isZeroNode(Op.getOperand(1))) {
3395 unsigned NumBits = VT.getSizeInBits();
3396 return getVShift(true, VT,
3397 DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(1)),
3398 NumBits/2, DAG, *this, dl);
3401 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3404 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3405 // is a non-constant being inserted into an element other than the low one,
3406 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3407 // movd/movss) to move this into the low element, then shuffle it into
3409 if (EVTBits == 32) {
3410 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3412 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3413 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3414 Subtarget->hasSSE2(), DAG);
3415 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3416 MVT MaskEVT = MaskVT.getVectorElementType();
3417 SmallVector<SDValue, 8> MaskVec;
3418 for (unsigned i = 0; i < NumElems; i++)
3419 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3420 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3421 &MaskVec[0], MaskVec.size());
3422 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, Item,
3423 DAG.getNode(ISD::UNDEF, VT), Mask);
3427 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3428 if (Values.size() == 1)
3431 // A vector full of immediates; various special cases are already
3432 // handled, so this is best done with a single constant-pool load.
3436 // Let legalizer expand 2-wide build_vectors.
3437 if (EVTBits == 64) {
3438 if (NumNonZero == 1) {
3439 // One half is zero or undef.
3440 unsigned Idx = CountTrailingZeros_32(NonZeros);
3441 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3442 Op.getOperand(Idx));
3443 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3444 Subtarget->hasSSE2(), DAG);
3449 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3450 if (EVTBits == 8 && NumElems == 16) {
3451 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3453 if (V.getNode()) return V;
3456 if (EVTBits == 16 && NumElems == 8) {
3457 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3459 if (V.getNode()) return V;
3462 // If element VT is == 32 bits, turn it into a number of shuffles.
3463 SmallVector<SDValue, 8> V;
3465 if (NumElems == 4 && NumZero > 0) {
3466 for (unsigned i = 0; i < 4; ++i) {
3467 bool isZero = !(NonZeros & (1 << i));
3469 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3471 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3474 for (unsigned i = 0; i < 2; ++i) {
3475 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3478 V[i] = V[i*2]; // Must be a zero vector.
3481 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[i*2+1], V[i*2],
3482 getMOVLMask(NumElems, DAG, dl));
3485 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[i*2], V[i*2+1],
3486 getMOVLMask(NumElems, DAG, dl));
3489 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[i*2], V[i*2+1],
3490 getUnpacklMask(NumElems, DAG, dl));
3495 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3496 MVT EVT = MaskVT.getVectorElementType();
3497 SmallVector<SDValue, 8> MaskVec;
3498 bool Reverse = (NonZeros & 0x3) == 2;
3499 for (unsigned i = 0; i < 2; ++i)
3501 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3503 MaskVec.push_back(DAG.getConstant(i, EVT));
3504 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3505 for (unsigned i = 0; i < 2; ++i)
3507 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3509 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3510 SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3511 &MaskVec[0], MaskVec.size());
3512 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[0], V[1], ShufMask);
3515 if (Values.size() > 2) {
3516 // Expand into a number of unpckl*.
3518 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3519 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3520 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3521 SDValue UnpckMask = getUnpacklMask(NumElems, DAG, dl);
3522 for (unsigned i = 0; i < NumElems; ++i)
3523 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3525 while (NumElems != 0) {
3526 for (unsigned i = 0; i < NumElems; ++i)
3527 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[i], V[i + NumElems],
3538 SDValue LowerVECTOR_SHUFFLEv8i16(SDValue V1, SDValue V2,
3539 SDValue PermMask, SelectionDAG &DAG,
3540 TargetLowering &TLI, DebugLoc dl) {
3542 MVT MaskVT = MVT::getIntVectorWithNumElements(8);
3543 MVT MaskEVT = MaskVT.getVectorElementType();
3544 MVT PtrVT = TLI.getPointerTy();
3545 SmallVector<SDValue, 8> MaskElts(PermMask.getNode()->op_begin(),
3546 PermMask.getNode()->op_end());
3548 // First record which half of which vector the low elements come from.
3549 SmallVector<unsigned, 4> LowQuad(4);
3550 for (unsigned i = 0; i < 4; ++i) {
3551 SDValue Elt = MaskElts[i];
3552 if (Elt.getOpcode() == ISD::UNDEF)
3554 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3555 int QuadIdx = EltIdx / 4;
3559 int BestLowQuad = -1;
3560 unsigned MaxQuad = 1;
3561 for (unsigned i = 0; i < 4; ++i) {
3562 if (LowQuad[i] > MaxQuad) {
3564 MaxQuad = LowQuad[i];
3568 // Record which half of which vector the high elements come from.
3569 SmallVector<unsigned, 4> HighQuad(4);
3570 for (unsigned i = 4; i < 8; ++i) {
3571 SDValue Elt = MaskElts[i];
3572 if (Elt.getOpcode() == ISD::UNDEF)
3574 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3575 int QuadIdx = EltIdx / 4;
3576 ++HighQuad[QuadIdx];
3579 int BestHighQuad = -1;
3581 for (unsigned i = 0; i < 4; ++i) {
3582 if (HighQuad[i] > MaxQuad) {
3584 MaxQuad = HighQuad[i];
3588 // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3589 if (BestLowQuad != -1 || BestHighQuad != -1) {
3590 // First sort the 4 chunks in order using shufpd.
3591 SmallVector<SDValue, 8> MaskVec;
3593 if (BestLowQuad != -1)
3594 MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3596 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3598 if (BestHighQuad != -1)
3599 MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3601 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3603 SDValue Mask= DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, &MaskVec[0],2);
3604 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v2i64,
3605 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
3606 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), Mask);
3607 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
3609 // Now sort high and low parts separately.
3610 BitVector InOrder(8);
3611 if (BestLowQuad != -1) {
3612 // Sort lower half in order using PSHUFLW.
3614 bool AnyOutOrder = false;
3616 for (unsigned i = 0; i != 4; ++i) {
3617 SDValue Elt = MaskElts[i];
3618 if (Elt.getOpcode() == ISD::UNDEF) {
3619 MaskVec.push_back(Elt);
3622 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3626 MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3628 // If this element is in the right place after this shuffle, then
3630 if ((int)(EltIdx / 4) == BestLowQuad)
3635 for (unsigned i = 4; i != 8; ++i)
3636 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3637 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3639 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v8i16,
3644 if (BestHighQuad != -1) {
3645 // Sort high half in order using PSHUFHW if possible.
3648 for (unsigned i = 0; i != 4; ++i)
3649 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3651 bool AnyOutOrder = false;
3652 for (unsigned i = 4; i != 8; ++i) {
3653 SDValue Elt = MaskElts[i];
3654 if (Elt.getOpcode() == ISD::UNDEF) {
3655 MaskVec.push_back(Elt);
3658 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3662 MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3664 // If this element is in the right place after this shuffle, then
3666 if ((int)(EltIdx / 4) == BestHighQuad)
3672 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl,
3673 MaskVT, &MaskVec[0], 8);
3674 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v8i16,
3679 // The other elements are put in the right place using pextrw and pinsrw.
3680 for (unsigned i = 0; i != 8; ++i) {
3683 SDValue Elt = MaskElts[i];
3684 if (Elt.getOpcode() == ISD::UNDEF)
3686 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3687 SDValue ExtOp = (EltIdx < 8)
3688 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
3689 DAG.getConstant(EltIdx, PtrVT))
3690 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
3691 DAG.getConstant(EltIdx - 8, PtrVT));
3692 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3693 DAG.getConstant(i, PtrVT));
3699 // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use as
3700 // few as possible. First, let's find out how many elements are already in the
3702 unsigned V1InOrder = 0;
3703 unsigned V1FromV1 = 0;
3704 unsigned V2InOrder = 0;
3705 unsigned V2FromV2 = 0;
3706 SmallVector<SDValue, 8> V1Elts;
3707 SmallVector<SDValue, 8> V2Elts;
3708 for (unsigned i = 0; i < 8; ++i) {
3709 SDValue Elt = MaskElts[i];
3710 if (Elt.getOpcode() == ISD::UNDEF) {
3711 V1Elts.push_back(Elt);
3712 V2Elts.push_back(Elt);
3717 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3719 V1Elts.push_back(Elt);
3720 V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3722 } else if (EltIdx == i+8) {
3723 V1Elts.push_back(Elt);
3724 V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3726 } else if (EltIdx < 8) {
3727 V1Elts.push_back(Elt);
3728 V2Elts.push_back(DAG.getConstant(EltIdx+8, MaskEVT));
3731 V1Elts.push_back(Elt);
3732 V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3737 if (V2InOrder > V1InOrder) {
3738 PermMask = CommuteVectorShuffleMask(PermMask, DAG, dl);
3740 std::swap(V1Elts, V2Elts);
3741 std::swap(V1FromV1, V2FromV2);
3744 if ((V1FromV1 + V1InOrder) != 8) {
3745 // Some elements are from V2.
3747 // If there are elements that are from V1 but out of place,
3748 // then first sort them in place
3749 SmallVector<SDValue, 8> MaskVec;
3750 for (unsigned i = 0; i < 8; ++i) {
3751 SDValue Elt = V1Elts[i];
3752 if (Elt.getOpcode() == ISD::UNDEF) {
3753 MaskVec.push_back(DAG.getNode(ISD::UNDEF, dl, MaskEVT));
3756 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3758 MaskVec.push_back(DAG.getNode(ISD::UNDEF, dl, MaskEVT));
3760 MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3762 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT, &MaskVec[0], 8);
3763 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v8i16, V1, V1, Mask);
3767 for (unsigned i = 0; i < 8; ++i) {
3768 SDValue Elt = V1Elts[i];
3769 if (Elt.getOpcode() == ISD::UNDEF)
3771 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3774 SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
3775 DAG.getConstant(EltIdx - 8, PtrVT));
3776 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3777 DAG.getConstant(i, PtrVT));
3781 // All elements are from V1.
3783 for (unsigned i = 0; i < 8; ++i) {
3784 SDValue Elt = V1Elts[i];
3785 if (Elt.getOpcode() == ISD::UNDEF)
3787 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3788 SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
3789 DAG.getConstant(EltIdx, PtrVT));
3790 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3791 DAG.getConstant(i, PtrVT));
3797 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3798 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3799 /// done when every pair / quad of shuffle mask elements point to elements in
3800 /// the right sequence. e.g.
3801 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3803 SDValue RewriteAsNarrowerShuffle(SDValue V1, SDValue V2,
3805 SDValue PermMask, SelectionDAG &DAG,
3806 TargetLowering &TLI, DebugLoc dl) {
3807 unsigned NumElems = PermMask.getNumOperands();
3808 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3809 MVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3810 MVT MaskEltVT = MaskVT.getVectorElementType();
3812 switch (VT.getSimpleVT()) {
3813 default: assert(false && "Unexpected!");
3814 case MVT::v4f32: NewVT = MVT::v2f64; break;
3815 case MVT::v4i32: NewVT = MVT::v2i64; break;
3816 case MVT::v8i16: NewVT = MVT::v4i32; break;
3817 case MVT::v16i8: NewVT = MVT::v4i32; break;
3820 if (NewWidth == 2) {
3826 unsigned Scale = NumElems / NewWidth;
3827 SmallVector<SDValue, 8> MaskVec;
3828 for (unsigned i = 0; i < NumElems; i += Scale) {
3829 unsigned StartIdx = ~0U;
3830 for (unsigned j = 0; j < Scale; ++j) {
3831 SDValue Elt = PermMask.getOperand(i+j);
3832 if (Elt.getOpcode() == ISD::UNDEF)
3834 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3835 if (StartIdx == ~0U)
3836 StartIdx = EltIdx - (EltIdx % Scale);
3837 if (EltIdx != StartIdx + j)
3840 if (StartIdx == ~0U)
3841 MaskVec.push_back(DAG.getNode(ISD::UNDEF, dl, MaskEltVT));
3843 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MaskEltVT));
3846 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
3847 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
3848 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, NewVT, V1, V2,
3849 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3850 &MaskVec[0], MaskVec.size()));
3853 /// getVZextMovL - Return a zero-extending vector move low node.
3855 static SDValue getVZextMovL(MVT VT, MVT OpVT,
3856 SDValue SrcOp, SelectionDAG &DAG,
3857 const X86Subtarget *Subtarget, DebugLoc dl) {
3858 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3859 LoadSDNode *LD = NULL;
3860 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
3861 LD = dyn_cast<LoadSDNode>(SrcOp);
3863 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3865 MVT EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3866 if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
3867 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3868 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3869 SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
3871 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3872 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3873 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3874 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3882 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3883 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3884 DAG.getNode(ISD::BIT_CONVERT, dl,
3888 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
3891 LowerVECTOR_SHUFFLE_4wide(SDValue V1, SDValue V2,
3892 SDValue PermMask, MVT VT, SelectionDAG &DAG,
3894 MVT MaskVT = PermMask.getValueType();
3895 MVT MaskEVT = MaskVT.getVectorElementType();
3896 SmallVector<std::pair<int, int>, 8> Locs;
3898 SmallVector<SDValue, 8> Mask1(4, DAG.getNode(ISD::UNDEF, dl, MaskEVT));
3901 for (unsigned i = 0; i != 4; ++i) {
3902 SDValue Elt = PermMask.getOperand(i);
3903 if (Elt.getOpcode() == ISD::UNDEF) {
3904 Locs[i] = std::make_pair(-1, -1);
3906 unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
3907 assert(Val < 8 && "Invalid VECTOR_SHUFFLE index!");
3909 Locs[i] = std::make_pair(0, NumLo);
3913 Locs[i] = std::make_pair(1, NumHi);
3915 Mask1[2+NumHi] = Elt;
3921 if (NumLo <= 2 && NumHi <= 2) {
3922 // If no more than two elements come from either vector. This can be
3923 // implemented with two shuffles. First shuffle gather the elements.
3924 // The second shuffle, which takes the first shuffle as both of its
3925 // vector operands, put the elements into the right order.
3926 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
3927 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3928 &Mask1[0], Mask1.size()));
3930 SmallVector<SDValue, 8> Mask2(4, DAG.getNode(ISD::UNDEF, dl, MaskEVT));
3931 for (unsigned i = 0; i != 4; ++i) {
3932 if (Locs[i].first == -1)
3935 unsigned Idx = (i < 2) ? 0 : 4;
3936 Idx += Locs[i].first * 2 + Locs[i].second;
3937 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3941 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V1,
3942 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3943 &Mask2[0], Mask2.size()));
3944 } else if (NumLo == 3 || NumHi == 3) {
3945 // Otherwise, we must have three elements from one vector, call it X, and
3946 // one element from the other, call it Y. First, use a shufps to build an
3947 // intermediate vector with the one element from Y and the element from X
3948 // that will be in the same half in the final destination (the indexes don't
3949 // matter). Then, use a shufps to build the final vector, taking the half
3950 // containing the element from Y from the intermediate, and the other half
3953 // Normalize it so the 3 elements come from V1.
3954 PermMask = CommuteVectorShuffleMask(PermMask, DAG, dl);
3958 // Find the element from V2.
3960 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
3961 SDValue Elt = PermMask.getOperand(HiIndex);
3962 if (Elt.getOpcode() == ISD::UNDEF)
3964 unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
3969 Mask1[0] = PermMask.getOperand(HiIndex);
3970 Mask1[1] = DAG.getNode(ISD::UNDEF, dl, MaskEVT);
3971 Mask1[2] = PermMask.getOperand(HiIndex^1);
3972 Mask1[3] = DAG.getNode(ISD::UNDEF, dl, MaskEVT);
3973 V2 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
3974 DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3977 Mask1[0] = PermMask.getOperand(0);
3978 Mask1[1] = PermMask.getOperand(1);
3979 Mask1[2] = DAG.getConstant(HiIndex & 1 ? 6 : 4, MaskEVT);
3980 Mask1[3] = DAG.getConstant(HiIndex & 1 ? 4 : 6, MaskEVT);
3981 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
3982 DAG.getNode(ISD::BUILD_VECTOR, dl,
3983 MaskVT, &Mask1[0], 4));
3985 Mask1[0] = DAG.getConstant(HiIndex & 1 ? 2 : 0, MaskEVT);
3986 Mask1[1] = DAG.getConstant(HiIndex & 1 ? 0 : 2, MaskEVT);
3987 Mask1[2] = PermMask.getOperand(2);
3988 Mask1[3] = PermMask.getOperand(3);
3989 if (Mask1[2].getOpcode() != ISD::UNDEF)
3991 DAG.getConstant(cast<ConstantSDNode>(Mask1[2])->getZExtValue()+4,
3993 if (Mask1[3].getOpcode() != ISD::UNDEF)
3995 DAG.getConstant(cast<ConstantSDNode>(Mask1[3])->getZExtValue()+4,
3997 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V2, V1,
3998 DAG.getNode(ISD::BUILD_VECTOR, dl,
3999 MaskVT, &Mask1[0], 4));
4003 // Break it into (shuffle shuffle_hi, shuffle_lo).
4005 SmallVector<SDValue,8> LoMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
4006 SmallVector<SDValue,8> HiMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
4007 SmallVector<SDValue,8> *MaskPtr = &LoMask;
4008 unsigned MaskIdx = 0;
4011 for (unsigned i = 0; i != 4; ++i) {
4018 SDValue Elt = PermMask.getOperand(i);
4019 if (Elt.getOpcode() == ISD::UNDEF) {
4020 Locs[i] = std::make_pair(-1, -1);
4021 } else if (cast<ConstantSDNode>(Elt)->getZExtValue() < 4) {
4022 Locs[i] = std::make_pair(MaskIdx, LoIdx);
4023 (*MaskPtr)[LoIdx] = Elt;
4026 Locs[i] = std::make_pair(MaskIdx, HiIdx);
4027 (*MaskPtr)[HiIdx] = Elt;
4032 SDValue LoShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
4033 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4034 &LoMask[0], LoMask.size()));
4035 SDValue HiShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
4036 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4037 &HiMask[0], HiMask.size()));
4038 SmallVector<SDValue, 8> MaskOps;
4039 for (unsigned i = 0; i != 4; ++i) {
4040 if (Locs[i].first == -1) {
4041 MaskOps.push_back(DAG.getNode(ISD::UNDEF, dl, MaskEVT));
4043 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4044 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
4047 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, LoShuffle, HiShuffle,
4048 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4049 &MaskOps[0], MaskOps.size()));
4053 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4054 SDValue V1 = Op.getOperand(0);
4055 SDValue V2 = Op.getOperand(1);
4056 SDValue PermMask = Op.getOperand(2);
4057 MVT VT = Op.getValueType();
4058 DebugLoc dl = Op.getNode()->getDebugLoc();
4059 unsigned NumElems = PermMask.getNumOperands();
4060 bool isMMX = VT.getSizeInBits() == 64;
4061 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4062 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4063 bool V1IsSplat = false;
4064 bool V2IsSplat = false;
4066 if (isUndefShuffle(Op.getNode()))
4067 return DAG.getNode(ISD::UNDEF, dl, VT);
4069 if (isZeroShuffle(Op.getNode()))
4070 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4072 if (isIdentityMask(PermMask.getNode()))
4074 else if (isIdentityMask(PermMask.getNode(), true))
4077 // Canonicalize movddup shuffles.
4078 if (V2IsUndef && Subtarget->hasSSE2() &&
4079 VT.getSizeInBits() == 128 &&
4080 X86::isMOVDDUPMask(PermMask.getNode()))
4081 return CanonicalizeMovddup(Op, V1, PermMask, DAG, Subtarget->hasSSE3());
4083 if (isSplatMask(PermMask.getNode())) {
4084 if (isMMX || NumElems < 4) return Op;
4085 // Promote it to a v4{if}32 splat.
4086 return PromoteSplat(Op, DAG, Subtarget->hasSSE2());
4089 // If the shuffle can be profitably rewritten as a narrower shuffle, then
4091 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4092 SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG,
4094 if (NewOp.getNode())
4095 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4096 LowerVECTOR_SHUFFLE(NewOp, DAG));
4097 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4098 // FIXME: Figure out a cleaner way to do this.
4099 // Try to make use of movq to zero out the top part.
4100 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4101 SDValue NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
4103 if (NewOp.getNode()) {
4104 SDValue NewV1 = NewOp.getOperand(0);
4105 SDValue NewV2 = NewOp.getOperand(1);
4106 SDValue NewMask = NewOp.getOperand(2);
4107 if (isCommutedMOVL(NewMask.getNode(), true, false)) {
4108 NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
4109 return getVZextMovL(VT, NewOp.getValueType(), NewV2, DAG, Subtarget,
4113 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4114 SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
4116 if (NewOp.getNode() && X86::isMOVLMask(NewOp.getOperand(2).getNode()))
4117 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4118 DAG, Subtarget, dl);
4122 // Check if this can be converted into a logical shift.
4123 bool isLeft = false;
4126 bool isShift = isVectorShift(Op, PermMask, DAG, isLeft, ShVal, ShAmt);
4127 if (isShift && ShVal.hasOneUse()) {
4128 // If the shifted value has multiple uses, it may be cheaper to use
4129 // v_set0 + movlhps or movhlps, etc.
4130 MVT EVT = VT.getVectorElementType();
4131 ShAmt *= EVT.getSizeInBits();
4132 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4135 if (X86::isMOVLMask(PermMask.getNode())) {
4138 if (ISD::isBuildVectorAllZeros(V1.getNode()))
4139 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4144 if (!isMMX && (X86::isMOVSHDUPMask(PermMask.getNode()) ||
4145 X86::isMOVSLDUPMask(PermMask.getNode()) ||
4146 X86::isMOVHLPSMask(PermMask.getNode()) ||
4147 X86::isMOVHPMask(PermMask.getNode()) ||
4148 X86::isMOVLPMask(PermMask.getNode())))
4151 if (ShouldXformToMOVHLPS(PermMask.getNode()) ||
4152 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), PermMask.getNode()))
4153 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4156 // No better options. Use a vshl / vsrl.
4157 MVT EVT = VT.getVectorElementType();
4158 ShAmt *= EVT.getSizeInBits();
4159 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4162 bool Commuted = false;
4163 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4164 // 1,1,1,1 -> v8i16 though.
4165 V1IsSplat = isSplatVector(V1.getNode());
4166 V2IsSplat = isSplatVector(V2.getNode());
4168 // Canonicalize the splat or undef, if present, to be on the RHS.
4169 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4170 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4171 std::swap(V1IsSplat, V2IsSplat);
4172 std::swap(V1IsUndef, V2IsUndef);
4176 // FIXME: Figure out a cleaner way to do this.
4177 if (isCommutedMOVL(PermMask.getNode(), V2IsSplat, V2IsUndef)) {
4178 if (V2IsUndef) return V1;
4179 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4181 // V2 is a splat, so the mask may be malformed. That is, it may point
4182 // to any V2 element. The instruction selectior won't like this. Get
4183 // a corrected mask and commute to form a proper MOVS{S|D}.
4184 SDValue NewMask = getMOVLMask(NumElems, DAG, dl);
4185 if (NewMask.getNode() != PermMask.getNode())
4186 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, NewMask);
4191 if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
4192 X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
4193 X86::isUNPCKLMask(PermMask.getNode()) ||
4194 X86::isUNPCKHMask(PermMask.getNode()))
4198 // Normalize mask so all entries that point to V2 points to its first
4199 // element then try to match unpck{h|l} again. If match, return a
4200 // new vector_shuffle with the corrected mask.
4201 SDValue NewMask = NormalizeMask(PermMask, DAG);
4202 if (NewMask.getNode() != PermMask.getNode()) {
4203 if (X86::isUNPCKLMask(PermMask.getNode(), true)) {
4204 SDValue NewMask = getUnpacklMask(NumElems, DAG, dl);
4205 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, NewMask);
4206 } else if (X86::isUNPCKHMask(PermMask.getNode(), true)) {
4207 SDValue NewMask = getUnpackhMask(NumElems, DAG, dl);
4208 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, NewMask);
4213 // Normalize the node to match x86 shuffle ops if needed
4214 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.getNode()))
4215 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4218 // Commute is back and try unpck* again.
4219 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4220 if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
4221 X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
4222 X86::isUNPCKLMask(PermMask.getNode()) ||
4223 X86::isUNPCKHMask(PermMask.getNode()))
4227 // Try PSHUF* first, then SHUFP*.
4228 // MMX doesn't have PSHUFD but it does have PSHUFW. While it's theoretically
4229 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
4230 if (isMMX && NumElems == 4 && X86::isPSHUFDMask(PermMask.getNode())) {
4231 if (V2.getOpcode() != ISD::UNDEF)
4232 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1,
4233 DAG.getNode(ISD::UNDEF, VT), PermMask);
4238 if (Subtarget->hasSSE2() &&
4239 (X86::isPSHUFDMask(PermMask.getNode()) ||
4240 X86::isPSHUFHWMask(PermMask.getNode()) ||
4241 X86::isPSHUFLWMask(PermMask.getNode()))) {
4243 if (VT == MVT::v4f32) {
4245 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, RVT,
4246 DAG.getNode(ISD::BIT_CONVERT, dl, RVT, V1),
4247 DAG.getNode(ISD::UNDEF, dl, RVT), PermMask);
4248 } else if (V2.getOpcode() != ISD::UNDEF)
4249 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, RVT, V1,
4250 DAG.getNode(ISD::UNDEF, dl, RVT), PermMask);
4252 Op = DAG.getNode(ISD::BIT_CONVERT, dl, VT, Op);
4256 // Binary or unary shufps.
4257 if (X86::isSHUFPMask(PermMask.getNode()) ||
4258 (V2.getOpcode() == ISD::UNDEF && X86::isPSHUFDMask(PermMask.getNode())))
4262 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4263 if (VT == MVT::v8i16) {
4264 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this, dl);
4265 if (NewOp.getNode())
4269 // Handle all 4 wide cases with a number of shuffles except for MMX.
4270 if (NumElems == 4 && !isMMX)
4271 return LowerVECTOR_SHUFFLE_4wide(V1, V2, PermMask, VT, DAG, dl);
4277 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4278 SelectionDAG &DAG) {
4279 MVT VT = Op.getValueType();
4280 DebugLoc dl = Op.getNode()->getDebugLoc();
4281 if (VT.getSizeInBits() == 8) {
4282 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4283 Op.getOperand(0), Op.getOperand(1));
4284 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4285 DAG.getValueType(VT));
4286 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4287 } else if (VT.getSizeInBits() == 16) {
4288 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4289 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4291 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4292 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4293 DAG.getNode(ISD::BIT_CONVERT, dl,
4297 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4298 Op.getOperand(0), Op.getOperand(1));
4299 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4300 DAG.getValueType(VT));
4301 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4302 } else if (VT == MVT::f32) {
4303 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4304 // the result back to FR32 register. It's only worth matching if the
4305 // result has a single use which is a store or a bitcast to i32. And in
4306 // the case of a store, it's not worth it if the index is a constant 0,
4307 // because a MOVSSmr can be used instead, which is smaller and faster.
4308 if (!Op.hasOneUse())
4310 SDNode *User = *Op.getNode()->use_begin();
4311 if ((User->getOpcode() != ISD::STORE ||
4312 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4313 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4314 (User->getOpcode() != ISD::BIT_CONVERT ||
4315 User->getValueType(0) != MVT::i32))
4317 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4318 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4321 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4322 } else if (VT == MVT::i32) {
4323 // ExtractPS works with constant index.
4324 if (isa<ConstantSDNode>(Op.getOperand(1)))
4332 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4333 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4336 if (Subtarget->hasSSE41()) {
4337 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4342 MVT VT = Op.getValueType();
4343 DebugLoc dl = Op.getNode()->getDebugLoc();
4344 // TODO: handle v16i8.
4345 if (VT.getSizeInBits() == 16) {
4346 SDValue Vec = Op.getOperand(0);
4347 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4349 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4350 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4351 DAG.getNode(ISD::BIT_CONVERT, dl,
4354 // Transform it so it match pextrw which produces a 32-bit result.
4355 MVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT()+1);
4356 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EVT,
4357 Op.getOperand(0), Op.getOperand(1));
4358 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EVT, Extract,
4359 DAG.getValueType(VT));
4360 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4361 } else if (VT.getSizeInBits() == 32) {
4362 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4365 // SHUFPS the element to the lowest double word, then movss.
4366 MVT MaskVT = MVT::getIntVectorWithNumElements(4);
4367 SmallVector<SDValue, 8> IdxVec;
4369 push_back(DAG.getConstant(Idx, MaskVT.getVectorElementType()));
4371 push_back(DAG.getNode(ISD::UNDEF, dl, MaskVT.getVectorElementType()));
4373 push_back(DAG.getNode(ISD::UNDEF, dl, MaskVT.getVectorElementType()));
4375 push_back(DAG.getNode(ISD::UNDEF, dl, MaskVT.getVectorElementType()));
4376 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4377 &IdxVec[0], IdxVec.size());
4378 SDValue Vec = Op.getOperand(0);
4379 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, Vec.getValueType(),
4380 Vec, DAG.getNode(ISD::UNDEF, dl, Vec.getValueType()),
4382 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4383 DAG.getIntPtrConstant(0));
4384 } else if (VT.getSizeInBits() == 64) {
4385 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4386 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4387 // to match extract_elt for f64.
4388 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4392 // UNPCKHPD the element to the lowest double word, then movsd.
4393 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4394 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4395 MVT MaskVT = MVT::getIntVectorWithNumElements(2);
4396 SmallVector<SDValue, 8> IdxVec;
4397 IdxVec.push_back(DAG.getConstant(1, MaskVT.getVectorElementType()));
4399 push_back(DAG.getNode(ISD::UNDEF, dl, MaskVT.getVectorElementType()));
4400 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4401 &IdxVec[0], IdxVec.size());
4402 SDValue Vec = Op.getOperand(0);
4403 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, Vec.getValueType(),
4404 Vec, DAG.getNode(ISD::UNDEF, dl, Vec.getValueType()),
4406 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4407 DAG.getIntPtrConstant(0));
4414 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4415 MVT VT = Op.getValueType();
4416 MVT EVT = VT.getVectorElementType();
4417 DebugLoc dl = Op.getNode()->getDebugLoc();
4419 SDValue N0 = Op.getOperand(0);
4420 SDValue N1 = Op.getOperand(1);
4421 SDValue N2 = Op.getOperand(2);
4423 if ((EVT.getSizeInBits() == 8 || EVT.getSizeInBits() == 16) &&
4424 isa<ConstantSDNode>(N2)) {
4425 unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4427 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4429 if (N1.getValueType() != MVT::i32)
4430 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4431 if (N2.getValueType() != MVT::i32)
4432 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4433 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4434 } else if (EVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4435 // Bits [7:6] of the constant are the source select. This will always be
4436 // zero here. The DAG Combiner may combine an extract_elt index into these
4437 // bits. For example (insert (extract, 3), 2) could be matched by putting
4438 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4439 // Bits [5:4] of the constant are the destination select. This is the
4440 // value of the incoming immediate.
4441 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4442 // combine either bitwise AND or insert of float 0.0 to set these bits.
4443 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4444 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4445 } else if (EVT == MVT::i32) {
4446 // InsertPS works with constant index.
4447 if (isa<ConstantSDNode>(N2))
4454 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4455 MVT VT = Op.getValueType();
4456 MVT EVT = VT.getVectorElementType();
4458 if (Subtarget->hasSSE41())
4459 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4464 DebugLoc dl = Op.getNode()->getDebugLoc();
4465 SDValue N0 = Op.getOperand(0);
4466 SDValue N1 = Op.getOperand(1);
4467 SDValue N2 = Op.getOperand(2);
4469 if (EVT.getSizeInBits() == 16) {
4470 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4471 // as its second argument.
4472 if (N1.getValueType() != MVT::i32)
4473 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4474 if (N2.getValueType() != MVT::i32)
4475 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4476 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
4482 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4483 DebugLoc dl = Op.getNode()->getDebugLoc();
4484 if (Op.getValueType() == MVT::v2f32)
4485 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4486 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4487 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4488 Op.getOperand(0))));
4490 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4491 MVT VT = MVT::v2i32;
4492 switch (Op.getValueType().getSimpleVT()) {
4499 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4500 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4503 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4504 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4505 // one of the above mentioned nodes. It has to be wrapped because otherwise
4506 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4507 // be used to form addressing mode. These wrapped nodes will be selected
4510 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4511 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4512 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(),
4514 CP->getAlignment());
4515 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4516 // With PIC, the address is actually $g + Offset.
4517 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4518 !Subtarget->isPICStyleRIPRel()) {
4519 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4520 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4528 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV,
4530 SelectionDAG &DAG) const {
4531 bool IsPic = getTargetMachine().getRelocationModel() == Reloc::PIC_;
4532 bool ExtraLoadRequired =
4533 Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false);
4535 // Create the TargetGlobalAddress node, folding in the constant
4536 // offset if it is legal.
4538 if (!IsPic && !ExtraLoadRequired && isInt32(Offset)) {
4539 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4542 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0);
4543 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4545 // With PIC, the address is actually $g + Offset.
4546 if (IsPic && !Subtarget->isPICStyleRIPRel()) {
4547 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4548 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4552 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4553 // load the value at address GV, not the value of GV itself. This means that
4554 // the GlobalAddress must be in the base or index register of the address, not
4555 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4556 // The same applies for external symbols during PIC codegen
4557 if (ExtraLoadRequired)
4558 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
4559 PseudoSourceValue::getGOT(), 0);
4561 // If there was a non-zero offset that we didn't fold, create an explicit
4564 Result = DAG.getNode(ISD::ADD, getPointerTy(), Result,
4565 DAG.getConstant(Offset, getPointerTy()));
4571 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4572 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4573 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4574 return LowerGlobalAddress(GV, Offset, DAG);
4577 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4579 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4582 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
4583 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
4584 DAG.getNode(X86ISD::GlobalBaseReg,
4586 InFlag = Chain.getValue(1);
4588 // emit leal symbol@TLSGD(,%ebx,1), %eax
4589 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4590 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4591 GA->getValueType(0),
4593 SDValue Ops[] = { Chain, TGA, InFlag };
4594 SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
4595 InFlag = Result.getValue(2);
4596 Chain = Result.getValue(1);
4598 // call ___tls_get_addr. This function receives its argument in
4599 // the register EAX.
4600 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Result, InFlag);
4601 InFlag = Chain.getValue(1);
4603 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4604 SDValue Ops1[] = { Chain,
4605 DAG.getTargetExternalSymbol("___tls_get_addr",
4607 DAG.getRegister(X86::EAX, PtrVT),
4608 DAG.getRegister(X86::EBX, PtrVT),
4610 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
4611 InFlag = Chain.getValue(1);
4613 return DAG.getCopyFromReg(Chain, dl, X86::EAX, PtrVT, InFlag);
4616 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4618 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4620 SDValue InFlag, Chain;
4621 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
4623 // emit leaq symbol@TLSGD(%rip), %rdi
4624 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4625 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4626 GA->getValueType(0),
4628 SDValue Ops[] = { DAG.getEntryNode(), TGA};
4629 SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 2);
4630 Chain = Result.getValue(1);
4631 InFlag = Result.getValue(2);
4633 // call __tls_get_addr. This function receives its argument in
4634 // the register RDI.
4635 Chain = DAG.getCopyToReg(Chain, dl, X86::RDI, Result, InFlag);
4636 InFlag = Chain.getValue(1);
4638 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4639 SDValue Ops1[] = { Chain,
4640 DAG.getTargetExternalSymbol("__tls_get_addr",
4642 DAG.getRegister(X86::RDI, PtrVT),
4644 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 4);
4645 InFlag = Chain.getValue(1);
4647 return DAG.getCopyFromReg(Chain, dl, X86::RAX, PtrVT, InFlag);
4650 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4651 // "local exec" model.
4652 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4654 // Get the Thread Pointer
4655 SDValue ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4656 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4658 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4659 GA->getValueType(0),
4661 SDValue Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4663 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4664 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
4665 PseudoSourceValue::getGOT(), 0);
4667 // The address of the thread local variable is the add of the thread
4668 // pointer with the offset of the variable.
4669 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4673 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4674 // TODO: implement the "local dynamic" model
4675 // TODO: implement the "initial exec"model for pic executables
4676 assert(Subtarget->isTargetELF() &&
4677 "TLS not implemented for non-ELF targets");
4678 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4679 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4680 // otherwise use the "Local Exec"TLS Model
4681 if (Subtarget->is64Bit()) {
4682 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4684 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4685 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4687 return LowerToTLSExecModel(GA, DAG, getPointerTy());
4692 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4693 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4694 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4695 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4696 // With PIC, the address is actually $g + Offset.
4697 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4698 !Subtarget->isPICStyleRIPRel()) {
4699 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4700 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4707 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4708 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4709 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4710 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4711 // With PIC, the address is actually $g + Offset.
4712 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4713 !Subtarget->isPICStyleRIPRel()) {
4714 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4715 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4722 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4723 /// take a 2 x i32 value to shift plus a shift amount.
4724 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4725 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4726 MVT VT = Op.getValueType();
4727 unsigned VTBits = VT.getSizeInBits();
4728 DebugLoc dl = Op.getNode()->getDebugLoc();
4729 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4730 SDValue ShOpLo = Op.getOperand(0);
4731 SDValue ShOpHi = Op.getOperand(1);
4732 SDValue ShAmt = Op.getOperand(2);
4733 SDValue Tmp1 = isSRA ?
4734 DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
4735 DAG.getConstant(VTBits - 1, MVT::i8)) :
4736 DAG.getConstant(0, VT);
4739 if (Op.getOpcode() == ISD::SHL_PARTS) {
4740 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
4741 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4743 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
4744 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
4747 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
4748 DAG.getConstant(VTBits, MVT::i8));
4749 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, VT,
4750 AndNode, DAG.getConstant(0, MVT::i8));
4753 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4754 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4755 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4757 if (Op.getOpcode() == ISD::SHL_PARTS) {
4758 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4759 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4761 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4762 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4765 SDValue Ops[2] = { Lo, Hi };
4766 return DAG.getMergeValues(Ops, 2, dl);
4769 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4770 MVT SrcVT = Op.getOperand(0).getValueType();
4771 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4772 "Unknown SINT_TO_FP to lower!");
4774 // These are really Legal; caller falls through into that case.
4775 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4777 if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 &&
4778 Subtarget->is64Bit())
4781 DebugLoc dl = Op.getNode()->getDebugLoc();
4782 unsigned Size = SrcVT.getSizeInBits()/8;
4783 MachineFunction &MF = DAG.getMachineFunction();
4784 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4785 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4786 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
4788 PseudoSourceValue::getFixedStack(SSFI), 0);
4792 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4794 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4796 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4797 SmallVector<SDValue, 8> Ops;
4798 Ops.push_back(Chain);
4799 Ops.push_back(StackSlot);
4800 Ops.push_back(DAG.getValueType(SrcVT));
4801 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
4802 Tys, &Ops[0], Ops.size());
4805 Chain = Result.getValue(1);
4806 SDValue InFlag = Result.getValue(2);
4808 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4809 // shouldn't be necessary except that RFP cannot be live across
4810 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4811 MachineFunction &MF = DAG.getMachineFunction();
4812 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4813 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4814 Tys = DAG.getVTList(MVT::Other);
4815 SmallVector<SDValue, 8> Ops;
4816 Ops.push_back(Chain);
4817 Ops.push_back(Result);
4818 Ops.push_back(StackSlot);
4819 Ops.push_back(DAG.getValueType(Op.getValueType()));
4820 Ops.push_back(InFlag);
4821 Chain = DAG.getNode(X86ISD::FST, dl, Tys, &Ops[0], Ops.size());
4822 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
4823 PseudoSourceValue::getFixedStack(SSFI), 0);
4829 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
4830 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
4831 // This algorithm is not obvious. Here it is in C code, more or less:
4833 double uint64_to_double( uint32_t hi, uint32_t lo ) {
4834 static const __m128i exp = { 0x4330000045300000ULL, 0 };
4835 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
4837 // Copy ints to xmm registers.
4838 __m128i xh = _mm_cvtsi32_si128( hi );
4839 __m128i xl = _mm_cvtsi32_si128( lo );
4841 // Combine into low half of a single xmm register.
4842 __m128i x = _mm_unpacklo_epi32( xh, xl );
4846 // Merge in appropriate exponents to give the integer bits the right
4848 x = _mm_unpacklo_epi32( x, exp );
4850 // Subtract away the biases to deal with the IEEE-754 double precision
4852 d = _mm_sub_pd( (__m128d) x, bias );
4854 // All conversions up to here are exact. The correctly rounded result is
4855 // calculated using the current rounding mode using the following
4857 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
4858 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
4859 // store doesn't really need to be here (except
4860 // maybe to zero the other double)
4865 DebugLoc dl = Op.getNode()->getDebugLoc();
4867 // Build some magic constants.
4868 std::vector<Constant*> CV0;
4869 CV0.push_back(ConstantInt::get(APInt(32, 0x45300000)));
4870 CV0.push_back(ConstantInt::get(APInt(32, 0x43300000)));
4871 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4872 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4873 Constant *C0 = ConstantVector::get(CV0);
4874 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 4);
4876 std::vector<Constant*> CV1;
4877 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4530000000000000ULL))));
4878 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4330000000000000ULL))));
4879 Constant *C1 = ConstantVector::get(CV1);
4880 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 4);
4882 SmallVector<SDValue, 4> MaskVec;
4883 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
4884 MaskVec.push_back(DAG.getConstant(4, MVT::i32));
4885 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
4886 MaskVec.push_back(DAG.getConstant(5, MVT::i32));
4887 SDValue UnpcklMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
4888 &MaskVec[0], MaskVec.size());
4889 SmallVector<SDValue, 4> MaskVec2;
4890 MaskVec2.push_back(DAG.getConstant(1, MVT::i32));
4891 MaskVec2.push_back(DAG.getConstant(0, MVT::i32));
4892 SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32,
4893 &MaskVec2[0], MaskVec2.size());
4895 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4896 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4898 DAG.getIntPtrConstant(1)));
4899 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4900 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4902 DAG.getIntPtrConstant(0)));
4903 SDValue Unpck1 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v4i32,
4904 XR1, XR2, UnpcklMask);
4905 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
4906 PseudoSourceValue::getConstantPool(), 0,
4908 SDValue Unpck2 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v4i32,
4909 Unpck1, CLod0, UnpcklMask);
4910 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
4911 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
4912 PseudoSourceValue::getConstantPool(), 0,
4914 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
4916 // Add the halves; easiest way is to swap them into another reg first.
4917 SDValue Shuf = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v2f64,
4918 Sub, Sub, ShufMask);
4919 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
4920 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
4921 DAG.getIntPtrConstant(0));
4924 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
4925 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
4926 DebugLoc dl = Op.getNode()->getDebugLoc();
4927 // FP constant to bias correct the final result.
4928 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
4931 // Load the 32-bit value into an XMM register.
4932 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4933 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4935 DAG.getIntPtrConstant(0)));
4937 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
4938 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
4939 DAG.getIntPtrConstant(0));
4941 // Or the load with the bias.
4942 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
4943 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4944 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4946 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4947 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4948 MVT::v2f64, Bias)));
4949 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
4950 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
4951 DAG.getIntPtrConstant(0));
4953 // Subtract the bias.
4954 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
4956 // Handle final rounding.
4957 MVT DestVT = Op.getValueType();
4959 if (DestVT.bitsLT(MVT::f64)) {
4960 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
4961 DAG.getIntPtrConstant(0));
4962 } else if (DestVT.bitsGT(MVT::f64)) {
4963 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
4966 // Handle final rounding.
4970 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4971 SDValue N0 = Op.getOperand(0);
4972 DebugLoc dl = Op.getNode()->getDebugLoc();
4974 // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
4975 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
4976 // the optimization here.
4977 if (DAG.SignBitIsZero(N0))
4978 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
4980 MVT SrcVT = N0.getValueType();
4981 if (SrcVT == MVT::i64) {
4982 // We only handle SSE2 f64 target here; caller can handle the rest.
4983 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
4986 return LowerUINT_TO_FP_i64(Op, DAG);
4987 } else if (SrcVT == MVT::i32) {
4988 return LowerUINT_TO_FP_i32(Op, DAG);
4991 assert(0 && "Unknown UINT_TO_FP to lower!");
4995 std::pair<SDValue,SDValue> X86TargetLowering::
4996 FP_TO_SINTHelper(SDValue Op, SelectionDAG &DAG) {
4997 DebugLoc dl = Op.getNode()->getDebugLoc();
4998 assert(Op.getValueType().getSimpleVT() <= MVT::i64 &&
4999 Op.getValueType().getSimpleVT() >= MVT::i16 &&
5000 "Unknown FP_TO_SINT to lower!");
5002 // These are really Legal.
5003 if (Op.getValueType() == MVT::i32 &&
5004 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5005 return std::make_pair(SDValue(), SDValue());
5006 if (Subtarget->is64Bit() &&
5007 Op.getValueType() == MVT::i64 &&
5008 Op.getOperand(0).getValueType() != MVT::f80)
5009 return std::make_pair(SDValue(), SDValue());
5011 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5013 MachineFunction &MF = DAG.getMachineFunction();
5014 unsigned MemSize = Op.getValueType().getSizeInBits()/8;
5015 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
5016 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5018 switch (Op.getValueType().getSimpleVT()) {
5019 default: assert(0 && "Invalid FP_TO_SINT to lower!");
5020 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5021 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5022 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5025 SDValue Chain = DAG.getEntryNode();
5026 SDValue Value = Op.getOperand(0);
5027 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5028 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5029 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5030 PseudoSourceValue::getFixedStack(SSFI), 0);
5031 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5033 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5035 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5036 Chain = Value.getValue(1);
5037 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
5038 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5041 // Build the FP_TO_INT*_IN_MEM
5042 SDValue Ops[] = { Chain, Value, StackSlot };
5043 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5045 return std::make_pair(FIST, StackSlot);
5048 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
5049 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(Op, DAG);
5050 SDValue FIST = Vals.first, StackSlot = Vals.second;
5051 if (FIST.getNode() == 0) return SDValue();
5054 return DAG.getLoad(Op.getValueType(), Op.getNode()->getDebugLoc(),
5055 FIST, StackSlot, NULL, 0);
5058 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
5059 DebugLoc dl = Op.getNode()->getDebugLoc();
5060 MVT VT = Op.getValueType();
5063 EltVT = VT.getVectorElementType();
5064 std::vector<Constant*> CV;
5065 if (EltVT == MVT::f64) {
5066 Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
5070 Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
5076 Constant *C = ConstantVector::get(CV);
5077 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
5078 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5079 PseudoSourceValue::getConstantPool(), 0,
5081 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5084 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
5085 DebugLoc dl = Op.getNode()->getDebugLoc();
5086 MVT VT = Op.getValueType();
5088 unsigned EltNum = 1;
5089 if (VT.isVector()) {
5090 EltVT = VT.getVectorElementType();
5091 EltNum = VT.getVectorNumElements();
5093 std::vector<Constant*> CV;
5094 if (EltVT == MVT::f64) {
5095 Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
5099 Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
5105 Constant *C = ConstantVector::get(CV);
5106 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
5107 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5108 PseudoSourceValue::getConstantPool(), 0,
5110 if (VT.isVector()) {
5111 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5112 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5113 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5115 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5117 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5121 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5122 SDValue Op0 = Op.getOperand(0);
5123 SDValue Op1 = Op.getOperand(1);
5124 DebugLoc dl = Op.getNode()->getDebugLoc();
5125 MVT VT = Op.getValueType();
5126 MVT SrcVT = Op1.getValueType();
5128 // If second operand is smaller, extend it first.
5129 if (SrcVT.bitsLT(VT)) {
5130 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5133 // And if it is bigger, shrink it first.
5134 if (SrcVT.bitsGT(VT)) {
5135 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5139 // At this point the operands and the result should have the same
5140 // type, and that won't be f80 since that is not custom lowered.
5142 // First get the sign bit of second operand.
5143 std::vector<Constant*> CV;
5144 if (SrcVT == MVT::f64) {
5145 CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
5146 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
5148 CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
5149 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5150 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5151 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5153 Constant *C = ConstantVector::get(CV);
5154 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
5155 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5156 PseudoSourceValue::getConstantPool(), 0,
5158 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5160 // Shift sign bit right or left if the two operands have different types.
5161 if (SrcVT.bitsGT(VT)) {
5162 // Op0 is MVT::f32, Op1 is MVT::f64.
5163 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5164 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5165 DAG.getConstant(32, MVT::i32));
5166 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5167 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5168 DAG.getIntPtrConstant(0));
5171 // Clear first operand sign bit.
5173 if (VT == MVT::f64) {
5174 CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
5175 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
5177 CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
5178 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5179 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5180 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5182 C = ConstantVector::get(CV);
5183 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
5184 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5185 PseudoSourceValue::getConstantPool(), 0,
5187 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5189 // Or the value with the sign bit.
5190 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5193 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5194 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5195 SDValue Op0 = Op.getOperand(0);
5196 SDValue Op1 = Op.getOperand(1);
5197 DebugLoc dl = Op.getNode()->getDebugLoc();
5198 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5200 // Lower (X & (1 << N)) == 0 to BT(X, N).
5201 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5202 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5203 if (Op0.getOpcode() == ISD::AND &&
5205 Op1.getOpcode() == ISD::Constant &&
5206 cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5207 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5209 if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
5210 if (ConstantSDNode *Op010C =
5211 dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
5212 if (Op010C->getZExtValue() == 1) {
5213 LHS = Op0.getOperand(0);
5214 RHS = Op0.getOperand(1).getOperand(1);
5216 } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
5217 if (ConstantSDNode *Op000C =
5218 dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
5219 if (Op000C->getZExtValue() == 1) {
5220 LHS = Op0.getOperand(1);
5221 RHS = Op0.getOperand(0).getOperand(1);
5223 } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
5224 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5225 SDValue AndLHS = Op0.getOperand(0);
5226 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5227 LHS = AndLHS.getOperand(0);
5228 RHS = AndLHS.getOperand(1);
5232 if (LHS.getNode()) {
5233 // If LHS is i8, promote it to i16 with any_extend. There is no i8 BT
5234 // instruction. Since the shift amount is in-range-or-undefined, we know
5235 // that doing a bittest on the i16 value is ok. We extend to i32 because
5236 // the encoding for the i16 version is larger than the i32 version.
5237 if (LHS.getValueType() == MVT::i8)
5238 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5240 // If the operand types disagree, extend the shift amount to match. Since
5241 // BT ignores high bits (like shifts) we can use anyextend.
5242 if (LHS.getValueType() != RHS.getValueType())
5243 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5245 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5246 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5247 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5248 DAG.getConstant(Cond, MVT::i8), BT);
5252 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5253 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5255 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5256 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5257 DAG.getConstant(X86CC, MVT::i8), Cond);
5260 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5262 SDValue Op0 = Op.getOperand(0);
5263 SDValue Op1 = Op.getOperand(1);
5264 SDValue CC = Op.getOperand(2);
5265 MVT VT = Op.getValueType();
5266 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5267 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5268 DebugLoc dl = Op.getNode()->getDebugLoc();
5272 MVT VT0 = Op0.getValueType();
5273 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5274 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5277 switch (SetCCOpcode) {
5280 case ISD::SETEQ: SSECC = 0; break;
5282 case ISD::SETGT: Swap = true; // Fallthrough
5284 case ISD::SETOLT: SSECC = 1; break;
5286 case ISD::SETGE: Swap = true; // Fallthrough
5288 case ISD::SETOLE: SSECC = 2; break;
5289 case ISD::SETUO: SSECC = 3; break;
5291 case ISD::SETNE: SSECC = 4; break;
5292 case ISD::SETULE: Swap = true;
5293 case ISD::SETUGE: SSECC = 5; break;
5294 case ISD::SETULT: Swap = true;
5295 case ISD::SETUGT: SSECC = 6; break;
5296 case ISD::SETO: SSECC = 7; break;
5299 std::swap(Op0, Op1);
5301 // In the two special cases we can't handle, emit two comparisons.
5303 if (SetCCOpcode == ISD::SETUEQ) {
5305 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5306 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5307 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
5309 else if (SetCCOpcode == ISD::SETONE) {
5311 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5312 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5313 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
5315 assert(0 && "Illegal FP comparison");
5317 // Handle all other FP comparisons here.
5318 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5321 // We are handling one of the integer comparisons here. Since SSE only has
5322 // GT and EQ comparisons for integer, swapping operands and multiple
5323 // operations may be required for some comparisons.
5324 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5325 bool Swap = false, Invert = false, FlipSigns = false;
5327 switch (VT.getSimpleVT()) {
5329 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5330 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5331 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5332 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5335 switch (SetCCOpcode) {
5337 case ISD::SETNE: Invert = true;
5338 case ISD::SETEQ: Opc = EQOpc; break;
5339 case ISD::SETLT: Swap = true;
5340 case ISD::SETGT: Opc = GTOpc; break;
5341 case ISD::SETGE: Swap = true;
5342 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
5343 case ISD::SETULT: Swap = true;
5344 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5345 case ISD::SETUGE: Swap = true;
5346 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5349 std::swap(Op0, Op1);
5351 // Since SSE has no unsigned integer comparisons, we need to flip the sign
5352 // bits of the inputs before performing those operations.
5354 MVT EltVT = VT.getVectorElementType();
5355 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
5357 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5358 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
5360 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
5361 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
5364 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
5366 // If the logical-not of the result is required, perform that now.
5368 Result = DAG.getNOT(dl, Result, VT);
5373 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5374 static bool isX86LogicalCmp(unsigned Opc) {
5375 return Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI;
5378 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5379 bool addTest = true;
5380 SDValue Cond = Op.getOperand(0);
5381 DebugLoc dl = Op.getNode()->getDebugLoc();
5384 if (Cond.getOpcode() == ISD::SETCC)
5385 Cond = LowerSETCC(Cond, DAG);
5387 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5388 // setting operand in place of the X86ISD::SETCC.
5389 if (Cond.getOpcode() == X86ISD::SETCC) {
5390 CC = Cond.getOperand(0);
5392 SDValue Cmp = Cond.getOperand(1);
5393 unsigned Opc = Cmp.getOpcode();
5394 MVT VT = Op.getValueType();
5396 bool IllegalFPCMov = false;
5397 if (VT.isFloatingPoint() && !VT.isVector() &&
5398 !isScalarFPTypeInSSEReg(VT)) // FPStack?
5399 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
5401 if ((isX86LogicalCmp(Opc) && !IllegalFPCMov) || Opc == X86ISD::BT) { // FIXME
5408 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5409 Cond= DAG.getNode(X86ISD::CMP, dl, MVT::i32, Cond,
5410 DAG.getConstant(0, MVT::i8));
5413 const MVT *VTs = DAG.getNodeValueTypes(Op.getValueType(),
5415 SmallVector<SDValue, 4> Ops;
5416 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
5417 // condition is true.
5418 Ops.push_back(Op.getOperand(2));
5419 Ops.push_back(Op.getOperand(1));
5421 Ops.push_back(Cond);
5422 return DAG.getNode(X86ISD::CMOV, dl, VTs, 2, &Ops[0], Ops.size());
5425 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
5426 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
5427 // from the AND / OR.
5428 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
5429 Opc = Op.getOpcode();
5430 if (Opc != ISD::OR && Opc != ISD::AND)
5432 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5433 Op.getOperand(0).hasOneUse() &&
5434 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
5435 Op.getOperand(1).hasOneUse());
5438 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
5439 // 1 and that the SETCC node has a single use.
5440 static bool isXor1OfSetCC(SDValue Op) {
5441 if (Op.getOpcode() != ISD::XOR)
5443 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5444 if (N1C && N1C->getAPIntValue() == 1) {
5445 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5446 Op.getOperand(0).hasOneUse();
5451 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
5452 bool addTest = true;
5453 SDValue Chain = Op.getOperand(0);
5454 SDValue Cond = Op.getOperand(1);
5455 SDValue Dest = Op.getOperand(2);
5456 DebugLoc dl = Op.getNode()->getDebugLoc();
5459 if (Cond.getOpcode() == ISD::SETCC)
5460 Cond = LowerSETCC(Cond, DAG);
5462 // FIXME: LowerXALUO doesn't handle these!!
5463 else if (Cond.getOpcode() == X86ISD::ADD ||
5464 Cond.getOpcode() == X86ISD::SUB ||
5465 Cond.getOpcode() == X86ISD::SMUL ||
5466 Cond.getOpcode() == X86ISD::UMUL)
5467 Cond = LowerXALUO(Cond, DAG);
5470 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5471 // setting operand in place of the X86ISD::SETCC.
5472 if (Cond.getOpcode() == X86ISD::SETCC) {
5473 CC = Cond.getOperand(0);
5475 SDValue Cmp = Cond.getOperand(1);
5476 unsigned Opc = Cmp.getOpcode();
5477 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
5478 if (isX86LogicalCmp(Opc) || Opc == X86ISD::BT) {
5482 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
5486 // These can only come from an arithmetic instruction with overflow,
5487 // e.g. SADDO, UADDO.
5488 Cond = Cond.getNode()->getOperand(1);
5495 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
5496 SDValue Cmp = Cond.getOperand(0).getOperand(1);
5497 unsigned Opc = Cmp.getOpcode();
5498 if (CondOpc == ISD::OR) {
5499 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
5500 // two branches instead of an explicit OR instruction with a
5502 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5503 isX86LogicalCmp(Opc)) {
5504 CC = Cond.getOperand(0).getOperand(0);
5505 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5506 Chain, Dest, CC, Cmp);
5507 CC = Cond.getOperand(1).getOperand(0);
5511 } else { // ISD::AND
5512 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
5513 // two branches instead of an explicit AND instruction with a
5514 // separate test. However, we only do this if this block doesn't
5515 // have a fall-through edge, because this requires an explicit
5516 // jmp when the condition is false.
5517 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5518 isX86LogicalCmp(Opc) &&
5519 Op.getNode()->hasOneUse()) {
5520 X86::CondCode CCode =
5521 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5522 CCode = X86::GetOppositeBranchCondition(CCode);
5523 CC = DAG.getConstant(CCode, MVT::i8);
5524 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
5525 // Look for an unconditional branch following this conditional branch.
5526 // We need this because we need to reverse the successors in order
5527 // to implement FCMP_OEQ.
5528 if (User.getOpcode() == ISD::BR) {
5529 SDValue FalseBB = User.getOperand(1);
5531 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
5532 assert(NewBR == User);
5535 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5536 Chain, Dest, CC, Cmp);
5537 X86::CondCode CCode =
5538 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
5539 CCode = X86::GetOppositeBranchCondition(CCode);
5540 CC = DAG.getConstant(CCode, MVT::i8);
5546 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
5547 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
5548 // It should be transformed during dag combiner except when the condition
5549 // is set by a arithmetics with overflow node.
5550 X86::CondCode CCode =
5551 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5552 CCode = X86::GetOppositeBranchCondition(CCode);
5553 CC = DAG.getConstant(CCode, MVT::i8);
5554 Cond = Cond.getOperand(0).getOperand(1);
5560 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5561 Cond= DAG.getNode(X86ISD::CMP, dl, MVT::i32, Cond,
5562 DAG.getConstant(0, MVT::i8));
5564 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5565 Chain, Dest, CC, Cond);
5569 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
5570 // Calls to _alloca is needed to probe the stack when allocating more than 4k
5571 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
5572 // that the guard pages used by the OS virtual memory manager are allocated in
5573 // correct sequence.
5575 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5576 SelectionDAG &DAG) {
5577 assert(Subtarget->isTargetCygMing() &&
5578 "This should be used only on Cygwin/Mingw targets");
5579 DebugLoc dl = Op.getNode()->getDebugLoc();
5582 SDValue Chain = Op.getOperand(0);
5583 SDValue Size = Op.getOperand(1);
5584 // FIXME: Ensure alignment here
5588 MVT IntPtr = getPointerTy();
5589 MVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
5591 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
5593 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
5594 Flag = Chain.getValue(1);
5596 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5597 SDValue Ops[] = { Chain,
5598 DAG.getTargetExternalSymbol("_alloca", IntPtr),
5599 DAG.getRegister(X86::EAX, IntPtr),
5600 DAG.getRegister(X86StackPtr, SPTy),
5602 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops, 5);
5603 Flag = Chain.getValue(1);
5605 Chain = DAG.getCALLSEQ_END(Chain,
5606 DAG.getIntPtrConstant(0, true),
5607 DAG.getIntPtrConstant(0, true),
5610 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
5612 SDValue Ops1[2] = { Chain.getValue(0), Chain };
5613 return DAG.getMergeValues(Ops1, 2, dl);
5617 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
5619 SDValue Dst, SDValue Src,
5620 SDValue Size, unsigned Align,
5622 uint64_t DstSVOff) {
5623 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5625 // If not DWORD aligned or size is more than the threshold, call the library.
5626 // The libc version is likely to be faster for these cases. It can use the
5627 // address value and run time information about the CPU.
5628 if ((Align & 3) != 0 ||
5630 ConstantSize->getZExtValue() >
5631 getSubtarget()->getMaxInlineSizeThreshold()) {
5632 SDValue InFlag(0, 0);
5634 // Check to see if there is a specialized entry-point for memory zeroing.
5635 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
5637 if (const char *bzeroEntry = V &&
5638 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
5639 MVT IntPtr = getPointerTy();
5640 const Type *IntPtrTy = TD->getIntPtrType();
5641 TargetLowering::ArgListTy Args;
5642 TargetLowering::ArgListEntry Entry;
5644 Entry.Ty = IntPtrTy;
5645 Args.push_back(Entry);
5647 Args.push_back(Entry);
5648 std::pair<SDValue,SDValue> CallResult =
5649 LowerCallTo(Chain, Type::VoidTy, false, false, false, false,
5650 CallingConv::C, false,
5651 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl);
5652 return CallResult.second;
5655 // Otherwise have the target-independent code call memset.
5659 uint64_t SizeVal = ConstantSize->getZExtValue();
5660 SDValue InFlag(0, 0);
5663 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
5664 unsigned BytesLeft = 0;
5665 bool TwoRepStos = false;
5668 uint64_t Val = ValC->getZExtValue() & 255;
5670 // If the value is a constant, then we can potentially use larger sets.
5671 switch (Align & 3) {
5672 case 2: // WORD aligned
5675 Val = (Val << 8) | Val;
5677 case 0: // DWORD aligned
5680 Val = (Val << 8) | Val;
5681 Val = (Val << 16) | Val;
5682 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
5685 Val = (Val << 32) | Val;
5688 default: // Byte aligned
5691 Count = DAG.getIntPtrConstant(SizeVal);
5695 if (AVT.bitsGT(MVT::i8)) {
5696 unsigned UBytes = AVT.getSizeInBits() / 8;
5697 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
5698 BytesLeft = SizeVal % UBytes;
5701 Chain = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
5703 InFlag = Chain.getValue(1);
5706 Count = DAG.getIntPtrConstant(SizeVal);
5707 Chain = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
5708 InFlag = Chain.getValue(1);
5711 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
5714 InFlag = Chain.getValue(1);
5715 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
5718 InFlag = Chain.getValue(1);
5720 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5721 SmallVector<SDValue, 8> Ops;
5722 Ops.push_back(Chain);
5723 Ops.push_back(DAG.getValueType(AVT));
5724 Ops.push_back(InFlag);
5725 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
5728 InFlag = Chain.getValue(1);
5730 MVT CVT = Count.getValueType();
5731 SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
5732 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
5733 Chain = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
5736 InFlag = Chain.getValue(1);
5737 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5739 Ops.push_back(Chain);
5740 Ops.push_back(DAG.getValueType(MVT::i8));
5741 Ops.push_back(InFlag);
5742 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
5743 } else if (BytesLeft) {
5744 // Handle the last 1 - 7 bytes.
5745 unsigned Offset = SizeVal - BytesLeft;
5746 MVT AddrVT = Dst.getValueType();
5747 MVT SizeVT = Size.getValueType();
5749 Chain = DAG.getMemset(Chain, dl,
5750 DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
5751 DAG.getConstant(Offset, AddrVT)),
5753 DAG.getConstant(BytesLeft, SizeVT),
5754 Align, DstSV, DstSVOff + Offset);
5757 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
5762 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
5763 SDValue Chain, SDValue Dst, SDValue Src,
5764 SDValue Size, unsigned Align,
5766 const Value *DstSV, uint64_t DstSVOff,
5767 const Value *SrcSV, uint64_t SrcSVOff) {
5768 // This requires the copy size to be a constant, preferrably
5769 // within a subtarget-specific limit.
5770 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5773 uint64_t SizeVal = ConstantSize->getZExtValue();
5774 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
5777 /// If not DWORD aligned, call the library.
5778 if ((Align & 3) != 0)
5783 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
5786 unsigned UBytes = AVT.getSizeInBits() / 8;
5787 unsigned CountVal = SizeVal / UBytes;
5788 SDValue Count = DAG.getIntPtrConstant(CountVal);
5789 unsigned BytesLeft = SizeVal % UBytes;
5791 SDValue InFlag(0, 0);
5792 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
5795 InFlag = Chain.getValue(1);
5796 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
5799 InFlag = Chain.getValue(1);
5800 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
5803 InFlag = Chain.getValue(1);
5805 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5806 SmallVector<SDValue, 8> Ops;
5807 Ops.push_back(Chain);
5808 Ops.push_back(DAG.getValueType(AVT));
5809 Ops.push_back(InFlag);
5810 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, &Ops[0], Ops.size());
5812 SmallVector<SDValue, 4> Results;
5813 Results.push_back(RepMovs);
5815 // Handle the last 1 - 7 bytes.
5816 unsigned Offset = SizeVal - BytesLeft;
5817 MVT DstVT = Dst.getValueType();
5818 MVT SrcVT = Src.getValueType();
5819 MVT SizeVT = Size.getValueType();
5820 Results.push_back(DAG.getMemcpy(Chain, dl,
5821 DAG.getNode(ISD::ADD, dl, DstVT, Dst,
5822 DAG.getConstant(Offset, DstVT)),
5823 DAG.getNode(ISD::ADD, dl, SrcVT, Src,
5824 DAG.getConstant(Offset, SrcVT)),
5825 DAG.getConstant(BytesLeft, SizeVT),
5826 Align, AlwaysInline,
5827 DstSV, DstSVOff + Offset,
5828 SrcSV, SrcSVOff + Offset));
5831 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5832 &Results[0], Results.size());
5835 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
5836 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5837 DebugLoc dl = Op.getNode()->getDebugLoc();
5839 if (!Subtarget->is64Bit()) {
5840 // vastart just stores the address of the VarArgsFrameIndex slot into the
5841 // memory location argument.
5842 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5843 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
5847 // gp_offset (0 - 6 * 8)
5848 // fp_offset (48 - 48 + 8 * 16)
5849 // overflow_arg_area (point to parameters coming in memory).
5851 SmallVector<SDValue, 8> MemOps;
5852 SDValue FIN = Op.getOperand(1);
5854 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
5855 DAG.getConstant(VarArgsGPOffset, MVT::i32),
5857 MemOps.push_back(Store);
5860 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5861 FIN, DAG.getIntPtrConstant(4));
5862 Store = DAG.getStore(Op.getOperand(0), dl,
5863 DAG.getConstant(VarArgsFPOffset, MVT::i32),
5865 MemOps.push_back(Store);
5867 // Store ptr to overflow_arg_area
5868 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5869 FIN, DAG.getIntPtrConstant(4));
5870 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5871 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0);
5872 MemOps.push_back(Store);
5874 // Store ptr to reg_save_area.
5875 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5876 FIN, DAG.getIntPtrConstant(8));
5877 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
5878 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0);
5879 MemOps.push_back(Store);
5880 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5881 &MemOps[0], MemOps.size());
5884 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
5885 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5886 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
5887 SDValue Chain = Op.getOperand(0);
5888 SDValue SrcPtr = Op.getOperand(1);
5889 SDValue SrcSV = Op.getOperand(2);
5891 assert(0 && "VAArgInst is not yet implemented for x86-64!");
5896 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
5897 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5898 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
5899 SDValue Chain = Op.getOperand(0);
5900 SDValue DstPtr = Op.getOperand(1);
5901 SDValue SrcPtr = Op.getOperand(2);
5902 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5903 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5904 DebugLoc dl = Op.getNode()->getDebugLoc();
5906 return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
5907 DAG.getIntPtrConstant(24), 8, false,
5908 DstSV, 0, SrcSV, 0);
5912 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
5913 DebugLoc dl = Op.getNode()->getDebugLoc();
5914 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5916 default: return SDValue(); // Don't custom lower most intrinsics.
5917 // Comparison intrinsics.
5918 case Intrinsic::x86_sse_comieq_ss:
5919 case Intrinsic::x86_sse_comilt_ss:
5920 case Intrinsic::x86_sse_comile_ss:
5921 case Intrinsic::x86_sse_comigt_ss:
5922 case Intrinsic::x86_sse_comige_ss:
5923 case Intrinsic::x86_sse_comineq_ss:
5924 case Intrinsic::x86_sse_ucomieq_ss:
5925 case Intrinsic::x86_sse_ucomilt_ss:
5926 case Intrinsic::x86_sse_ucomile_ss:
5927 case Intrinsic::x86_sse_ucomigt_ss:
5928 case Intrinsic::x86_sse_ucomige_ss:
5929 case Intrinsic::x86_sse_ucomineq_ss:
5930 case Intrinsic::x86_sse2_comieq_sd:
5931 case Intrinsic::x86_sse2_comilt_sd:
5932 case Intrinsic::x86_sse2_comile_sd:
5933 case Intrinsic::x86_sse2_comigt_sd:
5934 case Intrinsic::x86_sse2_comige_sd:
5935 case Intrinsic::x86_sse2_comineq_sd:
5936 case Intrinsic::x86_sse2_ucomieq_sd:
5937 case Intrinsic::x86_sse2_ucomilt_sd:
5938 case Intrinsic::x86_sse2_ucomile_sd:
5939 case Intrinsic::x86_sse2_ucomigt_sd:
5940 case Intrinsic::x86_sse2_ucomige_sd:
5941 case Intrinsic::x86_sse2_ucomineq_sd: {
5943 ISD::CondCode CC = ISD::SETCC_INVALID;
5946 case Intrinsic::x86_sse_comieq_ss:
5947 case Intrinsic::x86_sse2_comieq_sd:
5951 case Intrinsic::x86_sse_comilt_ss:
5952 case Intrinsic::x86_sse2_comilt_sd:
5956 case Intrinsic::x86_sse_comile_ss:
5957 case Intrinsic::x86_sse2_comile_sd:
5961 case Intrinsic::x86_sse_comigt_ss:
5962 case Intrinsic::x86_sse2_comigt_sd:
5966 case Intrinsic::x86_sse_comige_ss:
5967 case Intrinsic::x86_sse2_comige_sd:
5971 case Intrinsic::x86_sse_comineq_ss:
5972 case Intrinsic::x86_sse2_comineq_sd:
5976 case Intrinsic::x86_sse_ucomieq_ss:
5977 case Intrinsic::x86_sse2_ucomieq_sd:
5978 Opc = X86ISD::UCOMI;
5981 case Intrinsic::x86_sse_ucomilt_ss:
5982 case Intrinsic::x86_sse2_ucomilt_sd:
5983 Opc = X86ISD::UCOMI;
5986 case Intrinsic::x86_sse_ucomile_ss:
5987 case Intrinsic::x86_sse2_ucomile_sd:
5988 Opc = X86ISD::UCOMI;
5991 case Intrinsic::x86_sse_ucomigt_ss:
5992 case Intrinsic::x86_sse2_ucomigt_sd:
5993 Opc = X86ISD::UCOMI;
5996 case Intrinsic::x86_sse_ucomige_ss:
5997 case Intrinsic::x86_sse2_ucomige_sd:
5998 Opc = X86ISD::UCOMI;
6001 case Intrinsic::x86_sse_ucomineq_ss:
6002 case Intrinsic::x86_sse2_ucomineq_sd:
6003 Opc = X86ISD::UCOMI;
6008 SDValue LHS = Op.getOperand(1);
6009 SDValue RHS = Op.getOperand(2);
6010 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6011 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6012 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6013 DAG.getConstant(X86CC, MVT::i8), Cond);
6014 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6017 // Fix vector shift instructions where the last operand is a non-immediate
6019 case Intrinsic::x86_sse2_pslli_w:
6020 case Intrinsic::x86_sse2_pslli_d:
6021 case Intrinsic::x86_sse2_pslli_q:
6022 case Intrinsic::x86_sse2_psrli_w:
6023 case Intrinsic::x86_sse2_psrli_d:
6024 case Intrinsic::x86_sse2_psrli_q:
6025 case Intrinsic::x86_sse2_psrai_w:
6026 case Intrinsic::x86_sse2_psrai_d:
6027 case Intrinsic::x86_mmx_pslli_w:
6028 case Intrinsic::x86_mmx_pslli_d:
6029 case Intrinsic::x86_mmx_pslli_q:
6030 case Intrinsic::x86_mmx_psrli_w:
6031 case Intrinsic::x86_mmx_psrli_d:
6032 case Intrinsic::x86_mmx_psrli_q:
6033 case Intrinsic::x86_mmx_psrai_w:
6034 case Intrinsic::x86_mmx_psrai_d: {
6035 SDValue ShAmt = Op.getOperand(2);
6036 if (isa<ConstantSDNode>(ShAmt))
6039 unsigned NewIntNo = 0;
6040 MVT ShAmtVT = MVT::v4i32;
6042 case Intrinsic::x86_sse2_pslli_w:
6043 NewIntNo = Intrinsic::x86_sse2_psll_w;
6045 case Intrinsic::x86_sse2_pslli_d:
6046 NewIntNo = Intrinsic::x86_sse2_psll_d;
6048 case Intrinsic::x86_sse2_pslli_q:
6049 NewIntNo = Intrinsic::x86_sse2_psll_q;
6051 case Intrinsic::x86_sse2_psrli_w:
6052 NewIntNo = Intrinsic::x86_sse2_psrl_w;
6054 case Intrinsic::x86_sse2_psrli_d:
6055 NewIntNo = Intrinsic::x86_sse2_psrl_d;
6057 case Intrinsic::x86_sse2_psrli_q:
6058 NewIntNo = Intrinsic::x86_sse2_psrl_q;
6060 case Intrinsic::x86_sse2_psrai_w:
6061 NewIntNo = Intrinsic::x86_sse2_psra_w;
6063 case Intrinsic::x86_sse2_psrai_d:
6064 NewIntNo = Intrinsic::x86_sse2_psra_d;
6067 ShAmtVT = MVT::v2i32;
6069 case Intrinsic::x86_mmx_pslli_w:
6070 NewIntNo = Intrinsic::x86_mmx_psll_w;
6072 case Intrinsic::x86_mmx_pslli_d:
6073 NewIntNo = Intrinsic::x86_mmx_psll_d;
6075 case Intrinsic::x86_mmx_pslli_q:
6076 NewIntNo = Intrinsic::x86_mmx_psll_q;
6078 case Intrinsic::x86_mmx_psrli_w:
6079 NewIntNo = Intrinsic::x86_mmx_psrl_w;
6081 case Intrinsic::x86_mmx_psrli_d:
6082 NewIntNo = Intrinsic::x86_mmx_psrl_d;
6084 case Intrinsic::x86_mmx_psrli_q:
6085 NewIntNo = Intrinsic::x86_mmx_psrl_q;
6087 case Intrinsic::x86_mmx_psrai_w:
6088 NewIntNo = Intrinsic::x86_mmx_psra_w;
6090 case Intrinsic::x86_mmx_psrai_d:
6091 NewIntNo = Intrinsic::x86_mmx_psra_d;
6093 default: abort(); // Can't reach here.
6098 MVT VT = Op.getValueType();
6099 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT,
6100 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShAmtVT, ShAmt));
6101 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6102 DAG.getConstant(NewIntNo, MVT::i32),
6103 Op.getOperand(1), ShAmt);
6108 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
6109 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6110 DebugLoc dl = Op.getNode()->getDebugLoc();
6113 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6115 DAG.getConstant(TD->getPointerSize(),
6116 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6117 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6118 DAG.getNode(ISD::ADD, dl, getPointerTy(),
6123 // Just load the return address.
6124 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6125 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6126 RetAddrFI, NULL, 0);
6129 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
6130 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6131 MFI->setFrameAddressIsTaken(true);
6132 MVT VT = Op.getValueType();
6133 DebugLoc dl = Op.getNode()->getDebugLoc(); // FIXME probably not meaningful
6134 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6135 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6136 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6138 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
6142 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6143 SelectionDAG &DAG) {
6144 return DAG.getIntPtrConstant(2*TD->getPointerSize());
6147 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
6149 MachineFunction &MF = DAG.getMachineFunction();
6150 SDValue Chain = Op.getOperand(0);
6151 SDValue Offset = Op.getOperand(1);
6152 SDValue Handler = Op.getOperand(2);
6153 DebugLoc dl = Op.getNode()->getDebugLoc();
6155 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6157 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6159 SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
6160 DAG.getIntPtrConstant(-TD->getPointerSize()));
6161 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
6162 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0);
6163 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
6164 MF.getRegInfo().addLiveOut(StoreAddrReg);
6166 return DAG.getNode(X86ISD::EH_RETURN, dl,
6168 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6171 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6172 SelectionDAG &DAG) {
6173 SDValue Root = Op.getOperand(0);
6174 SDValue Trmp = Op.getOperand(1); // trampoline
6175 SDValue FPtr = Op.getOperand(2); // nested function
6176 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6177 DebugLoc dl = Op.getNode()->getDebugLoc();
6179 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6181 const X86InstrInfo *TII =
6182 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
6184 if (Subtarget->is64Bit()) {
6185 SDValue OutChains[6];
6187 // Large code-model.
6189 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
6190 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
6192 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
6193 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
6195 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
6197 // Load the pointer to the nested function into R11.
6198 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
6199 SDValue Addr = Trmp;
6200 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6203 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6204 DAG.getConstant(2, MVT::i64));
6205 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2, false, 2);
6207 // Load the 'nest' parameter value into R10.
6208 // R10 is specified in X86CallingConv.td
6209 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
6210 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6211 DAG.getConstant(10, MVT::i64));
6212 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6213 Addr, TrmpAddr, 10);
6215 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6216 DAG.getConstant(12, MVT::i64));
6217 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12, false, 2);
6219 // Jump to the nested function.
6220 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
6221 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6222 DAG.getConstant(20, MVT::i64));
6223 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6224 Addr, TrmpAddr, 20);
6226 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
6227 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6228 DAG.getConstant(22, MVT::i64));
6229 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
6233 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
6234 return DAG.getMergeValues(Ops, 2, dl);
6236 const Function *Func =
6237 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
6238 unsigned CC = Func->getCallingConv();
6243 assert(0 && "Unsupported calling convention");
6244 case CallingConv::C:
6245 case CallingConv::X86_StdCall: {
6246 // Pass 'nest' parameter in ECX.
6247 // Must be kept in sync with X86CallingConv.td
6250 // Check that ECX wasn't needed by an 'inreg' parameter.
6251 const FunctionType *FTy = Func->getFunctionType();
6252 const AttrListPtr &Attrs = Func->getAttributes();
6254 if (!Attrs.isEmpty() && !Func->isVarArg()) {
6255 unsigned InRegCount = 0;
6258 for (FunctionType::param_iterator I = FTy->param_begin(),
6259 E = FTy->param_end(); I != E; ++I, ++Idx)
6260 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6261 // FIXME: should only count parameters that are lowered to integers.
6262 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6264 if (InRegCount > 2) {
6265 cerr << "Nest register in use - reduce number of inreg parameters!\n";
6271 case CallingConv::X86_FastCall:
6272 case CallingConv::Fast:
6273 // Pass 'nest' parameter in EAX.
6274 // Must be kept in sync with X86CallingConv.td
6279 SDValue OutChains[4];
6282 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6283 DAG.getConstant(10, MVT::i32));
6284 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
6286 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
6287 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
6288 OutChains[0] = DAG.getStore(Root, dl,
6289 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
6292 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6293 DAG.getConstant(1, MVT::i32));
6294 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1, false, 1);
6296 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
6297 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6298 DAG.getConstant(5, MVT::i32));
6299 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
6300 TrmpAddr, 5, false, 1);
6302 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6303 DAG.getConstant(6, MVT::i32));
6304 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6, false, 1);
6307 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
6308 return DAG.getMergeValues(Ops, 2, dl);
6312 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
6314 The rounding mode is in bits 11:10 of FPSR, and has the following
6321 FLT_ROUNDS, on the other hand, expects the following:
6328 To perform the conversion, we do:
6329 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
6332 MachineFunction &MF = DAG.getMachineFunction();
6333 const TargetMachine &TM = MF.getTarget();
6334 const TargetFrameInfo &TFI = *TM.getFrameInfo();
6335 unsigned StackAlignment = TFI.getStackAlignment();
6336 MVT VT = Op.getValueType();
6337 DebugLoc dl = Op.getNode()->getDebugLoc();
6339 // Save FP Control Word to stack slot
6340 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
6341 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6343 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
6344 DAG.getEntryNode(), StackSlot);
6346 // Load FP Control Word from stack slot
6347 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0);
6349 // Transform as necessary
6351 DAG.getNode(ISD::SRL, dl, MVT::i16,
6352 DAG.getNode(ISD::AND, dl, MVT::i16,
6353 CWD, DAG.getConstant(0x800, MVT::i16)),
6354 DAG.getConstant(11, MVT::i8));
6356 DAG.getNode(ISD::SRL, dl, MVT::i16,
6357 DAG.getNode(ISD::AND, dl, MVT::i16,
6358 CWD, DAG.getConstant(0x400, MVT::i16)),
6359 DAG.getConstant(9, MVT::i8));
6362 DAG.getNode(ISD::AND, dl, MVT::i16,
6363 DAG.getNode(ISD::ADD, dl, MVT::i16,
6364 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
6365 DAG.getConstant(1, MVT::i16)),
6366 DAG.getConstant(3, MVT::i16));
6369 return DAG.getNode((VT.getSizeInBits() < 16 ?
6370 ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
6373 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
6374 MVT VT = Op.getValueType();
6376 unsigned NumBits = VT.getSizeInBits();
6377 DebugLoc dl = Op.getNode()->getDebugLoc();
6379 Op = Op.getOperand(0);
6380 if (VT == MVT::i8) {
6381 // Zero extend to i32 since there is not an i8 bsr.
6383 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6386 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
6387 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6388 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
6390 // If src is zero (i.e. bsr sets ZF), returns NumBits.
6391 SmallVector<SDValue, 4> Ops;
6393 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
6394 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6395 Ops.push_back(Op.getValue(1));
6396 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6398 // Finally xor with NumBits-1.
6399 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
6402 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6406 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
6407 MVT VT = Op.getValueType();
6409 unsigned NumBits = VT.getSizeInBits();
6410 DebugLoc dl = Op.getNode()->getDebugLoc();
6412 Op = Op.getOperand(0);
6413 if (VT == MVT::i8) {
6415 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6418 // Issue a bsf (scan bits forward) which also sets EFLAGS.
6419 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6420 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
6422 // If src is zero (i.e. bsf sets ZF), returns NumBits.
6423 SmallVector<SDValue, 4> Ops;
6425 Ops.push_back(DAG.getConstant(NumBits, OpVT));
6426 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6427 Ops.push_back(Op.getValue(1));
6428 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6431 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6435 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
6436 MVT VT = Op.getValueType();
6437 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
6438 DebugLoc dl = Op.getNode()->getDebugLoc();
6440 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
6441 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
6442 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
6443 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
6444 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
6446 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
6447 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
6448 // return AloBlo + AloBhi + AhiBlo;
6450 SDValue A = Op.getOperand(0);
6451 SDValue B = Op.getOperand(1);
6453 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6454 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6455 A, DAG.getConstant(32, MVT::i32));
6456 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6457 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6458 B, DAG.getConstant(32, MVT::i32));
6459 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6460 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6462 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6463 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6465 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6466 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6468 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6469 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6470 AloBhi, DAG.getConstant(32, MVT::i32));
6471 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6472 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6473 AhiBlo, DAG.getConstant(32, MVT::i32));
6474 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
6475 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
6480 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
6481 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
6482 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
6483 // looks for this combo and may remove the "setcc" instruction if the "setcc"
6484 // has only one use.
6485 SDNode *N = Op.getNode();
6486 SDValue LHS = N->getOperand(0);
6487 SDValue RHS = N->getOperand(1);
6488 unsigned BaseOp = 0;
6490 DebugLoc dl = Op.getNode()->getDebugLoc();
6492 switch (Op.getOpcode()) {
6493 default: assert(0 && "Unknown ovf instruction!");
6495 BaseOp = X86ISD::ADD;
6499 BaseOp = X86ISD::ADD;
6503 BaseOp = X86ISD::SUB;
6507 BaseOp = X86ISD::SUB;
6511 BaseOp = X86ISD::SMUL;
6515 BaseOp = X86ISD::UMUL;
6520 // Also sets EFLAGS.
6521 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
6522 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
6525 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
6526 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
6528 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
6532 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
6533 MVT T = Op.getValueType();
6534 DebugLoc dl = Op.getNode()->getDebugLoc();
6537 switch(T.getSimpleVT()) {
6539 assert(false && "Invalid value type!");
6540 case MVT::i8: Reg = X86::AL; size = 1; break;
6541 case MVT::i16: Reg = X86::AX; size = 2; break;
6542 case MVT::i32: Reg = X86::EAX; size = 4; break;
6544 assert(Subtarget->is64Bit() && "Node not type legal!");
6545 Reg = X86::RAX; size = 8;
6548 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
6549 Op.getOperand(2), SDValue());
6550 SDValue Ops[] = { cpIn.getValue(0),
6553 DAG.getTargetConstant(size, MVT::i8),
6555 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6556 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
6558 DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
6562 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
6563 SelectionDAG &DAG) {
6564 assert(Subtarget->is64Bit() && "Result not type legalized?");
6565 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6566 SDValue TheChain = Op.getOperand(0);
6567 DebugLoc dl = Op.getNode()->getDebugLoc();
6568 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6569 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
6570 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
6572 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
6573 DAG.getConstant(32, MVT::i8));
6575 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
6578 return DAG.getMergeValues(Ops, 2, dl);
6581 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
6582 SDNode *Node = Op.getNode();
6583 DebugLoc dl = Node->getDebugLoc();
6584 MVT T = Node->getValueType(0);
6585 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
6586 DAG.getConstant(0, T), Node->getOperand(2));
6587 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
6588 cast<AtomicSDNode>(Node)->getMemoryVT(),
6589 Node->getOperand(0),
6590 Node->getOperand(1), negOp,
6591 cast<AtomicSDNode>(Node)->getSrcValue(),
6592 cast<AtomicSDNode>(Node)->getAlignment());
6595 /// LowerOperation - Provide custom lowering hooks for some operations.
6597 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
6598 switch (Op.getOpcode()) {
6599 default: assert(0 && "Should not custom lower this!");
6600 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
6601 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
6602 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6603 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6604 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6605 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6606 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6607 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6608 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6609 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6610 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
6611 case ISD::SHL_PARTS:
6612 case ISD::SRA_PARTS:
6613 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
6614 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
6615 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
6616 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
6617 case ISD::FABS: return LowerFABS(Op, DAG);
6618 case ISD::FNEG: return LowerFNEG(Op, DAG);
6619 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6620 case ISD::SETCC: return LowerSETCC(Op, DAG);
6621 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
6622 case ISD::SELECT: return LowerSELECT(Op, DAG);
6623 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
6624 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6625 case ISD::CALL: return LowerCALL(Op, DAG);
6626 case ISD::RET: return LowerRET(Op, DAG);
6627 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
6628 case ISD::VASTART: return LowerVASTART(Op, DAG);
6629 case ISD::VAARG: return LowerVAARG(Op, DAG);
6630 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
6631 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6632 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6633 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6634 case ISD::FRAME_TO_ARGS_OFFSET:
6635 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
6636 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
6637 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
6638 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
6639 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6640 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
6641 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
6642 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
6648 case ISD::UMULO: return LowerXALUO(Op, DAG);
6649 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
6653 void X86TargetLowering::
6654 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
6655 SelectionDAG &DAG, unsigned NewOp) {
6656 MVT T = Node->getValueType(0);
6657 DebugLoc dl = Node->getDebugLoc();
6658 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
6660 SDValue Chain = Node->getOperand(0);
6661 SDValue In1 = Node->getOperand(1);
6662 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6663 Node->getOperand(2), DAG.getIntPtrConstant(0));
6664 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6665 Node->getOperand(2), DAG.getIntPtrConstant(1));
6666 // This is a generalized SDNode, not an AtomicSDNode, so it doesn't
6667 // have a MemOperand. Pass the info through as a normal operand.
6668 SDValue LSI = DAG.getMemOperand(cast<MemSDNode>(Node)->getMemOperand());
6669 SDValue Ops[] = { Chain, In1, In2L, In2H, LSI };
6670 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6671 SDValue Result = DAG.getNode(NewOp, dl, Tys, Ops, 5);
6672 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
6673 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6674 Results.push_back(Result.getValue(2));
6677 /// ReplaceNodeResults - Replace a node with an illegal result type
6678 /// with a new node built out of custom code.
6679 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
6680 SmallVectorImpl<SDValue>&Results,
6681 SelectionDAG &DAG) {
6682 DebugLoc dl = N->getDebugLoc();
6683 switch (N->getOpcode()) {
6685 assert(false && "Do not know how to custom type legalize this operation!");
6687 case ISD::FP_TO_SINT: {
6688 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(SDValue(N, 0), DAG);
6689 SDValue FIST = Vals.first, StackSlot = Vals.second;
6690 if (FIST.getNode() != 0) {
6691 MVT VT = N->getValueType(0);
6692 // Return a load from the stack slot.
6693 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0));
6697 case ISD::READCYCLECOUNTER: {
6698 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6699 SDValue TheChain = N->getOperand(0);
6700 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6701 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
6703 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
6705 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
6706 SDValue Ops[] = { eax, edx };
6707 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
6708 Results.push_back(edx.getValue(1));
6711 case ISD::ATOMIC_CMP_SWAP: {
6712 MVT T = N->getValueType(0);
6713 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
6714 SDValue cpInL, cpInH;
6715 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
6716 DAG.getConstant(0, MVT::i32));
6717 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
6718 DAG.getConstant(1, MVT::i32));
6719 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
6720 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
6722 SDValue swapInL, swapInH;
6723 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
6724 DAG.getConstant(0, MVT::i32));
6725 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
6726 DAG.getConstant(1, MVT::i32));
6727 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
6729 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
6730 swapInL.getValue(1));
6731 SDValue Ops[] = { swapInH.getValue(0),
6733 swapInH.getValue(1) };
6734 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6735 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
6736 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
6737 MVT::i32, Result.getValue(1));
6738 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
6739 MVT::i32, cpOutL.getValue(2));
6740 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
6741 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6742 Results.push_back(cpOutH.getValue(1));
6745 case ISD::ATOMIC_LOAD_ADD:
6746 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
6748 case ISD::ATOMIC_LOAD_AND:
6749 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
6751 case ISD::ATOMIC_LOAD_NAND:
6752 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
6754 case ISD::ATOMIC_LOAD_OR:
6755 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
6757 case ISD::ATOMIC_LOAD_SUB:
6758 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
6760 case ISD::ATOMIC_LOAD_XOR:
6761 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
6763 case ISD::ATOMIC_SWAP:
6764 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
6769 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
6771 default: return NULL;
6772 case X86ISD::BSF: return "X86ISD::BSF";
6773 case X86ISD::BSR: return "X86ISD::BSR";
6774 case X86ISD::SHLD: return "X86ISD::SHLD";
6775 case X86ISD::SHRD: return "X86ISD::SHRD";
6776 case X86ISD::FAND: return "X86ISD::FAND";
6777 case X86ISD::FOR: return "X86ISD::FOR";
6778 case X86ISD::FXOR: return "X86ISD::FXOR";
6779 case X86ISD::FSRL: return "X86ISD::FSRL";
6780 case X86ISD::FILD: return "X86ISD::FILD";
6781 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
6782 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
6783 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
6784 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
6785 case X86ISD::FLD: return "X86ISD::FLD";
6786 case X86ISD::FST: return "X86ISD::FST";
6787 case X86ISD::CALL: return "X86ISD::CALL";
6788 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
6789 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
6790 case X86ISD::BT: return "X86ISD::BT";
6791 case X86ISD::CMP: return "X86ISD::CMP";
6792 case X86ISD::COMI: return "X86ISD::COMI";
6793 case X86ISD::UCOMI: return "X86ISD::UCOMI";
6794 case X86ISD::SETCC: return "X86ISD::SETCC";
6795 case X86ISD::CMOV: return "X86ISD::CMOV";
6796 case X86ISD::BRCOND: return "X86ISD::BRCOND";
6797 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
6798 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
6799 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
6800 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
6801 case X86ISD::Wrapper: return "X86ISD::Wrapper";
6802 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
6803 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
6804 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
6805 case X86ISD::PINSRB: return "X86ISD::PINSRB";
6806 case X86ISD::PINSRW: return "X86ISD::PINSRW";
6807 case X86ISD::FMAX: return "X86ISD::FMAX";
6808 case X86ISD::FMIN: return "X86ISD::FMIN";
6809 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
6810 case X86ISD::FRCP: return "X86ISD::FRCP";
6811 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
6812 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
6813 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
6814 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
6815 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
6816 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
6817 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
6818 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
6819 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
6820 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
6821 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
6822 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
6823 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
6824 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
6825 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
6826 case X86ISD::VSHL: return "X86ISD::VSHL";
6827 case X86ISD::VSRL: return "X86ISD::VSRL";
6828 case X86ISD::CMPPD: return "X86ISD::CMPPD";
6829 case X86ISD::CMPPS: return "X86ISD::CMPPS";
6830 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
6831 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
6832 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
6833 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
6834 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
6835 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
6836 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
6837 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
6838 case X86ISD::ADD: return "X86ISD::ADD";
6839 case X86ISD::SUB: return "X86ISD::SUB";
6840 case X86ISD::SMUL: return "X86ISD::SMUL";
6841 case X86ISD::UMUL: return "X86ISD::UMUL";
6845 // isLegalAddressingMode - Return true if the addressing mode represented
6846 // by AM is legal for this target, for a load/store of the specified type.
6847 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
6848 const Type *Ty) const {
6849 // X86 supports extremely general addressing modes.
6851 // X86 allows a sign-extended 32-bit immediate field as a displacement.
6852 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
6856 // We can only fold this if we don't need an extra load.
6857 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
6859 // If BaseGV requires a register, we cannot also have a BaseReg.
6860 if (Subtarget->GVRequiresRegister(AM.BaseGV, getTargetMachine(), false) &&
6864 // X86-64 only supports addr of globals in small code model.
6865 if (Subtarget->is64Bit()) {
6866 if (getTargetMachine().getCodeModel() != CodeModel::Small)
6868 // If lower 4G is not available, then we must use rip-relative addressing.
6869 if (AM.BaseOffs || AM.Scale > 1)
6880 // These scales always work.
6885 // These scales are formed with basereg+scalereg. Only accept if there is
6890 default: // Other stuff never works.
6898 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
6899 if (!Ty1->isInteger() || !Ty2->isInteger())
6901 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6902 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6903 if (NumBits1 <= NumBits2)
6905 return Subtarget->is64Bit() || NumBits1 < 64;
6908 bool X86TargetLowering::isTruncateFree(MVT VT1, MVT VT2) const {
6909 if (!VT1.isInteger() || !VT2.isInteger())
6911 unsigned NumBits1 = VT1.getSizeInBits();
6912 unsigned NumBits2 = VT2.getSizeInBits();
6913 if (NumBits1 <= NumBits2)
6915 return Subtarget->is64Bit() || NumBits1 < 64;
6918 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6919 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6920 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6921 /// are assumed to be legal.
6923 X86TargetLowering::isShuffleMaskLegal(SDValue Mask, MVT VT) const {
6924 // Only do shuffles on 128-bit vector types for now.
6925 if (VT.getSizeInBits() == 64) return false;
6926 return (Mask.getNode()->getNumOperands() <= 4 ||
6927 isIdentityMask(Mask.getNode()) ||
6928 isIdentityMask(Mask.getNode(), true) ||
6929 isSplatMask(Mask.getNode()) ||
6930 isPSHUFHW_PSHUFLWMask(Mask.getNode()) ||
6931 X86::isUNPCKLMask(Mask.getNode()) ||
6932 X86::isUNPCKHMask(Mask.getNode()) ||
6933 X86::isUNPCKL_v_undef_Mask(Mask.getNode()) ||
6934 X86::isUNPCKH_v_undef_Mask(Mask.getNode()));
6938 X86TargetLowering::isVectorClearMaskLegal(const std::vector<SDValue> &BVOps,
6939 MVT EVT, SelectionDAG &DAG) const {
6940 unsigned NumElts = BVOps.size();
6941 // Only do shuffles on 128-bit vector types for now.
6942 if (EVT.getSizeInBits() * NumElts == 64) return false;
6943 if (NumElts == 2) return true;
6945 return (isMOVLMask(&BVOps[0], 4) ||
6946 isCommutedMOVL(&BVOps[0], 4, true) ||
6947 isSHUFPMask(&BVOps[0], 4) ||
6948 isCommutedSHUFP(&BVOps[0], 4));
6953 //===----------------------------------------------------------------------===//
6954 // X86 Scheduler Hooks
6955 //===----------------------------------------------------------------------===//
6957 // private utility function
6959 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
6960 MachineBasicBlock *MBB,
6968 TargetRegisterClass *RC,
6970 // For the atomic bitwise operator, we generate
6973 // ld t1 = [bitinstr.addr]
6974 // op t2 = t1, [bitinstr.val]
6976 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
6978 // fallthrough -->nextMBB
6979 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6980 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6981 MachineFunction::iterator MBBIter = MBB;
6984 /// First build the CFG
6985 MachineFunction *F = MBB->getParent();
6986 MachineBasicBlock *thisMBB = MBB;
6987 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6988 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6989 F->insert(MBBIter, newMBB);
6990 F->insert(MBBIter, nextMBB);
6992 // Move all successors to thisMBB to nextMBB
6993 nextMBB->transferSuccessors(thisMBB);
6995 // Update thisMBB to fall through to newMBB
6996 thisMBB->addSuccessor(newMBB);
6998 // newMBB jumps to itself and fall through to nextMBB
6999 newMBB->addSuccessor(nextMBB);
7000 newMBB->addSuccessor(newMBB);
7002 // Insert instructions into newMBB based on incoming instruction
7003 assert(bInstr->getNumOperands() < 8 && "unexpected number of operands");
7004 DebugLoc dl = bInstr->getDebugLoc();
7005 MachineOperand& destOper = bInstr->getOperand(0);
7006 MachineOperand* argOpers[6];
7007 int numArgs = bInstr->getNumOperands() - 1;
7008 for (int i=0; i < numArgs; ++i)
7009 argOpers[i] = &bInstr->getOperand(i+1);
7011 // x86 address has 4 operands: base, index, scale, and displacement
7012 int lastAddrIndx = 3; // [0,3]
7015 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7016 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7017 for (int i=0; i <= lastAddrIndx; ++i)
7018 (*MIB).addOperand(*argOpers[i]);
7020 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7022 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7027 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7028 assert((argOpers[valArgIndx]->isReg() ||
7029 argOpers[valArgIndx]->isImm()) &&
7031 if (argOpers[valArgIndx]->isReg())
7032 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7034 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7036 (*MIB).addOperand(*argOpers[valArgIndx]);
7038 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7041 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7042 for (int i=0; i <= lastAddrIndx; ++i)
7043 (*MIB).addOperand(*argOpers[i]);
7045 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7046 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7048 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7052 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7054 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7058 // private utility function: 64 bit atomics on 32 bit host.
7060 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7061 MachineBasicBlock *MBB,
7067 // For the atomic bitwise operator, we generate
7068 // thisMBB (instructions are in pairs, except cmpxchg8b)
7069 // ld t1,t2 = [bitinstr.addr]
7071 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7072 // op t5, t6 <- out1, out2, [bitinstr.val]
7073 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
7074 // mov ECX, EBX <- t5, t6
7075 // mov EAX, EDX <- t1, t2
7076 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
7077 // mov t3, t4 <- EAX, EDX
7079 // result in out1, out2
7080 // fallthrough -->nextMBB
7082 const TargetRegisterClass *RC = X86::GR32RegisterClass;
7083 const unsigned LoadOpc = X86::MOV32rm;
7084 const unsigned copyOpc = X86::MOV32rr;
7085 const unsigned NotOpc = X86::NOT32r;
7086 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7087 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7088 MachineFunction::iterator MBBIter = MBB;
7091 /// First build the CFG
7092 MachineFunction *F = MBB->getParent();
7093 MachineBasicBlock *thisMBB = MBB;
7094 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7095 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7096 F->insert(MBBIter, newMBB);
7097 F->insert(MBBIter, nextMBB);
7099 // Move all successors to thisMBB to nextMBB
7100 nextMBB->transferSuccessors(thisMBB);
7102 // Update thisMBB to fall through to newMBB
7103 thisMBB->addSuccessor(newMBB);
7105 // newMBB jumps to itself and fall through to nextMBB
7106 newMBB->addSuccessor(nextMBB);
7107 newMBB->addSuccessor(newMBB);
7109 DebugLoc dl = bInstr->getDebugLoc();
7110 // Insert instructions into newMBB based on incoming instruction
7111 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7112 assert(bInstr->getNumOperands() < 18 && "unexpected number of operands");
7113 MachineOperand& dest1Oper = bInstr->getOperand(0);
7114 MachineOperand& dest2Oper = bInstr->getOperand(1);
7115 MachineOperand* argOpers[6];
7116 for (int i=0; i < 6; ++i)
7117 argOpers[i] = &bInstr->getOperand(i+2);
7119 // x86 address has 4 operands: base, index, scale, and displacement
7120 int lastAddrIndx = 3; // [0,3]
7122 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7123 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
7124 for (int i=0; i <= lastAddrIndx; ++i)
7125 (*MIB).addOperand(*argOpers[i]);
7126 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7127 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
7128 // add 4 to displacement.
7129 for (int i=0; i <= lastAddrIndx-1; ++i)
7130 (*MIB).addOperand(*argOpers[i]);
7131 MachineOperand newOp3 = *(argOpers[3]);
7133 newOp3.setImm(newOp3.getImm()+4);
7135 newOp3.setOffset(newOp3.getOffset()+4);
7136 (*MIB).addOperand(newOp3);
7138 // t3/4 are defined later, at the bottom of the loop
7139 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
7140 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
7141 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
7142 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
7143 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
7144 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
7146 unsigned tt1 = F->getRegInfo().createVirtualRegister(RC);
7147 unsigned tt2 = F->getRegInfo().createVirtualRegister(RC);
7149 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt1).addReg(t1);
7150 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt2).addReg(t2);
7156 assert((argOpers[4]->isReg() || argOpers[4]->isImm()) &&
7158 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
7159 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
7160 if (argOpers[4]->isReg())
7161 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
7163 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
7164 if (regOpcL != X86::MOV32rr)
7166 (*MIB).addOperand(*argOpers[4]);
7167 assert(argOpers[5]->isReg() == argOpers[4]->isReg());
7168 assert(argOpers[5]->isImm() == argOpers[4]->isImm());
7169 if (argOpers[5]->isReg())
7170 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
7172 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
7173 if (regOpcH != X86::MOV32rr)
7175 (*MIB).addOperand(*argOpers[5]);
7177 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
7179 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
7182 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
7184 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
7187 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
7188 for (int i=0; i <= lastAddrIndx; ++i)
7189 (*MIB).addOperand(*argOpers[i]);
7191 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7192 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7194 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
7195 MIB.addReg(X86::EAX);
7196 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
7197 MIB.addReg(X86::EDX);
7200 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7202 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7206 // private utility function
7208 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
7209 MachineBasicBlock *MBB,
7211 // For the atomic min/max operator, we generate
7214 // ld t1 = [min/max.addr]
7215 // mov t2 = [min/max.val]
7217 // cmov[cond] t2 = t1
7219 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7221 // fallthrough -->nextMBB
7223 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7224 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7225 MachineFunction::iterator MBBIter = MBB;
7228 /// First build the CFG
7229 MachineFunction *F = MBB->getParent();
7230 MachineBasicBlock *thisMBB = MBB;
7231 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7232 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7233 F->insert(MBBIter, newMBB);
7234 F->insert(MBBIter, nextMBB);
7236 // Move all successors to thisMBB to nextMBB
7237 nextMBB->transferSuccessors(thisMBB);
7239 // Update thisMBB to fall through to newMBB
7240 thisMBB->addSuccessor(newMBB);
7242 // newMBB jumps to newMBB and fall through to nextMBB
7243 newMBB->addSuccessor(nextMBB);
7244 newMBB->addSuccessor(newMBB);
7246 DebugLoc dl = mInstr->getDebugLoc();
7247 // Insert instructions into newMBB based on incoming instruction
7248 assert(mInstr->getNumOperands() < 8 && "unexpected number of operands");
7249 MachineOperand& destOper = mInstr->getOperand(0);
7250 MachineOperand* argOpers[6];
7251 int numArgs = mInstr->getNumOperands() - 1;
7252 for (int i=0; i < numArgs; ++i)
7253 argOpers[i] = &mInstr->getOperand(i+1);
7255 // x86 address has 4 operands: base, index, scale, and displacement
7256 int lastAddrIndx = 3; // [0,3]
7259 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7260 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
7261 for (int i=0; i <= lastAddrIndx; ++i)
7262 (*MIB).addOperand(*argOpers[i]);
7264 // We only support register and immediate values
7265 assert((argOpers[valArgIndx]->isReg() ||
7266 argOpers[valArgIndx]->isImm()) &&
7269 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7270 if (argOpers[valArgIndx]->isReg())
7271 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7273 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7274 (*MIB).addOperand(*argOpers[valArgIndx]);
7276 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
7279 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
7284 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7285 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
7289 // Cmp and exchange if none has modified the memory location
7290 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
7291 for (int i=0; i <= lastAddrIndx; ++i)
7292 (*MIB).addOperand(*argOpers[i]);
7294 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7295 (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
7297 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
7298 MIB.addReg(X86::EAX);
7301 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7303 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
7309 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7310 MachineBasicBlock *BB) {
7311 DebugLoc dl = MI->getDebugLoc();
7312 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7313 switch (MI->getOpcode()) {
7314 default: assert(false && "Unexpected instr type to insert");
7315 case X86::CMOV_V1I64:
7316 case X86::CMOV_FR32:
7317 case X86::CMOV_FR64:
7318 case X86::CMOV_V4F32:
7319 case X86::CMOV_V2F64:
7320 case X86::CMOV_V2I64: {
7321 // To "insert" a SELECT_CC instruction, we actually have to insert the
7322 // diamond control-flow pattern. The incoming instruction knows the
7323 // destination vreg to set, the condition code register to branch on, the
7324 // true/false values to select between, and a branch opcode to use.
7325 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7326 MachineFunction::iterator It = BB;
7332 // cmpTY ccX, r1, r2
7334 // fallthrough --> copy0MBB
7335 MachineBasicBlock *thisMBB = BB;
7336 MachineFunction *F = BB->getParent();
7337 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7338 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7340 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
7341 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
7342 F->insert(It, copy0MBB);
7343 F->insert(It, sinkMBB);
7344 // Update machine-CFG edges by transferring all successors of the current
7345 // block to the new block which will contain the Phi node for the select.
7346 sinkMBB->transferSuccessors(BB);
7348 // Add the true and fallthrough blocks as its successors.
7349 BB->addSuccessor(copy0MBB);
7350 BB->addSuccessor(sinkMBB);
7353 // %FalseValue = ...
7354 // # fallthrough to sinkMBB
7357 // Update machine-CFG edges
7358 BB->addSuccessor(sinkMBB);
7361 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7364 BuildMI(BB, dl, TII->get(X86::PHI), MI->getOperand(0).getReg())
7365 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7366 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7368 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7372 case X86::FP32_TO_INT16_IN_MEM:
7373 case X86::FP32_TO_INT32_IN_MEM:
7374 case X86::FP32_TO_INT64_IN_MEM:
7375 case X86::FP64_TO_INT16_IN_MEM:
7376 case X86::FP64_TO_INT32_IN_MEM:
7377 case X86::FP64_TO_INT64_IN_MEM:
7378 case X86::FP80_TO_INT16_IN_MEM:
7379 case X86::FP80_TO_INT32_IN_MEM:
7380 case X86::FP80_TO_INT64_IN_MEM: {
7381 // Change the floating point control register to use "round towards zero"
7382 // mode when truncating to an integer value.
7383 MachineFunction *F = BB->getParent();
7384 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
7385 addFrameReference(BuildMI(BB, dl, TII->get(X86::FNSTCW16m)), CWFrameIdx);
7387 // Load the old value of the high byte of the control word...
7389 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
7390 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16rm), OldCW),
7393 // Set the high part to be round to zero...
7394 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mi)), CWFrameIdx)
7397 // Reload the modified control word now...
7398 addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7400 // Restore the memory image of control word to original value
7401 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mr)), CWFrameIdx)
7404 // Get the X86 opcode to use.
7406 switch (MI->getOpcode()) {
7407 default: assert(0 && "illegal opcode!");
7408 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
7409 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
7410 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
7411 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
7412 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
7413 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
7414 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
7415 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
7416 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
7420 MachineOperand &Op = MI->getOperand(0);
7422 AM.BaseType = X86AddressMode::RegBase;
7423 AM.Base.Reg = Op.getReg();
7425 AM.BaseType = X86AddressMode::FrameIndexBase;
7426 AM.Base.FrameIndex = Op.getIndex();
7428 Op = MI->getOperand(1);
7430 AM.Scale = Op.getImm();
7431 Op = MI->getOperand(2);
7433 AM.IndexReg = Op.getImm();
7434 Op = MI->getOperand(3);
7435 if (Op.isGlobal()) {
7436 AM.GV = Op.getGlobal();
7438 AM.Disp = Op.getImm();
7440 addFullAddress(BuildMI(BB, dl, TII->get(Opc)), AM)
7441 .addReg(MI->getOperand(4).getReg());
7443 // Reload the original control word now.
7444 addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7446 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7449 case X86::ATOMAND32:
7450 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7451 X86::AND32ri, X86::MOV32rm,
7452 X86::LCMPXCHG32, X86::MOV32rr,
7453 X86::NOT32r, X86::EAX,
7454 X86::GR32RegisterClass);
7456 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
7457 X86::OR32ri, X86::MOV32rm,
7458 X86::LCMPXCHG32, X86::MOV32rr,
7459 X86::NOT32r, X86::EAX,
7460 X86::GR32RegisterClass);
7461 case X86::ATOMXOR32:
7462 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
7463 X86::XOR32ri, X86::MOV32rm,
7464 X86::LCMPXCHG32, X86::MOV32rr,
7465 X86::NOT32r, X86::EAX,
7466 X86::GR32RegisterClass);
7467 case X86::ATOMNAND32:
7468 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7469 X86::AND32ri, X86::MOV32rm,
7470 X86::LCMPXCHG32, X86::MOV32rr,
7471 X86::NOT32r, X86::EAX,
7472 X86::GR32RegisterClass, true);
7473 case X86::ATOMMIN32:
7474 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
7475 case X86::ATOMMAX32:
7476 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
7477 case X86::ATOMUMIN32:
7478 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
7479 case X86::ATOMUMAX32:
7480 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
7482 case X86::ATOMAND16:
7483 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7484 X86::AND16ri, X86::MOV16rm,
7485 X86::LCMPXCHG16, X86::MOV16rr,
7486 X86::NOT16r, X86::AX,
7487 X86::GR16RegisterClass);
7489 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
7490 X86::OR16ri, X86::MOV16rm,
7491 X86::LCMPXCHG16, X86::MOV16rr,
7492 X86::NOT16r, X86::AX,
7493 X86::GR16RegisterClass);
7494 case X86::ATOMXOR16:
7495 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
7496 X86::XOR16ri, X86::MOV16rm,
7497 X86::LCMPXCHG16, X86::MOV16rr,
7498 X86::NOT16r, X86::AX,
7499 X86::GR16RegisterClass);
7500 case X86::ATOMNAND16:
7501 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7502 X86::AND16ri, X86::MOV16rm,
7503 X86::LCMPXCHG16, X86::MOV16rr,
7504 X86::NOT16r, X86::AX,
7505 X86::GR16RegisterClass, true);
7506 case X86::ATOMMIN16:
7507 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
7508 case X86::ATOMMAX16:
7509 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
7510 case X86::ATOMUMIN16:
7511 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
7512 case X86::ATOMUMAX16:
7513 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
7516 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7517 X86::AND8ri, X86::MOV8rm,
7518 X86::LCMPXCHG8, X86::MOV8rr,
7519 X86::NOT8r, X86::AL,
7520 X86::GR8RegisterClass);
7522 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
7523 X86::OR8ri, X86::MOV8rm,
7524 X86::LCMPXCHG8, X86::MOV8rr,
7525 X86::NOT8r, X86::AL,
7526 X86::GR8RegisterClass);
7528 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
7529 X86::XOR8ri, X86::MOV8rm,
7530 X86::LCMPXCHG8, X86::MOV8rr,
7531 X86::NOT8r, X86::AL,
7532 X86::GR8RegisterClass);
7533 case X86::ATOMNAND8:
7534 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7535 X86::AND8ri, X86::MOV8rm,
7536 X86::LCMPXCHG8, X86::MOV8rr,
7537 X86::NOT8r, X86::AL,
7538 X86::GR8RegisterClass, true);
7539 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
7540 // This group is for 64-bit host.
7541 case X86::ATOMAND64:
7542 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7543 X86::AND64ri32, X86::MOV64rm,
7544 X86::LCMPXCHG64, X86::MOV64rr,
7545 X86::NOT64r, X86::RAX,
7546 X86::GR64RegisterClass);
7548 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
7549 X86::OR64ri32, X86::MOV64rm,
7550 X86::LCMPXCHG64, X86::MOV64rr,
7551 X86::NOT64r, X86::RAX,
7552 X86::GR64RegisterClass);
7553 case X86::ATOMXOR64:
7554 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
7555 X86::XOR64ri32, X86::MOV64rm,
7556 X86::LCMPXCHG64, X86::MOV64rr,
7557 X86::NOT64r, X86::RAX,
7558 X86::GR64RegisterClass);
7559 case X86::ATOMNAND64:
7560 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7561 X86::AND64ri32, X86::MOV64rm,
7562 X86::LCMPXCHG64, X86::MOV64rr,
7563 X86::NOT64r, X86::RAX,
7564 X86::GR64RegisterClass, true);
7565 case X86::ATOMMIN64:
7566 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
7567 case X86::ATOMMAX64:
7568 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
7569 case X86::ATOMUMIN64:
7570 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
7571 case X86::ATOMUMAX64:
7572 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
7574 // This group does 64-bit operations on a 32-bit host.
7575 case X86::ATOMAND6432:
7576 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7577 X86::AND32rr, X86::AND32rr,
7578 X86::AND32ri, X86::AND32ri,
7580 case X86::ATOMOR6432:
7581 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7582 X86::OR32rr, X86::OR32rr,
7583 X86::OR32ri, X86::OR32ri,
7585 case X86::ATOMXOR6432:
7586 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7587 X86::XOR32rr, X86::XOR32rr,
7588 X86::XOR32ri, X86::XOR32ri,
7590 case X86::ATOMNAND6432:
7591 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7592 X86::AND32rr, X86::AND32rr,
7593 X86::AND32ri, X86::AND32ri,
7595 case X86::ATOMADD6432:
7596 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7597 X86::ADD32rr, X86::ADC32rr,
7598 X86::ADD32ri, X86::ADC32ri,
7600 case X86::ATOMSUB6432:
7601 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7602 X86::SUB32rr, X86::SBB32rr,
7603 X86::SUB32ri, X86::SBB32ri,
7605 case X86::ATOMSWAP6432:
7606 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7607 X86::MOV32rr, X86::MOV32rr,
7608 X86::MOV32ri, X86::MOV32ri,
7613 //===----------------------------------------------------------------------===//
7614 // X86 Optimization Hooks
7615 //===----------------------------------------------------------------------===//
7617 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
7621 const SelectionDAG &DAG,
7622 unsigned Depth) const {
7623 unsigned Opc = Op.getOpcode();
7624 assert((Opc >= ISD::BUILTIN_OP_END ||
7625 Opc == ISD::INTRINSIC_WO_CHAIN ||
7626 Opc == ISD::INTRINSIC_W_CHAIN ||
7627 Opc == ISD::INTRINSIC_VOID) &&
7628 "Should use MaskedValueIsZero if you don't know whether Op"
7629 " is a target node!");
7631 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
7638 // These nodes' second result is a boolean.
7639 if (Op.getResNo() == 0)
7643 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
7644 Mask.getBitWidth() - 1);
7649 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
7650 /// node is a GlobalAddress + offset.
7651 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
7652 GlobalValue* &GA, int64_t &Offset) const{
7653 if (N->getOpcode() == X86ISD::Wrapper) {
7654 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
7655 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
7656 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
7660 return TargetLowering::isGAPlusOffset(N, GA, Offset);
7663 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
7664 const TargetLowering &TLI) {
7667 if (TLI.isGAPlusOffset(Base, GV, Offset))
7668 return (GV->getAlignment() >= N && (Offset % N) == 0);
7669 // DAG combine handles the stack object case.
7673 static bool EltsFromConsecutiveLoads(SDNode *N, SDValue PermMask,
7674 unsigned NumElems, MVT EVT,
7676 SelectionDAG &DAG, MachineFrameInfo *MFI,
7677 const TargetLowering &TLI) {
7679 for (unsigned i = 0; i < NumElems; ++i) {
7680 SDValue Idx = PermMask.getOperand(i);
7681 if (Idx.getOpcode() == ISD::UNDEF) {
7687 SDValue Elt = DAG.getShuffleScalarElt(N, i);
7688 if (!Elt.getNode() ||
7689 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
7692 Base = Elt.getNode();
7693 if (Base->getOpcode() == ISD::UNDEF)
7697 if (Elt.getOpcode() == ISD::UNDEF)
7700 if (!TLI.isConsecutiveLoad(Elt.getNode(), Base,
7701 EVT.getSizeInBits()/8, i, MFI))
7707 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
7708 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
7709 /// if the load addresses are consecutive, non-overlapping, and in the right
7711 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
7712 const TargetLowering &TLI) {
7713 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7714 DebugLoc dl = N->getDebugLoc();
7715 MVT VT = N->getValueType(0);
7716 MVT EVT = VT.getVectorElementType();
7717 SDValue PermMask = N->getOperand(2);
7718 unsigned NumElems = PermMask.getNumOperands();
7719 SDNode *Base = NULL;
7720 if (!EltsFromConsecutiveLoads(N, PermMask, NumElems, EVT, Base,
7724 LoadSDNode *LD = cast<LoadSDNode>(Base);
7725 if (isBaseAlignmentOfN(16, Base->getOperand(1).getNode(), TLI))
7726 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
7727 LD->getSrcValue(), LD->getSrcValueOffset(),
7729 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
7730 LD->getSrcValue(), LD->getSrcValueOffset(),
7731 LD->isVolatile(), LD->getAlignment());
7734 /// PerformBuildVectorCombine - build_vector 0,(load i64 / f64) -> movq / movsd.
7735 static SDValue PerformBuildVectorCombine(SDNode *N, SelectionDAG &DAG,
7736 TargetLowering::DAGCombinerInfo &DCI,
7737 const X86Subtarget *Subtarget,
7738 const TargetLowering &TLI) {
7739 unsigned NumOps = N->getNumOperands();
7740 DebugLoc dl = N->getDebugLoc();
7742 // Ignore single operand BUILD_VECTOR.
7746 MVT VT = N->getValueType(0);
7747 MVT EVT = VT.getVectorElementType();
7748 if ((EVT != MVT::i64 && EVT != MVT::f64) || Subtarget->is64Bit())
7749 // We are looking for load i64 and zero extend. We want to transform
7750 // it before legalizer has a chance to expand it. Also look for i64
7751 // BUILD_PAIR bit casted to f64.
7753 // This must be an insertion into a zero vector.
7754 SDValue HighElt = N->getOperand(1);
7755 if (!isZeroNode(HighElt))
7758 // Value must be a load.
7759 SDNode *Base = N->getOperand(0).getNode();
7760 if (!isa<LoadSDNode>(Base)) {
7761 if (Base->getOpcode() != ISD::BIT_CONVERT)
7763 Base = Base->getOperand(0).getNode();
7764 if (!isa<LoadSDNode>(Base))
7768 // Transform it into VZEXT_LOAD addr.
7769 LoadSDNode *LD = cast<LoadSDNode>(Base);
7771 // Load must not be an extload.
7772 if (LD->getExtensionType() != ISD::NON_EXTLOAD)
7775 // Load type should legal type so we don't have to legalize it.
7776 if (!TLI.isTypeLegal(VT))
7779 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
7780 SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
7781 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
7782 TargetLowering::TargetLoweringOpt TLO(DAG);
7783 TLO.CombineTo(SDValue(Base, 1), ResNode.getValue(1));
7784 DCI.CommitTargetLoweringOpt(TLO);
7788 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
7789 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
7790 const X86Subtarget *Subtarget) {
7791 DebugLoc dl = N->getDebugLoc();
7792 SDValue Cond = N->getOperand(0);
7794 // If we have SSE[12] support, try to form min/max nodes.
7795 if (Subtarget->hasSSE2() &&
7796 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
7797 if (Cond.getOpcode() == ISD::SETCC) {
7798 // Get the LHS/RHS of the select.
7799 SDValue LHS = N->getOperand(1);
7800 SDValue RHS = N->getOperand(2);
7801 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
7803 unsigned Opcode = 0;
7804 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
7807 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
7810 if (!UnsafeFPMath) break;
7812 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
7814 Opcode = X86ISD::FMIN;
7817 case ISD::SETOGT: // (X > Y) ? X : Y -> max
7820 if (!UnsafeFPMath) break;
7822 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
7824 Opcode = X86ISD::FMAX;
7827 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
7830 case ISD::SETOGT: // (X > Y) ? Y : X -> min
7833 if (!UnsafeFPMath) break;
7835 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
7837 Opcode = X86ISD::FMIN;
7840 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
7843 if (!UnsafeFPMath) break;
7845 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
7847 Opcode = X86ISD::FMAX;
7853 return DAG.getNode(Opcode, dl, N->getValueType(0), LHS, RHS);
7861 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
7863 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
7864 const X86Subtarget *Subtarget) {
7865 // On X86 with SSE2 support, we can transform this to a vector shift if
7866 // all elements are shifted by the same amount. We can't do this in legalize
7867 // because the a constant vector is typically transformed to a constant pool
7868 // so we have no knowledge of the shift amount.
7869 if (!Subtarget->hasSSE2())
7872 MVT VT = N->getValueType(0);
7873 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
7876 SDValue ShAmtOp = N->getOperand(1);
7877 MVT EltVT = VT.getVectorElementType();
7878 DebugLoc dl = N->getDebugLoc();
7880 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
7881 unsigned NumElts = VT.getVectorNumElements();
7883 for (; i != NumElts; ++i) {
7884 SDValue Arg = ShAmtOp.getOperand(i);
7885 if (Arg.getOpcode() == ISD::UNDEF) continue;
7889 for (; i != NumElts; ++i) {
7890 SDValue Arg = ShAmtOp.getOperand(i);
7891 if (Arg.getOpcode() == ISD::UNDEF) continue;
7892 if (Arg != BaseShAmt) {
7896 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
7897 isSplatMask(ShAmtOp.getOperand(2).getNode())) {
7898 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, ShAmtOp,
7899 DAG.getIntPtrConstant(0));
7903 if (EltVT.bitsGT(MVT::i32))
7904 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
7905 else if (EltVT.bitsLT(MVT::i32))
7906 BaseShAmt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BaseShAmt);
7908 // The shift amount is identical so we can do a vector shift.
7909 SDValue ValOp = N->getOperand(0);
7910 switch (N->getOpcode()) {
7912 assert(0 && "Unknown shift opcode!");
7915 if (VT == MVT::v2i64)
7916 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7917 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7919 if (VT == MVT::v4i32)
7920 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7921 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
7923 if (VT == MVT::v8i16)
7924 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7925 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
7929 if (VT == MVT::v4i32)
7930 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7931 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
7933 if (VT == MVT::v8i16)
7934 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7935 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
7939 if (VT == MVT::v2i64)
7940 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7941 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7943 if (VT == MVT::v4i32)
7944 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7945 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
7947 if (VT == MVT::v8i16)
7948 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7949 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
7956 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
7957 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
7958 const X86Subtarget *Subtarget) {
7959 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
7960 // the FP state in cases where an emms may be missing.
7961 // A preferable solution to the general problem is to figure out the right
7962 // places to insert EMMS. This qualifies as a quick hack.
7963 StoreSDNode *St = cast<StoreSDNode>(N);
7964 if (St->getValue().getValueType().isVector() &&
7965 St->getValue().getValueType().getSizeInBits() == 64 &&
7966 isa<LoadSDNode>(St->getValue()) &&
7967 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
7968 St->getChain().hasOneUse() && !St->isVolatile()) {
7969 SDNode* LdVal = St->getValue().getNode();
7971 int TokenFactorIndex = -1;
7972 SmallVector<SDValue, 8> Ops;
7973 SDNode* ChainVal = St->getChain().getNode();
7974 // Must be a store of a load. We currently handle two cases: the load
7975 // is a direct child, and it's under an intervening TokenFactor. It is
7976 // possible to dig deeper under nested TokenFactors.
7977 if (ChainVal == LdVal)
7978 Ld = cast<LoadSDNode>(St->getChain());
7979 else if (St->getValue().hasOneUse() &&
7980 ChainVal->getOpcode() == ISD::TokenFactor) {
7981 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
7982 if (ChainVal->getOperand(i).getNode() == LdVal) {
7983 TokenFactorIndex = i;
7984 Ld = cast<LoadSDNode>(St->getValue());
7986 Ops.push_back(ChainVal->getOperand(i));
7990 DebugLoc dl = N->getDebugLoc();
7991 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
7992 if (Subtarget->is64Bit()) {
7993 SDValue NewLd = DAG.getLoad(MVT::i64, dl, Ld->getChain(),
7994 Ld->getBasePtr(), Ld->getSrcValue(),
7995 Ld->getSrcValueOffset(), Ld->isVolatile(),
7996 Ld->getAlignment());
7997 SDValue NewChain = NewLd.getValue(1);
7998 if (TokenFactorIndex != -1) {
7999 Ops.push_back(NewChain);
8000 NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Ops[0],
8003 return DAG.getStore(NewChain, dl, NewLd, St->getBasePtr(),
8004 St->getSrcValue(), St->getSrcValueOffset(),
8005 St->isVolatile(), St->getAlignment());
8008 // Otherwise, lower to two 32-bit copies.
8009 SDValue LoAddr = Ld->getBasePtr();
8010 SDValue HiAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, LoAddr,
8011 DAG.getConstant(4, MVT::i32));
8013 SDValue LoLd = DAG.getLoad(MVT::i32, dl, Ld->getChain(), LoAddr,
8014 Ld->getSrcValue(), Ld->getSrcValueOffset(),
8015 Ld->isVolatile(), Ld->getAlignment());
8016 SDValue HiLd = DAG.getLoad(MVT::i32, dl, Ld->getChain(), HiAddr,
8017 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
8019 MinAlign(Ld->getAlignment(), 4));
8021 SDValue NewChain = LoLd.getValue(1);
8022 if (TokenFactorIndex != -1) {
8023 Ops.push_back(LoLd);
8024 Ops.push_back(HiLd);
8025 NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Ops[0],
8029 LoAddr = St->getBasePtr();
8030 HiAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, LoAddr,
8031 DAG.getConstant(4, MVT::i32));
8033 SDValue LoSt = DAG.getStore(NewChain, dl, LoLd, LoAddr,
8034 St->getSrcValue(), St->getSrcValueOffset(),
8035 St->isVolatile(), St->getAlignment());
8036 SDValue HiSt = DAG.getStore(NewChain, dl, HiLd, HiAddr,
8038 St->getSrcValueOffset() + 4,
8040 MinAlign(St->getAlignment(), 4));
8041 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoSt, HiSt);
8047 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
8048 /// X86ISD::FXOR nodes.
8049 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
8050 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
8051 // F[X]OR(0.0, x) -> x
8052 // F[X]OR(x, 0.0) -> x
8053 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8054 if (C->getValueAPF().isPosZero())
8055 return N->getOperand(1);
8056 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8057 if (C->getValueAPF().isPosZero())
8058 return N->getOperand(0);
8062 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
8063 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
8064 // FAND(0.0, x) -> 0.0
8065 // FAND(x, 0.0) -> 0.0
8066 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8067 if (C->getValueAPF().isPosZero())
8068 return N->getOperand(0);
8069 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8070 if (C->getValueAPF().isPosZero())
8071 return N->getOperand(1);
8075 static SDValue PerformBTCombine(SDNode *N,
8077 TargetLowering::DAGCombinerInfo &DCI) {
8078 // BT ignores high bits in the bit index operand.
8079 SDValue Op1 = N->getOperand(1);
8080 if (Op1.hasOneUse()) {
8081 unsigned BitWidth = Op1.getValueSizeInBits();
8082 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
8083 APInt KnownZero, KnownOne;
8084 TargetLowering::TargetLoweringOpt TLO(DAG);
8085 TargetLowering &TLI = DAG.getTargetLoweringInfo();
8086 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
8087 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
8088 DCI.CommitTargetLoweringOpt(TLO);
8093 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
8094 DAGCombinerInfo &DCI) const {
8095 SelectionDAG &DAG = DCI.DAG;
8096 switch (N->getOpcode()) {
8098 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
8099 case ISD::BUILD_VECTOR:
8100 return PerformBuildVectorCombine(N, DAG, DCI, Subtarget, *this);
8101 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
8104 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
8105 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
8107 case X86ISD::FOR: return PerformFORCombine(N, DAG);
8108 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
8109 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
8115 //===----------------------------------------------------------------------===//
8116 // X86 Inline Assembly Support
8117 //===----------------------------------------------------------------------===//
8119 /// getConstraintType - Given a constraint letter, return the type of
8120 /// constraint it is for this target.
8121 X86TargetLowering::ConstraintType
8122 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
8123 if (Constraint.size() == 1) {
8124 switch (Constraint[0]) {
8136 return C_RegisterClass;
8141 return TargetLowering::getConstraintType(Constraint);
8144 /// LowerXConstraint - try to replace an X constraint, which matches anything,
8145 /// with another that has more specific requirements based on the type of the
8146 /// corresponding operand.
8147 const char *X86TargetLowering::
8148 LowerXConstraint(MVT ConstraintVT) const {
8149 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
8150 // 'f' like normal targets.
8151 if (ConstraintVT.isFloatingPoint()) {
8152 if (Subtarget->hasSSE2())
8154 if (Subtarget->hasSSE1())
8158 return TargetLowering::LowerXConstraint(ConstraintVT);
8161 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8162 /// vector. If it is invalid, don't add anything to Ops.
8163 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8166 std::vector<SDValue>&Ops,
8167 SelectionDAG &DAG) const {
8168 SDValue Result(0, 0);
8170 switch (Constraint) {
8173 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8174 if (C->getZExtValue() <= 31) {
8175 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8181 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8182 if (C->getZExtValue() <= 63) {
8183 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8189 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8190 if (C->getZExtValue() <= 255) {
8191 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8197 // Literal immediates are always ok.
8198 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
8199 Result = DAG.getTargetConstant(CST->getZExtValue(), Op.getValueType());
8203 // If we are in non-pic codegen mode, we allow the address of a global (with
8204 // an optional displacement) to be used with 'i'.
8205 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
8208 // Match either (GA) or (GA+C)
8210 Offset = GA->getOffset();
8211 } else if (Op.getOpcode() == ISD::ADD) {
8212 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8213 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
8215 Offset = GA->getOffset()+C->getZExtValue();
8217 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8218 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
8220 Offset = GA->getOffset()+C->getZExtValue();
8228 Op = LowerGlobalAddress(GA->getGlobal(), Offset, DAG);
8230 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
8236 // Otherwise, not valid for this mode.
8241 if (Result.getNode()) {
8242 Ops.push_back(Result);
8245 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
8249 std::vector<unsigned> X86TargetLowering::
8250 getRegClassForInlineAsmConstraint(const std::string &Constraint,
8252 if (Constraint.size() == 1) {
8253 // FIXME: not handling fp-stack yet!
8254 switch (Constraint[0]) { // GCC X86 Constraint Letters
8255 default: break; // Unknown constraint letter
8256 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
8259 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
8260 else if (VT == MVT::i16)
8261 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
8262 else if (VT == MVT::i8)
8263 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
8264 else if (VT == MVT::i64)
8265 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
8270 return std::vector<unsigned>();
8273 std::pair<unsigned, const TargetRegisterClass*>
8274 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8276 // First, see if this is a constraint that directly corresponds to an LLVM
8278 if (Constraint.size() == 1) {
8279 // GCC Constraint Letters
8280 switch (Constraint[0]) {
8282 case 'r': // GENERAL_REGS
8283 case 'R': // LEGACY_REGS
8284 case 'l': // INDEX_REGS
8286 return std::make_pair(0U, X86::GR8RegisterClass);
8288 return std::make_pair(0U, X86::GR16RegisterClass);
8289 if (VT == MVT::i32 || !Subtarget->is64Bit())
8290 return std::make_pair(0U, X86::GR32RegisterClass);
8291 return std::make_pair(0U, X86::GR64RegisterClass);
8292 case 'f': // FP Stack registers.
8293 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
8294 // value to the correct fpstack register class.
8295 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
8296 return std::make_pair(0U, X86::RFP32RegisterClass);
8297 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
8298 return std::make_pair(0U, X86::RFP64RegisterClass);
8299 return std::make_pair(0U, X86::RFP80RegisterClass);
8300 case 'y': // MMX_REGS if MMX allowed.
8301 if (!Subtarget->hasMMX()) break;
8302 return std::make_pair(0U, X86::VR64RegisterClass);
8303 case 'Y': // SSE_REGS if SSE2 allowed
8304 if (!Subtarget->hasSSE2()) break;
8306 case 'x': // SSE_REGS if SSE1 allowed
8307 if (!Subtarget->hasSSE1()) break;
8309 switch (VT.getSimpleVT()) {
8311 // Scalar SSE types.
8314 return std::make_pair(0U, X86::FR32RegisterClass);
8317 return std::make_pair(0U, X86::FR64RegisterClass);
8325 return std::make_pair(0U, X86::VR128RegisterClass);
8331 // Use the default implementation in TargetLowering to convert the register
8332 // constraint into a member of a register class.
8333 std::pair<unsigned, const TargetRegisterClass*> Res;
8334 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8336 // Not found as a standard register?
8337 if (Res.second == 0) {
8338 // GCC calls "st(0)" just plain "st".
8339 if (StringsEqualNoCase("{st}", Constraint)) {
8340 Res.first = X86::ST0;
8341 Res.second = X86::RFP80RegisterClass;
8343 // 'A' means EAX + EDX.
8344 if (Constraint == "A") {
8345 Res.first = X86::EAX;
8346 Res.second = X86::GRADRegisterClass;
8351 // Otherwise, check to see if this is a register class of the wrong value
8352 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
8353 // turn into {ax},{dx}.
8354 if (Res.second->hasType(VT))
8355 return Res; // Correct type already, nothing to do.
8357 // All of the single-register GCC register classes map their values onto
8358 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
8359 // really want an 8-bit or 32-bit register, map to the appropriate register
8360 // class and return the appropriate register.
8361 if (Res.second == X86::GR16RegisterClass) {
8362 if (VT == MVT::i8) {
8363 unsigned DestReg = 0;
8364 switch (Res.first) {
8366 case X86::AX: DestReg = X86::AL; break;
8367 case X86::DX: DestReg = X86::DL; break;
8368 case X86::CX: DestReg = X86::CL; break;
8369 case X86::BX: DestReg = X86::BL; break;
8372 Res.first = DestReg;
8373 Res.second = Res.second = X86::GR8RegisterClass;
8375 } else if (VT == MVT::i32) {
8376 unsigned DestReg = 0;
8377 switch (Res.first) {
8379 case X86::AX: DestReg = X86::EAX; break;
8380 case X86::DX: DestReg = X86::EDX; break;
8381 case X86::CX: DestReg = X86::ECX; break;
8382 case X86::BX: DestReg = X86::EBX; break;
8383 case X86::SI: DestReg = X86::ESI; break;
8384 case X86::DI: DestReg = X86::EDI; break;
8385 case X86::BP: DestReg = X86::EBP; break;
8386 case X86::SP: DestReg = X86::ESP; break;
8389 Res.first = DestReg;
8390 Res.second = Res.second = X86::GR32RegisterClass;
8392 } else if (VT == MVT::i64) {
8393 unsigned DestReg = 0;
8394 switch (Res.first) {
8396 case X86::AX: DestReg = X86::RAX; break;
8397 case X86::DX: DestReg = X86::RDX; break;
8398 case X86::CX: DestReg = X86::RCX; break;
8399 case X86::BX: DestReg = X86::RBX; break;
8400 case X86::SI: DestReg = X86::RSI; break;
8401 case X86::DI: DestReg = X86::RDI; break;
8402 case X86::BP: DestReg = X86::RBP; break;
8403 case X86::SP: DestReg = X86::RSP; break;
8406 Res.first = DestReg;
8407 Res.second = Res.second = X86::GR64RegisterClass;
8410 } else if (Res.second == X86::FR32RegisterClass ||
8411 Res.second == X86::FR64RegisterClass ||
8412 Res.second == X86::VR128RegisterClass) {
8413 // Handle references to XMM physical registers that got mapped into the
8414 // wrong class. This can happen with constraints like {xmm0} where the
8415 // target independent register mapper will just pick the first match it can
8416 // find, ignoring the required type.
8418 Res.second = X86::FR32RegisterClass;
8419 else if (VT == MVT::f64)
8420 Res.second = X86::FR64RegisterClass;
8421 else if (X86::VR128RegisterClass->hasType(VT))
8422 Res.second = X86::VR128RegisterClass;
8428 //===----------------------------------------------------------------------===//
8429 // X86 Widen vector type
8430 //===----------------------------------------------------------------------===//
8432 /// getWidenVectorType: given a vector type, returns the type to widen
8433 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
8434 /// If there is no vector type that we want to widen to, returns MVT::Other
8435 /// When and where to widen is target dependent based on the cost of
8436 /// scalarizing vs using the wider vector type.
8438 MVT X86TargetLowering::getWidenVectorType(MVT VT) const {
8439 assert(VT.isVector());
8440 if (isTypeLegal(VT))
8443 // TODO: In computeRegisterProperty, we can compute the list of legal vector
8444 // type based on element type. This would speed up our search (though
8445 // it may not be worth it since the size of the list is relatively
8447 MVT EltVT = VT.getVectorElementType();
8448 unsigned NElts = VT.getVectorNumElements();
8450 // On X86, it make sense to widen any vector wider than 1
8454 for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
8455 nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
8456 MVT SVT = (MVT::SimpleValueType)nVT;
8458 if (isTypeLegal(SVT) &&
8459 SVT.getVectorElementType() == EltVT &&
8460 SVT.getVectorNumElements() > NElts)