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 (!UseSoftFloat && 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 (!UseSoftFloat && 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);
461 } else if (!UseSoftFloat) {
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 if (!UseSoftFloat && !NoImplicitFloat) {
497 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
498 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
499 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
502 APFloat TmpFlt(+0.0);
503 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
505 addLegalFPImmediate(TmpFlt); // FLD0
507 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
508 APFloat TmpFlt2(+1.0);
509 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
511 addLegalFPImmediate(TmpFlt2); // FLD1
512 TmpFlt2.changeSign();
513 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
517 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
518 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
522 // Always use a library call for pow.
523 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
524 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
525 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
527 setOperationAction(ISD::FLOG, MVT::f80, Expand);
528 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
529 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
530 setOperationAction(ISD::FEXP, MVT::f80, Expand);
531 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
533 // First set operation action for all vector types to either promote
534 // (for widening) or expand (for scalarization). Then we will selectively
535 // turn on ones that can be effectively codegen'd.
536 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
537 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
538 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
539 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
540 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
541 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
542 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
543 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
544 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
545 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
546 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
547 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
548 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
549 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
550 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
551 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
552 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
553 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
554 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
555 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
556 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
557 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
558 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
559 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
560 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
561 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
562 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
563 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
564 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
565 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
566 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
567 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
568 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
569 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
570 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
571 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
572 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
573 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
574 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
575 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
576 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
577 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
578 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
579 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
580 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
583 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
584 // with -msoft-float, disable use of MMX as well.
585 if (!UseSoftFloat && !NoImplicitFloat && !DisableMMX && Subtarget->hasMMX()) {
586 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
587 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
588 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
589 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
590 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
592 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
593 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
594 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
595 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
597 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
598 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
599 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
600 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
602 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
603 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
605 setOperationAction(ISD::AND, MVT::v8i8, Promote);
606 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
607 setOperationAction(ISD::AND, MVT::v4i16, Promote);
608 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
609 setOperationAction(ISD::AND, MVT::v2i32, Promote);
610 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
611 setOperationAction(ISD::AND, MVT::v1i64, Legal);
613 setOperationAction(ISD::OR, MVT::v8i8, Promote);
614 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
615 setOperationAction(ISD::OR, MVT::v4i16, Promote);
616 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
617 setOperationAction(ISD::OR, MVT::v2i32, Promote);
618 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
619 setOperationAction(ISD::OR, MVT::v1i64, Legal);
621 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
622 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
623 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
624 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
625 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
626 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
627 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
629 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
630 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
631 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
632 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
633 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
634 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
635 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
636 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
637 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
639 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
640 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
641 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
642 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
643 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
645 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
646 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
647 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
648 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
650 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
651 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
652 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
653 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
655 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
657 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
658 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Expand);
659 setOperationAction(ISD::SELECT, MVT::v8i8, Promote);
660 setOperationAction(ISD::SELECT, MVT::v4i16, Promote);
661 setOperationAction(ISD::SELECT, MVT::v2i32, Promote);
662 setOperationAction(ISD::SELECT, MVT::v1i64, Custom);
665 if (!UseSoftFloat && !NoImplicitFloat && Subtarget->hasSSE1()) {
666 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
668 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
669 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
670 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
671 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
672 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
673 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
674 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
675 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
676 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
677 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
678 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
679 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
682 if (!UseSoftFloat && !NoImplicitFloat && Subtarget->hasSSE2()) {
683 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
685 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
686 // registers cannot be used even for integer operations.
687 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
688 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
689 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
690 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
692 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
693 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
694 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
695 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
696 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
697 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
698 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
699 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
700 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
701 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
702 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
703 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
704 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
705 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
706 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
707 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
709 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
710 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
711 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
712 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
714 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
715 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
716 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
717 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
718 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
720 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
721 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
722 MVT VT = (MVT::SimpleValueType)i;
723 // Do not attempt to custom lower non-power-of-2 vectors
724 if (!isPowerOf2_32(VT.getVectorNumElements()))
726 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
727 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
728 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
731 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
732 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
733 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
734 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
735 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
736 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
738 if (Subtarget->is64Bit()) {
739 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
740 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
743 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
744 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
745 setOperationAction(ISD::AND, (MVT::SimpleValueType)VT, Promote);
746 AddPromotedToType (ISD::AND, (MVT::SimpleValueType)VT, MVT::v2i64);
747 setOperationAction(ISD::OR, (MVT::SimpleValueType)VT, Promote);
748 AddPromotedToType (ISD::OR, (MVT::SimpleValueType)VT, MVT::v2i64);
749 setOperationAction(ISD::XOR, (MVT::SimpleValueType)VT, Promote);
750 AddPromotedToType (ISD::XOR, (MVT::SimpleValueType)VT, MVT::v2i64);
751 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Promote);
752 AddPromotedToType (ISD::LOAD, (MVT::SimpleValueType)VT, MVT::v2i64);
753 setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
754 AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v2i64);
757 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
759 // Custom lower v2i64 and v2f64 selects.
760 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
761 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
762 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
763 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
767 if (Subtarget->hasSSE41()) {
768 // FIXME: Do we need to handle scalar-to-vector here?
769 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
771 // i8 and i16 vectors are custom , because the source register and source
772 // source memory operand types are not the same width. f32 vectors are
773 // custom since the immediate controlling the insert encodes additional
775 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
776 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
777 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
778 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
780 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
781 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
782 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
783 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
785 if (Subtarget->is64Bit()) {
786 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
787 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
791 if (Subtarget->hasSSE42()) {
792 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
795 // We want to custom lower some of our intrinsics.
796 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
798 // Add/Sub/Mul with overflow operations are custom lowered.
799 setOperationAction(ISD::SADDO, MVT::i32, Custom);
800 setOperationAction(ISD::SADDO, MVT::i64, Custom);
801 setOperationAction(ISD::UADDO, MVT::i32, Custom);
802 setOperationAction(ISD::UADDO, MVT::i64, Custom);
803 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
804 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
805 setOperationAction(ISD::USUBO, MVT::i32, Custom);
806 setOperationAction(ISD::USUBO, MVT::i64, Custom);
807 setOperationAction(ISD::SMULO, MVT::i32, Custom);
808 setOperationAction(ISD::SMULO, MVT::i64, Custom);
809 setOperationAction(ISD::UMULO, MVT::i32, Custom);
810 setOperationAction(ISD::UMULO, MVT::i64, Custom);
812 // We have target-specific dag combine patterns for the following nodes:
813 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
814 setTargetDAGCombine(ISD::BUILD_VECTOR);
815 setTargetDAGCombine(ISD::SELECT);
816 setTargetDAGCombine(ISD::SHL);
817 setTargetDAGCombine(ISD::SRA);
818 setTargetDAGCombine(ISD::SRL);
819 setTargetDAGCombine(ISD::STORE);
821 computeRegisterProperties();
823 // FIXME: These should be based on subtarget info. Plus, the values should
824 // be smaller when we are in optimizing for size mode.
825 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
826 maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
827 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
828 allowUnalignedMemoryAccesses = true; // x86 supports it!
829 setPrefLoopAlignment(16);
833 MVT X86TargetLowering::getSetCCResultType(MVT VT) const {
838 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
839 /// the desired ByVal argument alignment.
840 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
843 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
844 if (VTy->getBitWidth() == 128)
846 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
847 unsigned EltAlign = 0;
848 getMaxByValAlign(ATy->getElementType(), EltAlign);
849 if (EltAlign > MaxAlign)
851 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
852 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
853 unsigned EltAlign = 0;
854 getMaxByValAlign(STy->getElementType(i), EltAlign);
855 if (EltAlign > MaxAlign)
864 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
865 /// function arguments in the caller parameter area. For X86, aggregates
866 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
867 /// are at 4-byte boundaries.
868 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
869 if (Subtarget->is64Bit()) {
870 // Max of 8 and alignment of type.
871 unsigned TyAlign = TD->getABITypeAlignment(Ty);
878 if (Subtarget->hasSSE1())
879 getMaxByValAlign(Ty, Align);
883 /// getOptimalMemOpType - Returns the target specific optimal type for load
884 /// and store operations as a result of memset, memcpy, and memmove
885 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
888 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
889 bool isSrcConst, bool isSrcStr) const {
890 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
891 // linux. This is because the stack realignment code can't handle certain
892 // cases like PR2962. This should be removed when PR2962 is fixed.
893 if (!NoImplicitFloat && Subtarget->getStackAlignment() >= 16) {
894 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
896 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
899 if (Subtarget->is64Bit() && Size >= 8)
904 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
906 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
907 SelectionDAG &DAG) const {
908 if (usesGlobalOffsetTable())
909 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy());
910 if (!Subtarget->isPICStyleRIPRel())
911 // This doesn't have DebugLoc associated with it, but is not really the
912 // same as a Register.
913 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc::getUnknownLoc(),
918 //===----------------------------------------------------------------------===//
919 // Return Value Calling Convention Implementation
920 //===----------------------------------------------------------------------===//
922 #include "X86GenCallingConv.inc"
924 /// LowerRET - Lower an ISD::RET node.
925 SDValue X86TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
926 DebugLoc dl = Op.getDebugLoc();
927 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
929 SmallVector<CCValAssign, 16> RVLocs;
930 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
931 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
932 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
933 CCInfo.AnalyzeReturn(Op.getNode(), RetCC_X86);
935 // If this is the first return lowered for this function, add the regs to the
936 // liveout set for the function.
937 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
938 for (unsigned i = 0; i != RVLocs.size(); ++i)
939 if (RVLocs[i].isRegLoc())
940 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
942 SDValue Chain = Op.getOperand(0);
944 // Handle tail call return.
945 Chain = GetPossiblePreceedingTailCall(Chain, X86ISD::TAILCALL);
946 if (Chain.getOpcode() == X86ISD::TAILCALL) {
947 SDValue TailCall = Chain;
948 SDValue TargetAddress = TailCall.getOperand(1);
949 SDValue StackAdjustment = TailCall.getOperand(2);
950 assert(((TargetAddress.getOpcode() == ISD::Register &&
951 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::EAX ||
952 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
953 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
954 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
955 "Expecting an global address, external symbol, or register");
956 assert(StackAdjustment.getOpcode() == ISD::Constant &&
957 "Expecting a const value");
959 SmallVector<SDValue,8> Operands;
960 Operands.push_back(Chain.getOperand(0));
961 Operands.push_back(TargetAddress);
962 Operands.push_back(StackAdjustment);
963 // Copy registers used by the call. Last operand is a flag so it is not
965 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
966 Operands.push_back(Chain.getOperand(i));
968 return DAG.getNode(X86ISD::TC_RETURN, dl, MVT::Other, &Operands[0],
975 SmallVector<SDValue, 6> RetOps;
976 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
977 // Operand #1 = Bytes To Pop
978 RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
980 // Copy the result values into the output registers.
981 for (unsigned i = 0; i != RVLocs.size(); ++i) {
982 CCValAssign &VA = RVLocs[i];
983 assert(VA.isRegLoc() && "Can only return in registers!");
984 SDValue ValToCopy = Op.getOperand(i*2+1);
986 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
987 // the RET instruction and handled by the FP Stackifier.
988 if (VA.getLocReg() == X86::ST0 ||
989 VA.getLocReg() == X86::ST1) {
990 // If this is a copy from an xmm register to ST(0), use an FPExtend to
991 // change the value to the FP stack register class.
992 if (isScalarFPTypeInSSEReg(VA.getValVT()))
993 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
994 RetOps.push_back(ValToCopy);
995 // Don't emit a copytoreg.
999 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1000 // which is returned in RAX / RDX.
1001 if (Subtarget->is64Bit()) {
1002 MVT ValVT = ValToCopy.getValueType();
1003 if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1004 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1005 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1006 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1010 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1011 Flag = Chain.getValue(1);
1014 // The x86-64 ABI for returning structs by value requires that we copy
1015 // the sret argument into %rax for the return. We saved the argument into
1016 // a virtual register in the entry block, so now we copy the value out
1018 if (Subtarget->is64Bit() &&
1019 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1020 MachineFunction &MF = DAG.getMachineFunction();
1021 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1022 unsigned Reg = FuncInfo->getSRetReturnReg();
1024 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1025 FuncInfo->setSRetReturnReg(Reg);
1027 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1029 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1030 Flag = Chain.getValue(1);
1033 RetOps[0] = Chain; // Update chain.
1035 // Add the flag if we have it.
1037 RetOps.push_back(Flag);
1039 return DAG.getNode(X86ISD::RET_FLAG, dl,
1040 MVT::Other, &RetOps[0], RetOps.size());
1044 /// LowerCallResult - Lower the result values of an ISD::CALL into the
1045 /// appropriate copies out of appropriate physical registers. This assumes that
1046 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
1047 /// being lowered. The returns a SDNode with the same number of values as the
1049 SDNode *X86TargetLowering::
1050 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall,
1051 unsigned CallingConv, SelectionDAG &DAG) {
1053 DebugLoc dl = TheCall->getDebugLoc();
1054 // Assign locations to each value returned by this call.
1055 SmallVector<CCValAssign, 16> RVLocs;
1056 bool isVarArg = TheCall->isVarArg();
1057 bool Is64Bit = Subtarget->is64Bit();
1058 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
1059 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
1061 SmallVector<SDValue, 8> ResultVals;
1063 // Copy all of the result registers out of their specified physreg.
1064 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1065 CCValAssign &VA = RVLocs[i];
1066 MVT CopyVT = VA.getValVT();
1068 // If this is x86-64, and we disabled SSE, we can't return FP values
1069 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1070 ((Is64Bit || TheCall->isInreg()) && !Subtarget->hasSSE1())) {
1071 cerr << "SSE register return with SSE disabled\n";
1075 // If this is a call to a function that returns an fp value on the floating
1076 // point stack, but where we prefer to use the value in xmm registers, copy
1077 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1078 if ((VA.getLocReg() == X86::ST0 ||
1079 VA.getLocReg() == X86::ST1) &&
1080 isScalarFPTypeInSSEReg(VA.getValVT())) {
1085 if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1086 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1087 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1088 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1089 MVT::v2i64, InFlag).getValue(1);
1090 Val = Chain.getValue(0);
1091 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1092 Val, DAG.getConstant(0, MVT::i64));
1094 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1095 MVT::i64, InFlag).getValue(1);
1096 Val = Chain.getValue(0);
1098 Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1100 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1101 CopyVT, InFlag).getValue(1);
1102 Val = Chain.getValue(0);
1104 InFlag = Chain.getValue(2);
1106 if (CopyVT != VA.getValVT()) {
1107 // Round the F80 the right size, which also moves to the appropriate xmm
1109 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1110 // This truncation won't change the value.
1111 DAG.getIntPtrConstant(1));
1114 ResultVals.push_back(Val);
1117 // Merge everything together with a MERGE_VALUES node.
1118 ResultVals.push_back(Chain);
1119 return DAG.getNode(ISD::MERGE_VALUES, dl, TheCall->getVTList(),
1120 &ResultVals[0], ResultVals.size()).getNode();
1124 //===----------------------------------------------------------------------===//
1125 // C & StdCall & Fast Calling Convention implementation
1126 //===----------------------------------------------------------------------===//
1127 // StdCall calling convention seems to be standard for many Windows' API
1128 // routines and around. It differs from C calling convention just a little:
1129 // callee should clean up the stack, not caller. Symbols should be also
1130 // decorated in some fancy way :) It doesn't support any vector arguments.
1131 // For info on fast calling convention see Fast Calling Convention (tail call)
1132 // implementation LowerX86_32FastCCCallTo.
1134 /// AddLiveIn - This helper function adds the specified physical register to the
1135 /// MachineFunction as a live in value. It also creates a corresponding virtual
1136 /// register for it.
1137 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
1138 const TargetRegisterClass *RC) {
1139 assert(RC->contains(PReg) && "Not the correct regclass!");
1140 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
1141 MF.getRegInfo().addLiveIn(PReg, VReg);
1145 /// CallIsStructReturn - Determines whether a CALL node uses struct return
1147 static bool CallIsStructReturn(CallSDNode *TheCall) {
1148 unsigned NumOps = TheCall->getNumArgs();
1152 return TheCall->getArgFlags(0).isSRet();
1155 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
1156 /// return semantics.
1157 static bool ArgsAreStructReturn(SDValue Op) {
1158 unsigned NumArgs = Op.getNode()->getNumValues() - 1;
1162 return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
1165 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
1166 /// the callee to pop its own arguments. Callee pop is necessary to support tail
1168 bool X86TargetLowering::IsCalleePop(bool IsVarArg, unsigned CallingConv) {
1172 switch (CallingConv) {
1175 case CallingConv::X86_StdCall:
1176 return !Subtarget->is64Bit();
1177 case CallingConv::X86_FastCall:
1178 return !Subtarget->is64Bit();
1179 case CallingConv::Fast:
1180 return PerformTailCallOpt;
1184 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1185 /// given CallingConvention value.
1186 CCAssignFn *X86TargetLowering::CCAssignFnForNode(unsigned CC) const {
1187 if (Subtarget->is64Bit()) {
1188 if (Subtarget->isTargetWin64())
1189 return CC_X86_Win64_C;
1190 else if (CC == CallingConv::Fast && PerformTailCallOpt)
1191 return CC_X86_64_TailCall;
1196 if (CC == CallingConv::X86_FastCall)
1197 return CC_X86_32_FastCall;
1198 else if (CC == CallingConv::Fast)
1199 return CC_X86_32_FastCC;
1204 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1205 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1207 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDValue Op) {
1208 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1209 if (CC == CallingConv::X86_FastCall)
1211 else if (CC == CallingConv::X86_StdCall)
1217 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1218 /// in a register before calling.
1219 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1220 return !IsTailCall && !Is64Bit &&
1221 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1222 Subtarget->isPICStyleGOT();
1225 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1226 /// address to be loaded in a register.
1228 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1229 return !Is64Bit && IsTailCall &&
1230 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1231 Subtarget->isPICStyleGOT();
1234 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1235 /// by "Src" to address "Dst" with size and alignment information specified by
1236 /// the specific parameter attribute. The copy will be passed as a byval
1237 /// function parameter.
1239 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1240 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1242 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1243 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1244 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1247 SDValue X86TargetLowering::LowerMemArgument(SDValue Op, SelectionDAG &DAG,
1248 const CCValAssign &VA,
1249 MachineFrameInfo *MFI,
1251 SDValue Root, unsigned i) {
1252 // Create the nodes corresponding to a load from this parameter slot.
1253 ISD::ArgFlagsTy Flags =
1254 cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1255 bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1256 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1258 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1259 // changed with more analysis.
1260 // In case of tail call optimization mark all arguments mutable. Since they
1261 // could be overwritten by lowering of arguments in case of a tail call.
1262 int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1263 VA.getLocMemOffset(), isImmutable);
1264 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1265 if (Flags.isByVal())
1267 return DAG.getLoad(VA.getValVT(), Op.getDebugLoc(), Root, FIN,
1268 PseudoSourceValue::getFixedStack(FI), 0);
1272 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) {
1273 MachineFunction &MF = DAG.getMachineFunction();
1274 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1275 DebugLoc dl = Op.getDebugLoc();
1277 const Function* Fn = MF.getFunction();
1278 if (Fn->hasExternalLinkage() &&
1279 Subtarget->isTargetCygMing() &&
1280 Fn->getName() == "main")
1281 FuncInfo->setForceFramePointer(true);
1283 // Decorate the function name.
1284 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1286 MachineFrameInfo *MFI = MF.getFrameInfo();
1287 SDValue Root = Op.getOperand(0);
1288 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
1289 unsigned CC = MF.getFunction()->getCallingConv();
1290 bool Is64Bit = Subtarget->is64Bit();
1291 bool IsWin64 = Subtarget->isTargetWin64();
1293 assert(!(isVarArg && CC == CallingConv::Fast) &&
1294 "Var args not supported with calling convention fastcc");
1296 // Assign locations to all of the incoming arguments.
1297 SmallVector<CCValAssign, 16> ArgLocs;
1298 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1299 CCInfo.AnalyzeFormalArguments(Op.getNode(), CCAssignFnForNode(CC));
1301 SmallVector<SDValue, 8> ArgValues;
1302 unsigned LastVal = ~0U;
1303 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1304 CCValAssign &VA = ArgLocs[i];
1305 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1307 assert(VA.getValNo() != LastVal &&
1308 "Don't support value assigned to multiple locs yet");
1309 LastVal = VA.getValNo();
1311 if (VA.isRegLoc()) {
1312 MVT RegVT = VA.getLocVT();
1313 TargetRegisterClass *RC = NULL;
1314 if (RegVT == MVT::i32)
1315 RC = X86::GR32RegisterClass;
1316 else if (Is64Bit && RegVT == MVT::i64)
1317 RC = X86::GR64RegisterClass;
1318 else if (RegVT == MVT::f32)
1319 RC = X86::FR32RegisterClass;
1320 else if (RegVT == MVT::f64)
1321 RC = X86::FR64RegisterClass;
1322 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1323 RC = X86::VR128RegisterClass;
1324 else if (RegVT.isVector()) {
1325 assert(RegVT.getSizeInBits() == 64);
1327 RC = X86::VR64RegisterClass; // MMX values are passed in MMXs.
1329 // Darwin calling convention passes MMX values in either GPRs or
1330 // XMMs in x86-64. Other targets pass them in memory.
1331 if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1332 RC = X86::VR128RegisterClass; // MMX values are passed in XMMs.
1335 RC = X86::GR64RegisterClass; // v1i64 values are passed in GPRs.
1340 assert(0 && "Unknown argument type!");
1343 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1344 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, RegVT);
1346 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1347 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1349 if (VA.getLocInfo() == CCValAssign::SExt)
1350 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1351 DAG.getValueType(VA.getValVT()));
1352 else if (VA.getLocInfo() == CCValAssign::ZExt)
1353 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1354 DAG.getValueType(VA.getValVT()));
1356 if (VA.getLocInfo() != CCValAssign::Full)
1357 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1359 // Handle MMX values passed in GPRs.
1360 if (Is64Bit && RegVT != VA.getLocVT()) {
1361 if (RegVT.getSizeInBits() == 64 && RC == X86::GR64RegisterClass)
1362 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1363 else if (RC == X86::VR128RegisterClass) {
1364 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1365 ArgValue, DAG.getConstant(0, MVT::i64));
1366 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1370 ArgValues.push_back(ArgValue);
1372 assert(VA.isMemLoc());
1373 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1377 // The x86-64 ABI for returning structs by value requires that we copy
1378 // the sret argument into %rax for the return. Save the argument into
1379 // a virtual register so that we can access it from the return points.
1380 if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1381 MachineFunction &MF = DAG.getMachineFunction();
1382 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1383 unsigned Reg = FuncInfo->getSRetReturnReg();
1385 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1386 FuncInfo->setSRetReturnReg(Reg);
1388 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, ArgValues[0]);
1389 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Root);
1392 unsigned StackSize = CCInfo.getNextStackOffset();
1393 // align stack specially for tail calls
1394 if (PerformTailCallOpt && CC == CallingConv::Fast)
1395 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1397 // If the function takes variable number of arguments, make a frame index for
1398 // the start of the first vararg value... for expansion of llvm.va_start.
1400 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1401 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1404 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1406 // FIXME: We should really autogenerate these arrays
1407 static const unsigned GPR64ArgRegsWin64[] = {
1408 X86::RCX, X86::RDX, X86::R8, X86::R9
1410 static const unsigned XMMArgRegsWin64[] = {
1411 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1413 static const unsigned GPR64ArgRegs64Bit[] = {
1414 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1416 static const unsigned XMMArgRegs64Bit[] = {
1417 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1418 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1420 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1423 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1424 GPR64ArgRegs = GPR64ArgRegsWin64;
1425 XMMArgRegs = XMMArgRegsWin64;
1427 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1428 GPR64ArgRegs = GPR64ArgRegs64Bit;
1429 XMMArgRegs = XMMArgRegs64Bit;
1431 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1433 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1436 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1437 "SSE register cannot be used when SSE is disabled!");
1438 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloat) &&
1439 "SSE register cannot be used when SSE is disabled!");
1440 if (UseSoftFloat || NoImplicitFloat || !Subtarget->hasSSE1())
1441 // Kernel mode asks for SSE to be disabled, so don't push them
1443 TotalNumXMMRegs = 0;
1445 // For X86-64, if there are vararg parameters that are passed via
1446 // registers, then we must store them to their spots on the stack so they
1447 // may be loaded by deferencing the result of va_next.
1448 VarArgsGPOffset = NumIntRegs * 8;
1449 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1450 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1451 TotalNumXMMRegs * 16, 16);
1453 // Store the integer parameter registers.
1454 SmallVector<SDValue, 8> MemOps;
1455 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1456 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1457 DAG.getIntPtrConstant(VarArgsGPOffset));
1458 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1459 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1460 X86::GR64RegisterClass);
1461 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::i64);
1463 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1464 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1465 MemOps.push_back(Store);
1466 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1467 DAG.getIntPtrConstant(8));
1470 // Now store the XMM (fp + vector) parameter registers.
1471 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1472 DAG.getIntPtrConstant(VarArgsFPOffset));
1473 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1474 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1475 X86::VR128RegisterClass);
1476 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::v4f32);
1478 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1479 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1480 MemOps.push_back(Store);
1481 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1482 DAG.getIntPtrConstant(16));
1484 if (!MemOps.empty())
1485 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1486 &MemOps[0], MemOps.size());
1490 ArgValues.push_back(Root);
1492 // Some CCs need callee pop.
1493 if (IsCalleePop(isVarArg, CC)) {
1494 BytesToPopOnReturn = StackSize; // Callee pops everything.
1495 BytesCallerReserves = 0;
1497 BytesToPopOnReturn = 0; // Callee pops nothing.
1498 // If this is an sret function, the return should pop the hidden pointer.
1499 if (!Is64Bit && CC != CallingConv::Fast && ArgsAreStructReturn(Op))
1500 BytesToPopOnReturn = 4;
1501 BytesCallerReserves = StackSize;
1505 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1506 if (CC == CallingConv::X86_FastCall)
1507 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1510 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1512 // Return the new list of results.
1513 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(),
1514 &ArgValues[0], ArgValues.size()).getValue(Op.getResNo());
1518 X86TargetLowering::LowerMemOpCallTo(CallSDNode *TheCall, SelectionDAG &DAG,
1519 const SDValue &StackPtr,
1520 const CCValAssign &VA,
1522 SDValue Arg, ISD::ArgFlagsTy Flags) {
1523 DebugLoc dl = TheCall->getDebugLoc();
1524 unsigned LocMemOffset = VA.getLocMemOffset();
1525 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1526 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1527 if (Flags.isByVal()) {
1528 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1530 return DAG.getStore(Chain, dl, Arg, PtrOff,
1531 PseudoSourceValue::getStack(), LocMemOffset);
1534 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1535 /// optimization is performed and it is required.
1537 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1538 SDValue &OutRetAddr,
1544 if (!IsTailCall || FPDiff==0) return Chain;
1546 // Adjust the Return address stack slot.
1547 MVT VT = getPointerTy();
1548 OutRetAddr = getReturnAddressFrameIndex(DAG);
1550 // Load the "old" Return address.
1551 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0);
1552 return SDValue(OutRetAddr.getNode(), 1);
1555 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1556 /// optimization is performed and it is required (FPDiff!=0).
1558 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1559 SDValue Chain, SDValue RetAddrFrIdx,
1560 bool Is64Bit, int FPDiff, DebugLoc dl) {
1561 // Store the return address to the appropriate stack slot.
1562 if (!FPDiff) return Chain;
1563 // Calculate the new stack slot for the return address.
1564 int SlotSize = Is64Bit ? 8 : 4;
1565 int NewReturnAddrFI =
1566 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1567 MVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1568 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1569 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1570 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1574 SDValue X86TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1575 MachineFunction &MF = DAG.getMachineFunction();
1576 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
1577 SDValue Chain = TheCall->getChain();
1578 unsigned CC = TheCall->getCallingConv();
1579 bool isVarArg = TheCall->isVarArg();
1580 bool IsTailCall = TheCall->isTailCall() &&
1581 CC == CallingConv::Fast && PerformTailCallOpt;
1582 SDValue Callee = TheCall->getCallee();
1583 bool Is64Bit = Subtarget->is64Bit();
1584 bool IsStructRet = CallIsStructReturn(TheCall);
1585 DebugLoc dl = TheCall->getDebugLoc();
1587 assert(!(isVarArg && CC == CallingConv::Fast) &&
1588 "Var args not supported with calling convention fastcc");
1590 // Analyze operands of the call, assigning locations to each operand.
1591 SmallVector<CCValAssign, 16> ArgLocs;
1592 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1593 CCInfo.AnalyzeCallOperands(TheCall, CCAssignFnForNode(CC));
1595 // Get a count of how many bytes are to be pushed on the stack.
1596 unsigned NumBytes = CCInfo.getNextStackOffset();
1597 if (PerformTailCallOpt && CC == CallingConv::Fast)
1598 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1602 // Lower arguments at fp - stackoffset + fpdiff.
1603 unsigned NumBytesCallerPushed =
1604 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1605 FPDiff = NumBytesCallerPushed - NumBytes;
1607 // Set the delta of movement of the returnaddr stackslot.
1608 // But only set if delta is greater than previous delta.
1609 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1610 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1613 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1615 SDValue RetAddrFrIdx;
1616 // Load return adress for tail calls.
1617 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1620 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1621 SmallVector<SDValue, 8> MemOpChains;
1624 // Walk the register/memloc assignments, inserting copies/loads. In the case
1625 // of tail call optimization arguments are handle later.
1626 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1627 CCValAssign &VA = ArgLocs[i];
1628 SDValue Arg = TheCall->getArg(i);
1629 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1630 bool isByVal = Flags.isByVal();
1632 // Promote the value if needed.
1633 switch (VA.getLocInfo()) {
1634 default: assert(0 && "Unknown loc info!");
1635 case CCValAssign::Full: break;
1636 case CCValAssign::SExt:
1637 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1639 case CCValAssign::ZExt:
1640 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1642 case CCValAssign::AExt:
1643 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1647 if (VA.isRegLoc()) {
1649 MVT RegVT = VA.getLocVT();
1650 if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1651 switch (VA.getLocReg()) {
1654 case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1656 // Special case: passing MMX values in GPR registers.
1657 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1660 case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1661 case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1662 // Special case: passing MMX values in XMM registers.
1663 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1664 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1665 Arg = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v2i64,
1666 DAG.getUNDEF(MVT::v2i64), Arg,
1667 getMOVLMask(2, DAG, dl));
1672 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1674 if (!IsTailCall || (IsTailCall && isByVal)) {
1675 assert(VA.isMemLoc());
1676 if (StackPtr.getNode() == 0)
1677 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1679 MemOpChains.push_back(LowerMemOpCallTo(TheCall, DAG, StackPtr, VA,
1680 Chain, Arg, Flags));
1685 if (!MemOpChains.empty())
1686 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1687 &MemOpChains[0], MemOpChains.size());
1689 // Build a sequence of copy-to-reg nodes chained together with token chain
1690 // and flag operands which copy the outgoing args into registers.
1692 // Tail call byval lowering might overwrite argument registers so in case of
1693 // tail call optimization the copies to registers are lowered later.
1695 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1696 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1697 RegsToPass[i].second, InFlag);
1698 InFlag = Chain.getValue(1);
1701 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1703 if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1704 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1705 DAG.getNode(X86ISD::GlobalBaseReg,
1706 DebugLoc::getUnknownLoc(),
1709 InFlag = Chain.getValue(1);
1711 // If we are tail calling and generating PIC/GOT style code load the address
1712 // of the callee into ecx. The value in ecx is used as target of the tail
1713 // jump. This is done to circumvent the ebx/callee-saved problem for tail
1714 // calls on PIC/GOT architectures. Normally we would just put the address of
1715 // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1716 // restored (since ebx is callee saved) before jumping to the target@PLT.
1717 if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1718 // Note: The actual moving to ecx is done further down.
1719 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1720 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1721 !G->getGlobal()->hasProtectedVisibility())
1722 Callee = LowerGlobalAddress(Callee, DAG);
1723 else if (isa<ExternalSymbolSDNode>(Callee))
1724 Callee = LowerExternalSymbol(Callee,DAG);
1727 if (Is64Bit && isVarArg) {
1728 // From AMD64 ABI document:
1729 // For calls that may call functions that use varargs or stdargs
1730 // (prototype-less calls or calls to functions containing ellipsis (...) in
1731 // the declaration) %al is used as hidden argument to specify the number
1732 // of SSE registers used. The contents of %al do not need to match exactly
1733 // the number of registers, but must be an ubound on the number of SSE
1734 // registers used and is in the range 0 - 8 inclusive.
1736 // FIXME: Verify this on Win64
1737 // Count the number of XMM registers allocated.
1738 static const unsigned XMMArgRegs[] = {
1739 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1740 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1742 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1743 assert((Subtarget->hasSSE1() || !NumXMMRegs)
1744 && "SSE registers cannot be used when SSE is disabled");
1746 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1747 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1748 InFlag = Chain.getValue(1);
1752 // For tail calls lower the arguments to the 'real' stack slot.
1754 SmallVector<SDValue, 8> MemOpChains2;
1757 // Do not flag preceeding copytoreg stuff together with the following stuff.
1759 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1760 CCValAssign &VA = ArgLocs[i];
1761 if (!VA.isRegLoc()) {
1762 assert(VA.isMemLoc());
1763 SDValue Arg = TheCall->getArg(i);
1764 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1765 // Create frame index.
1766 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1767 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1768 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1769 FIN = DAG.getFrameIndex(FI, getPointerTy());
1771 if (Flags.isByVal()) {
1772 // Copy relative to framepointer.
1773 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1774 if (StackPtr.getNode() == 0)
1775 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
1777 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
1779 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1782 // Store relative to framepointer.
1783 MemOpChains2.push_back(
1784 DAG.getStore(Chain, dl, Arg, FIN,
1785 PseudoSourceValue::getFixedStack(FI), 0));
1790 if (!MemOpChains2.empty())
1791 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1792 &MemOpChains2[0], MemOpChains2.size());
1794 // Copy arguments to their registers.
1795 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1796 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1797 RegsToPass[i].second, InFlag);
1798 InFlag = Chain.getValue(1);
1802 // Store the return address to the appropriate stack slot.
1803 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1807 // If the callee is a GlobalAddress node (quite common, every direct call is)
1808 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1809 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1810 // We should use extra load for direct calls to dllimported functions in
1812 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1813 getTargetMachine(), true))
1814 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy(),
1816 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1817 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1818 } else if (IsTailCall) {
1819 unsigned Opc = Is64Bit ? X86::R9 : X86::EAX;
1821 Chain = DAG.getCopyToReg(Chain, dl,
1822 DAG.getRegister(Opc, getPointerTy()),
1824 Callee = DAG.getRegister(Opc, getPointerTy());
1825 // Add register as live out.
1826 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1829 // Returns a chain & a flag for retval copy to use.
1830 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1831 SmallVector<SDValue, 8> Ops;
1834 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1835 DAG.getIntPtrConstant(0, true), InFlag);
1836 InFlag = Chain.getValue(1);
1838 // Returns a chain & a flag for retval copy to use.
1839 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1843 Ops.push_back(Chain);
1844 Ops.push_back(Callee);
1847 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1849 // Add argument registers to the end of the list so that they are known live
1851 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1852 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1853 RegsToPass[i].second.getValueType()));
1855 // Add an implicit use GOT pointer in EBX.
1856 if (!IsTailCall && !Is64Bit &&
1857 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1858 Subtarget->isPICStyleGOT())
1859 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1861 // Add an implicit use of AL for x86 vararg functions.
1862 if (Is64Bit && isVarArg)
1863 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1865 if (InFlag.getNode())
1866 Ops.push_back(InFlag);
1869 assert(InFlag.getNode() &&
1870 "Flag must be set. Depend on flag being set in LowerRET");
1871 Chain = DAG.getNode(X86ISD::TAILCALL, dl,
1872 TheCall->getVTList(), &Ops[0], Ops.size());
1874 return SDValue(Chain.getNode(), Op.getResNo());
1877 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
1878 InFlag = Chain.getValue(1);
1880 // Create the CALLSEQ_END node.
1881 unsigned NumBytesForCalleeToPush;
1882 if (IsCalleePop(isVarArg, CC))
1883 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1884 else if (!Is64Bit && CC != CallingConv::Fast && IsStructRet)
1885 // If this is is a call to a struct-return function, the callee
1886 // pops the hidden struct pointer, so we have to push it back.
1887 // This is common for Darwin/X86, Linux & Mingw32 targets.
1888 NumBytesForCalleeToPush = 4;
1890 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1892 // Returns a flag for retval copy to use.
1893 Chain = DAG.getCALLSEQ_END(Chain,
1894 DAG.getIntPtrConstant(NumBytes, true),
1895 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
1898 InFlag = Chain.getValue(1);
1900 // Handle result values, copying them out of physregs into vregs that we
1902 return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
1907 //===----------------------------------------------------------------------===//
1908 // Fast Calling Convention (tail call) implementation
1909 //===----------------------------------------------------------------------===//
1911 // Like std call, callee cleans arguments, convention except that ECX is
1912 // reserved for storing the tail called function address. Only 2 registers are
1913 // free for argument passing (inreg). Tail call optimization is performed
1915 // * tailcallopt is enabled
1916 // * caller/callee are fastcc
1917 // On X86_64 architecture with GOT-style position independent code only local
1918 // (within module) calls are supported at the moment.
1919 // To keep the stack aligned according to platform abi the function
1920 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1921 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1922 // If a tail called function callee has more arguments than the caller the
1923 // caller needs to make sure that there is room to move the RETADDR to. This is
1924 // achieved by reserving an area the size of the argument delta right after the
1925 // original REtADDR, but before the saved framepointer or the spilled registers
1926 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1938 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1939 /// for a 16 byte align requirement.
1940 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1941 SelectionDAG& DAG) {
1942 MachineFunction &MF = DAG.getMachineFunction();
1943 const TargetMachine &TM = MF.getTarget();
1944 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1945 unsigned StackAlignment = TFI.getStackAlignment();
1946 uint64_t AlignMask = StackAlignment - 1;
1947 int64_t Offset = StackSize;
1948 uint64_t SlotSize = TD->getPointerSize();
1949 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1950 // Number smaller than 12 so just add the difference.
1951 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1953 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1954 Offset = ((~AlignMask) & Offset) + StackAlignment +
1955 (StackAlignment-SlotSize);
1960 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1961 /// following the call is a return. A function is eligible if caller/callee
1962 /// calling conventions match, currently only fastcc supports tail calls, and
1963 /// the function CALL is immediatly followed by a RET.
1964 bool X86TargetLowering::IsEligibleForTailCallOptimization(CallSDNode *TheCall,
1966 SelectionDAG& DAG) const {
1967 if (!PerformTailCallOpt)
1970 if (CheckTailCallReturnConstraints(TheCall, Ret)) {
1971 MachineFunction &MF = DAG.getMachineFunction();
1972 unsigned CallerCC = MF.getFunction()->getCallingConv();
1973 unsigned CalleeCC= TheCall->getCallingConv();
1974 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1975 SDValue Callee = TheCall->getCallee();
1976 // On x86/32Bit PIC/GOT tail calls are supported.
1977 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1978 !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1981 // Can only do local tail calls (in same module, hidden or protected) on
1982 // x86_64 PIC/GOT at the moment.
1983 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1984 return G->getGlobal()->hasHiddenVisibility()
1985 || G->getGlobal()->hasProtectedVisibility();
1993 X86TargetLowering::createFastISel(MachineFunction &mf,
1994 MachineModuleInfo *mmo,
1996 DenseMap<const Value *, unsigned> &vm,
1997 DenseMap<const BasicBlock *,
1998 MachineBasicBlock *> &bm,
1999 DenseMap<const AllocaInst *, int> &am
2001 , SmallSet<Instruction*, 8> &cil
2004 return X86::createFastISel(mf, mmo, dw, vm, bm, am
2012 //===----------------------------------------------------------------------===//
2013 // Other Lowering Hooks
2014 //===----------------------------------------------------------------------===//
2017 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2018 MachineFunction &MF = DAG.getMachineFunction();
2019 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2020 int ReturnAddrIndex = FuncInfo->getRAIndex();
2022 if (ReturnAddrIndex == 0) {
2023 // Set up a frame object for the return address.
2024 uint64_t SlotSize = TD->getPointerSize();
2025 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize);
2026 FuncInfo->setRAIndex(ReturnAddrIndex);
2029 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2033 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2034 /// specific condition code, returning the condition code and the LHS/RHS of the
2035 /// comparison to make.
2036 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2037 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2039 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2040 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2041 // X > -1 -> X == 0, jump !sign.
2042 RHS = DAG.getConstant(0, RHS.getValueType());
2043 return X86::COND_NS;
2044 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2045 // X < 0 -> X == 0, jump on sign.
2047 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2049 RHS = DAG.getConstant(0, RHS.getValueType());
2050 return X86::COND_LE;
2054 switch (SetCCOpcode) {
2055 default: assert(0 && "Invalid integer condition!");
2056 case ISD::SETEQ: return X86::COND_E;
2057 case ISD::SETGT: return X86::COND_G;
2058 case ISD::SETGE: return X86::COND_GE;
2059 case ISD::SETLT: return X86::COND_L;
2060 case ISD::SETLE: return X86::COND_LE;
2061 case ISD::SETNE: return X86::COND_NE;
2062 case ISD::SETULT: return X86::COND_B;
2063 case ISD::SETUGT: return X86::COND_A;
2064 case ISD::SETULE: return X86::COND_BE;
2065 case ISD::SETUGE: return X86::COND_AE;
2069 // First determine if it is required or is profitable to flip the operands.
2071 // If LHS is a foldable load, but RHS is not, flip the condition.
2072 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2073 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2074 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2075 std::swap(LHS, RHS);
2078 switch (SetCCOpcode) {
2084 std::swap(LHS, RHS);
2088 // On a floating point condition, the flags are set as follows:
2090 // 0 | 0 | 0 | X > Y
2091 // 0 | 0 | 1 | X < Y
2092 // 1 | 0 | 0 | X == Y
2093 // 1 | 1 | 1 | unordered
2094 switch (SetCCOpcode) {
2095 default: assert(0 && "Condcode should be pre-legalized away");
2097 case ISD::SETEQ: return X86::COND_E;
2098 case ISD::SETOLT: // flipped
2100 case ISD::SETGT: return X86::COND_A;
2101 case ISD::SETOLE: // flipped
2103 case ISD::SETGE: return X86::COND_AE;
2104 case ISD::SETUGT: // flipped
2106 case ISD::SETLT: return X86::COND_B;
2107 case ISD::SETUGE: // flipped
2109 case ISD::SETLE: return X86::COND_BE;
2111 case ISD::SETNE: return X86::COND_NE;
2112 case ISD::SETUO: return X86::COND_P;
2113 case ISD::SETO: return X86::COND_NP;
2117 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2118 /// code. Current x86 isa includes the following FP cmov instructions:
2119 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2120 static bool hasFPCMov(unsigned X86CC) {
2136 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
2137 /// true if Op is undef or if its value falls within the specified range (L, H].
2138 static bool isUndefOrInRange(SDValue Op, unsigned Low, unsigned Hi) {
2139 if (Op.getOpcode() == ISD::UNDEF)
2142 unsigned Val = cast<ConstantSDNode>(Op)->getZExtValue();
2143 return (Val >= Low && Val < Hi);
2146 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
2147 /// true if Op is undef or if its value equal to the specified value.
2148 static bool isUndefOrEqual(SDValue Op, unsigned Val) {
2149 if (Op.getOpcode() == ISD::UNDEF)
2151 return cast<ConstantSDNode>(Op)->getZExtValue() == Val;
2154 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2155 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
2156 bool X86::isPSHUFDMask(SDNode *N) {
2157 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2159 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
2162 // Check if the value doesn't reference the second vector.
2163 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2164 SDValue Arg = N->getOperand(i);
2165 if (Arg.getOpcode() == ISD::UNDEF) continue;
2166 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2167 if (cast<ConstantSDNode>(Arg)->getZExtValue() >= e)
2174 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2175 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2176 bool X86::isPSHUFHWMask(SDNode *N) {
2177 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2179 if (N->getNumOperands() != 8)
2182 // Lower quadword copied in order.
2183 for (unsigned i = 0; i != 4; ++i) {
2184 SDValue Arg = N->getOperand(i);
2185 if (Arg.getOpcode() == ISD::UNDEF) continue;
2186 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2187 if (cast<ConstantSDNode>(Arg)->getZExtValue() != i)
2191 // Upper quadword shuffled.
2192 for (unsigned i = 4; i != 8; ++i) {
2193 SDValue Arg = N->getOperand(i);
2194 if (Arg.getOpcode() == ISD::UNDEF) continue;
2195 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2196 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2197 if (Val < 4 || Val > 7)
2204 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2205 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2206 bool X86::isPSHUFLWMask(SDNode *N) {
2207 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2209 if (N->getNumOperands() != 8)
2212 // Upper quadword copied in order.
2213 for (unsigned i = 4; i != 8; ++i)
2214 if (!isUndefOrEqual(N->getOperand(i), i))
2217 // Lower quadword shuffled.
2218 for (unsigned i = 0; i != 4; ++i)
2219 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2225 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2226 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2227 template<class SDOperand>
2228 static bool isSHUFPMask(SDOperand *Elems, unsigned NumElems) {
2229 if (NumElems != 2 && NumElems != 4) return false;
2231 unsigned Half = NumElems / 2;
2232 for (unsigned i = 0; i < Half; ++i)
2233 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2235 for (unsigned i = Half; i < NumElems; ++i)
2236 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2242 bool X86::isSHUFPMask(SDNode *N) {
2243 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2244 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2247 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2248 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2249 /// half elements to come from vector 1 (which would equal the dest.) and
2250 /// the upper half to come from vector 2.
2251 template<class SDOperand>
2252 static bool isCommutedSHUFP(SDOperand *Ops, unsigned NumOps) {
2253 if (NumOps != 2 && NumOps != 4) return false;
2255 unsigned Half = NumOps / 2;
2256 for (unsigned i = 0; i < Half; ++i)
2257 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2259 for (unsigned i = Half; i < NumOps; ++i)
2260 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2265 static bool isCommutedSHUFP(SDNode *N) {
2266 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2267 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2270 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2271 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2272 bool X86::isMOVHLPSMask(SDNode *N) {
2273 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2275 if (N->getNumOperands() != 4)
2278 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2279 return isUndefOrEqual(N->getOperand(0), 6) &&
2280 isUndefOrEqual(N->getOperand(1), 7) &&
2281 isUndefOrEqual(N->getOperand(2), 2) &&
2282 isUndefOrEqual(N->getOperand(3), 3);
2285 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2286 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2288 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2289 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2291 if (N->getNumOperands() != 4)
2294 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2295 return isUndefOrEqual(N->getOperand(0), 2) &&
2296 isUndefOrEqual(N->getOperand(1), 3) &&
2297 isUndefOrEqual(N->getOperand(2), 2) &&
2298 isUndefOrEqual(N->getOperand(3), 3);
2301 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2302 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2303 bool X86::isMOVLPMask(SDNode *N) {
2304 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2306 unsigned NumElems = N->getNumOperands();
2307 if (NumElems != 2 && NumElems != 4)
2310 for (unsigned i = 0; i < NumElems/2; ++i)
2311 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2314 for (unsigned i = NumElems/2; i < NumElems; ++i)
2315 if (!isUndefOrEqual(N->getOperand(i), i))
2321 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2322 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2324 bool X86::isMOVHPMask(SDNode *N) {
2325 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2327 unsigned NumElems = N->getNumOperands();
2328 if (NumElems != 2 && NumElems != 4)
2331 for (unsigned i = 0; i < NumElems/2; ++i)
2332 if (!isUndefOrEqual(N->getOperand(i), i))
2335 for (unsigned i = 0; i < NumElems/2; ++i) {
2336 SDValue Arg = N->getOperand(i + NumElems/2);
2337 if (!isUndefOrEqual(Arg, i + NumElems))
2344 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2345 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2346 template<class SDOperand>
2347 bool static isUNPCKLMask(SDOperand *Elts, unsigned NumElts,
2348 bool V2IsSplat = false) {
2349 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2352 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2353 SDValue BitI = Elts[i];
2354 SDValue BitI1 = Elts[i+1];
2355 if (!isUndefOrEqual(BitI, j))
2358 if (!isUndefOrEqual(BitI1, NumElts))
2361 if (!isUndefOrEqual(BitI1, j + NumElts))
2369 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2370 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2371 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2374 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2375 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2376 template<class SDOperand>
2377 bool static isUNPCKHMask(SDOperand *Elts, unsigned NumElts,
2378 bool V2IsSplat = false) {
2379 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2382 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2383 SDValue BitI = Elts[i];
2384 SDValue BitI1 = Elts[i+1];
2385 if (!isUndefOrEqual(BitI, j + NumElts/2))
2388 if (isUndefOrEqual(BitI1, NumElts))
2391 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2399 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2400 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2401 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2404 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2405 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2407 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2408 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2410 unsigned NumElems = N->getNumOperands();
2411 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2414 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2415 SDValue BitI = N->getOperand(i);
2416 SDValue BitI1 = N->getOperand(i+1);
2418 if (!isUndefOrEqual(BitI, j))
2420 if (!isUndefOrEqual(BitI1, j))
2427 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2428 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2430 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2431 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2433 unsigned NumElems = N->getNumOperands();
2434 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2437 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2438 SDValue BitI = N->getOperand(i);
2439 SDValue BitI1 = N->getOperand(i + 1);
2441 if (!isUndefOrEqual(BitI, j))
2443 if (!isUndefOrEqual(BitI1, j))
2450 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2451 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2452 /// MOVSD, and MOVD, i.e. setting the lowest element.
2453 template<class SDOperand>
2454 static bool isMOVLMask(SDOperand *Elts, unsigned NumElts) {
2455 if (NumElts != 2 && NumElts != 4)
2458 if (!isUndefOrEqual(Elts[0], NumElts))
2461 for (unsigned i = 1; i < NumElts; ++i) {
2462 if (!isUndefOrEqual(Elts[i], i))
2469 bool X86::isMOVLMask(SDNode *N) {
2470 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2471 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2474 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2475 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2476 /// element of vector 2 and the other elements to come from vector 1 in order.
2477 template<class SDOperand>
2478 static bool isCommutedMOVL(SDOperand *Ops, unsigned NumOps,
2479 bool V2IsSplat = false,
2480 bool V2IsUndef = false) {
2481 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2484 if (!isUndefOrEqual(Ops[0], 0))
2487 for (unsigned i = 1; i < NumOps; ++i) {
2488 SDValue Arg = Ops[i];
2489 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2490 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2491 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2498 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2499 bool V2IsUndef = false) {
2500 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2501 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2502 V2IsSplat, V2IsUndef);
2505 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2506 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2507 bool X86::isMOVSHDUPMask(SDNode *N) {
2508 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2510 if (N->getNumOperands() != 4)
2513 // Expect 1, 1, 3, 3
2514 for (unsigned i = 0; i < 2; ++i) {
2515 SDValue Arg = N->getOperand(i);
2516 if (Arg.getOpcode() == ISD::UNDEF) continue;
2517 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2518 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2519 if (Val != 1) return false;
2523 for (unsigned i = 2; i < 4; ++i) {
2524 SDValue Arg = N->getOperand(i);
2525 if (Arg.getOpcode() == ISD::UNDEF) continue;
2526 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2527 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2528 if (Val != 3) return false;
2532 // Don't use movshdup if it can be done with a shufps.
2536 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2537 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2538 bool X86::isMOVSLDUPMask(SDNode *N) {
2539 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2541 if (N->getNumOperands() != 4)
2544 // Expect 0, 0, 2, 2
2545 for (unsigned i = 0; i < 2; ++i) {
2546 SDValue Arg = N->getOperand(i);
2547 if (Arg.getOpcode() == ISD::UNDEF) continue;
2548 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2549 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2550 if (Val != 0) return false;
2554 for (unsigned i = 2; i < 4; ++i) {
2555 SDValue Arg = N->getOperand(i);
2556 if (Arg.getOpcode() == ISD::UNDEF) continue;
2557 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2558 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2559 if (Val != 2) return false;
2563 // Don't use movshdup if it can be done with a shufps.
2567 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2568 /// specifies a identity operation on the LHS or RHS.
2569 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2570 unsigned NumElems = N->getNumOperands();
2571 for (unsigned i = 0; i < NumElems; ++i)
2572 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2577 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2578 /// a splat of a single element.
2579 static bool isSplatMask(SDNode *N) {
2580 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2582 // This is a splat operation if each element of the permute is the same, and
2583 // if the value doesn't reference the second vector.
2584 unsigned NumElems = N->getNumOperands();
2585 SDValue ElementBase;
2587 for (; i != NumElems; ++i) {
2588 SDValue Elt = N->getOperand(i);
2589 if (isa<ConstantSDNode>(Elt)) {
2595 if (!ElementBase.getNode())
2598 for (; i != NumElems; ++i) {
2599 SDValue Arg = N->getOperand(i);
2600 if (Arg.getOpcode() == ISD::UNDEF) continue;
2601 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2602 if (Arg != ElementBase) return false;
2605 // Make sure it is a splat of the first vector operand.
2606 return cast<ConstantSDNode>(ElementBase)->getZExtValue() < NumElems;
2609 /// getSplatMaskEltNo - Given a splat mask, return the index to the element
2610 /// we want to splat.
2611 static SDValue getSplatMaskEltNo(SDNode *N) {
2612 assert(isSplatMask(N) && "Not a splat mask");
2613 unsigned NumElems = N->getNumOperands();
2614 SDValue ElementBase;
2616 for (; i != NumElems; ++i) {
2617 SDValue Elt = N->getOperand(i);
2618 if (isa<ConstantSDNode>(Elt))
2621 assert(0 && " No splat value found!");
2626 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2627 /// a splat of a single element and it's a 2 or 4 element mask.
2628 bool X86::isSplatMask(SDNode *N) {
2629 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2631 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2632 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2634 return ::isSplatMask(N);
2637 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2638 /// specifies a splat of zero element.
2639 bool X86::isSplatLoMask(SDNode *N) {
2640 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2642 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2643 if (!isUndefOrEqual(N->getOperand(i), 0))
2648 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2649 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2650 bool X86::isMOVDDUPMask(SDNode *N) {
2651 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2653 unsigned e = N->getNumOperands() / 2;
2654 for (unsigned i = 0; i < e; ++i)
2655 if (!isUndefOrEqual(N->getOperand(i), i))
2657 for (unsigned i = 0; i < e; ++i)
2658 if (!isUndefOrEqual(N->getOperand(e+i), i))
2663 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2664 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2666 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2667 unsigned NumOperands = N->getNumOperands();
2668 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2670 for (unsigned i = 0; i < NumOperands; ++i) {
2672 SDValue Arg = N->getOperand(NumOperands-i-1);
2673 if (Arg.getOpcode() != ISD::UNDEF)
2674 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2675 if (Val >= NumOperands) Val -= NumOperands;
2677 if (i != NumOperands - 1)
2684 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2685 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2687 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2689 // 8 nodes, but we only care about the last 4.
2690 for (unsigned i = 7; i >= 4; --i) {
2692 SDValue Arg = N->getOperand(i);
2693 if (Arg.getOpcode() != ISD::UNDEF) {
2694 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2704 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2705 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2707 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2709 // 8 nodes, but we only care about the first 4.
2710 for (int i = 3; i >= 0; --i) {
2712 SDValue Arg = N->getOperand(i);
2713 if (Arg.getOpcode() != ISD::UNDEF)
2714 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2723 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2724 /// values in ther permute mask.
2725 static SDValue CommuteVectorShuffle(SDValue Op, SDValue &V1,
2726 SDValue &V2, SDValue &Mask,
2727 SelectionDAG &DAG) {
2728 MVT VT = Op.getValueType();
2729 MVT MaskVT = Mask.getValueType();
2730 MVT EltVT = MaskVT.getVectorElementType();
2731 unsigned NumElems = Mask.getNumOperands();
2732 SmallVector<SDValue, 8> MaskVec;
2733 DebugLoc dl = Op.getDebugLoc();
2735 for (unsigned i = 0; i != NumElems; ++i) {
2736 SDValue Arg = Mask.getOperand(i);
2737 if (Arg.getOpcode() == ISD::UNDEF) {
2738 MaskVec.push_back(DAG.getUNDEF(EltVT));
2741 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2742 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2744 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2746 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2750 Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT, &MaskVec[0], NumElems);
2751 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, Mask);
2754 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2755 /// the two vector operands have swapped position.
2757 SDValue CommuteVectorShuffleMask(SDValue Mask, SelectionDAG &DAG, DebugLoc dl) {
2758 MVT MaskVT = Mask.getValueType();
2759 MVT EltVT = MaskVT.getVectorElementType();
2760 unsigned NumElems = Mask.getNumOperands();
2761 SmallVector<SDValue, 8> MaskVec;
2762 for (unsigned i = 0; i != NumElems; ++i) {
2763 SDValue Arg = Mask.getOperand(i);
2764 if (Arg.getOpcode() == ISD::UNDEF) {
2765 MaskVec.push_back(DAG.getUNDEF(EltVT));
2768 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2769 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2771 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2773 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2775 return DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT, &MaskVec[0], NumElems);
2779 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2780 /// match movhlps. The lower half elements should come from upper half of
2781 /// V1 (and in order), and the upper half elements should come from the upper
2782 /// half of V2 (and in order).
2783 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2784 unsigned NumElems = Mask->getNumOperands();
2787 for (unsigned i = 0, e = 2; i != e; ++i)
2788 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2790 for (unsigned i = 2; i != 4; ++i)
2791 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2796 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2797 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2799 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2800 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
2802 N = N->getOperand(0).getNode();
2803 if (!ISD::isNON_EXTLoad(N))
2806 *LD = cast<LoadSDNode>(N);
2810 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2811 /// match movlp{s|d}. The lower half elements should come from lower half of
2812 /// V1 (and in order), and the upper half elements should come from the upper
2813 /// half of V2 (and in order). And since V1 will become the source of the
2814 /// MOVLP, it must be either a vector load or a scalar load to vector.
2815 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2816 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2818 // Is V2 is a vector load, don't do this transformation. We will try to use
2819 // load folding shufps op.
2820 if (ISD::isNON_EXTLoad(V2))
2823 unsigned NumElems = Mask->getNumOperands();
2824 if (NumElems != 2 && NumElems != 4)
2826 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2827 if (!isUndefOrEqual(Mask->getOperand(i), i))
2829 for (unsigned i = NumElems/2; i != NumElems; ++i)
2830 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2835 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2837 static bool isSplatVector(SDNode *N) {
2838 if (N->getOpcode() != ISD::BUILD_VECTOR)
2841 SDValue SplatValue = N->getOperand(0);
2842 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2843 if (N->getOperand(i) != SplatValue)
2848 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2850 static bool isUndefShuffle(SDNode *N) {
2851 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2854 SDValue V1 = N->getOperand(0);
2855 SDValue V2 = N->getOperand(1);
2856 SDValue Mask = N->getOperand(2);
2857 unsigned NumElems = Mask.getNumOperands();
2858 for (unsigned i = 0; i != NumElems; ++i) {
2859 SDValue Arg = Mask.getOperand(i);
2860 if (Arg.getOpcode() != ISD::UNDEF) {
2861 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2862 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2864 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2871 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2873 static inline bool isZeroNode(SDValue Elt) {
2874 return ((isa<ConstantSDNode>(Elt) &&
2875 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2876 (isa<ConstantFPSDNode>(Elt) &&
2877 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2880 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2881 /// to an zero vector.
2882 static bool isZeroShuffle(SDNode *N) {
2883 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2886 SDValue V1 = N->getOperand(0);
2887 SDValue V2 = N->getOperand(1);
2888 SDValue Mask = N->getOperand(2);
2889 unsigned NumElems = Mask.getNumOperands();
2890 for (unsigned i = 0; i != NumElems; ++i) {
2891 SDValue Arg = Mask.getOperand(i);
2892 if (Arg.getOpcode() == ISD::UNDEF)
2895 unsigned Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2896 if (Idx < NumElems) {
2897 unsigned Opc = V1.getNode()->getOpcode();
2898 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
2900 if (Opc != ISD::BUILD_VECTOR ||
2901 !isZeroNode(V1.getNode()->getOperand(Idx)))
2903 } else if (Idx >= NumElems) {
2904 unsigned Opc = V2.getNode()->getOpcode();
2905 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
2907 if (Opc != ISD::BUILD_VECTOR ||
2908 !isZeroNode(V2.getNode()->getOperand(Idx - NumElems)))
2915 /// getZeroVector - Returns a vector of specified type with all zero elements.
2917 static SDValue getZeroVector(MVT VT, bool HasSSE2, SelectionDAG &DAG,
2919 assert(VT.isVector() && "Expected a vector type");
2921 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2922 // type. This ensures they get CSE'd.
2924 if (VT.getSizeInBits() == 64) { // MMX
2925 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2926 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2927 } else if (HasSSE2) { // SSE2
2928 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2929 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2931 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2932 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
2934 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2937 /// getOnesVector - Returns a vector of specified type with all bits set.
2939 static SDValue getOnesVector(MVT VT, SelectionDAG &DAG, DebugLoc dl) {
2940 assert(VT.isVector() && "Expected a vector type");
2942 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2943 // type. This ensures they get CSE'd.
2944 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2946 if (VT.getSizeInBits() == 64) // MMX
2947 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2949 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2950 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2954 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2955 /// that point to V2 points to its first element.
2956 static SDValue NormalizeMask(SDValue Mask, SelectionDAG &DAG) {
2957 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2959 bool Changed = false;
2960 SmallVector<SDValue, 8> MaskVec;
2961 unsigned NumElems = Mask.getNumOperands();
2962 for (unsigned i = 0; i != NumElems; ++i) {
2963 SDValue Arg = Mask.getOperand(i);
2964 if (Arg.getOpcode() != ISD::UNDEF) {
2965 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2966 if (Val > NumElems) {
2967 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2971 MaskVec.push_back(Arg);
2975 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getDebugLoc(),
2976 Mask.getValueType(),
2977 &MaskVec[0], MaskVec.size());
2981 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2982 /// operation of specified width.
2983 static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG, DebugLoc dl) {
2984 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2985 MVT BaseVT = MaskVT.getVectorElementType();
2987 SmallVector<SDValue, 8> MaskVec;
2988 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2989 for (unsigned i = 1; i != NumElems; ++i)
2990 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2991 return DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
2992 &MaskVec[0], MaskVec.size());
2995 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2996 /// of specified width.
2997 static SDValue getUnpacklMask(unsigned NumElems, SelectionDAG &DAG,
2999 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3000 MVT BaseVT = MaskVT.getVectorElementType();
3001 SmallVector<SDValue, 8> MaskVec;
3002 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3003 MaskVec.push_back(DAG.getConstant(i, BaseVT));
3004 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
3006 return DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3007 &MaskVec[0], MaskVec.size());
3010 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
3011 /// of specified width.
3012 static SDValue getUnpackhMask(unsigned NumElems, SelectionDAG &DAG,
3014 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3015 MVT BaseVT = MaskVT.getVectorElementType();
3016 unsigned Half = NumElems/2;
3017 SmallVector<SDValue, 8> MaskVec;
3018 for (unsigned i = 0; i != Half; ++i) {
3019 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
3020 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
3022 return DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3023 &MaskVec[0], MaskVec.size());
3026 /// getSwapEltZeroMask - Returns a vector_shuffle mask for a shuffle that swaps
3027 /// element #0 of a vector with the specified index, leaving the rest of the
3028 /// elements in place.
3029 static SDValue getSwapEltZeroMask(unsigned NumElems, unsigned DestElt,
3030 SelectionDAG &DAG, DebugLoc dl) {
3031 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3032 MVT BaseVT = MaskVT.getVectorElementType();
3033 SmallVector<SDValue, 8> MaskVec;
3034 // Element #0 of the result gets the elt we are replacing.
3035 MaskVec.push_back(DAG.getConstant(DestElt, BaseVT));
3036 for (unsigned i = 1; i != NumElems; ++i)
3037 MaskVec.push_back(DAG.getConstant(i == DestElt ? 0 : i, BaseVT));
3038 return DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3039 &MaskVec[0], MaskVec.size());
3042 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3043 static SDValue PromoteSplat(SDValue Op, SelectionDAG &DAG, bool HasSSE2) {
3044 MVT PVT = HasSSE2 ? MVT::v4i32 : MVT::v4f32;
3045 MVT VT = Op.getValueType();
3048 SDValue V1 = Op.getOperand(0);
3049 SDValue Mask = Op.getOperand(2);
3050 unsigned MaskNumElems = Mask.getNumOperands();
3051 unsigned NumElems = MaskNumElems;
3052 DebugLoc dl = Op.getDebugLoc();
3053 // Special handling of v4f32 -> v4i32.
3054 if (VT != MVT::v4f32) {
3055 // Find which element we want to splat.
3056 SDNode* EltNoNode = getSplatMaskEltNo(Mask.getNode()).getNode();
3057 unsigned EltNo = cast<ConstantSDNode>(EltNoNode)->getZExtValue();
3058 // unpack elements to the correct location
3059 while (NumElems > 4) {
3060 if (EltNo < NumElems/2) {
3061 Mask = getUnpacklMask(MaskNumElems, DAG, dl);
3063 Mask = getUnpackhMask(MaskNumElems, DAG, dl);
3064 EltNo -= NumElems/2;
3066 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V1, Mask);
3069 SDValue Cst = DAG.getConstant(EltNo, MVT::i32);
3070 Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3073 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3074 SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, PVT, V1,
3075 DAG.getUNDEF(PVT), Mask);
3076 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Shuffle);
3079 /// isVectorLoad - Returns true if the node is a vector load, a scalar
3080 /// load that's promoted to vector, or a load bitcasted.
3081 static bool isVectorLoad(SDValue Op) {
3082 assert(Op.getValueType().isVector() && "Expected a vector type");
3083 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR ||
3084 Op.getOpcode() == ISD::BIT_CONVERT) {
3085 return isa<LoadSDNode>(Op.getOperand(0));
3087 return isa<LoadSDNode>(Op);
3091 /// CanonicalizeMovddup - Cannonicalize movddup shuffle to v2f64.
3093 static SDValue CanonicalizeMovddup(SDValue Op, SDValue V1, SDValue Mask,
3094 SelectionDAG &DAG, bool HasSSE3) {
3095 // If we have sse3 and shuffle has more than one use or input is a load, then
3096 // use movddup. Otherwise, use movlhps.
3097 bool UseMovddup = HasSSE3 && (!Op.hasOneUse() || isVectorLoad(V1));
3098 MVT PVT = UseMovddup ? MVT::v2f64 : MVT::v4f32;
3099 MVT VT = Op.getValueType();
3102 DebugLoc dl = Op.getDebugLoc();
3103 unsigned NumElems = PVT.getVectorNumElements();
3104 if (NumElems == 2) {
3105 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3106 Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3108 assert(NumElems == 4);
3109 SDValue Cst0 = DAG.getTargetConstant(0, MVT::i32);
3110 SDValue Cst1 = DAG.getTargetConstant(1, MVT::i32);
3111 Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
3112 Cst0, Cst1, Cst0, Cst1);
3115 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3116 SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, PVT, V1,
3117 DAG.getUNDEF(PVT), Mask);
3118 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Shuffle);
3121 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3122 /// vector of zero or undef vector. This produces a shuffle where the low
3123 /// element of V2 is swizzled into the zero/undef vector, landing at element
3124 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3125 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3126 bool isZero, bool HasSSE2,
3127 SelectionDAG &DAG) {
3128 DebugLoc dl = V2.getDebugLoc();
3129 MVT VT = V2.getValueType();
3131 ? getZeroVector(VT, HasSSE2, DAG, dl) : DAG.getUNDEF(VT);
3132 unsigned NumElems = V2.getValueType().getVectorNumElements();
3133 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3134 MVT EVT = MaskVT.getVectorElementType();
3135 SmallVector<SDValue, 16> MaskVec;
3136 for (unsigned i = 0; i != NumElems; ++i)
3137 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
3138 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
3140 MaskVec.push_back(DAG.getConstant(i, EVT));
3141 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3142 &MaskVec[0], MaskVec.size());
3143 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, Mask);
3146 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3147 /// a shuffle that is zero.
3149 unsigned getNumOfConsecutiveZeros(SDValue Op, SDValue Mask,
3150 unsigned NumElems, bool Low,
3151 SelectionDAG &DAG) {
3152 unsigned NumZeros = 0;
3153 for (unsigned i = 0; i < NumElems; ++i) {
3154 unsigned Index = Low ? i : NumElems-i-1;
3155 SDValue Idx = Mask.getOperand(Index);
3156 if (Idx.getOpcode() == ISD::UNDEF) {
3160 SDValue Elt = DAG.getShuffleScalarElt(Op.getNode(), Index);
3161 if (Elt.getNode() && isZeroNode(Elt))
3169 /// isVectorShift - Returns true if the shuffle can be implemented as a
3170 /// logical left or right shift of a vector.
3171 static bool isVectorShift(SDValue Op, SDValue Mask, SelectionDAG &DAG,
3172 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3173 unsigned NumElems = Mask.getNumOperands();
3176 unsigned NumZeros= getNumOfConsecutiveZeros(Op, Mask, NumElems, true, DAG);
3179 NumZeros = getNumOfConsecutiveZeros(Op, Mask, NumElems, false, DAG);
3184 bool SeenV1 = false;
3185 bool SeenV2 = false;
3186 for (unsigned i = NumZeros; i < NumElems; ++i) {
3187 unsigned Val = isLeft ? (i - NumZeros) : i;
3188 SDValue Idx = Mask.getOperand(isLeft ? i : (i - NumZeros));
3189 if (Idx.getOpcode() == ISD::UNDEF)
3191 unsigned Index = cast<ConstantSDNode>(Idx)->getZExtValue();
3192 if (Index < NumElems)
3201 if (SeenV1 && SeenV2)
3204 ShVal = SeenV1 ? Op.getOperand(0) : Op.getOperand(1);
3210 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3212 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3213 unsigned NumNonZero, unsigned NumZero,
3214 SelectionDAG &DAG, TargetLowering &TLI) {
3218 DebugLoc dl = Op.getDebugLoc();
3221 for (unsigned i = 0; i < 16; ++i) {
3222 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3223 if (ThisIsNonZero && First) {
3225 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3227 V = DAG.getUNDEF(MVT::v8i16);
3232 SDValue ThisElt(0, 0), LastElt(0, 0);
3233 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3234 if (LastIsNonZero) {
3235 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3236 MVT::i16, Op.getOperand(i-1));
3238 if (ThisIsNonZero) {
3239 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3240 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3241 ThisElt, DAG.getConstant(8, MVT::i8));
3243 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3247 if (ThisElt.getNode())
3248 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3249 DAG.getIntPtrConstant(i/2));
3253 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3256 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3258 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3259 unsigned NumNonZero, unsigned NumZero,
3260 SelectionDAG &DAG, TargetLowering &TLI) {
3264 DebugLoc dl = Op.getDebugLoc();
3267 for (unsigned i = 0; i < 8; ++i) {
3268 bool isNonZero = (NonZeros & (1 << i)) != 0;
3272 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3274 V = DAG.getUNDEF(MVT::v8i16);
3277 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3278 MVT::v8i16, V, Op.getOperand(i),
3279 DAG.getIntPtrConstant(i));
3286 /// getVShift - Return a vector logical shift node.
3288 static SDValue getVShift(bool isLeft, MVT VT, SDValue SrcOp,
3289 unsigned NumBits, SelectionDAG &DAG,
3290 const TargetLowering &TLI, DebugLoc dl) {
3291 bool isMMX = VT.getSizeInBits() == 64;
3292 MVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3293 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3294 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3295 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3296 DAG.getNode(Opc, dl, ShVT, SrcOp,
3297 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3301 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3302 DebugLoc dl = Op.getDebugLoc();
3303 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3304 if (ISD::isBuildVectorAllZeros(Op.getNode())
3305 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3306 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3307 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3308 // eliminated on x86-32 hosts.
3309 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3312 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3313 return getOnesVector(Op.getValueType(), DAG, dl);
3314 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3317 MVT VT = Op.getValueType();
3318 MVT EVT = VT.getVectorElementType();
3319 unsigned EVTBits = EVT.getSizeInBits();
3321 unsigned NumElems = Op.getNumOperands();
3322 unsigned NumZero = 0;
3323 unsigned NumNonZero = 0;
3324 unsigned NonZeros = 0;
3325 bool IsAllConstants = true;
3326 SmallSet<SDValue, 8> Values;
3327 for (unsigned i = 0; i < NumElems; ++i) {
3328 SDValue Elt = Op.getOperand(i);
3329 if (Elt.getOpcode() == ISD::UNDEF)
3332 if (Elt.getOpcode() != ISD::Constant &&
3333 Elt.getOpcode() != ISD::ConstantFP)
3334 IsAllConstants = false;
3335 if (isZeroNode(Elt))
3338 NonZeros |= (1 << i);
3343 if (NumNonZero == 0) {
3344 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3345 return DAG.getUNDEF(VT);
3348 // Special case for single non-zero, non-undef, element.
3349 if (NumNonZero == 1 && NumElems <= 4) {
3350 unsigned Idx = CountTrailingZeros_32(NonZeros);
3351 SDValue Item = Op.getOperand(Idx);
3353 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3354 // the value are obviously zero, truncate the value to i32 and do the
3355 // insertion that way. Only do this if the value is non-constant or if the
3356 // value is a constant being inserted into element 0. It is cheaper to do
3357 // a constant pool load than it is to do a movd + shuffle.
3358 if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3359 (!IsAllConstants || Idx == 0)) {
3360 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3361 // Handle MMX and SSE both.
3362 MVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3363 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3365 // Truncate the value (which may itself be a constant) to i32, and
3366 // convert it to a vector with movd (S2V+shuffle to zero extend).
3367 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3368 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3369 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3370 Subtarget->hasSSE2(), DAG);
3372 // Now we have our 32-bit value zero extended in the low element of
3373 // a vector. If Idx != 0, swizzle it into place.
3376 Item, DAG.getUNDEF(Item.getValueType()),
3377 getSwapEltZeroMask(VecElts, Idx, DAG, dl)
3379 Item = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VecVT, Ops, 3);
3381 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3385 // If we have a constant or non-constant insertion into the low element of
3386 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3387 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3388 // depending on what the source datatype is. Because we can only get here
3389 // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3391 // Don't do this for i64 values on x86-32.
3392 (EVT != MVT::i64 || Subtarget->is64Bit())) {
3393 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3394 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3395 return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3396 Subtarget->hasSSE2(), DAG);
3399 // Is it a vector logical left shift?
3400 if (NumElems == 2 && Idx == 1 &&
3401 isZeroNode(Op.getOperand(0)) && !isZeroNode(Op.getOperand(1))) {
3402 unsigned NumBits = VT.getSizeInBits();
3403 return getVShift(true, VT,
3404 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3405 VT, Op.getOperand(1)),
3406 NumBits/2, DAG, *this, dl);
3409 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3412 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3413 // is a non-constant being inserted into an element other than the low one,
3414 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3415 // movd/movss) to move this into the low element, then shuffle it into
3417 if (EVTBits == 32) {
3418 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3420 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3421 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3422 Subtarget->hasSSE2(), DAG);
3423 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3424 MVT MaskEVT = MaskVT.getVectorElementType();
3425 SmallVector<SDValue, 8> MaskVec;
3426 for (unsigned i = 0; i < NumElems; i++)
3427 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3428 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3429 &MaskVec[0], MaskVec.size());
3430 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, Item,
3431 DAG.getUNDEF(VT), Mask);
3435 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3436 if (Values.size() == 1)
3439 // A vector full of immediates; various special cases are already
3440 // handled, so this is best done with a single constant-pool load.
3444 // Let legalizer expand 2-wide build_vectors.
3445 if (EVTBits == 64) {
3446 if (NumNonZero == 1) {
3447 // One half is zero or undef.
3448 unsigned Idx = CountTrailingZeros_32(NonZeros);
3449 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3450 Op.getOperand(Idx));
3451 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3452 Subtarget->hasSSE2(), DAG);
3457 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3458 if (EVTBits == 8 && NumElems == 16) {
3459 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3461 if (V.getNode()) return V;
3464 if (EVTBits == 16 && NumElems == 8) {
3465 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3467 if (V.getNode()) return V;
3470 // If element VT is == 32 bits, turn it into a number of shuffles.
3471 SmallVector<SDValue, 8> V;
3473 if (NumElems == 4 && NumZero > 0) {
3474 for (unsigned i = 0; i < 4; ++i) {
3475 bool isZero = !(NonZeros & (1 << i));
3477 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3479 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3482 for (unsigned i = 0; i < 2; ++i) {
3483 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3486 V[i] = V[i*2]; // Must be a zero vector.
3489 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[i*2+1], V[i*2],
3490 getMOVLMask(NumElems, DAG, dl));
3493 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[i*2], V[i*2+1],
3494 getMOVLMask(NumElems, DAG, dl));
3497 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[i*2], V[i*2+1],
3498 getUnpacklMask(NumElems, DAG, dl));
3503 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3504 MVT EVT = MaskVT.getVectorElementType();
3505 SmallVector<SDValue, 8> MaskVec;
3506 bool Reverse = (NonZeros & 0x3) == 2;
3507 for (unsigned i = 0; i < 2; ++i)
3509 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3511 MaskVec.push_back(DAG.getConstant(i, EVT));
3512 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3513 for (unsigned i = 0; i < 2; ++i)
3515 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3517 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3518 SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3519 &MaskVec[0], MaskVec.size());
3520 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[0], V[1], ShufMask);
3523 if (Values.size() > 2) {
3524 // Expand into a number of unpckl*.
3526 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3527 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3528 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3529 SDValue UnpckMask = getUnpacklMask(NumElems, DAG, dl);
3530 for (unsigned i = 0; i < NumElems; ++i)
3531 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3533 while (NumElems != 0) {
3534 for (unsigned i = 0; i < NumElems; ++i)
3535 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[i], V[i + NumElems],
3545 // v8i16 shuffles - Prefer shuffles in the following order:
3546 // 1. [all] pshuflw, pshufhw, optional move
3547 // 2. [ssse3] 1 x pshufb
3548 // 3. [ssse3] 2 x pshufb + 1 x por
3549 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
3551 SDValue LowerVECTOR_SHUFFLEv8i16(SDValue V1, SDValue V2,
3552 SDValue PermMask, SelectionDAG &DAG,
3553 X86TargetLowering &TLI, DebugLoc dl) {
3554 SmallVector<SDValue, 8> MaskElts(PermMask.getNode()->op_begin(),
3555 PermMask.getNode()->op_end());
3556 SmallVector<int, 8> MaskVals;
3558 // Determine if more than 1 of the words in each of the low and high quadwords
3559 // of the result come from the same quadword of one of the two inputs. Undef
3560 // mask values count as coming from any quadword, for better codegen.
3561 SmallVector<unsigned, 4> LoQuad(4);
3562 SmallVector<unsigned, 4> HiQuad(4);
3563 BitVector InputQuads(4);
3564 for (unsigned i = 0; i < 8; ++i) {
3565 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
3566 SDValue Elt = MaskElts[i];
3567 int EltIdx = Elt.getOpcode() == ISD::UNDEF ? -1 :
3568 cast<ConstantSDNode>(Elt)->getZExtValue();
3569 MaskVals.push_back(EltIdx);
3578 InputQuads.set(EltIdx / 4);
3581 int BestLoQuad = -1;
3582 unsigned MaxQuad = 1;
3583 for (unsigned i = 0; i < 4; ++i) {
3584 if (LoQuad[i] > MaxQuad) {
3586 MaxQuad = LoQuad[i];
3590 int BestHiQuad = -1;
3592 for (unsigned i = 0; i < 4; ++i) {
3593 if (HiQuad[i] > MaxQuad) {
3595 MaxQuad = HiQuad[i];
3599 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
3600 // of the two input vectors, shuffle them into one input vector so only a
3601 // single pshufb instruction is necessary. If There are more than 2 input
3602 // quads, disable the next transformation since it does not help SSSE3.
3603 bool V1Used = InputQuads[0] || InputQuads[1];
3604 bool V2Used = InputQuads[2] || InputQuads[3];
3605 if (TLI.getSubtarget()->hasSSSE3()) {
3606 if (InputQuads.count() == 2 && V1Used && V2Used) {
3607 BestLoQuad = InputQuads.find_first();
3608 BestHiQuad = InputQuads.find_next(BestLoQuad);
3610 if (InputQuads.count() > 2) {
3616 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
3617 // the shuffle mask. If a quad is scored as -1, that means that it contains
3618 // words from all 4 input quadwords.
3620 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
3621 SmallVector<SDValue,8> MaskV;
3622 MaskV.push_back(DAG.getConstant(BestLoQuad < 0 ? 0 : BestLoQuad, MVT::i64));
3623 MaskV.push_back(DAG.getConstant(BestHiQuad < 0 ? 1 : BestHiQuad, MVT::i64));
3624 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i64, &MaskV[0], 2);
3626 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v2i64,
3627 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
3628 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), Mask);
3629 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
3631 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
3632 // source words for the shuffle, to aid later transformations.
3633 bool AllWordsInNewV = true;
3634 bool InOrder[2] = { true, true };
3635 for (unsigned i = 0; i != 8; ++i) {
3636 int idx = MaskVals[i];
3638 InOrder[i/4] = false;
3639 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
3641 AllWordsInNewV = false;
3645 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
3646 if (AllWordsInNewV) {
3647 for (int i = 0; i != 8; ++i) {
3648 int idx = MaskVals[i];
3651 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
3652 if ((idx != i) && idx < 4)
3654 if ((idx != i) && idx > 3)
3663 // If we've eliminated the use of V2, and the new mask is a pshuflw or
3664 // pshufhw, that's as cheap as it gets. Return the new shuffle.
3665 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
3667 for (unsigned i = 0; i != 8; ++i)
3668 MaskV.push_back((MaskVals[i] < 0) ? DAG.getUNDEF(MVT::i16)
3669 : DAG.getConstant(MaskVals[i],
3671 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v8i16, NewV,
3672 DAG.getUNDEF(MVT::v8i16),
3673 DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i16,
3678 // If we have SSSE3, and all words of the result are from 1 input vector,
3679 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
3680 // is present, fall back to case 4.
3681 if (TLI.getSubtarget()->hasSSSE3()) {
3682 SmallVector<SDValue,16> pshufbMask;
3684 // If we have elements from both input vectors, set the high bit of the
3685 // shuffle mask element to zero out elements that come from V2 in the V1
3686 // mask, and elements that come from V1 in the V2 mask, so that the two
3687 // results can be OR'd together.
3688 bool TwoInputs = V1Used && V2Used;
3689 for (unsigned i = 0; i != 8; ++i) {
3690 int EltIdx = MaskVals[i] * 2;
3691 if (TwoInputs && (EltIdx >= 16)) {
3692 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3693 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3696 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3697 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
3699 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
3700 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3701 DAG.getNode(ISD::BUILD_VECTOR, dl,
3702 MVT::v16i8, &pshufbMask[0], 16));
3704 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3706 // Calculate the shuffle mask for the second input, shuffle it, and
3707 // OR it with the first shuffled input.
3709 for (unsigned i = 0; i != 8; ++i) {
3710 int EltIdx = MaskVals[i] * 2;
3712 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3713 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3716 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3717 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
3719 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
3720 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3721 DAG.getNode(ISD::BUILD_VECTOR, dl,
3722 MVT::v16i8, &pshufbMask[0], 16));
3723 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3724 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3727 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
3728 // and update MaskVals with new element order.
3729 BitVector InOrder(8);
3730 if (BestLoQuad >= 0) {
3731 SmallVector<SDValue, 8> MaskV;
3732 for (int i = 0; i != 4; ++i) {
3733 int idx = MaskVals[i];
3735 MaskV.push_back(DAG.getUNDEF(MVT::i16));
3737 } else if ((idx / 4) == BestLoQuad) {
3738 MaskV.push_back(DAG.getConstant(idx & 3, MVT::i16));
3741 MaskV.push_back(DAG.getUNDEF(MVT::i16));
3744 for (unsigned i = 4; i != 8; ++i)
3745 MaskV.push_back(DAG.getConstant(i, MVT::i16));
3746 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v8i16, NewV,
3747 DAG.getUNDEF(MVT::v8i16),
3748 DAG.getNode(ISD::BUILD_VECTOR, dl,
3749 MVT::v8i16, &MaskV[0], 8));
3752 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
3753 // and update MaskVals with the new element order.
3754 if (BestHiQuad >= 0) {
3755 SmallVector<SDValue, 8> MaskV;
3756 for (unsigned i = 0; i != 4; ++i)
3757 MaskV.push_back(DAG.getConstant(i, MVT::i16));
3758 for (unsigned i = 4; i != 8; ++i) {
3759 int idx = MaskVals[i];
3761 MaskV.push_back(DAG.getUNDEF(MVT::i16));
3763 } else if ((idx / 4) == BestHiQuad) {
3764 MaskV.push_back(DAG.getConstant((idx & 3) + 4, MVT::i16));
3767 MaskV.push_back(DAG.getUNDEF(MVT::i16));
3770 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v8i16, NewV,
3771 DAG.getUNDEF(MVT::v8i16),
3772 DAG.getNode(ISD::BUILD_VECTOR, dl,
3773 MVT::v8i16, &MaskV[0], 8));
3776 // In case BestHi & BestLo were both -1, which means each quadword has a word
3777 // from each of the four input quadwords, calculate the InOrder bitvector now
3778 // before falling through to the insert/extract cleanup.
3779 if (BestLoQuad == -1 && BestHiQuad == -1) {
3781 for (int i = 0; i != 8; ++i)
3782 if (MaskVals[i] < 0 || MaskVals[i] == i)
3786 // The other elements are put in the right place using pextrw and pinsrw.
3787 for (unsigned i = 0; i != 8; ++i) {
3790 int EltIdx = MaskVals[i];
3793 SDValue ExtOp = (EltIdx < 8)
3794 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
3795 DAG.getIntPtrConstant(EltIdx))
3796 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
3797 DAG.getIntPtrConstant(EltIdx - 8));
3798 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3799 DAG.getIntPtrConstant(i));
3804 // v16i8 shuffles - Prefer shuffles in the following order:
3805 // 1. [ssse3] 1 x pshufb
3806 // 2. [ssse3] 2 x pshufb + 1 x por
3807 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
3809 SDValue LowerVECTOR_SHUFFLEv16i8(SDValue V1, SDValue V2,
3810 SDValue PermMask, SelectionDAG &DAG,
3811 X86TargetLowering &TLI, DebugLoc dl) {
3812 SmallVector<SDValue, 16> MaskElts(PermMask.getNode()->op_begin(),
3813 PermMask.getNode()->op_end());
3814 SmallVector<int, 16> MaskVals;
3816 // If we have SSSE3, case 1 is generated when all result bytes come from
3817 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
3818 // present, fall back to case 3.
3819 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
3822 for (unsigned i = 0; i < 16; ++i) {
3823 SDValue Elt = MaskElts[i];
3824 int EltIdx = Elt.getOpcode() == ISD::UNDEF ? -1 :
3825 cast<ConstantSDNode>(Elt)->getZExtValue();
3826 MaskVals.push_back(EltIdx);
3835 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
3836 if (TLI.getSubtarget()->hasSSSE3()) {
3837 SmallVector<SDValue,16> pshufbMask;
3839 // If all result elements are from one input vector, then only translate
3840 // undef mask values to 0x80 (zero out result) in the pshufb mask.
3842 // Otherwise, we have elements from both input vectors, and must zero out
3843 // elements that come from V2 in the first mask, and V1 in the second mask
3844 // so that we can OR them together.
3845 bool TwoInputs = !(V1Only || V2Only);
3846 for (unsigned i = 0; i != 16; ++i) {
3847 int EltIdx = MaskVals[i];
3848 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
3849 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3852 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3854 // If all the elements are from V2, assign it to V1 and return after
3855 // building the first pshufb.
3858 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3859 DAG.getNode(ISD::BUILD_VECTOR, dl,
3860 MVT::v16i8, &pshufbMask[0], 16));
3864 // Calculate the shuffle mask for the second input, shuffle it, and
3865 // OR it with the first shuffled input.
3867 for (unsigned i = 0; i != 16; ++i) {
3868 int EltIdx = MaskVals[i];
3870 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3873 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3875 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3876 DAG.getNode(ISD::BUILD_VECTOR, dl,
3877 MVT::v16i8, &pshufbMask[0], 16));
3878 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3881 // No SSSE3 - Calculate in place words and then fix all out of place words
3882 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
3883 // the 16 different words that comprise the two doublequadword input vectors.
3884 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3885 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
3886 SDValue NewV = V2Only ? V2 : V1;
3887 for (int i = 0; i != 8; ++i) {
3888 int Elt0 = MaskVals[i*2];
3889 int Elt1 = MaskVals[i*2+1];
3891 // This word of the result is all undef, skip it.
3892 if (Elt0 < 0 && Elt1 < 0)
3895 // This word of the result is already in the correct place, skip it.
3896 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
3898 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
3901 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
3902 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
3905 // If Elt0 and Elt1 are defined, are consecutive, and can be load
3906 // using a single extract together, load it and store it.
3907 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
3908 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3909 DAG.getIntPtrConstant(Elt1 / 2));
3910 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3911 DAG.getIntPtrConstant(i));
3915 // If Elt1 is defined, extract it from the appropriate source. If the
3916 // source byte is not also odd, shift the extracted word left 8 bits
3917 // otherwise clear the bottom 8 bits if we need to do an or.
3919 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3920 DAG.getIntPtrConstant(Elt1 / 2));
3921 if ((Elt1 & 1) == 0)
3922 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
3923 DAG.getConstant(8, TLI.getShiftAmountTy()));
3925 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
3926 DAG.getConstant(0xFF00, MVT::i16));
3928 // If Elt0 is defined, extract it from the appropriate source. If the
3929 // source byte is not also even, shift the extracted word right 8 bits. If
3930 // Elt1 was also defined, OR the extracted values together before
3931 // inserting them in the result.
3933 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
3934 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
3935 if ((Elt0 & 1) != 0)
3936 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
3937 DAG.getConstant(8, TLI.getShiftAmountTy()));
3939 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
3940 DAG.getConstant(0x00FF, MVT::i16));
3941 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
3944 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3945 DAG.getIntPtrConstant(i));
3947 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
3950 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3951 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3952 /// done when every pair / quad of shuffle mask elements point to elements in
3953 /// the right sequence. e.g.
3954 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3956 SDValue RewriteAsNarrowerShuffle(SDValue V1, SDValue V2,
3958 SDValue PermMask, SelectionDAG &DAG,
3959 TargetLowering &TLI, DebugLoc dl) {
3960 unsigned NumElems = PermMask.getNumOperands();
3961 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3962 MVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3963 MVT MaskEltVT = MaskVT.getVectorElementType();
3965 switch (VT.getSimpleVT()) {
3966 default: assert(false && "Unexpected!");
3967 case MVT::v4f32: NewVT = MVT::v2f64; break;
3968 case MVT::v4i32: NewVT = MVT::v2i64; break;
3969 case MVT::v8i16: NewVT = MVT::v4i32; break;
3970 case MVT::v16i8: NewVT = MVT::v4i32; break;
3973 if (NewWidth == 2) {
3979 unsigned Scale = NumElems / NewWidth;
3980 SmallVector<SDValue, 8> MaskVec;
3981 for (unsigned i = 0; i < NumElems; i += Scale) {
3982 unsigned StartIdx = ~0U;
3983 for (unsigned j = 0; j < Scale; ++j) {
3984 SDValue Elt = PermMask.getOperand(i+j);
3985 if (Elt.getOpcode() == ISD::UNDEF)
3987 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3988 if (StartIdx == ~0U)
3989 StartIdx = EltIdx - (EltIdx % Scale);
3990 if (EltIdx != StartIdx + j)
3993 if (StartIdx == ~0U)
3994 MaskVec.push_back(DAG.getUNDEF(MaskEltVT));
3996 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MaskEltVT));
3999 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4000 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4001 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, NewVT, V1, V2,
4002 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4003 &MaskVec[0], MaskVec.size()));
4006 /// getVZextMovL - Return a zero-extending vector move low node.
4008 static SDValue getVZextMovL(MVT VT, MVT OpVT,
4009 SDValue SrcOp, SelectionDAG &DAG,
4010 const X86Subtarget *Subtarget, DebugLoc dl) {
4011 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4012 LoadSDNode *LD = NULL;
4013 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4014 LD = dyn_cast<LoadSDNode>(SrcOp);
4016 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4018 MVT EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4019 if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
4020 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4021 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4022 SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
4024 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4025 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4026 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4027 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4035 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4036 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4037 DAG.getNode(ISD::BIT_CONVERT, dl,
4041 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4044 LowerVECTOR_SHUFFLE_4wide(SDValue V1, SDValue V2,
4045 SDValue PermMask, MVT VT, SelectionDAG &DAG,
4047 MVT MaskVT = PermMask.getValueType();
4048 MVT MaskEVT = MaskVT.getVectorElementType();
4049 SmallVector<std::pair<int, int>, 8> Locs;
4051 SmallVector<SDValue, 8> Mask1(4, DAG.getUNDEF(MaskEVT));
4054 for (unsigned i = 0; i != 4; ++i) {
4055 SDValue Elt = PermMask.getOperand(i);
4056 if (Elt.getOpcode() == ISD::UNDEF) {
4057 Locs[i] = std::make_pair(-1, -1);
4059 unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
4060 assert(Val < 8 && "Invalid VECTOR_SHUFFLE index!");
4062 Locs[i] = std::make_pair(0, NumLo);
4066 Locs[i] = std::make_pair(1, NumHi);
4068 Mask1[2+NumHi] = Elt;
4074 if (NumLo <= 2 && NumHi <= 2) {
4075 // If no more than two elements come from either vector. This can be
4076 // implemented with two shuffles. First shuffle gather the elements.
4077 // The second shuffle, which takes the first shuffle as both of its
4078 // vector operands, put the elements into the right order.
4079 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
4080 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4081 &Mask1[0], Mask1.size()));
4083 SmallVector<SDValue, 8> Mask2(4, DAG.getUNDEF(MaskEVT));
4084 for (unsigned i = 0; i != 4; ++i) {
4085 if (Locs[i].first == -1)
4088 unsigned Idx = (i < 2) ? 0 : 4;
4089 Idx += Locs[i].first * 2 + Locs[i].second;
4090 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
4094 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V1,
4095 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4096 &Mask2[0], Mask2.size()));
4097 } else if (NumLo == 3 || NumHi == 3) {
4098 // Otherwise, we must have three elements from one vector, call it X, and
4099 // one element from the other, call it Y. First, use a shufps to build an
4100 // intermediate vector with the one element from Y and the element from X
4101 // that will be in the same half in the final destination (the indexes don't
4102 // matter). Then, use a shufps to build the final vector, taking the half
4103 // containing the element from Y from the intermediate, and the other half
4106 // Normalize it so the 3 elements come from V1.
4107 PermMask = CommuteVectorShuffleMask(PermMask, DAG, dl);
4111 // Find the element from V2.
4113 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4114 SDValue Elt = PermMask.getOperand(HiIndex);
4115 if (Elt.getOpcode() == ISD::UNDEF)
4117 unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
4122 Mask1[0] = PermMask.getOperand(HiIndex);
4123 Mask1[1] = DAG.getUNDEF(MaskEVT);
4124 Mask1[2] = PermMask.getOperand(HiIndex^1);
4125 Mask1[3] = DAG.getUNDEF(MaskEVT);
4126 V2 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
4127 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT, &Mask1[0], 4));
4130 Mask1[0] = PermMask.getOperand(0);
4131 Mask1[1] = PermMask.getOperand(1);
4132 Mask1[2] = DAG.getConstant(HiIndex & 1 ? 6 : 4, MaskEVT);
4133 Mask1[3] = DAG.getConstant(HiIndex & 1 ? 4 : 6, MaskEVT);
4134 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
4135 DAG.getNode(ISD::BUILD_VECTOR, dl,
4136 MaskVT, &Mask1[0], 4));
4138 Mask1[0] = DAG.getConstant(HiIndex & 1 ? 2 : 0, MaskEVT);
4139 Mask1[1] = DAG.getConstant(HiIndex & 1 ? 0 : 2, MaskEVT);
4140 Mask1[2] = PermMask.getOperand(2);
4141 Mask1[3] = PermMask.getOperand(3);
4142 if (Mask1[2].getOpcode() != ISD::UNDEF)
4144 DAG.getConstant(cast<ConstantSDNode>(Mask1[2])->getZExtValue()+4,
4146 if (Mask1[3].getOpcode() != ISD::UNDEF)
4148 DAG.getConstant(cast<ConstantSDNode>(Mask1[3])->getZExtValue()+4,
4150 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V2, V1,
4151 DAG.getNode(ISD::BUILD_VECTOR, dl,
4152 MaskVT, &Mask1[0], 4));
4156 // Break it into (shuffle shuffle_hi, shuffle_lo).
4158 SmallVector<SDValue,8> LoMask(4, DAG.getUNDEF(MaskEVT));
4159 SmallVector<SDValue,8> HiMask(4, DAG.getUNDEF(MaskEVT));
4160 SmallVector<SDValue,8> *MaskPtr = &LoMask;
4161 unsigned MaskIdx = 0;
4164 for (unsigned i = 0; i != 4; ++i) {
4171 SDValue Elt = PermMask.getOperand(i);
4172 if (Elt.getOpcode() == ISD::UNDEF) {
4173 Locs[i] = std::make_pair(-1, -1);
4174 } else if (cast<ConstantSDNode>(Elt)->getZExtValue() < 4) {
4175 Locs[i] = std::make_pair(MaskIdx, LoIdx);
4176 (*MaskPtr)[LoIdx] = Elt;
4179 Locs[i] = std::make_pair(MaskIdx, HiIdx);
4180 (*MaskPtr)[HiIdx] = Elt;
4185 SDValue LoShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
4186 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4187 &LoMask[0], LoMask.size()));
4188 SDValue HiShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
4189 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4190 &HiMask[0], HiMask.size()));
4191 SmallVector<SDValue, 8> MaskOps;
4192 for (unsigned i = 0; i != 4; ++i) {
4193 if (Locs[i].first == -1) {
4194 MaskOps.push_back(DAG.getUNDEF(MaskEVT));
4196 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4197 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
4200 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, LoShuffle, HiShuffle,
4201 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4202 &MaskOps[0], MaskOps.size()));
4206 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4207 SDValue V1 = Op.getOperand(0);
4208 SDValue V2 = Op.getOperand(1);
4209 SDValue PermMask = Op.getOperand(2);
4210 MVT VT = Op.getValueType();
4211 DebugLoc dl = Op.getDebugLoc();
4212 unsigned NumElems = PermMask.getNumOperands();
4213 bool isMMX = VT.getSizeInBits() == 64;
4214 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4215 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4216 bool V1IsSplat = false;
4217 bool V2IsSplat = false;
4219 // FIXME: Check for legal shuffle and return?
4221 if (isUndefShuffle(Op.getNode()))
4222 return DAG.getUNDEF(VT);
4224 if (isZeroShuffle(Op.getNode()))
4225 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4227 if (isIdentityMask(PermMask.getNode()))
4229 else if (isIdentityMask(PermMask.getNode(), true))
4232 // Canonicalize movddup shuffles.
4233 if (V2IsUndef && Subtarget->hasSSE2() &&
4234 VT.getSizeInBits() == 128 &&
4235 X86::isMOVDDUPMask(PermMask.getNode()))
4236 return CanonicalizeMovddup(Op, V1, PermMask, DAG, Subtarget->hasSSE3());
4238 if (isSplatMask(PermMask.getNode())) {
4239 if (isMMX || NumElems < 4) return Op;
4240 // Promote it to a v4{if}32 splat.
4241 return PromoteSplat(Op, DAG, Subtarget->hasSSE2());
4244 // If the shuffle can be profitably rewritten as a narrower shuffle, then
4246 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4247 SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG,
4249 if (NewOp.getNode())
4250 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4251 LowerVECTOR_SHUFFLE(NewOp, DAG));
4252 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4253 // FIXME: Figure out a cleaner way to do this.
4254 // Try to make use of movq to zero out the top part.
4255 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4256 SDValue NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
4258 if (NewOp.getNode()) {
4259 SDValue NewV1 = NewOp.getOperand(0);
4260 SDValue NewV2 = NewOp.getOperand(1);
4261 SDValue NewMask = NewOp.getOperand(2);
4262 if (isCommutedMOVL(NewMask.getNode(), true, false)) {
4263 NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
4264 return getVZextMovL(VT, NewOp.getValueType(), NewV2, DAG, Subtarget,
4268 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4269 SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
4271 if (NewOp.getNode() && X86::isMOVLMask(NewOp.getOperand(2).getNode()))
4272 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4273 DAG, Subtarget, dl);
4277 // Check if this can be converted into a logical shift.
4278 bool isLeft = false;
4281 bool isShift = isVectorShift(Op, PermMask, DAG, isLeft, ShVal, ShAmt);
4282 if (isShift && ShVal.hasOneUse()) {
4283 // If the shifted value has multiple uses, it may be cheaper to use
4284 // v_set0 + movlhps or movhlps, etc.
4285 MVT EVT = VT.getVectorElementType();
4286 ShAmt *= EVT.getSizeInBits();
4287 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4290 if (X86::isMOVLMask(PermMask.getNode())) {
4293 if (ISD::isBuildVectorAllZeros(V1.getNode()))
4294 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4299 if (!isMMX && (X86::isMOVSHDUPMask(PermMask.getNode()) ||
4300 X86::isMOVSLDUPMask(PermMask.getNode()) ||
4301 X86::isMOVHLPSMask(PermMask.getNode()) ||
4302 X86::isMOVHPMask(PermMask.getNode()) ||
4303 X86::isMOVLPMask(PermMask.getNode())))
4306 if (ShouldXformToMOVHLPS(PermMask.getNode()) ||
4307 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), PermMask.getNode()))
4308 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4311 // No better options. Use a vshl / vsrl.
4312 MVT EVT = VT.getVectorElementType();
4313 ShAmt *= EVT.getSizeInBits();
4314 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4317 bool Commuted = false;
4318 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4319 // 1,1,1,1 -> v8i16 though.
4320 V1IsSplat = isSplatVector(V1.getNode());
4321 V2IsSplat = isSplatVector(V2.getNode());
4323 // Canonicalize the splat or undef, if present, to be on the RHS.
4324 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4325 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4326 std::swap(V1IsSplat, V2IsSplat);
4327 std::swap(V1IsUndef, V2IsUndef);
4331 // FIXME: Figure out a cleaner way to do this.
4332 if (isCommutedMOVL(PermMask.getNode(), V2IsSplat, V2IsUndef)) {
4333 if (V2IsUndef) return V1;
4334 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4336 // V2 is a splat, so the mask may be malformed. That is, it may point
4337 // to any V2 element. The instruction selectior won't like this. Get
4338 // a corrected mask and commute to form a proper MOVS{S|D}.
4339 SDValue NewMask = getMOVLMask(NumElems, DAG, dl);
4340 if (NewMask.getNode() != PermMask.getNode())
4341 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, NewMask);
4346 if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
4347 X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
4348 X86::isUNPCKLMask(PermMask.getNode()) ||
4349 X86::isUNPCKHMask(PermMask.getNode()))
4353 // Normalize mask so all entries that point to V2 points to its first
4354 // element then try to match unpck{h|l} again. If match, return a
4355 // new vector_shuffle with the corrected mask.
4356 SDValue NewMask = NormalizeMask(PermMask, DAG);
4357 if (NewMask.getNode() != PermMask.getNode()) {
4358 if (X86::isUNPCKLMask(NewMask.getNode(), true)) {
4359 SDValue NewMask = getUnpacklMask(NumElems, DAG, dl);
4360 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, NewMask);
4361 } else if (X86::isUNPCKHMask(NewMask.getNode(), true)) {
4362 SDValue NewMask = getUnpackhMask(NumElems, DAG, dl);
4363 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, NewMask);
4368 // Normalize the node to match x86 shuffle ops if needed
4369 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.getNode()))
4370 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4373 // Commute is back and try unpck* again.
4374 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4375 if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
4376 X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
4377 X86::isUNPCKLMask(PermMask.getNode()) ||
4378 X86::isUNPCKHMask(PermMask.getNode()))
4382 // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4383 // Try PSHUF* first, then SHUFP*.
4384 // MMX doesn't have PSHUFD but it does have PSHUFW. While it's theoretically
4385 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
4386 if (isMMX && NumElems == 4 && X86::isPSHUFDMask(PermMask.getNode())) {
4387 if (V2.getOpcode() != ISD::UNDEF)
4388 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1,
4389 DAG.getUNDEF(VT), PermMask);
4394 if (Subtarget->hasSSE2() &&
4395 (X86::isPSHUFDMask(PermMask.getNode()) ||
4396 X86::isPSHUFHWMask(PermMask.getNode()) ||
4397 X86::isPSHUFLWMask(PermMask.getNode()))) {
4399 if (VT == MVT::v4f32) {
4401 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, RVT,
4402 DAG.getNode(ISD::BIT_CONVERT, dl, RVT, V1),
4403 DAG.getUNDEF(RVT), PermMask);
4404 } else if (V2.getOpcode() != ISD::UNDEF)
4405 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, RVT, V1,
4406 DAG.getUNDEF(RVT), PermMask);
4408 Op = DAG.getNode(ISD::BIT_CONVERT, dl, VT, Op);
4412 // Binary or unary shufps.
4413 if (X86::isSHUFPMask(PermMask.getNode()) ||
4414 (V2.getOpcode() == ISD::UNDEF && X86::isPSHUFDMask(PermMask.getNode())))
4418 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4419 if (VT == MVT::v8i16) {
4420 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this, dl);
4421 if (NewOp.getNode())
4425 if (VT == MVT::v16i8) {
4426 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(V1, V2, PermMask, DAG, *this, dl);
4427 if (NewOp.getNode())
4431 // Handle all 4 wide cases with a number of shuffles except for MMX.
4432 if (NumElems == 4 && !isMMX)
4433 return LowerVECTOR_SHUFFLE_4wide(V1, V2, PermMask, VT, DAG, dl);
4439 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4440 SelectionDAG &DAG) {
4441 MVT VT = Op.getValueType();
4442 DebugLoc dl = Op.getDebugLoc();
4443 if (VT.getSizeInBits() == 8) {
4444 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4445 Op.getOperand(0), Op.getOperand(1));
4446 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4447 DAG.getValueType(VT));
4448 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4449 } else if (VT.getSizeInBits() == 16) {
4450 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4451 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4453 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4454 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4455 DAG.getNode(ISD::BIT_CONVERT, dl,
4459 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4460 Op.getOperand(0), Op.getOperand(1));
4461 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4462 DAG.getValueType(VT));
4463 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4464 } else if (VT == MVT::f32) {
4465 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4466 // the result back to FR32 register. It's only worth matching if the
4467 // result has a single use which is a store or a bitcast to i32. And in
4468 // the case of a store, it's not worth it if the index is a constant 0,
4469 // because a MOVSSmr can be used instead, which is smaller and faster.
4470 if (!Op.hasOneUse())
4472 SDNode *User = *Op.getNode()->use_begin();
4473 if ((User->getOpcode() != ISD::STORE ||
4474 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4475 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4476 (User->getOpcode() != ISD::BIT_CONVERT ||
4477 User->getValueType(0) != MVT::i32))
4479 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4480 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4483 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4484 } else if (VT == MVT::i32) {
4485 // ExtractPS works with constant index.
4486 if (isa<ConstantSDNode>(Op.getOperand(1)))
4494 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4495 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4498 if (Subtarget->hasSSE41()) {
4499 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4504 MVT VT = Op.getValueType();
4505 DebugLoc dl = Op.getDebugLoc();
4506 // TODO: handle v16i8.
4507 if (VT.getSizeInBits() == 16) {
4508 SDValue Vec = Op.getOperand(0);
4509 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4511 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4512 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4513 DAG.getNode(ISD::BIT_CONVERT, dl,
4516 // Transform it so it match pextrw which produces a 32-bit result.
4517 MVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT()+1);
4518 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EVT,
4519 Op.getOperand(0), Op.getOperand(1));
4520 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EVT, Extract,
4521 DAG.getValueType(VT));
4522 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4523 } else if (VT.getSizeInBits() == 32) {
4524 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4527 // SHUFPS the element to the lowest double word, then movss.
4528 MVT MaskVT = MVT::getIntVectorWithNumElements(4);
4529 SmallVector<SDValue, 8> IdxVec;
4531 push_back(DAG.getConstant(Idx, MaskVT.getVectorElementType()));
4533 push_back(DAG.getUNDEF(MaskVT.getVectorElementType()));
4535 push_back(DAG.getUNDEF(MaskVT.getVectorElementType()));
4537 push_back(DAG.getUNDEF(MaskVT.getVectorElementType()));
4538 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4539 &IdxVec[0], IdxVec.size());
4540 SDValue Vec = Op.getOperand(0);
4541 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, Vec.getValueType(),
4542 Vec, DAG.getUNDEF(Vec.getValueType()), Mask);
4543 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4544 DAG.getIntPtrConstant(0));
4545 } else if (VT.getSizeInBits() == 64) {
4546 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4547 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4548 // to match extract_elt for f64.
4549 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4553 // UNPCKHPD the element to the lowest double word, then movsd.
4554 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4555 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4556 MVT MaskVT = MVT::getIntVectorWithNumElements(2);
4557 SmallVector<SDValue, 8> IdxVec;
4558 IdxVec.push_back(DAG.getConstant(1, MaskVT.getVectorElementType()));
4560 push_back(DAG.getUNDEF(MaskVT.getVectorElementType()));
4561 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4562 &IdxVec[0], IdxVec.size());
4563 SDValue Vec = Op.getOperand(0);
4564 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, Vec.getValueType(),
4565 Vec, DAG.getUNDEF(Vec.getValueType()),
4567 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4568 DAG.getIntPtrConstant(0));
4575 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4576 MVT VT = Op.getValueType();
4577 MVT EVT = VT.getVectorElementType();
4578 DebugLoc dl = Op.getDebugLoc();
4580 SDValue N0 = Op.getOperand(0);
4581 SDValue N1 = Op.getOperand(1);
4582 SDValue N2 = Op.getOperand(2);
4584 if ((EVT.getSizeInBits() == 8 || EVT.getSizeInBits() == 16) &&
4585 isa<ConstantSDNode>(N2)) {
4586 unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4588 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4590 if (N1.getValueType() != MVT::i32)
4591 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4592 if (N2.getValueType() != MVT::i32)
4593 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4594 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4595 } else if (EVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4596 // Bits [7:6] of the constant are the source select. This will always be
4597 // zero here. The DAG Combiner may combine an extract_elt index into these
4598 // bits. For example (insert (extract, 3), 2) could be matched by putting
4599 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4600 // Bits [5:4] of the constant are the destination select. This is the
4601 // value of the incoming immediate.
4602 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4603 // combine either bitwise AND or insert of float 0.0 to set these bits.
4604 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4605 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4606 } else if (EVT == MVT::i32) {
4607 // InsertPS works with constant index.
4608 if (isa<ConstantSDNode>(N2))
4615 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4616 MVT VT = Op.getValueType();
4617 MVT EVT = VT.getVectorElementType();
4619 if (Subtarget->hasSSE41())
4620 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4625 DebugLoc dl = Op.getDebugLoc();
4626 SDValue N0 = Op.getOperand(0);
4627 SDValue N1 = Op.getOperand(1);
4628 SDValue N2 = Op.getOperand(2);
4630 if (EVT.getSizeInBits() == 16) {
4631 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4632 // as its second argument.
4633 if (N1.getValueType() != MVT::i32)
4634 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4635 if (N2.getValueType() != MVT::i32)
4636 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4637 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
4643 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4644 DebugLoc dl = Op.getDebugLoc();
4645 if (Op.getValueType() == MVT::v2f32)
4646 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4647 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4648 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4649 Op.getOperand(0))));
4651 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4652 MVT VT = MVT::v2i32;
4653 switch (Op.getValueType().getSimpleVT()) {
4660 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4661 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4664 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4665 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4666 // one of the above mentioned nodes. It has to be wrapped because otherwise
4667 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4668 // be used to form addressing mode. These wrapped nodes will be selected
4671 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4672 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4673 // FIXME there isn't really any debug info here, should come from the parent
4674 DebugLoc dl = CP->getDebugLoc();
4675 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(),
4677 CP->getAlignment());
4678 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4679 // With PIC, the address is actually $g + Offset.
4680 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4681 !Subtarget->isPICStyleRIPRel()) {
4682 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4683 DAG.getNode(X86ISD::GlobalBaseReg,
4684 DebugLoc::getUnknownLoc(),
4693 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
4695 SelectionDAG &DAG) const {
4696 bool IsPic = getTargetMachine().getRelocationModel() == Reloc::PIC_;
4697 bool ExtraLoadRequired =
4698 Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false);
4700 // Create the TargetGlobalAddress node, folding in the constant
4701 // offset if it is legal.
4703 if (!IsPic && !ExtraLoadRequired && isInt32(Offset)) {
4704 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4707 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0);
4708 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4710 // With PIC, the address is actually $g + Offset.
4711 if (IsPic && !Subtarget->isPICStyleRIPRel()) {
4712 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4713 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4717 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4718 // load the value at address GV, not the value of GV itself. This means that
4719 // the GlobalAddress must be in the base or index register of the address, not
4720 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4721 // The same applies for external symbols during PIC codegen
4722 if (ExtraLoadRequired)
4723 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
4724 PseudoSourceValue::getGOT(), 0);
4726 // If there was a non-zero offset that we didn't fold, create an explicit
4729 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
4730 DAG.getConstant(Offset, getPointerTy()));
4736 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4737 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4738 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4739 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
4742 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4744 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4747 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
4748 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
4749 DAG.getNode(X86ISD::GlobalBaseReg,
4750 DebugLoc::getUnknownLoc(),
4752 InFlag = Chain.getValue(1);
4754 // emit leal symbol@TLSGD(,%ebx,1), %eax
4755 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4756 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4757 GA->getValueType(0),
4759 SDValue Ops[] = { Chain, TGA, InFlag };
4760 SDValue Result = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
4761 InFlag = Result.getValue(2);
4762 Chain = Result.getValue(1);
4764 // call ___tls_get_addr. This function receives its argument in
4765 // the register EAX.
4766 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Result, InFlag);
4767 InFlag = Chain.getValue(1);
4769 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4770 SDValue Ops1[] = { Chain,
4771 DAG.getTargetExternalSymbol("___tls_get_addr",
4773 DAG.getRegister(X86::EAX, PtrVT),
4774 DAG.getRegister(X86::EBX, PtrVT),
4776 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops1, 5);
4777 InFlag = Chain.getValue(1);
4779 return DAG.getCopyFromReg(Chain, dl, X86::EAX, PtrVT, InFlag);
4782 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4784 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4786 SDValue InFlag, Chain;
4787 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
4789 // emit leaq symbol@TLSGD(%rip), %rdi
4790 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4791 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4792 GA->getValueType(0),
4794 SDValue Ops[] = { DAG.getEntryNode(), TGA};
4795 SDValue Result = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
4796 Chain = Result.getValue(1);
4797 InFlag = Result.getValue(2);
4799 // call __tls_get_addr. This function receives its argument in
4800 // the register RDI.
4801 Chain = DAG.getCopyToReg(Chain, dl, X86::RDI, Result, InFlag);
4802 InFlag = Chain.getValue(1);
4804 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4805 SDValue Ops1[] = { Chain,
4806 DAG.getTargetExternalSymbol("__tls_get_addr",
4808 DAG.getRegister(X86::RDI, PtrVT),
4810 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops1, 4);
4811 InFlag = Chain.getValue(1);
4813 return DAG.getCopyFromReg(Chain, dl, X86::RAX, PtrVT, InFlag);
4816 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4817 // "local exec" model.
4818 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4819 const MVT PtrVT, TLSModel::Model model) {
4820 DebugLoc dl = GA->getDebugLoc();
4821 // Get the Thread Pointer
4822 SDValue ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER,
4823 DebugLoc::getUnknownLoc(), PtrVT);
4824 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4826 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4827 GA->getValueType(0),
4829 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
4831 if (model == TLSModel::InitialExec)
4832 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
4833 PseudoSourceValue::getGOT(), 0);
4835 // The address of the thread local variable is the add of the thread
4836 // pointer with the offset of the variable.
4837 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
4841 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4842 // TODO: implement the "local dynamic" model
4843 // TODO: implement the "initial exec"model for pic executables
4844 assert(Subtarget->isTargetELF() &&
4845 "TLS not implemented for non-ELF targets");
4846 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4847 GlobalValue *GV = GA->getGlobal();
4848 TLSModel::Model model =
4849 getTLSModel (GV, getTargetMachine().getRelocationModel());
4850 if (Subtarget->is64Bit()) {
4852 case TLSModel::GeneralDynamic:
4853 case TLSModel::LocalDynamic: // not implemented
4854 case TLSModel::InitialExec: // not implemented
4855 case TLSModel::LocalExec: // not implemented
4856 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4858 assert (0 && "Unknown TLS model");
4862 case TLSModel::GeneralDynamic:
4863 case TLSModel::LocalDynamic: // not implemented
4864 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4866 case TLSModel::InitialExec:
4867 case TLSModel::LocalExec:
4868 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model);
4870 assert (0 && "Unknown TLS model");
4876 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4877 // FIXME there isn't really any debug info here
4878 DebugLoc dl = Op.getDebugLoc();
4879 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4880 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4881 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4882 // With PIC, the address is actually $g + Offset.
4883 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4884 !Subtarget->isPICStyleRIPRel()) {
4885 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4886 DAG.getNode(X86ISD::GlobalBaseReg,
4887 DebugLoc::getUnknownLoc(),
4895 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4896 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4897 // FIXME there isn't really any debug into here
4898 DebugLoc dl = JT->getDebugLoc();
4899 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4900 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4901 // With PIC, the address is actually $g + Offset.
4902 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4903 !Subtarget->isPICStyleRIPRel()) {
4904 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4905 DAG.getNode(X86ISD::GlobalBaseReg,
4906 DebugLoc::getUnknownLoc(),
4914 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4915 /// take a 2 x i32 value to shift plus a shift amount.
4916 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4917 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4918 MVT VT = Op.getValueType();
4919 unsigned VTBits = VT.getSizeInBits();
4920 DebugLoc dl = Op.getDebugLoc();
4921 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4922 SDValue ShOpLo = Op.getOperand(0);
4923 SDValue ShOpHi = Op.getOperand(1);
4924 SDValue ShAmt = Op.getOperand(2);
4925 SDValue Tmp1 = isSRA ?
4926 DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
4927 DAG.getConstant(VTBits - 1, MVT::i8)) :
4928 DAG.getConstant(0, VT);
4931 if (Op.getOpcode() == ISD::SHL_PARTS) {
4932 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
4933 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4935 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
4936 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
4939 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
4940 DAG.getConstant(VTBits, MVT::i8));
4941 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, VT,
4942 AndNode, DAG.getConstant(0, MVT::i8));
4945 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4946 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4947 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4949 if (Op.getOpcode() == ISD::SHL_PARTS) {
4950 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4951 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4953 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4954 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4957 SDValue Ops[2] = { Lo, Hi };
4958 return DAG.getMergeValues(Ops, 2, dl);
4961 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4962 MVT SrcVT = Op.getOperand(0).getValueType();
4963 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4964 "Unknown SINT_TO_FP to lower!");
4966 // These are really Legal; caller falls through into that case.
4967 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4969 if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 &&
4970 Subtarget->is64Bit())
4973 DebugLoc dl = Op.getDebugLoc();
4974 unsigned Size = SrcVT.getSizeInBits()/8;
4975 MachineFunction &MF = DAG.getMachineFunction();
4976 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4977 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4978 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
4980 PseudoSourceValue::getFixedStack(SSFI), 0);
4984 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4986 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4988 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4989 SmallVector<SDValue, 8> Ops;
4990 Ops.push_back(Chain);
4991 Ops.push_back(StackSlot);
4992 Ops.push_back(DAG.getValueType(SrcVT));
4993 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
4994 Tys, &Ops[0], Ops.size());
4997 Chain = Result.getValue(1);
4998 SDValue InFlag = Result.getValue(2);
5000 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5001 // shouldn't be necessary except that RFP cannot be live across
5002 // multiple blocks. When stackifier is fixed, they can be uncoupled.
5003 MachineFunction &MF = DAG.getMachineFunction();
5004 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
5005 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5006 Tys = DAG.getVTList(MVT::Other);
5007 SmallVector<SDValue, 8> Ops;
5008 Ops.push_back(Chain);
5009 Ops.push_back(Result);
5010 Ops.push_back(StackSlot);
5011 Ops.push_back(DAG.getValueType(Op.getValueType()));
5012 Ops.push_back(InFlag);
5013 Chain = DAG.getNode(X86ISD::FST, dl, Tys, &Ops[0], Ops.size());
5014 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5015 PseudoSourceValue::getFixedStack(SSFI), 0);
5021 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5022 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
5023 // This algorithm is not obvious. Here it is in C code, more or less:
5025 double uint64_to_double( uint32_t hi, uint32_t lo ) {
5026 static const __m128i exp = { 0x4330000045300000ULL, 0 };
5027 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5029 // Copy ints to xmm registers.
5030 __m128i xh = _mm_cvtsi32_si128( hi );
5031 __m128i xl = _mm_cvtsi32_si128( lo );
5033 // Combine into low half of a single xmm register.
5034 __m128i x = _mm_unpacklo_epi32( xh, xl );
5038 // Merge in appropriate exponents to give the integer bits the right
5040 x = _mm_unpacklo_epi32( x, exp );
5042 // Subtract away the biases to deal with the IEEE-754 double precision
5044 d = _mm_sub_pd( (__m128d) x, bias );
5046 // All conversions up to here are exact. The correctly rounded result is
5047 // calculated using the current rounding mode using the following
5049 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5050 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
5051 // store doesn't really need to be here (except
5052 // maybe to zero the other double)
5057 DebugLoc dl = Op.getDebugLoc();
5059 // Build some magic constants.
5060 std::vector<Constant*> CV0;
5061 CV0.push_back(ConstantInt::get(APInt(32, 0x45300000)));
5062 CV0.push_back(ConstantInt::get(APInt(32, 0x43300000)));
5063 CV0.push_back(ConstantInt::get(APInt(32, 0)));
5064 CV0.push_back(ConstantInt::get(APInt(32, 0)));
5065 Constant *C0 = ConstantVector::get(CV0);
5066 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 4);
5068 std::vector<Constant*> CV1;
5069 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4530000000000000ULL))));
5070 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4330000000000000ULL))));
5071 Constant *C1 = ConstantVector::get(CV1);
5072 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 4);
5074 SmallVector<SDValue, 4> MaskVec;
5075 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
5076 MaskVec.push_back(DAG.getConstant(4, MVT::i32));
5077 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
5078 MaskVec.push_back(DAG.getConstant(5, MVT::i32));
5079 SDValue UnpcklMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
5080 &MaskVec[0], MaskVec.size());
5081 SmallVector<SDValue, 4> MaskVec2;
5082 MaskVec2.push_back(DAG.getConstant(1, MVT::i32));
5083 MaskVec2.push_back(DAG.getConstant(0, MVT::i32));
5084 SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32,
5085 &MaskVec2[0], MaskVec2.size());
5087 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5088 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5090 DAG.getIntPtrConstant(1)));
5091 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5092 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5094 DAG.getIntPtrConstant(0)));
5095 SDValue Unpck1 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v4i32,
5096 XR1, XR2, UnpcklMask);
5097 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5098 PseudoSourceValue::getConstantPool(), 0,
5100 SDValue Unpck2 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v4i32,
5101 Unpck1, CLod0, UnpcklMask);
5102 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5103 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5104 PseudoSourceValue::getConstantPool(), 0,
5106 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5108 // Add the halves; easiest way is to swap them into another reg first.
5109 SDValue Shuf = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v2f64,
5110 Sub, Sub, ShufMask);
5111 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5112 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5113 DAG.getIntPtrConstant(0));
5116 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5117 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
5118 DebugLoc dl = Op.getDebugLoc();
5119 // FP constant to bias correct the final result.
5120 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5123 // Load the 32-bit value into an XMM register.
5124 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5125 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5127 DAG.getIntPtrConstant(0)));
5129 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5130 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5131 DAG.getIntPtrConstant(0));
5133 // Or the load with the bias.
5134 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5135 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5136 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5138 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5139 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5140 MVT::v2f64, Bias)));
5141 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5142 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5143 DAG.getIntPtrConstant(0));
5145 // Subtract the bias.
5146 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5148 // Handle final rounding.
5149 MVT DestVT = Op.getValueType();
5151 if (DestVT.bitsLT(MVT::f64)) {
5152 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5153 DAG.getIntPtrConstant(0));
5154 } else if (DestVT.bitsGT(MVT::f64)) {
5155 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5158 // Handle final rounding.
5162 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5163 SDValue N0 = Op.getOperand(0);
5164 DebugLoc dl = Op.getDebugLoc();
5166 // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
5167 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5168 // the optimization here.
5169 if (DAG.SignBitIsZero(N0))
5170 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5172 MVT SrcVT = N0.getValueType();
5173 if (SrcVT == MVT::i64) {
5174 // We only handle SSE2 f64 target here; caller can handle the rest.
5175 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
5178 return LowerUINT_TO_FP_i64(Op, DAG);
5179 } else if (SrcVT == MVT::i32) {
5180 return LowerUINT_TO_FP_i32(Op, DAG);
5183 assert(0 && "Unknown UINT_TO_FP to lower!");
5187 std::pair<SDValue,SDValue> X86TargetLowering::
5188 FP_TO_SINTHelper(SDValue Op, SelectionDAG &DAG) {
5189 DebugLoc dl = Op.getDebugLoc();
5190 assert(Op.getValueType().getSimpleVT() <= MVT::i64 &&
5191 Op.getValueType().getSimpleVT() >= MVT::i16 &&
5192 "Unknown FP_TO_SINT to lower!");
5194 // These are really Legal.
5195 if (Op.getValueType() == MVT::i32 &&
5196 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5197 return std::make_pair(SDValue(), SDValue());
5198 if (Subtarget->is64Bit() &&
5199 Op.getValueType() == MVT::i64 &&
5200 Op.getOperand(0).getValueType() != MVT::f80)
5201 return std::make_pair(SDValue(), SDValue());
5203 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5205 MachineFunction &MF = DAG.getMachineFunction();
5206 unsigned MemSize = Op.getValueType().getSizeInBits()/8;
5207 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
5208 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5210 switch (Op.getValueType().getSimpleVT()) {
5211 default: assert(0 && "Invalid FP_TO_SINT to lower!");
5212 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5213 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5214 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5217 SDValue Chain = DAG.getEntryNode();
5218 SDValue Value = Op.getOperand(0);
5219 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5220 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5221 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5222 PseudoSourceValue::getFixedStack(SSFI), 0);
5223 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5225 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5227 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5228 Chain = Value.getValue(1);
5229 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
5230 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5233 // Build the FP_TO_INT*_IN_MEM
5234 SDValue Ops[] = { Chain, Value, StackSlot };
5235 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5237 return std::make_pair(FIST, StackSlot);
5240 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
5241 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(Op, DAG);
5242 SDValue FIST = Vals.first, StackSlot = Vals.second;
5243 if (FIST.getNode() == 0) return SDValue();
5246 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5247 FIST, StackSlot, NULL, 0);
5250 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
5251 DebugLoc dl = Op.getDebugLoc();
5252 MVT VT = Op.getValueType();
5255 EltVT = VT.getVectorElementType();
5256 std::vector<Constant*> CV;
5257 if (EltVT == MVT::f64) {
5258 Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
5262 Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
5268 Constant *C = ConstantVector::get(CV);
5269 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
5270 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5271 PseudoSourceValue::getConstantPool(), 0,
5273 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5276 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
5277 DebugLoc dl = Op.getDebugLoc();
5278 MVT VT = Op.getValueType();
5280 unsigned EltNum = 1;
5281 if (VT.isVector()) {
5282 EltVT = VT.getVectorElementType();
5283 EltNum = VT.getVectorNumElements();
5285 std::vector<Constant*> CV;
5286 if (EltVT == MVT::f64) {
5287 Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
5291 Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
5297 Constant *C = ConstantVector::get(CV);
5298 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
5299 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5300 PseudoSourceValue::getConstantPool(), 0,
5302 if (VT.isVector()) {
5303 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5304 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5305 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5307 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5309 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5313 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5314 SDValue Op0 = Op.getOperand(0);
5315 SDValue Op1 = Op.getOperand(1);
5316 DebugLoc dl = Op.getDebugLoc();
5317 MVT VT = Op.getValueType();
5318 MVT SrcVT = Op1.getValueType();
5320 // If second operand is smaller, extend it first.
5321 if (SrcVT.bitsLT(VT)) {
5322 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5325 // And if it is bigger, shrink it first.
5326 if (SrcVT.bitsGT(VT)) {
5327 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5331 // At this point the operands and the result should have the same
5332 // type, and that won't be f80 since that is not custom lowered.
5334 // First get the sign bit of second operand.
5335 std::vector<Constant*> CV;
5336 if (SrcVT == MVT::f64) {
5337 CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
5338 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
5340 CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
5341 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5342 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5343 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5345 Constant *C = ConstantVector::get(CV);
5346 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
5347 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5348 PseudoSourceValue::getConstantPool(), 0,
5350 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5352 // Shift sign bit right or left if the two operands have different types.
5353 if (SrcVT.bitsGT(VT)) {
5354 // Op0 is MVT::f32, Op1 is MVT::f64.
5355 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5356 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5357 DAG.getConstant(32, MVT::i32));
5358 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5359 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5360 DAG.getIntPtrConstant(0));
5363 // Clear first operand sign bit.
5365 if (VT == MVT::f64) {
5366 CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
5367 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
5369 CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
5370 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5371 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5372 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5374 C = ConstantVector::get(CV);
5375 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
5376 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5377 PseudoSourceValue::getConstantPool(), 0,
5379 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5381 // Or the value with the sign bit.
5382 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5385 /// Emit nodes that will be selected as "test Op0,Op0", or something
5387 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5388 SelectionDAG &DAG) {
5389 DebugLoc dl = Op.getDebugLoc();
5391 // CF and OF aren't always set the way we want. Determine which
5392 // of these we need.
5393 bool NeedCF = false;
5394 bool NeedOF = false;
5396 case X86::COND_A: case X86::COND_AE:
5397 case X86::COND_B: case X86::COND_BE:
5400 case X86::COND_G: case X86::COND_GE:
5401 case X86::COND_L: case X86::COND_LE:
5402 case X86::COND_O: case X86::COND_NO:
5408 // See if we can use the EFLAGS value from the operand instead of
5409 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5410 // we prove that the arithmetic won't overflow, we can't use OF or CF.
5411 if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5412 unsigned Opcode = 0;
5413 unsigned NumOperands = 0;
5414 switch (Op.getNode()->getOpcode()) {
5416 // Due to an isel shortcoming, be conservative if this add is likely to
5417 // be selected as part of a load-modify-store instruction. When the root
5418 // node in a match is a store, isel doesn't know how to remap non-chain
5419 // non-flag uses of other nodes in the match, such as the ADD in this
5420 // case. This leads to the ADD being left around and reselected, with
5421 // the result being two adds in the output.
5422 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5423 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5424 if (UI->getOpcode() == ISD::STORE)
5426 if (ConstantSDNode *C =
5427 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5428 // An add of one will be selected as an INC.
5429 if (C->getAPIntValue() == 1) {
5430 Opcode = X86ISD::INC;
5434 // An add of negative one (subtract of one) will be selected as a DEC.
5435 if (C->getAPIntValue().isAllOnesValue()) {
5436 Opcode = X86ISD::DEC;
5441 // Otherwise use a regular EFLAGS-setting add.
5442 Opcode = X86ISD::ADD;
5446 // Due to the ISEL shortcoming noted above, be conservative if this sub is
5447 // likely to be selected as part of a load-modify-store instruction.
5448 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5449 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5450 if (UI->getOpcode() == ISD::STORE)
5452 // Otherwise use a regular EFLAGS-setting sub.
5453 Opcode = X86ISD::SUB;
5460 return SDValue(Op.getNode(), 1);
5466 const MVT *VTs = DAG.getNodeValueTypes(Op.getValueType(), MVT::i32);
5467 SmallVector<SDValue, 4> Ops;
5468 for (unsigned i = 0; i != NumOperands; ++i)
5469 Ops.push_back(Op.getOperand(i));
5470 SDValue New = DAG.getNode(Opcode, dl, VTs, 2, &Ops[0], NumOperands);
5471 DAG.ReplaceAllUsesWith(Op, New);
5472 return SDValue(New.getNode(), 1);
5476 // Otherwise just emit a CMP with 0, which is the TEST pattern.
5477 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5478 DAG.getConstant(0, Op.getValueType()));
5481 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
5483 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5484 SelectionDAG &DAG) {
5485 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5486 if (C->getAPIntValue() == 0)
5487 return EmitTest(Op0, X86CC, DAG);
5489 DebugLoc dl = Op0.getDebugLoc();
5490 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5493 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5494 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5495 SDValue Op0 = Op.getOperand(0);
5496 SDValue Op1 = Op.getOperand(1);
5497 DebugLoc dl = Op.getDebugLoc();
5498 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5500 // Lower (X & (1 << N)) == 0 to BT(X, N).
5501 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5502 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5503 if (Op0.getOpcode() == ISD::AND &&
5505 Op1.getOpcode() == ISD::Constant &&
5506 cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5507 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5509 if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
5510 if (ConstantSDNode *Op010C =
5511 dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
5512 if (Op010C->getZExtValue() == 1) {
5513 LHS = Op0.getOperand(0);
5514 RHS = Op0.getOperand(1).getOperand(1);
5516 } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
5517 if (ConstantSDNode *Op000C =
5518 dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
5519 if (Op000C->getZExtValue() == 1) {
5520 LHS = Op0.getOperand(1);
5521 RHS = Op0.getOperand(0).getOperand(1);
5523 } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
5524 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5525 SDValue AndLHS = Op0.getOperand(0);
5526 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5527 LHS = AndLHS.getOperand(0);
5528 RHS = AndLHS.getOperand(1);
5532 if (LHS.getNode()) {
5533 // If LHS is i8, promote it to i16 with any_extend. There is no i8 BT
5534 // instruction. Since the shift amount is in-range-or-undefined, we know
5535 // that doing a bittest on the i16 value is ok. We extend to i32 because
5536 // the encoding for the i16 version is larger than the i32 version.
5537 if (LHS.getValueType() == MVT::i8)
5538 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5540 // If the operand types disagree, extend the shift amount to match. Since
5541 // BT ignores high bits (like shifts) we can use anyextend.
5542 if (LHS.getValueType() != RHS.getValueType())
5543 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5545 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5546 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5547 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5548 DAG.getConstant(Cond, MVT::i8), BT);
5552 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5553 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5555 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
5556 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5557 DAG.getConstant(X86CC, MVT::i8), Cond);
5560 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5562 SDValue Op0 = Op.getOperand(0);
5563 SDValue Op1 = Op.getOperand(1);
5564 SDValue CC = Op.getOperand(2);
5565 MVT VT = Op.getValueType();
5566 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5567 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5568 DebugLoc dl = Op.getDebugLoc();
5572 MVT VT0 = Op0.getValueType();
5573 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5574 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5577 switch (SetCCOpcode) {
5580 case ISD::SETEQ: SSECC = 0; break;
5582 case ISD::SETGT: Swap = true; // Fallthrough
5584 case ISD::SETOLT: SSECC = 1; break;
5586 case ISD::SETGE: Swap = true; // Fallthrough
5588 case ISD::SETOLE: SSECC = 2; break;
5589 case ISD::SETUO: SSECC = 3; break;
5591 case ISD::SETNE: SSECC = 4; break;
5592 case ISD::SETULE: Swap = true;
5593 case ISD::SETUGE: SSECC = 5; break;
5594 case ISD::SETULT: Swap = true;
5595 case ISD::SETUGT: SSECC = 6; break;
5596 case ISD::SETO: SSECC = 7; break;
5599 std::swap(Op0, Op1);
5601 // In the two special cases we can't handle, emit two comparisons.
5603 if (SetCCOpcode == ISD::SETUEQ) {
5605 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5606 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5607 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
5609 else if (SetCCOpcode == ISD::SETONE) {
5611 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5612 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5613 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
5615 assert(0 && "Illegal FP comparison");
5617 // Handle all other FP comparisons here.
5618 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5621 // We are handling one of the integer comparisons here. Since SSE only has
5622 // GT and EQ comparisons for integer, swapping operands and multiple
5623 // operations may be required for some comparisons.
5624 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5625 bool Swap = false, Invert = false, FlipSigns = false;
5627 switch (VT.getSimpleVT()) {
5629 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5630 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5631 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5632 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5635 switch (SetCCOpcode) {
5637 case ISD::SETNE: Invert = true;
5638 case ISD::SETEQ: Opc = EQOpc; break;
5639 case ISD::SETLT: Swap = true;
5640 case ISD::SETGT: Opc = GTOpc; break;
5641 case ISD::SETGE: Swap = true;
5642 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
5643 case ISD::SETULT: Swap = true;
5644 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5645 case ISD::SETUGE: Swap = true;
5646 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5649 std::swap(Op0, Op1);
5651 // Since SSE has no unsigned integer comparisons, we need to flip the sign
5652 // bits of the inputs before performing those operations.
5654 MVT EltVT = VT.getVectorElementType();
5655 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
5657 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5658 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
5660 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
5661 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
5664 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
5666 // If the logical-not of the result is required, perform that now.
5668 Result = DAG.getNOT(dl, Result, VT);
5673 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5674 static bool isX86LogicalCmp(SDValue Op) {
5675 unsigned Opc = Op.getNode()->getOpcode();
5676 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
5678 if (Op.getResNo() == 1 &&
5679 (Opc == X86ISD::ADD ||
5680 Opc == X86ISD::SUB ||
5681 Opc == X86ISD::SMUL ||
5682 Opc == X86ISD::UMUL ||
5683 Opc == X86ISD::INC ||
5684 Opc == X86ISD::DEC))
5690 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5691 bool addTest = true;
5692 SDValue Cond = Op.getOperand(0);
5693 DebugLoc dl = Op.getDebugLoc();
5696 if (Cond.getOpcode() == ISD::SETCC)
5697 Cond = LowerSETCC(Cond, DAG);
5699 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5700 // setting operand in place of the X86ISD::SETCC.
5701 if (Cond.getOpcode() == X86ISD::SETCC) {
5702 CC = Cond.getOperand(0);
5704 SDValue Cmp = Cond.getOperand(1);
5705 unsigned Opc = Cmp.getOpcode();
5706 MVT VT = Op.getValueType();
5708 bool IllegalFPCMov = false;
5709 if (VT.isFloatingPoint() && !VT.isVector() &&
5710 !isScalarFPTypeInSSEReg(VT)) // FPStack?
5711 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
5713 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) || Opc == X86ISD::BT) { // FIXME
5720 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5721 Cond = EmitTest(Cond, X86::COND_NE, DAG);
5724 const MVT *VTs = DAG.getNodeValueTypes(Op.getValueType(),
5726 SmallVector<SDValue, 4> Ops;
5727 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
5728 // condition is true.
5729 Ops.push_back(Op.getOperand(2));
5730 Ops.push_back(Op.getOperand(1));
5732 Ops.push_back(Cond);
5733 return DAG.getNode(X86ISD::CMOV, dl, VTs, 2, &Ops[0], Ops.size());
5736 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
5737 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
5738 // from the AND / OR.
5739 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
5740 Opc = Op.getOpcode();
5741 if (Opc != ISD::OR && Opc != ISD::AND)
5743 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5744 Op.getOperand(0).hasOneUse() &&
5745 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
5746 Op.getOperand(1).hasOneUse());
5749 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
5750 // 1 and that the SETCC node has a single use.
5751 static bool isXor1OfSetCC(SDValue Op) {
5752 if (Op.getOpcode() != ISD::XOR)
5754 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5755 if (N1C && N1C->getAPIntValue() == 1) {
5756 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5757 Op.getOperand(0).hasOneUse();
5762 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
5763 bool addTest = true;
5764 SDValue Chain = Op.getOperand(0);
5765 SDValue Cond = Op.getOperand(1);
5766 SDValue Dest = Op.getOperand(2);
5767 DebugLoc dl = Op.getDebugLoc();
5770 if (Cond.getOpcode() == ISD::SETCC)
5771 Cond = LowerSETCC(Cond, DAG);
5773 // FIXME: LowerXALUO doesn't handle these!!
5774 else if (Cond.getOpcode() == X86ISD::ADD ||
5775 Cond.getOpcode() == X86ISD::SUB ||
5776 Cond.getOpcode() == X86ISD::SMUL ||
5777 Cond.getOpcode() == X86ISD::UMUL)
5778 Cond = LowerXALUO(Cond, DAG);
5781 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5782 // setting operand in place of the X86ISD::SETCC.
5783 if (Cond.getOpcode() == X86ISD::SETCC) {
5784 CC = Cond.getOperand(0);
5786 SDValue Cmp = Cond.getOperand(1);
5787 unsigned Opc = Cmp.getOpcode();
5788 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
5789 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
5793 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
5797 // These can only come from an arithmetic instruction with overflow,
5798 // e.g. SADDO, UADDO.
5799 Cond = Cond.getNode()->getOperand(1);
5806 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
5807 SDValue Cmp = Cond.getOperand(0).getOperand(1);
5808 if (CondOpc == ISD::OR) {
5809 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
5810 // two branches instead of an explicit OR instruction with a
5812 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5813 isX86LogicalCmp(Cmp)) {
5814 CC = Cond.getOperand(0).getOperand(0);
5815 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5816 Chain, Dest, CC, Cmp);
5817 CC = Cond.getOperand(1).getOperand(0);
5821 } else { // ISD::AND
5822 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
5823 // two branches instead of an explicit AND instruction with a
5824 // separate test. However, we only do this if this block doesn't
5825 // have a fall-through edge, because this requires an explicit
5826 // jmp when the condition is false.
5827 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5828 isX86LogicalCmp(Cmp) &&
5829 Op.getNode()->hasOneUse()) {
5830 X86::CondCode CCode =
5831 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5832 CCode = X86::GetOppositeBranchCondition(CCode);
5833 CC = DAG.getConstant(CCode, MVT::i8);
5834 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
5835 // Look for an unconditional branch following this conditional branch.
5836 // We need this because we need to reverse the successors in order
5837 // to implement FCMP_OEQ.
5838 if (User.getOpcode() == ISD::BR) {
5839 SDValue FalseBB = User.getOperand(1);
5841 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
5842 assert(NewBR == User);
5845 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5846 Chain, Dest, CC, Cmp);
5847 X86::CondCode CCode =
5848 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
5849 CCode = X86::GetOppositeBranchCondition(CCode);
5850 CC = DAG.getConstant(CCode, MVT::i8);
5856 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
5857 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
5858 // It should be transformed during dag combiner except when the condition
5859 // is set by a arithmetics with overflow node.
5860 X86::CondCode CCode =
5861 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5862 CCode = X86::GetOppositeBranchCondition(CCode);
5863 CC = DAG.getConstant(CCode, MVT::i8);
5864 Cond = Cond.getOperand(0).getOperand(1);
5870 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5871 Cond = EmitTest(Cond, X86::COND_NE, DAG);
5873 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5874 Chain, Dest, CC, Cond);
5878 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
5879 // Calls to _alloca is needed to probe the stack when allocating more than 4k
5880 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
5881 // that the guard pages used by the OS virtual memory manager are allocated in
5882 // correct sequence.
5884 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5885 SelectionDAG &DAG) {
5886 assert(Subtarget->isTargetCygMing() &&
5887 "This should be used only on Cygwin/Mingw targets");
5888 DebugLoc dl = Op.getDebugLoc();
5891 SDValue Chain = Op.getOperand(0);
5892 SDValue Size = Op.getOperand(1);
5893 // FIXME: Ensure alignment here
5897 MVT IntPtr = getPointerTy();
5898 MVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
5900 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
5902 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
5903 Flag = Chain.getValue(1);
5905 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5906 SDValue Ops[] = { Chain,
5907 DAG.getTargetExternalSymbol("_alloca", IntPtr),
5908 DAG.getRegister(X86::EAX, IntPtr),
5909 DAG.getRegister(X86StackPtr, SPTy),
5911 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops, 5);
5912 Flag = Chain.getValue(1);
5914 Chain = DAG.getCALLSEQ_END(Chain,
5915 DAG.getIntPtrConstant(0, true),
5916 DAG.getIntPtrConstant(0, true),
5919 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
5921 SDValue Ops1[2] = { Chain.getValue(0), Chain };
5922 return DAG.getMergeValues(Ops1, 2, dl);
5926 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
5928 SDValue Dst, SDValue Src,
5929 SDValue Size, unsigned Align,
5931 uint64_t DstSVOff) {
5932 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5934 // If not DWORD aligned or size is more than the threshold, call the library.
5935 // The libc version is likely to be faster for these cases. It can use the
5936 // address value and run time information about the CPU.
5937 if ((Align & 3) != 0 ||
5939 ConstantSize->getZExtValue() >
5940 getSubtarget()->getMaxInlineSizeThreshold()) {
5941 SDValue InFlag(0, 0);
5943 // Check to see if there is a specialized entry-point for memory zeroing.
5944 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
5946 if (const char *bzeroEntry = V &&
5947 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
5948 MVT IntPtr = getPointerTy();
5949 const Type *IntPtrTy = TD->getIntPtrType();
5950 TargetLowering::ArgListTy Args;
5951 TargetLowering::ArgListEntry Entry;
5953 Entry.Ty = IntPtrTy;
5954 Args.push_back(Entry);
5956 Args.push_back(Entry);
5957 std::pair<SDValue,SDValue> CallResult =
5958 LowerCallTo(Chain, Type::VoidTy, false, false, false, false,
5959 CallingConv::C, false,
5960 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl);
5961 return CallResult.second;
5964 // Otherwise have the target-independent code call memset.
5968 uint64_t SizeVal = ConstantSize->getZExtValue();
5969 SDValue InFlag(0, 0);
5972 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
5973 unsigned BytesLeft = 0;
5974 bool TwoRepStos = false;
5977 uint64_t Val = ValC->getZExtValue() & 255;
5979 // If the value is a constant, then we can potentially use larger sets.
5980 switch (Align & 3) {
5981 case 2: // WORD aligned
5984 Val = (Val << 8) | Val;
5986 case 0: // DWORD aligned
5989 Val = (Val << 8) | Val;
5990 Val = (Val << 16) | Val;
5991 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
5994 Val = (Val << 32) | Val;
5997 default: // Byte aligned
6000 Count = DAG.getIntPtrConstant(SizeVal);
6004 if (AVT.bitsGT(MVT::i8)) {
6005 unsigned UBytes = AVT.getSizeInBits() / 8;
6006 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
6007 BytesLeft = SizeVal % UBytes;
6010 Chain = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
6012 InFlag = Chain.getValue(1);
6015 Count = DAG.getIntPtrConstant(SizeVal);
6016 Chain = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
6017 InFlag = Chain.getValue(1);
6020 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6023 InFlag = Chain.getValue(1);
6024 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6027 InFlag = Chain.getValue(1);
6029 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6030 SmallVector<SDValue, 8> Ops;
6031 Ops.push_back(Chain);
6032 Ops.push_back(DAG.getValueType(AVT));
6033 Ops.push_back(InFlag);
6034 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
6037 InFlag = Chain.getValue(1);
6039 MVT CVT = Count.getValueType();
6040 SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
6041 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
6042 Chain = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
6045 InFlag = Chain.getValue(1);
6046 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6048 Ops.push_back(Chain);
6049 Ops.push_back(DAG.getValueType(MVT::i8));
6050 Ops.push_back(InFlag);
6051 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
6052 } else if (BytesLeft) {
6053 // Handle the last 1 - 7 bytes.
6054 unsigned Offset = SizeVal - BytesLeft;
6055 MVT AddrVT = Dst.getValueType();
6056 MVT SizeVT = Size.getValueType();
6058 Chain = DAG.getMemset(Chain, dl,
6059 DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
6060 DAG.getConstant(Offset, AddrVT)),
6062 DAG.getConstant(BytesLeft, SizeVT),
6063 Align, DstSV, DstSVOff + Offset);
6066 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
6071 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
6072 SDValue Chain, SDValue Dst, SDValue Src,
6073 SDValue Size, unsigned Align,
6075 const Value *DstSV, uint64_t DstSVOff,
6076 const Value *SrcSV, uint64_t SrcSVOff) {
6077 // This requires the copy size to be a constant, preferrably
6078 // within a subtarget-specific limit.
6079 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6082 uint64_t SizeVal = ConstantSize->getZExtValue();
6083 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
6086 /// If not DWORD aligned, call the library.
6087 if ((Align & 3) != 0)
6092 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
6095 unsigned UBytes = AVT.getSizeInBits() / 8;
6096 unsigned CountVal = SizeVal / UBytes;
6097 SDValue Count = DAG.getIntPtrConstant(CountVal);
6098 unsigned BytesLeft = SizeVal % UBytes;
6100 SDValue InFlag(0, 0);
6101 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6104 InFlag = Chain.getValue(1);
6105 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6108 InFlag = Chain.getValue(1);
6109 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
6112 InFlag = Chain.getValue(1);
6114 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6115 SmallVector<SDValue, 8> Ops;
6116 Ops.push_back(Chain);
6117 Ops.push_back(DAG.getValueType(AVT));
6118 Ops.push_back(InFlag);
6119 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, &Ops[0], Ops.size());
6121 SmallVector<SDValue, 4> Results;
6122 Results.push_back(RepMovs);
6124 // Handle the last 1 - 7 bytes.
6125 unsigned Offset = SizeVal - BytesLeft;
6126 MVT DstVT = Dst.getValueType();
6127 MVT SrcVT = Src.getValueType();
6128 MVT SizeVT = Size.getValueType();
6129 Results.push_back(DAG.getMemcpy(Chain, dl,
6130 DAG.getNode(ISD::ADD, dl, DstVT, Dst,
6131 DAG.getConstant(Offset, DstVT)),
6132 DAG.getNode(ISD::ADD, dl, SrcVT, Src,
6133 DAG.getConstant(Offset, SrcVT)),
6134 DAG.getConstant(BytesLeft, SizeVT),
6135 Align, AlwaysInline,
6136 DstSV, DstSVOff + Offset,
6137 SrcSV, SrcSVOff + Offset));
6140 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6141 &Results[0], Results.size());
6144 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
6145 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6146 DebugLoc dl = Op.getDebugLoc();
6148 if (!Subtarget->is64Bit()) {
6149 // vastart just stores the address of the VarArgsFrameIndex slot into the
6150 // memory location argument.
6151 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6152 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
6156 // gp_offset (0 - 6 * 8)
6157 // fp_offset (48 - 48 + 8 * 16)
6158 // overflow_arg_area (point to parameters coming in memory).
6160 SmallVector<SDValue, 8> MemOps;
6161 SDValue FIN = Op.getOperand(1);
6163 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6164 DAG.getConstant(VarArgsGPOffset, MVT::i32),
6166 MemOps.push_back(Store);
6169 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6170 FIN, DAG.getIntPtrConstant(4));
6171 Store = DAG.getStore(Op.getOperand(0), dl,
6172 DAG.getConstant(VarArgsFPOffset, MVT::i32),
6174 MemOps.push_back(Store);
6176 // Store ptr to overflow_arg_area
6177 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6178 FIN, DAG.getIntPtrConstant(4));
6179 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6180 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0);
6181 MemOps.push_back(Store);
6183 // Store ptr to reg_save_area.
6184 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6185 FIN, DAG.getIntPtrConstant(8));
6186 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
6187 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0);
6188 MemOps.push_back(Store);
6189 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6190 &MemOps[0], MemOps.size());
6193 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
6194 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6195 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6196 SDValue Chain = Op.getOperand(0);
6197 SDValue SrcPtr = Op.getOperand(1);
6198 SDValue SrcSV = Op.getOperand(2);
6200 assert(0 && "VAArgInst is not yet implemented for x86-64!");
6205 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
6206 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6207 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6208 SDValue Chain = Op.getOperand(0);
6209 SDValue DstPtr = Op.getOperand(1);
6210 SDValue SrcPtr = Op.getOperand(2);
6211 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6212 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6213 DebugLoc dl = Op.getDebugLoc();
6215 return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6216 DAG.getIntPtrConstant(24), 8, false,
6217 DstSV, 0, SrcSV, 0);
6221 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
6222 DebugLoc dl = Op.getDebugLoc();
6223 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6225 default: return SDValue(); // Don't custom lower most intrinsics.
6226 // Comparison intrinsics.
6227 case Intrinsic::x86_sse_comieq_ss:
6228 case Intrinsic::x86_sse_comilt_ss:
6229 case Intrinsic::x86_sse_comile_ss:
6230 case Intrinsic::x86_sse_comigt_ss:
6231 case Intrinsic::x86_sse_comige_ss:
6232 case Intrinsic::x86_sse_comineq_ss:
6233 case Intrinsic::x86_sse_ucomieq_ss:
6234 case Intrinsic::x86_sse_ucomilt_ss:
6235 case Intrinsic::x86_sse_ucomile_ss:
6236 case Intrinsic::x86_sse_ucomigt_ss:
6237 case Intrinsic::x86_sse_ucomige_ss:
6238 case Intrinsic::x86_sse_ucomineq_ss:
6239 case Intrinsic::x86_sse2_comieq_sd:
6240 case Intrinsic::x86_sse2_comilt_sd:
6241 case Intrinsic::x86_sse2_comile_sd:
6242 case Intrinsic::x86_sse2_comigt_sd:
6243 case Intrinsic::x86_sse2_comige_sd:
6244 case Intrinsic::x86_sse2_comineq_sd:
6245 case Intrinsic::x86_sse2_ucomieq_sd:
6246 case Intrinsic::x86_sse2_ucomilt_sd:
6247 case Intrinsic::x86_sse2_ucomile_sd:
6248 case Intrinsic::x86_sse2_ucomigt_sd:
6249 case Intrinsic::x86_sse2_ucomige_sd:
6250 case Intrinsic::x86_sse2_ucomineq_sd: {
6252 ISD::CondCode CC = ISD::SETCC_INVALID;
6255 case Intrinsic::x86_sse_comieq_ss:
6256 case Intrinsic::x86_sse2_comieq_sd:
6260 case Intrinsic::x86_sse_comilt_ss:
6261 case Intrinsic::x86_sse2_comilt_sd:
6265 case Intrinsic::x86_sse_comile_ss:
6266 case Intrinsic::x86_sse2_comile_sd:
6270 case Intrinsic::x86_sse_comigt_ss:
6271 case Intrinsic::x86_sse2_comigt_sd:
6275 case Intrinsic::x86_sse_comige_ss:
6276 case Intrinsic::x86_sse2_comige_sd:
6280 case Intrinsic::x86_sse_comineq_ss:
6281 case Intrinsic::x86_sse2_comineq_sd:
6285 case Intrinsic::x86_sse_ucomieq_ss:
6286 case Intrinsic::x86_sse2_ucomieq_sd:
6287 Opc = X86ISD::UCOMI;
6290 case Intrinsic::x86_sse_ucomilt_ss:
6291 case Intrinsic::x86_sse2_ucomilt_sd:
6292 Opc = X86ISD::UCOMI;
6295 case Intrinsic::x86_sse_ucomile_ss:
6296 case Intrinsic::x86_sse2_ucomile_sd:
6297 Opc = X86ISD::UCOMI;
6300 case Intrinsic::x86_sse_ucomigt_ss:
6301 case Intrinsic::x86_sse2_ucomigt_sd:
6302 Opc = X86ISD::UCOMI;
6305 case Intrinsic::x86_sse_ucomige_ss:
6306 case Intrinsic::x86_sse2_ucomige_sd:
6307 Opc = X86ISD::UCOMI;
6310 case Intrinsic::x86_sse_ucomineq_ss:
6311 case Intrinsic::x86_sse2_ucomineq_sd:
6312 Opc = X86ISD::UCOMI;
6317 SDValue LHS = Op.getOperand(1);
6318 SDValue RHS = Op.getOperand(2);
6319 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6320 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6321 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6322 DAG.getConstant(X86CC, MVT::i8), Cond);
6323 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6326 // Fix vector shift instructions where the last operand is a non-immediate
6328 case Intrinsic::x86_sse2_pslli_w:
6329 case Intrinsic::x86_sse2_pslli_d:
6330 case Intrinsic::x86_sse2_pslli_q:
6331 case Intrinsic::x86_sse2_psrli_w:
6332 case Intrinsic::x86_sse2_psrli_d:
6333 case Intrinsic::x86_sse2_psrli_q:
6334 case Intrinsic::x86_sse2_psrai_w:
6335 case Intrinsic::x86_sse2_psrai_d:
6336 case Intrinsic::x86_mmx_pslli_w:
6337 case Intrinsic::x86_mmx_pslli_d:
6338 case Intrinsic::x86_mmx_pslli_q:
6339 case Intrinsic::x86_mmx_psrli_w:
6340 case Intrinsic::x86_mmx_psrli_d:
6341 case Intrinsic::x86_mmx_psrli_q:
6342 case Intrinsic::x86_mmx_psrai_w:
6343 case Intrinsic::x86_mmx_psrai_d: {
6344 SDValue ShAmt = Op.getOperand(2);
6345 if (isa<ConstantSDNode>(ShAmt))
6348 unsigned NewIntNo = 0;
6349 MVT ShAmtVT = MVT::v4i32;
6351 case Intrinsic::x86_sse2_pslli_w:
6352 NewIntNo = Intrinsic::x86_sse2_psll_w;
6354 case Intrinsic::x86_sse2_pslli_d:
6355 NewIntNo = Intrinsic::x86_sse2_psll_d;
6357 case Intrinsic::x86_sse2_pslli_q:
6358 NewIntNo = Intrinsic::x86_sse2_psll_q;
6360 case Intrinsic::x86_sse2_psrli_w:
6361 NewIntNo = Intrinsic::x86_sse2_psrl_w;
6363 case Intrinsic::x86_sse2_psrli_d:
6364 NewIntNo = Intrinsic::x86_sse2_psrl_d;
6366 case Intrinsic::x86_sse2_psrli_q:
6367 NewIntNo = Intrinsic::x86_sse2_psrl_q;
6369 case Intrinsic::x86_sse2_psrai_w:
6370 NewIntNo = Intrinsic::x86_sse2_psra_w;
6372 case Intrinsic::x86_sse2_psrai_d:
6373 NewIntNo = Intrinsic::x86_sse2_psra_d;
6376 ShAmtVT = MVT::v2i32;
6378 case Intrinsic::x86_mmx_pslli_w:
6379 NewIntNo = Intrinsic::x86_mmx_psll_w;
6381 case Intrinsic::x86_mmx_pslli_d:
6382 NewIntNo = Intrinsic::x86_mmx_psll_d;
6384 case Intrinsic::x86_mmx_pslli_q:
6385 NewIntNo = Intrinsic::x86_mmx_psll_q;
6387 case Intrinsic::x86_mmx_psrli_w:
6388 NewIntNo = Intrinsic::x86_mmx_psrl_w;
6390 case Intrinsic::x86_mmx_psrli_d:
6391 NewIntNo = Intrinsic::x86_mmx_psrl_d;
6393 case Intrinsic::x86_mmx_psrli_q:
6394 NewIntNo = Intrinsic::x86_mmx_psrl_q;
6396 case Intrinsic::x86_mmx_psrai_w:
6397 NewIntNo = Intrinsic::x86_mmx_psra_w;
6399 case Intrinsic::x86_mmx_psrai_d:
6400 NewIntNo = Intrinsic::x86_mmx_psra_d;
6402 default: abort(); // Can't reach here.
6407 MVT VT = Op.getValueType();
6408 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT,
6409 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShAmtVT, ShAmt));
6410 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6411 DAG.getConstant(NewIntNo, MVT::i32),
6412 Op.getOperand(1), ShAmt);
6417 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
6418 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6419 DebugLoc dl = Op.getDebugLoc();
6422 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6424 DAG.getConstant(TD->getPointerSize(),
6425 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6426 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6427 DAG.getNode(ISD::ADD, dl, getPointerTy(),
6432 // Just load the return address.
6433 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6434 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6435 RetAddrFI, NULL, 0);
6438 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
6439 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6440 MFI->setFrameAddressIsTaken(true);
6441 MVT VT = Op.getValueType();
6442 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
6443 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6444 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6445 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6447 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
6451 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6452 SelectionDAG &DAG) {
6453 return DAG.getIntPtrConstant(2*TD->getPointerSize());
6456 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
6458 MachineFunction &MF = DAG.getMachineFunction();
6459 SDValue Chain = Op.getOperand(0);
6460 SDValue Offset = Op.getOperand(1);
6461 SDValue Handler = Op.getOperand(2);
6462 DebugLoc dl = Op.getDebugLoc();
6464 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6466 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6468 SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
6469 DAG.getIntPtrConstant(-TD->getPointerSize()));
6470 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
6471 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0);
6472 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
6473 MF.getRegInfo().addLiveOut(StoreAddrReg);
6475 return DAG.getNode(X86ISD::EH_RETURN, dl,
6477 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6480 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6481 SelectionDAG &DAG) {
6482 SDValue Root = Op.getOperand(0);
6483 SDValue Trmp = Op.getOperand(1); // trampoline
6484 SDValue FPtr = Op.getOperand(2); // nested function
6485 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6486 DebugLoc dl = Op.getDebugLoc();
6488 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6490 const X86InstrInfo *TII =
6491 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
6493 if (Subtarget->is64Bit()) {
6494 SDValue OutChains[6];
6496 // Large code-model.
6498 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
6499 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
6501 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
6502 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
6504 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
6506 // Load the pointer to the nested function into R11.
6507 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
6508 SDValue Addr = Trmp;
6509 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6512 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6513 DAG.getConstant(2, MVT::i64));
6514 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2, false, 2);
6516 // Load the 'nest' parameter value into R10.
6517 // R10 is specified in X86CallingConv.td
6518 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
6519 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6520 DAG.getConstant(10, MVT::i64));
6521 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6522 Addr, TrmpAddr, 10);
6524 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6525 DAG.getConstant(12, MVT::i64));
6526 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12, false, 2);
6528 // Jump to the nested function.
6529 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
6530 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6531 DAG.getConstant(20, MVT::i64));
6532 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6533 Addr, TrmpAddr, 20);
6535 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
6536 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6537 DAG.getConstant(22, MVT::i64));
6538 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
6542 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
6543 return DAG.getMergeValues(Ops, 2, dl);
6545 const Function *Func =
6546 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
6547 unsigned CC = Func->getCallingConv();
6552 assert(0 && "Unsupported calling convention");
6553 case CallingConv::C:
6554 case CallingConv::X86_StdCall: {
6555 // Pass 'nest' parameter in ECX.
6556 // Must be kept in sync with X86CallingConv.td
6559 // Check that ECX wasn't needed by an 'inreg' parameter.
6560 const FunctionType *FTy = Func->getFunctionType();
6561 const AttrListPtr &Attrs = Func->getAttributes();
6563 if (!Attrs.isEmpty() && !Func->isVarArg()) {
6564 unsigned InRegCount = 0;
6567 for (FunctionType::param_iterator I = FTy->param_begin(),
6568 E = FTy->param_end(); I != E; ++I, ++Idx)
6569 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6570 // FIXME: should only count parameters that are lowered to integers.
6571 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6573 if (InRegCount > 2) {
6574 cerr << "Nest register in use - reduce number of inreg parameters!\n";
6580 case CallingConv::X86_FastCall:
6581 case CallingConv::Fast:
6582 // Pass 'nest' parameter in EAX.
6583 // Must be kept in sync with X86CallingConv.td
6588 SDValue OutChains[4];
6591 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6592 DAG.getConstant(10, MVT::i32));
6593 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
6595 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
6596 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
6597 OutChains[0] = DAG.getStore(Root, dl,
6598 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
6601 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6602 DAG.getConstant(1, MVT::i32));
6603 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1, false, 1);
6605 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
6606 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6607 DAG.getConstant(5, MVT::i32));
6608 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
6609 TrmpAddr, 5, false, 1);
6611 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6612 DAG.getConstant(6, MVT::i32));
6613 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6, false, 1);
6616 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
6617 return DAG.getMergeValues(Ops, 2, dl);
6621 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
6623 The rounding mode is in bits 11:10 of FPSR, and has the following
6630 FLT_ROUNDS, on the other hand, expects the following:
6637 To perform the conversion, we do:
6638 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
6641 MachineFunction &MF = DAG.getMachineFunction();
6642 const TargetMachine &TM = MF.getTarget();
6643 const TargetFrameInfo &TFI = *TM.getFrameInfo();
6644 unsigned StackAlignment = TFI.getStackAlignment();
6645 MVT VT = Op.getValueType();
6646 DebugLoc dl = Op.getDebugLoc();
6648 // Save FP Control Word to stack slot
6649 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
6650 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6652 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
6653 DAG.getEntryNode(), StackSlot);
6655 // Load FP Control Word from stack slot
6656 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0);
6658 // Transform as necessary
6660 DAG.getNode(ISD::SRL, dl, MVT::i16,
6661 DAG.getNode(ISD::AND, dl, MVT::i16,
6662 CWD, DAG.getConstant(0x800, MVT::i16)),
6663 DAG.getConstant(11, MVT::i8));
6665 DAG.getNode(ISD::SRL, dl, MVT::i16,
6666 DAG.getNode(ISD::AND, dl, MVT::i16,
6667 CWD, DAG.getConstant(0x400, MVT::i16)),
6668 DAG.getConstant(9, MVT::i8));
6671 DAG.getNode(ISD::AND, dl, MVT::i16,
6672 DAG.getNode(ISD::ADD, dl, MVT::i16,
6673 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
6674 DAG.getConstant(1, MVT::i16)),
6675 DAG.getConstant(3, MVT::i16));
6678 return DAG.getNode((VT.getSizeInBits() < 16 ?
6679 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6682 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
6683 MVT VT = Op.getValueType();
6685 unsigned NumBits = VT.getSizeInBits();
6686 DebugLoc dl = Op.getDebugLoc();
6688 Op = Op.getOperand(0);
6689 if (VT == MVT::i8) {
6690 // Zero extend to i32 since there is not an i8 bsr.
6692 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6695 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
6696 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6697 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
6699 // If src is zero (i.e. bsr sets ZF), returns NumBits.
6700 SmallVector<SDValue, 4> Ops;
6702 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
6703 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6704 Ops.push_back(Op.getValue(1));
6705 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6707 // Finally xor with NumBits-1.
6708 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
6711 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6715 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
6716 MVT VT = Op.getValueType();
6718 unsigned NumBits = VT.getSizeInBits();
6719 DebugLoc dl = Op.getDebugLoc();
6721 Op = Op.getOperand(0);
6722 if (VT == MVT::i8) {
6724 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6727 // Issue a bsf (scan bits forward) which also sets EFLAGS.
6728 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6729 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
6731 // If src is zero (i.e. bsf sets ZF), returns NumBits.
6732 SmallVector<SDValue, 4> Ops;
6734 Ops.push_back(DAG.getConstant(NumBits, OpVT));
6735 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6736 Ops.push_back(Op.getValue(1));
6737 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6740 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6744 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
6745 MVT VT = Op.getValueType();
6746 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
6747 DebugLoc dl = Op.getDebugLoc();
6749 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
6750 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
6751 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
6752 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
6753 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
6755 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
6756 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
6757 // return AloBlo + AloBhi + AhiBlo;
6759 SDValue A = Op.getOperand(0);
6760 SDValue B = Op.getOperand(1);
6762 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6763 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6764 A, DAG.getConstant(32, MVT::i32));
6765 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6766 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6767 B, DAG.getConstant(32, MVT::i32));
6768 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6769 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6771 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6772 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6774 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6775 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6777 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6778 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6779 AloBhi, DAG.getConstant(32, MVT::i32));
6780 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6781 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6782 AhiBlo, DAG.getConstant(32, MVT::i32));
6783 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
6784 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
6789 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
6790 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
6791 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
6792 // looks for this combo and may remove the "setcc" instruction if the "setcc"
6793 // has only one use.
6794 SDNode *N = Op.getNode();
6795 SDValue LHS = N->getOperand(0);
6796 SDValue RHS = N->getOperand(1);
6797 unsigned BaseOp = 0;
6799 DebugLoc dl = Op.getDebugLoc();
6801 switch (Op.getOpcode()) {
6802 default: assert(0 && "Unknown ovf instruction!");
6804 // A subtract of one will be selected as a INC. Note that INC doesn't
6805 // set CF, so we can't do this for UADDO.
6806 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6807 if (C->getAPIntValue() == 1) {
6808 BaseOp = X86ISD::INC;
6812 BaseOp = X86ISD::ADD;
6816 BaseOp = X86ISD::ADD;
6820 // A subtract of one will be selected as a DEC. Note that DEC doesn't
6821 // set CF, so we can't do this for USUBO.
6822 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6823 if (C->getAPIntValue() == 1) {
6824 BaseOp = X86ISD::DEC;
6828 BaseOp = X86ISD::SUB;
6832 BaseOp = X86ISD::SUB;
6836 BaseOp = X86ISD::SMUL;
6840 BaseOp = X86ISD::UMUL;
6845 // Also sets EFLAGS.
6846 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
6847 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
6850 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
6851 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
6853 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
6857 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
6858 MVT T = Op.getValueType();
6859 DebugLoc dl = Op.getDebugLoc();
6862 switch(T.getSimpleVT()) {
6864 assert(false && "Invalid value type!");
6865 case MVT::i8: Reg = X86::AL; size = 1; break;
6866 case MVT::i16: Reg = X86::AX; size = 2; break;
6867 case MVT::i32: Reg = X86::EAX; size = 4; break;
6869 assert(Subtarget->is64Bit() && "Node not type legal!");
6870 Reg = X86::RAX; size = 8;
6873 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
6874 Op.getOperand(2), SDValue());
6875 SDValue Ops[] = { cpIn.getValue(0),
6878 DAG.getTargetConstant(size, MVT::i8),
6880 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6881 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
6883 DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
6887 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
6888 SelectionDAG &DAG) {
6889 assert(Subtarget->is64Bit() && "Result not type legalized?");
6890 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6891 SDValue TheChain = Op.getOperand(0);
6892 DebugLoc dl = Op.getDebugLoc();
6893 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6894 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
6895 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
6897 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
6898 DAG.getConstant(32, MVT::i8));
6900 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
6903 return DAG.getMergeValues(Ops, 2, dl);
6906 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
6907 SDNode *Node = Op.getNode();
6908 DebugLoc dl = Node->getDebugLoc();
6909 MVT T = Node->getValueType(0);
6910 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
6911 DAG.getConstant(0, T), Node->getOperand(2));
6912 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
6913 cast<AtomicSDNode>(Node)->getMemoryVT(),
6914 Node->getOperand(0),
6915 Node->getOperand(1), negOp,
6916 cast<AtomicSDNode>(Node)->getSrcValue(),
6917 cast<AtomicSDNode>(Node)->getAlignment());
6920 /// LowerOperation - Provide custom lowering hooks for some operations.
6922 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
6923 switch (Op.getOpcode()) {
6924 default: assert(0 && "Should not custom lower this!");
6925 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
6926 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
6927 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6928 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6929 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6930 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6931 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6932 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6933 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6934 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6935 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
6936 case ISD::SHL_PARTS:
6937 case ISD::SRA_PARTS:
6938 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
6939 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
6940 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
6941 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
6942 case ISD::FABS: return LowerFABS(Op, DAG);
6943 case ISD::FNEG: return LowerFNEG(Op, DAG);
6944 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6945 case ISD::SETCC: return LowerSETCC(Op, DAG);
6946 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
6947 case ISD::SELECT: return LowerSELECT(Op, DAG);
6948 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
6949 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6950 case ISD::CALL: return LowerCALL(Op, DAG);
6951 case ISD::RET: return LowerRET(Op, DAG);
6952 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
6953 case ISD::VASTART: return LowerVASTART(Op, DAG);
6954 case ISD::VAARG: return LowerVAARG(Op, DAG);
6955 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
6956 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6957 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6958 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6959 case ISD::FRAME_TO_ARGS_OFFSET:
6960 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
6961 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
6962 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
6963 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
6964 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6965 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
6966 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
6967 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
6973 case ISD::UMULO: return LowerXALUO(Op, DAG);
6974 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
6978 void X86TargetLowering::
6979 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
6980 SelectionDAG &DAG, unsigned NewOp) {
6981 MVT T = Node->getValueType(0);
6982 DebugLoc dl = Node->getDebugLoc();
6983 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
6985 SDValue Chain = Node->getOperand(0);
6986 SDValue In1 = Node->getOperand(1);
6987 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6988 Node->getOperand(2), DAG.getIntPtrConstant(0));
6989 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6990 Node->getOperand(2), DAG.getIntPtrConstant(1));
6991 // This is a generalized SDNode, not an AtomicSDNode, so it doesn't
6992 // have a MemOperand. Pass the info through as a normal operand.
6993 SDValue LSI = DAG.getMemOperand(cast<MemSDNode>(Node)->getMemOperand());
6994 SDValue Ops[] = { Chain, In1, In2L, In2H, LSI };
6995 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6996 SDValue Result = DAG.getNode(NewOp, dl, Tys, Ops, 5);
6997 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
6998 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6999 Results.push_back(Result.getValue(2));
7002 /// ReplaceNodeResults - Replace a node with an illegal result type
7003 /// with a new node built out of custom code.
7004 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7005 SmallVectorImpl<SDValue>&Results,
7006 SelectionDAG &DAG) {
7007 DebugLoc dl = N->getDebugLoc();
7008 switch (N->getOpcode()) {
7010 assert(false && "Do not know how to custom type legalize this operation!");
7012 case ISD::FP_TO_SINT: {
7013 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(SDValue(N, 0), DAG);
7014 SDValue FIST = Vals.first, StackSlot = Vals.second;
7015 if (FIST.getNode() != 0) {
7016 MVT VT = N->getValueType(0);
7017 // Return a load from the stack slot.
7018 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0));
7022 case ISD::READCYCLECOUNTER: {
7023 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7024 SDValue TheChain = N->getOperand(0);
7025 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7026 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7028 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7030 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7031 SDValue Ops[] = { eax, edx };
7032 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7033 Results.push_back(edx.getValue(1));
7036 case ISD::ATOMIC_CMP_SWAP: {
7037 MVT T = N->getValueType(0);
7038 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7039 SDValue cpInL, cpInH;
7040 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7041 DAG.getConstant(0, MVT::i32));
7042 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7043 DAG.getConstant(1, MVT::i32));
7044 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7045 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7047 SDValue swapInL, swapInH;
7048 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7049 DAG.getConstant(0, MVT::i32));
7050 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7051 DAG.getConstant(1, MVT::i32));
7052 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7054 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7055 swapInL.getValue(1));
7056 SDValue Ops[] = { swapInH.getValue(0),
7058 swapInH.getValue(1) };
7059 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7060 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7061 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7062 MVT::i32, Result.getValue(1));
7063 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7064 MVT::i32, cpOutL.getValue(2));
7065 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7066 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7067 Results.push_back(cpOutH.getValue(1));
7070 case ISD::ATOMIC_LOAD_ADD:
7071 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7073 case ISD::ATOMIC_LOAD_AND:
7074 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7076 case ISD::ATOMIC_LOAD_NAND:
7077 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7079 case ISD::ATOMIC_LOAD_OR:
7080 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7082 case ISD::ATOMIC_LOAD_SUB:
7083 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7085 case ISD::ATOMIC_LOAD_XOR:
7086 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7088 case ISD::ATOMIC_SWAP:
7089 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7094 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7096 default: return NULL;
7097 case X86ISD::BSF: return "X86ISD::BSF";
7098 case X86ISD::BSR: return "X86ISD::BSR";
7099 case X86ISD::SHLD: return "X86ISD::SHLD";
7100 case X86ISD::SHRD: return "X86ISD::SHRD";
7101 case X86ISD::FAND: return "X86ISD::FAND";
7102 case X86ISD::FOR: return "X86ISD::FOR";
7103 case X86ISD::FXOR: return "X86ISD::FXOR";
7104 case X86ISD::FSRL: return "X86ISD::FSRL";
7105 case X86ISD::FILD: return "X86ISD::FILD";
7106 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
7107 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7108 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7109 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7110 case X86ISD::FLD: return "X86ISD::FLD";
7111 case X86ISD::FST: return "X86ISD::FST";
7112 case X86ISD::CALL: return "X86ISD::CALL";
7113 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
7114 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
7115 case X86ISD::BT: return "X86ISD::BT";
7116 case X86ISD::CMP: return "X86ISD::CMP";
7117 case X86ISD::COMI: return "X86ISD::COMI";
7118 case X86ISD::UCOMI: return "X86ISD::UCOMI";
7119 case X86ISD::SETCC: return "X86ISD::SETCC";
7120 case X86ISD::CMOV: return "X86ISD::CMOV";
7121 case X86ISD::BRCOND: return "X86ISD::BRCOND";
7122 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
7123 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
7124 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
7125 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
7126 case X86ISD::Wrapper: return "X86ISD::Wrapper";
7127 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
7128 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
7129 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
7130 case X86ISD::PINSRB: return "X86ISD::PINSRB";
7131 case X86ISD::PINSRW: return "X86ISD::PINSRW";
7132 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
7133 case X86ISD::FMAX: return "X86ISD::FMAX";
7134 case X86ISD::FMIN: return "X86ISD::FMIN";
7135 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
7136 case X86ISD::FRCP: return "X86ISD::FRCP";
7137 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
7138 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
7139 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
7140 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
7141 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
7142 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
7143 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
7144 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
7145 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
7146 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
7147 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
7148 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
7149 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
7150 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
7151 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
7152 case X86ISD::VSHL: return "X86ISD::VSHL";
7153 case X86ISD::VSRL: return "X86ISD::VSRL";
7154 case X86ISD::CMPPD: return "X86ISD::CMPPD";
7155 case X86ISD::CMPPS: return "X86ISD::CMPPS";
7156 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
7157 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
7158 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
7159 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
7160 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
7161 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
7162 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
7163 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
7164 case X86ISD::ADD: return "X86ISD::ADD";
7165 case X86ISD::SUB: return "X86ISD::SUB";
7166 case X86ISD::SMUL: return "X86ISD::SMUL";
7167 case X86ISD::UMUL: return "X86ISD::UMUL";
7168 case X86ISD::INC: return "X86ISD::INC";
7169 case X86ISD::DEC: return "X86ISD::DEC";
7173 // isLegalAddressingMode - Return true if the addressing mode represented
7174 // by AM is legal for this target, for a load/store of the specified type.
7175 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7176 const Type *Ty) const {
7177 // X86 supports extremely general addressing modes.
7179 // X86 allows a sign-extended 32-bit immediate field as a displacement.
7180 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
7184 // We can only fold this if we don't need an extra load.
7185 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
7187 // If BaseGV requires a register, we cannot also have a BaseReg.
7188 if (Subtarget->GVRequiresRegister(AM.BaseGV, getTargetMachine(), false) &&
7192 // X86-64 only supports addr of globals in small code model.
7193 if (Subtarget->is64Bit()) {
7194 if (getTargetMachine().getCodeModel() != CodeModel::Small)
7196 // If lower 4G is not available, then we must use rip-relative addressing.
7197 if (AM.BaseOffs || AM.Scale > 1)
7208 // These scales always work.
7213 // These scales are formed with basereg+scalereg. Only accept if there is
7218 default: // Other stuff never works.
7226 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7227 if (!Ty1->isInteger() || !Ty2->isInteger())
7229 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7230 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7231 if (NumBits1 <= NumBits2)
7233 return Subtarget->is64Bit() || NumBits1 < 64;
7236 bool X86TargetLowering::isTruncateFree(MVT VT1, MVT VT2) const {
7237 if (!VT1.isInteger() || !VT2.isInteger())
7239 unsigned NumBits1 = VT1.getSizeInBits();
7240 unsigned NumBits2 = VT2.getSizeInBits();
7241 if (NumBits1 <= NumBits2)
7243 return Subtarget->is64Bit() || NumBits1 < 64;
7246 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7247 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7248 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7249 /// are assumed to be legal.
7251 X86TargetLowering::isShuffleMaskLegal(SDValue Mask, MVT VT) const {
7252 // Only do shuffles on 128-bit vector types for now.
7253 // FIXME: pshufb, blends
7254 if (VT.getSizeInBits() == 64) return false;
7255 return (Mask.getNode()->getNumOperands() <= 4 ||
7256 isIdentityMask(Mask.getNode()) ||
7257 isIdentityMask(Mask.getNode(), true) ||
7258 isSplatMask(Mask.getNode()) ||
7259 X86::isPSHUFHWMask(Mask.getNode()) ||
7260 X86::isPSHUFLWMask(Mask.getNode()) ||
7261 X86::isUNPCKLMask(Mask.getNode()) ||
7262 X86::isUNPCKHMask(Mask.getNode()) ||
7263 X86::isUNPCKL_v_undef_Mask(Mask.getNode()) ||
7264 X86::isUNPCKH_v_undef_Mask(Mask.getNode()));
7268 X86TargetLowering::isVectorClearMaskLegal(const std::vector<SDValue> &BVOps,
7269 MVT EVT, SelectionDAG &DAG) const {
7270 unsigned NumElts = BVOps.size();
7271 // Only do shuffles on 128-bit vector types for now.
7272 if (EVT.getSizeInBits() * NumElts == 64) return false;
7273 if (NumElts == 2) return true;
7275 return (isMOVLMask(&BVOps[0], 4) ||
7276 isCommutedMOVL(&BVOps[0], 4, true) ||
7277 isSHUFPMask(&BVOps[0], 4) ||
7278 isCommutedSHUFP(&BVOps[0], 4));
7283 //===----------------------------------------------------------------------===//
7284 // X86 Scheduler Hooks
7285 //===----------------------------------------------------------------------===//
7287 // private utility function
7289 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7290 MachineBasicBlock *MBB,
7298 TargetRegisterClass *RC,
7299 bool invSrc) const {
7300 // For the atomic bitwise operator, we generate
7303 // ld t1 = [bitinstr.addr]
7304 // op t2 = t1, [bitinstr.val]
7306 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7308 // fallthrough -->nextMBB
7309 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7310 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7311 MachineFunction::iterator MBBIter = MBB;
7314 /// First build the CFG
7315 MachineFunction *F = MBB->getParent();
7316 MachineBasicBlock *thisMBB = MBB;
7317 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7318 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7319 F->insert(MBBIter, newMBB);
7320 F->insert(MBBIter, nextMBB);
7322 // Move all successors to thisMBB to nextMBB
7323 nextMBB->transferSuccessors(thisMBB);
7325 // Update thisMBB to fall through to newMBB
7326 thisMBB->addSuccessor(newMBB);
7328 // newMBB jumps to itself and fall through to nextMBB
7329 newMBB->addSuccessor(nextMBB);
7330 newMBB->addSuccessor(newMBB);
7332 // Insert instructions into newMBB based on incoming instruction
7333 assert(bInstr->getNumOperands() < 8 && "unexpected number of operands");
7334 DebugLoc dl = bInstr->getDebugLoc();
7335 MachineOperand& destOper = bInstr->getOperand(0);
7336 MachineOperand* argOpers[6];
7337 int numArgs = bInstr->getNumOperands() - 1;
7338 for (int i=0; i < numArgs; ++i)
7339 argOpers[i] = &bInstr->getOperand(i+1);
7341 // x86 address has 4 operands: base, index, scale, and displacement
7342 int lastAddrIndx = 3; // [0,3]
7345 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7346 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7347 for (int i=0; i <= lastAddrIndx; ++i)
7348 (*MIB).addOperand(*argOpers[i]);
7350 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7352 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7357 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7358 assert((argOpers[valArgIndx]->isReg() ||
7359 argOpers[valArgIndx]->isImm()) &&
7361 if (argOpers[valArgIndx]->isReg())
7362 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7364 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7366 (*MIB).addOperand(*argOpers[valArgIndx]);
7368 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7371 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7372 for (int i=0; i <= lastAddrIndx; ++i)
7373 (*MIB).addOperand(*argOpers[i]);
7375 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7376 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7378 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7382 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7384 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7388 // private utility function: 64 bit atomics on 32 bit host.
7390 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7391 MachineBasicBlock *MBB,
7396 bool invSrc) const {
7397 // For the atomic bitwise operator, we generate
7398 // thisMBB (instructions are in pairs, except cmpxchg8b)
7399 // ld t1,t2 = [bitinstr.addr]
7401 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7402 // op t5, t6 <- out1, out2, [bitinstr.val]
7403 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
7404 // mov ECX, EBX <- t5, t6
7405 // mov EAX, EDX <- t1, t2
7406 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
7407 // mov t3, t4 <- EAX, EDX
7409 // result in out1, out2
7410 // fallthrough -->nextMBB
7412 const TargetRegisterClass *RC = X86::GR32RegisterClass;
7413 const unsigned LoadOpc = X86::MOV32rm;
7414 const unsigned copyOpc = X86::MOV32rr;
7415 const unsigned NotOpc = X86::NOT32r;
7416 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7417 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7418 MachineFunction::iterator MBBIter = MBB;
7421 /// First build the CFG
7422 MachineFunction *F = MBB->getParent();
7423 MachineBasicBlock *thisMBB = MBB;
7424 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7425 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7426 F->insert(MBBIter, newMBB);
7427 F->insert(MBBIter, nextMBB);
7429 // Move all successors to thisMBB to nextMBB
7430 nextMBB->transferSuccessors(thisMBB);
7432 // Update thisMBB to fall through to newMBB
7433 thisMBB->addSuccessor(newMBB);
7435 // newMBB jumps to itself and fall through to nextMBB
7436 newMBB->addSuccessor(nextMBB);
7437 newMBB->addSuccessor(newMBB);
7439 DebugLoc dl = bInstr->getDebugLoc();
7440 // Insert instructions into newMBB based on incoming instruction
7441 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7442 assert(bInstr->getNumOperands() < 18 && "unexpected number of operands");
7443 MachineOperand& dest1Oper = bInstr->getOperand(0);
7444 MachineOperand& dest2Oper = bInstr->getOperand(1);
7445 MachineOperand* argOpers[6];
7446 for (int i=0; i < 6; ++i)
7447 argOpers[i] = &bInstr->getOperand(i+2);
7449 // x86 address has 4 operands: base, index, scale, and displacement
7450 int lastAddrIndx = 3; // [0,3]
7452 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7453 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
7454 for (int i=0; i <= lastAddrIndx; ++i)
7455 (*MIB).addOperand(*argOpers[i]);
7456 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7457 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
7458 // add 4 to displacement.
7459 for (int i=0; i <= lastAddrIndx-1; ++i)
7460 (*MIB).addOperand(*argOpers[i]);
7461 MachineOperand newOp3 = *(argOpers[3]);
7463 newOp3.setImm(newOp3.getImm()+4);
7465 newOp3.setOffset(newOp3.getOffset()+4);
7466 (*MIB).addOperand(newOp3);
7468 // t3/4 are defined later, at the bottom of the loop
7469 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
7470 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
7471 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
7472 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
7473 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
7474 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
7476 unsigned tt1 = F->getRegInfo().createVirtualRegister(RC);
7477 unsigned tt2 = F->getRegInfo().createVirtualRegister(RC);
7479 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt1).addReg(t1);
7480 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt2).addReg(t2);
7486 assert((argOpers[4]->isReg() || argOpers[4]->isImm()) &&
7488 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
7489 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
7490 if (argOpers[4]->isReg())
7491 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
7493 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
7494 if (regOpcL != X86::MOV32rr)
7496 (*MIB).addOperand(*argOpers[4]);
7497 assert(argOpers[5]->isReg() == argOpers[4]->isReg());
7498 assert(argOpers[5]->isImm() == argOpers[4]->isImm());
7499 if (argOpers[5]->isReg())
7500 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
7502 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
7503 if (regOpcH != X86::MOV32rr)
7505 (*MIB).addOperand(*argOpers[5]);
7507 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
7509 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
7512 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
7514 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
7517 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
7518 for (int i=0; i <= lastAddrIndx; ++i)
7519 (*MIB).addOperand(*argOpers[i]);
7521 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7522 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7524 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
7525 MIB.addReg(X86::EAX);
7526 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
7527 MIB.addReg(X86::EDX);
7530 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7532 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7536 // private utility function
7538 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
7539 MachineBasicBlock *MBB,
7540 unsigned cmovOpc) const {
7541 // For the atomic min/max operator, we generate
7544 // ld t1 = [min/max.addr]
7545 // mov t2 = [min/max.val]
7547 // cmov[cond] t2 = t1
7549 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7551 // fallthrough -->nextMBB
7553 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7554 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7555 MachineFunction::iterator MBBIter = MBB;
7558 /// First build the CFG
7559 MachineFunction *F = MBB->getParent();
7560 MachineBasicBlock *thisMBB = MBB;
7561 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7562 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7563 F->insert(MBBIter, newMBB);
7564 F->insert(MBBIter, nextMBB);
7566 // Move all successors to thisMBB to nextMBB
7567 nextMBB->transferSuccessors(thisMBB);
7569 // Update thisMBB to fall through to newMBB
7570 thisMBB->addSuccessor(newMBB);
7572 // newMBB jumps to newMBB and fall through to nextMBB
7573 newMBB->addSuccessor(nextMBB);
7574 newMBB->addSuccessor(newMBB);
7576 DebugLoc dl = mInstr->getDebugLoc();
7577 // Insert instructions into newMBB based on incoming instruction
7578 assert(mInstr->getNumOperands() < 8 && "unexpected number of operands");
7579 MachineOperand& destOper = mInstr->getOperand(0);
7580 MachineOperand* argOpers[6];
7581 int numArgs = mInstr->getNumOperands() - 1;
7582 for (int i=0; i < numArgs; ++i)
7583 argOpers[i] = &mInstr->getOperand(i+1);
7585 // x86 address has 4 operands: base, index, scale, and displacement
7586 int lastAddrIndx = 3; // [0,3]
7589 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7590 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
7591 for (int i=0; i <= lastAddrIndx; ++i)
7592 (*MIB).addOperand(*argOpers[i]);
7594 // We only support register and immediate values
7595 assert((argOpers[valArgIndx]->isReg() ||
7596 argOpers[valArgIndx]->isImm()) &&
7599 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7600 if (argOpers[valArgIndx]->isReg())
7601 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7603 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7604 (*MIB).addOperand(*argOpers[valArgIndx]);
7606 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
7609 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
7614 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7615 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
7619 // Cmp and exchange if none has modified the memory location
7620 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
7621 for (int i=0; i <= lastAddrIndx; ++i)
7622 (*MIB).addOperand(*argOpers[i]);
7624 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7625 (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
7627 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
7628 MIB.addReg(X86::EAX);
7631 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7633 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
7639 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7640 MachineBasicBlock *BB) const {
7641 DebugLoc dl = MI->getDebugLoc();
7642 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7643 switch (MI->getOpcode()) {
7644 default: assert(false && "Unexpected instr type to insert");
7645 case X86::CMOV_V1I64:
7646 case X86::CMOV_FR32:
7647 case X86::CMOV_FR64:
7648 case X86::CMOV_V4F32:
7649 case X86::CMOV_V2F64:
7650 case X86::CMOV_V2I64: {
7651 // To "insert" a SELECT_CC instruction, we actually have to insert the
7652 // diamond control-flow pattern. The incoming instruction knows the
7653 // destination vreg to set, the condition code register to branch on, the
7654 // true/false values to select between, and a branch opcode to use.
7655 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7656 MachineFunction::iterator It = BB;
7662 // cmpTY ccX, r1, r2
7664 // fallthrough --> copy0MBB
7665 MachineBasicBlock *thisMBB = BB;
7666 MachineFunction *F = BB->getParent();
7667 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7668 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7670 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
7671 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
7672 F->insert(It, copy0MBB);
7673 F->insert(It, sinkMBB);
7674 // Update machine-CFG edges by transferring all successors of the current
7675 // block to the new block which will contain the Phi node for the select.
7676 sinkMBB->transferSuccessors(BB);
7678 // Add the true and fallthrough blocks as its successors.
7679 BB->addSuccessor(copy0MBB);
7680 BB->addSuccessor(sinkMBB);
7683 // %FalseValue = ...
7684 // # fallthrough to sinkMBB
7687 // Update machine-CFG edges
7688 BB->addSuccessor(sinkMBB);
7691 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7694 BuildMI(BB, dl, TII->get(X86::PHI), MI->getOperand(0).getReg())
7695 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7696 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7698 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7702 case X86::FP32_TO_INT16_IN_MEM:
7703 case X86::FP32_TO_INT32_IN_MEM:
7704 case X86::FP32_TO_INT64_IN_MEM:
7705 case X86::FP64_TO_INT16_IN_MEM:
7706 case X86::FP64_TO_INT32_IN_MEM:
7707 case X86::FP64_TO_INT64_IN_MEM:
7708 case X86::FP80_TO_INT16_IN_MEM:
7709 case X86::FP80_TO_INT32_IN_MEM:
7710 case X86::FP80_TO_INT64_IN_MEM: {
7711 // Change the floating point control register to use "round towards zero"
7712 // mode when truncating to an integer value.
7713 MachineFunction *F = BB->getParent();
7714 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
7715 addFrameReference(BuildMI(BB, dl, TII->get(X86::FNSTCW16m)), CWFrameIdx);
7717 // Load the old value of the high byte of the control word...
7719 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
7720 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16rm), OldCW),
7723 // Set the high part to be round to zero...
7724 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mi)), CWFrameIdx)
7727 // Reload the modified control word now...
7728 addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7730 // Restore the memory image of control word to original value
7731 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mr)), CWFrameIdx)
7734 // Get the X86 opcode to use.
7736 switch (MI->getOpcode()) {
7737 default: assert(0 && "illegal opcode!");
7738 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
7739 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
7740 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
7741 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
7742 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
7743 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
7744 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
7745 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
7746 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
7750 MachineOperand &Op = MI->getOperand(0);
7752 AM.BaseType = X86AddressMode::RegBase;
7753 AM.Base.Reg = Op.getReg();
7755 AM.BaseType = X86AddressMode::FrameIndexBase;
7756 AM.Base.FrameIndex = Op.getIndex();
7758 Op = MI->getOperand(1);
7760 AM.Scale = Op.getImm();
7761 Op = MI->getOperand(2);
7763 AM.IndexReg = Op.getImm();
7764 Op = MI->getOperand(3);
7765 if (Op.isGlobal()) {
7766 AM.GV = Op.getGlobal();
7768 AM.Disp = Op.getImm();
7770 addFullAddress(BuildMI(BB, dl, TII->get(Opc)), AM)
7771 .addReg(MI->getOperand(4).getReg());
7773 // Reload the original control word now.
7774 addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7776 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7779 case X86::ATOMAND32:
7780 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7781 X86::AND32ri, X86::MOV32rm,
7782 X86::LCMPXCHG32, X86::MOV32rr,
7783 X86::NOT32r, X86::EAX,
7784 X86::GR32RegisterClass);
7786 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
7787 X86::OR32ri, X86::MOV32rm,
7788 X86::LCMPXCHG32, X86::MOV32rr,
7789 X86::NOT32r, X86::EAX,
7790 X86::GR32RegisterClass);
7791 case X86::ATOMXOR32:
7792 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
7793 X86::XOR32ri, X86::MOV32rm,
7794 X86::LCMPXCHG32, X86::MOV32rr,
7795 X86::NOT32r, X86::EAX,
7796 X86::GR32RegisterClass);
7797 case X86::ATOMNAND32:
7798 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7799 X86::AND32ri, X86::MOV32rm,
7800 X86::LCMPXCHG32, X86::MOV32rr,
7801 X86::NOT32r, X86::EAX,
7802 X86::GR32RegisterClass, true);
7803 case X86::ATOMMIN32:
7804 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
7805 case X86::ATOMMAX32:
7806 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
7807 case X86::ATOMUMIN32:
7808 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
7809 case X86::ATOMUMAX32:
7810 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
7812 case X86::ATOMAND16:
7813 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7814 X86::AND16ri, X86::MOV16rm,
7815 X86::LCMPXCHG16, X86::MOV16rr,
7816 X86::NOT16r, X86::AX,
7817 X86::GR16RegisterClass);
7819 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
7820 X86::OR16ri, X86::MOV16rm,
7821 X86::LCMPXCHG16, X86::MOV16rr,
7822 X86::NOT16r, X86::AX,
7823 X86::GR16RegisterClass);
7824 case X86::ATOMXOR16:
7825 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
7826 X86::XOR16ri, X86::MOV16rm,
7827 X86::LCMPXCHG16, X86::MOV16rr,
7828 X86::NOT16r, X86::AX,
7829 X86::GR16RegisterClass);
7830 case X86::ATOMNAND16:
7831 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7832 X86::AND16ri, X86::MOV16rm,
7833 X86::LCMPXCHG16, X86::MOV16rr,
7834 X86::NOT16r, X86::AX,
7835 X86::GR16RegisterClass, true);
7836 case X86::ATOMMIN16:
7837 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
7838 case X86::ATOMMAX16:
7839 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
7840 case X86::ATOMUMIN16:
7841 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
7842 case X86::ATOMUMAX16:
7843 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
7846 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7847 X86::AND8ri, X86::MOV8rm,
7848 X86::LCMPXCHG8, X86::MOV8rr,
7849 X86::NOT8r, X86::AL,
7850 X86::GR8RegisterClass);
7852 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
7853 X86::OR8ri, X86::MOV8rm,
7854 X86::LCMPXCHG8, X86::MOV8rr,
7855 X86::NOT8r, X86::AL,
7856 X86::GR8RegisterClass);
7858 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
7859 X86::XOR8ri, X86::MOV8rm,
7860 X86::LCMPXCHG8, X86::MOV8rr,
7861 X86::NOT8r, X86::AL,
7862 X86::GR8RegisterClass);
7863 case X86::ATOMNAND8:
7864 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7865 X86::AND8ri, X86::MOV8rm,
7866 X86::LCMPXCHG8, X86::MOV8rr,
7867 X86::NOT8r, X86::AL,
7868 X86::GR8RegisterClass, true);
7869 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
7870 // This group is for 64-bit host.
7871 case X86::ATOMAND64:
7872 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7873 X86::AND64ri32, X86::MOV64rm,
7874 X86::LCMPXCHG64, X86::MOV64rr,
7875 X86::NOT64r, X86::RAX,
7876 X86::GR64RegisterClass);
7878 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
7879 X86::OR64ri32, X86::MOV64rm,
7880 X86::LCMPXCHG64, X86::MOV64rr,
7881 X86::NOT64r, X86::RAX,
7882 X86::GR64RegisterClass);
7883 case X86::ATOMXOR64:
7884 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
7885 X86::XOR64ri32, X86::MOV64rm,
7886 X86::LCMPXCHG64, X86::MOV64rr,
7887 X86::NOT64r, X86::RAX,
7888 X86::GR64RegisterClass);
7889 case X86::ATOMNAND64:
7890 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7891 X86::AND64ri32, X86::MOV64rm,
7892 X86::LCMPXCHG64, X86::MOV64rr,
7893 X86::NOT64r, X86::RAX,
7894 X86::GR64RegisterClass, true);
7895 case X86::ATOMMIN64:
7896 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
7897 case X86::ATOMMAX64:
7898 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
7899 case X86::ATOMUMIN64:
7900 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
7901 case X86::ATOMUMAX64:
7902 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
7904 // This group does 64-bit operations on a 32-bit host.
7905 case X86::ATOMAND6432:
7906 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7907 X86::AND32rr, X86::AND32rr,
7908 X86::AND32ri, X86::AND32ri,
7910 case X86::ATOMOR6432:
7911 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7912 X86::OR32rr, X86::OR32rr,
7913 X86::OR32ri, X86::OR32ri,
7915 case X86::ATOMXOR6432:
7916 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7917 X86::XOR32rr, X86::XOR32rr,
7918 X86::XOR32ri, X86::XOR32ri,
7920 case X86::ATOMNAND6432:
7921 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7922 X86::AND32rr, X86::AND32rr,
7923 X86::AND32ri, X86::AND32ri,
7925 case X86::ATOMADD6432:
7926 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7927 X86::ADD32rr, X86::ADC32rr,
7928 X86::ADD32ri, X86::ADC32ri,
7930 case X86::ATOMSUB6432:
7931 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7932 X86::SUB32rr, X86::SBB32rr,
7933 X86::SUB32ri, X86::SBB32ri,
7935 case X86::ATOMSWAP6432:
7936 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7937 X86::MOV32rr, X86::MOV32rr,
7938 X86::MOV32ri, X86::MOV32ri,
7943 //===----------------------------------------------------------------------===//
7944 // X86 Optimization Hooks
7945 //===----------------------------------------------------------------------===//
7947 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
7951 const SelectionDAG &DAG,
7952 unsigned Depth) const {
7953 unsigned Opc = Op.getOpcode();
7954 assert((Opc >= ISD::BUILTIN_OP_END ||
7955 Opc == ISD::INTRINSIC_WO_CHAIN ||
7956 Opc == ISD::INTRINSIC_W_CHAIN ||
7957 Opc == ISD::INTRINSIC_VOID) &&
7958 "Should use MaskedValueIsZero if you don't know whether Op"
7959 " is a target node!");
7961 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
7970 // These nodes' second result is a boolean.
7971 if (Op.getResNo() == 0)
7975 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
7976 Mask.getBitWidth() - 1);
7981 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
7982 /// node is a GlobalAddress + offset.
7983 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
7984 GlobalValue* &GA, int64_t &Offset) const{
7985 if (N->getOpcode() == X86ISD::Wrapper) {
7986 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
7987 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
7988 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
7992 return TargetLowering::isGAPlusOffset(N, GA, Offset);
7995 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
7996 const TargetLowering &TLI) {
7999 if (TLI.isGAPlusOffset(Base, GV, Offset))
8000 return (GV->getAlignment() >= N && (Offset % N) == 0);
8001 // DAG combine handles the stack object case.
8005 static bool EltsFromConsecutiveLoads(SDNode *N, SDValue PermMask,
8006 unsigned NumElems, MVT EVT,
8008 SelectionDAG &DAG, MachineFrameInfo *MFI,
8009 const TargetLowering &TLI) {
8011 for (unsigned i = 0; i < NumElems; ++i) {
8012 SDValue Idx = PermMask.getOperand(i);
8013 if (Idx.getOpcode() == ISD::UNDEF) {
8019 SDValue Elt = DAG.getShuffleScalarElt(N, i);
8020 if (!Elt.getNode() ||
8021 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
8024 Base = Elt.getNode();
8025 if (Base->getOpcode() == ISD::UNDEF)
8029 if (Elt.getOpcode() == ISD::UNDEF)
8032 if (!TLI.isConsecutiveLoad(Elt.getNode(), Base,
8033 EVT.getSizeInBits()/8, i, MFI))
8039 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8040 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8041 /// if the load addresses are consecutive, non-overlapping, and in the right
8043 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8044 const TargetLowering &TLI) {
8045 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8046 DebugLoc dl = N->getDebugLoc();
8047 MVT VT = N->getValueType(0);
8048 MVT EVT = VT.getVectorElementType();
8049 SDValue PermMask = N->getOperand(2);
8050 unsigned NumElems = PermMask.getNumOperands();
8051 SDNode *Base = NULL;
8052 if (!EltsFromConsecutiveLoads(N, PermMask, NumElems, EVT, Base,
8056 LoadSDNode *LD = cast<LoadSDNode>(Base);
8057 if (isBaseAlignmentOfN(16, Base->getOperand(1).getNode(), TLI))
8058 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8059 LD->getSrcValue(), LD->getSrcValueOffset(),
8061 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8062 LD->getSrcValue(), LD->getSrcValueOffset(),
8063 LD->isVolatile(), LD->getAlignment());
8066 /// PerformBuildVectorCombine - build_vector 0,(load i64 / f64) -> movq / movsd.
8067 static SDValue PerformBuildVectorCombine(SDNode *N, SelectionDAG &DAG,
8068 TargetLowering::DAGCombinerInfo &DCI,
8069 const X86Subtarget *Subtarget,
8070 const TargetLowering &TLI) {
8071 unsigned NumOps = N->getNumOperands();
8072 DebugLoc dl = N->getDebugLoc();
8074 // Ignore single operand BUILD_VECTOR.
8078 MVT VT = N->getValueType(0);
8079 MVT EVT = VT.getVectorElementType();
8080 if ((EVT != MVT::i64 && EVT != MVT::f64) || Subtarget->is64Bit())
8081 // We are looking for load i64 and zero extend. We want to transform
8082 // it before legalizer has a chance to expand it. Also look for i64
8083 // BUILD_PAIR bit casted to f64.
8085 // This must be an insertion into a zero vector.
8086 SDValue HighElt = N->getOperand(1);
8087 if (!isZeroNode(HighElt))
8090 // Value must be a load.
8091 SDNode *Base = N->getOperand(0).getNode();
8092 if (!isa<LoadSDNode>(Base)) {
8093 if (Base->getOpcode() != ISD::BIT_CONVERT)
8095 Base = Base->getOperand(0).getNode();
8096 if (!isa<LoadSDNode>(Base))
8100 // Transform it into VZEXT_LOAD addr.
8101 LoadSDNode *LD = cast<LoadSDNode>(Base);
8103 // Load must not be an extload.
8104 if (LD->getExtensionType() != ISD::NON_EXTLOAD)
8107 // Load type should legal type so we don't have to legalize it.
8108 if (!TLI.isTypeLegal(VT))
8111 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
8112 SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
8113 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
8114 TargetLowering::TargetLoweringOpt TLO(DAG);
8115 TLO.CombineTo(SDValue(Base, 1), ResNode.getValue(1));
8116 DCI.CommitTargetLoweringOpt(TLO);
8120 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
8121 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
8122 const X86Subtarget *Subtarget) {
8123 DebugLoc DL = N->getDebugLoc();
8124 SDValue Cond = N->getOperand(0);
8125 // Get the LHS/RHS of the select.
8126 SDValue LHS = N->getOperand(1);
8127 SDValue RHS = N->getOperand(2);
8129 // If we have SSE[12] support, try to form min/max nodes.
8130 if (Subtarget->hasSSE2() &&
8131 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
8132 Cond.getOpcode() == ISD::SETCC) {
8133 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
8135 unsigned Opcode = 0;
8136 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
8139 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
8142 if (!UnsafeFPMath) break;
8144 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
8146 Opcode = X86ISD::FMIN;
8149 case ISD::SETOGT: // (X > Y) ? X : Y -> max
8152 if (!UnsafeFPMath) break;
8154 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
8156 Opcode = X86ISD::FMAX;
8159 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
8162 case ISD::SETOGT: // (X > Y) ? Y : X -> min
8165 if (!UnsafeFPMath) break;
8167 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
8169 Opcode = X86ISD::FMIN;
8172 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
8175 if (!UnsafeFPMath) break;
8177 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
8179 Opcode = X86ISD::FMAX;
8185 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
8191 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
8193 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
8194 const X86Subtarget *Subtarget) {
8195 // On X86 with SSE2 support, we can transform this to a vector shift if
8196 // all elements are shifted by the same amount. We can't do this in legalize
8197 // because the a constant vector is typically transformed to a constant pool
8198 // so we have no knowledge of the shift amount.
8199 if (!Subtarget->hasSSE2())
8202 MVT VT = N->getValueType(0);
8203 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
8206 SDValue ShAmtOp = N->getOperand(1);
8207 MVT EltVT = VT.getVectorElementType();
8208 DebugLoc DL = N->getDebugLoc();
8210 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
8211 unsigned NumElts = VT.getVectorNumElements();
8213 for (; i != NumElts; ++i) {
8214 SDValue Arg = ShAmtOp.getOperand(i);
8215 if (Arg.getOpcode() == ISD::UNDEF) continue;
8219 for (; i != NumElts; ++i) {
8220 SDValue Arg = ShAmtOp.getOperand(i);
8221 if (Arg.getOpcode() == ISD::UNDEF) continue;
8222 if (Arg != BaseShAmt) {
8226 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
8227 isSplatMask(ShAmtOp.getOperand(2).getNode())) {
8228 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
8229 DAG.getIntPtrConstant(0));
8233 if (EltVT.bitsGT(MVT::i32))
8234 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
8235 else if (EltVT.bitsLT(MVT::i32))
8236 BaseShAmt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, BaseShAmt);
8238 // The shift amount is identical so we can do a vector shift.
8239 SDValue ValOp = N->getOperand(0);
8240 switch (N->getOpcode()) {
8242 assert(0 && "Unknown shift opcode!");
8245 if (VT == MVT::v2i64)
8246 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8247 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8249 if (VT == MVT::v4i32)
8250 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8251 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8253 if (VT == MVT::v8i16)
8254 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8255 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8259 if (VT == MVT::v4i32)
8260 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8261 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8263 if (VT == MVT::v8i16)
8264 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8265 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8269 if (VT == MVT::v2i64)
8270 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8271 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8273 if (VT == MVT::v4i32)
8274 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8275 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8277 if (VT == MVT::v8i16)
8278 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8279 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8286 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
8287 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
8288 const X86Subtarget *Subtarget) {
8289 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
8290 // the FP state in cases where an emms may be missing.
8291 // A preferable solution to the general problem is to figure out the right
8292 // places to insert EMMS. This qualifies as a quick hack.
8293 StoreSDNode *St = cast<StoreSDNode>(N);
8294 if (St->getValue().getValueType().isVector() &&
8295 St->getValue().getValueType().getSizeInBits() == 64 &&
8296 isa<LoadSDNode>(St->getValue()) &&
8297 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
8298 St->getChain().hasOneUse() && !St->isVolatile()) {
8299 SDNode* LdVal = St->getValue().getNode();
8301 int TokenFactorIndex = -1;
8302 SmallVector<SDValue, 8> Ops;
8303 SDNode* ChainVal = St->getChain().getNode();
8304 // Must be a store of a load. We currently handle two cases: the load
8305 // is a direct child, and it's under an intervening TokenFactor. It is
8306 // possible to dig deeper under nested TokenFactors.
8307 if (ChainVal == LdVal)
8308 Ld = cast<LoadSDNode>(St->getChain());
8309 else if (St->getValue().hasOneUse() &&
8310 ChainVal->getOpcode() == ISD::TokenFactor) {
8311 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
8312 if (ChainVal->getOperand(i).getNode() == LdVal) {
8313 TokenFactorIndex = i;
8314 Ld = cast<LoadSDNode>(St->getValue());
8316 Ops.push_back(ChainVal->getOperand(i));
8320 DebugLoc DL = N->getDebugLoc();
8321 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
8322 if (Subtarget->is64Bit()) {
8323 SDValue NewLd = DAG.getLoad(MVT::i64, DL, Ld->getChain(),
8324 Ld->getBasePtr(), Ld->getSrcValue(),
8325 Ld->getSrcValueOffset(), Ld->isVolatile(),
8326 Ld->getAlignment());
8327 SDValue NewChain = NewLd.getValue(1);
8328 if (TokenFactorIndex != -1) {
8329 Ops.push_back(NewChain);
8330 NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Ops[0],
8333 return DAG.getStore(NewChain, DL, NewLd, St->getBasePtr(),
8334 St->getSrcValue(), St->getSrcValueOffset(),
8335 St->isVolatile(), St->getAlignment());
8338 // Otherwise, lower to two 32-bit copies.
8339 SDValue LoAddr = Ld->getBasePtr();
8340 SDValue HiAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, LoAddr,
8341 DAG.getConstant(4, MVT::i32));
8343 SDValue LoLd = DAG.getLoad(MVT::i32, DL, Ld->getChain(), LoAddr,
8344 Ld->getSrcValue(), Ld->getSrcValueOffset(),
8345 Ld->isVolatile(), Ld->getAlignment());
8346 SDValue HiLd = DAG.getLoad(MVT::i32, DL, Ld->getChain(), HiAddr,
8347 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
8349 MinAlign(Ld->getAlignment(), 4));
8351 SDValue NewChain = LoLd.getValue(1);
8352 if (TokenFactorIndex != -1) {
8353 Ops.push_back(LoLd);
8354 Ops.push_back(HiLd);
8355 NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &Ops[0],
8359 LoAddr = St->getBasePtr();
8360 HiAddr = DAG.getNode(ISD::ADD, DL, MVT::i32, LoAddr,
8361 DAG.getConstant(4, MVT::i32));
8363 SDValue LoSt = DAG.getStore(NewChain, DL, LoLd, LoAddr,
8364 St->getSrcValue(), St->getSrcValueOffset(),
8365 St->isVolatile(), St->getAlignment());
8366 SDValue HiSt = DAG.getStore(NewChain, DL, HiLd, HiAddr,
8368 St->getSrcValueOffset() + 4,
8370 MinAlign(St->getAlignment(), 4));
8371 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, LoSt, HiSt);
8377 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
8378 /// X86ISD::FXOR nodes.
8379 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
8380 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
8381 // F[X]OR(0.0, x) -> x
8382 // F[X]OR(x, 0.0) -> x
8383 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8384 if (C->getValueAPF().isPosZero())
8385 return N->getOperand(1);
8386 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8387 if (C->getValueAPF().isPosZero())
8388 return N->getOperand(0);
8392 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
8393 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
8394 // FAND(0.0, x) -> 0.0
8395 // FAND(x, 0.0) -> 0.0
8396 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8397 if (C->getValueAPF().isPosZero())
8398 return N->getOperand(0);
8399 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8400 if (C->getValueAPF().isPosZero())
8401 return N->getOperand(1);
8405 static SDValue PerformBTCombine(SDNode *N,
8407 TargetLowering::DAGCombinerInfo &DCI) {
8408 // BT ignores high bits in the bit index operand.
8409 SDValue Op1 = N->getOperand(1);
8410 if (Op1.hasOneUse()) {
8411 unsigned BitWidth = Op1.getValueSizeInBits();
8412 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
8413 APInt KnownZero, KnownOne;
8414 TargetLowering::TargetLoweringOpt TLO(DAG);
8415 TargetLowering &TLI = DAG.getTargetLoweringInfo();
8416 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
8417 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
8418 DCI.CommitTargetLoweringOpt(TLO);
8423 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
8424 DAGCombinerInfo &DCI) const {
8425 SelectionDAG &DAG = DCI.DAG;
8426 switch (N->getOpcode()) {
8428 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
8429 case ISD::BUILD_VECTOR:
8430 return PerformBuildVectorCombine(N, DAG, DCI, Subtarget, *this);
8431 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
8434 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
8435 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
8437 case X86ISD::FOR: return PerformFORCombine(N, DAG);
8438 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
8439 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
8445 //===----------------------------------------------------------------------===//
8446 // X86 Inline Assembly Support
8447 //===----------------------------------------------------------------------===//
8449 /// getConstraintType - Given a constraint letter, return the type of
8450 /// constraint it is for this target.
8451 X86TargetLowering::ConstraintType
8452 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
8453 if (Constraint.size() == 1) {
8454 switch (Constraint[0]) {
8466 return C_RegisterClass;
8474 return TargetLowering::getConstraintType(Constraint);
8477 /// LowerXConstraint - try to replace an X constraint, which matches anything,
8478 /// with another that has more specific requirements based on the type of the
8479 /// corresponding operand.
8480 const char *X86TargetLowering::
8481 LowerXConstraint(MVT ConstraintVT) const {
8482 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
8483 // 'f' like normal targets.
8484 if (ConstraintVT.isFloatingPoint()) {
8485 if (Subtarget->hasSSE2())
8487 if (Subtarget->hasSSE1())
8491 return TargetLowering::LowerXConstraint(ConstraintVT);
8494 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8495 /// vector. If it is invalid, don't add anything to Ops.
8496 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8499 std::vector<SDValue>&Ops,
8500 SelectionDAG &DAG) const {
8501 SDValue Result(0, 0);
8503 switch (Constraint) {
8506 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8507 if (C->getZExtValue() <= 31) {
8508 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8514 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8515 if (C->getZExtValue() <= 63) {
8516 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8522 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8523 if (C->getZExtValue() <= 255) {
8524 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8530 // 32-bit signed value
8531 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8532 const ConstantInt *CI = C->getConstantIntValue();
8533 if (CI->isValueValidForType(Type::Int32Ty, C->getSExtValue())) {
8534 // Widen to 64 bits here to get it sign extended.
8535 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
8538 // FIXME gcc accepts some relocatable values here too, but only in certain
8539 // memory models; it's complicated.
8544 // 32-bit unsigned value
8545 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8546 const ConstantInt *CI = C->getConstantIntValue();
8547 if (CI->isValueValidForType(Type::Int32Ty, C->getZExtValue())) {
8548 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8552 // FIXME gcc accepts some relocatable values here too, but only in certain
8553 // memory models; it's complicated.
8557 // Literal immediates are always ok.
8558 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
8559 // Widen to 64 bits here to get it sign extended.
8560 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
8564 // If we are in non-pic codegen mode, we allow the address of a global (with
8565 // an optional displacement) to be used with 'i'.
8566 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
8569 // Match either (GA) or (GA+C)
8571 Offset = GA->getOffset();
8572 } else if (Op.getOpcode() == ISD::ADD) {
8573 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8574 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
8576 Offset = GA->getOffset()+C->getZExtValue();
8578 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8579 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
8581 Offset = GA->getOffset()+C->getZExtValue();
8589 Op = LowerGlobalAddress(GA->getGlobal(), Op.getDebugLoc(),
8592 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
8598 // Otherwise, not valid for this mode.
8603 if (Result.getNode()) {
8604 Ops.push_back(Result);
8607 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
8611 std::vector<unsigned> X86TargetLowering::
8612 getRegClassForInlineAsmConstraint(const std::string &Constraint,
8614 if (Constraint.size() == 1) {
8615 // FIXME: not handling fp-stack yet!
8616 switch (Constraint[0]) { // GCC X86 Constraint Letters
8617 default: break; // Unknown constraint letter
8618 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
8621 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
8622 else if (VT == MVT::i16)
8623 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
8624 else if (VT == MVT::i8)
8625 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
8626 else if (VT == MVT::i64)
8627 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
8632 return std::vector<unsigned>();
8635 std::pair<unsigned, const TargetRegisterClass*>
8636 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8638 // First, see if this is a constraint that directly corresponds to an LLVM
8640 if (Constraint.size() == 1) {
8641 // GCC Constraint Letters
8642 switch (Constraint[0]) {
8644 case 'r': // GENERAL_REGS
8645 case 'R': // LEGACY_REGS
8646 case 'l': // INDEX_REGS
8648 return std::make_pair(0U, X86::GR8RegisterClass);
8650 return std::make_pair(0U, X86::GR16RegisterClass);
8651 if (VT == MVT::i32 || !Subtarget->is64Bit())
8652 return std::make_pair(0U, X86::GR32RegisterClass);
8653 return std::make_pair(0U, X86::GR64RegisterClass);
8654 case 'f': // FP Stack registers.
8655 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
8656 // value to the correct fpstack register class.
8657 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
8658 return std::make_pair(0U, X86::RFP32RegisterClass);
8659 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
8660 return std::make_pair(0U, X86::RFP64RegisterClass);
8661 return std::make_pair(0U, X86::RFP80RegisterClass);
8662 case 'y': // MMX_REGS if MMX allowed.
8663 if (!Subtarget->hasMMX()) break;
8664 return std::make_pair(0U, X86::VR64RegisterClass);
8665 case 'Y': // SSE_REGS if SSE2 allowed
8666 if (!Subtarget->hasSSE2()) break;
8668 case 'x': // SSE_REGS if SSE1 allowed
8669 if (!Subtarget->hasSSE1()) break;
8671 switch (VT.getSimpleVT()) {
8673 // Scalar SSE types.
8676 return std::make_pair(0U, X86::FR32RegisterClass);
8679 return std::make_pair(0U, X86::FR64RegisterClass);
8687 return std::make_pair(0U, X86::VR128RegisterClass);
8693 // Use the default implementation in TargetLowering to convert the register
8694 // constraint into a member of a register class.
8695 std::pair<unsigned, const TargetRegisterClass*> Res;
8696 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8698 // Not found as a standard register?
8699 if (Res.second == 0) {
8700 // GCC calls "st(0)" just plain "st".
8701 if (StringsEqualNoCase("{st}", Constraint)) {
8702 Res.first = X86::ST0;
8703 Res.second = X86::RFP80RegisterClass;
8705 // 'A' means EAX + EDX.
8706 if (Constraint == "A") {
8707 Res.first = X86::EAX;
8708 Res.second = X86::GRADRegisterClass;
8713 // Otherwise, check to see if this is a register class of the wrong value
8714 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
8715 // turn into {ax},{dx}.
8716 if (Res.second->hasType(VT))
8717 return Res; // Correct type already, nothing to do.
8719 // All of the single-register GCC register classes map their values onto
8720 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
8721 // really want an 8-bit or 32-bit register, map to the appropriate register
8722 // class and return the appropriate register.
8723 if (Res.second == X86::GR16RegisterClass) {
8724 if (VT == MVT::i8) {
8725 unsigned DestReg = 0;
8726 switch (Res.first) {
8728 case X86::AX: DestReg = X86::AL; break;
8729 case X86::DX: DestReg = X86::DL; break;
8730 case X86::CX: DestReg = X86::CL; break;
8731 case X86::BX: DestReg = X86::BL; break;
8734 Res.first = DestReg;
8735 Res.second = Res.second = X86::GR8RegisterClass;
8737 } else if (VT == MVT::i32) {
8738 unsigned DestReg = 0;
8739 switch (Res.first) {
8741 case X86::AX: DestReg = X86::EAX; break;
8742 case X86::DX: DestReg = X86::EDX; break;
8743 case X86::CX: DestReg = X86::ECX; break;
8744 case X86::BX: DestReg = X86::EBX; break;
8745 case X86::SI: DestReg = X86::ESI; break;
8746 case X86::DI: DestReg = X86::EDI; break;
8747 case X86::BP: DestReg = X86::EBP; break;
8748 case X86::SP: DestReg = X86::ESP; break;
8751 Res.first = DestReg;
8752 Res.second = Res.second = X86::GR32RegisterClass;
8754 } else if (VT == MVT::i64) {
8755 unsigned DestReg = 0;
8756 switch (Res.first) {
8758 case X86::AX: DestReg = X86::RAX; break;
8759 case X86::DX: DestReg = X86::RDX; break;
8760 case X86::CX: DestReg = X86::RCX; break;
8761 case X86::BX: DestReg = X86::RBX; break;
8762 case X86::SI: DestReg = X86::RSI; break;
8763 case X86::DI: DestReg = X86::RDI; break;
8764 case X86::BP: DestReg = X86::RBP; break;
8765 case X86::SP: DestReg = X86::RSP; break;
8768 Res.first = DestReg;
8769 Res.second = Res.second = X86::GR64RegisterClass;
8772 } else if (Res.second == X86::FR32RegisterClass ||
8773 Res.second == X86::FR64RegisterClass ||
8774 Res.second == X86::VR128RegisterClass) {
8775 // Handle references to XMM physical registers that got mapped into the
8776 // wrong class. This can happen with constraints like {xmm0} where the
8777 // target independent register mapper will just pick the first match it can
8778 // find, ignoring the required type.
8780 Res.second = X86::FR32RegisterClass;
8781 else if (VT == MVT::f64)
8782 Res.second = X86::FR64RegisterClass;
8783 else if (X86::VR128RegisterClass->hasType(VT))
8784 Res.second = X86::VR128RegisterClass;
8790 //===----------------------------------------------------------------------===//
8791 // X86 Widen vector type
8792 //===----------------------------------------------------------------------===//
8794 /// getWidenVectorType: given a vector type, returns the type to widen
8795 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
8796 /// If there is no vector type that we want to widen to, returns MVT::Other
8797 /// When and where to widen is target dependent based on the cost of
8798 /// scalarizing vs using the wider vector type.
8800 MVT X86TargetLowering::getWidenVectorType(MVT VT) const {
8801 assert(VT.isVector());
8802 if (isTypeLegal(VT))
8805 // TODO: In computeRegisterProperty, we can compute the list of legal vector
8806 // type based on element type. This would speed up our search (though
8807 // it may not be worth it since the size of the list is relatively
8809 MVT EltVT = VT.getVectorElementType();
8810 unsigned NElts = VT.getVectorNumElements();
8812 // On X86, it make sense to widen any vector wider than 1
8816 for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
8817 nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
8818 MVT SVT = (MVT::SimpleValueType)nVT;
8820 if (isTypeLegal(SVT) &&
8821 SVT.getVectorElementType() == EltVT &&
8822 SVT.getVectorNumElements() > NElts)