1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
16 #include "X86InstrBuilder.h"
17 #include "X86ISelLowering.h"
18 #include "X86MachineFunctionInfo.h"
19 #include "X86TargetMachine.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Function.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/ADT/BitVector.h"
27 #include "llvm/ADT/VectorExtras.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/PseudoSourceValue.h"
35 #include "llvm/CodeGen/SelectionDAG.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/ADT/SmallSet.h"
40 #include "llvm/ADT/StringExtras.h"
41 #include "llvm/Support/CommandLine.h"
45 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
47 // Forward declarations.
48 static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG, DebugLoc dl);
50 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
51 : TargetLowering(TM) {
52 Subtarget = &TM.getSubtarget<X86Subtarget>();
53 X86ScalarSSEf64 = Subtarget->hasSSE2();
54 X86ScalarSSEf32 = Subtarget->hasSSE1();
55 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
59 RegInfo = TM.getRegisterInfo();
62 // Set up the TargetLowering object.
64 // X86 is weird, it always uses i8 for shift amounts and setcc results.
65 setShiftAmountType(MVT::i8);
66 setBooleanContents(ZeroOrOneBooleanContent);
67 setSchedulingPreference(SchedulingForRegPressure);
68 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
69 setStackPointerRegisterToSaveRestore(X86StackPtr);
71 if (Subtarget->isTargetDarwin()) {
72 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
73 setUseUnderscoreSetJmp(false);
74 setUseUnderscoreLongJmp(false);
75 } else if (Subtarget->isTargetMingw()) {
76 // MS runtime is weird: it exports _setjmp, but longjmp!
77 setUseUnderscoreSetJmp(true);
78 setUseUnderscoreLongJmp(false);
80 setUseUnderscoreSetJmp(true);
81 setUseUnderscoreLongJmp(true);
84 // Set up the register classes.
85 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
86 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
87 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
88 if (Subtarget->is64Bit())
89 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
91 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
93 // We don't accept any truncstore of integer registers.
94 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
95 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
96 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
97 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
98 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
99 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
101 // SETOEQ and SETUNE require checking two conditions.
102 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
103 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
104 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
105 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
106 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
107 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
109 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
111 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
112 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
113 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
115 if (Subtarget->is64Bit()) {
116 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
117 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
119 if (X86ScalarSSEf64) {
120 // We have an impenetrably clever algorithm for ui64->double only.
121 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
123 // We have faster algorithm for ui32->single only.
124 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
126 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
129 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
131 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
132 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
133 // SSE has no i16 to fp conversion, only i32
134 if (X86ScalarSSEf32) {
135 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
136 // f32 and f64 cases are Legal, f80 case is not
137 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
139 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
140 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
143 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
144 // are Legal, f80 is custom lowered.
145 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
146 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
148 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
150 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
151 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
153 if (X86ScalarSSEf32) {
154 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
155 // f32 and f64 cases are Legal, f80 case is not
156 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
158 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
159 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
162 // Handle FP_TO_UINT by promoting the destination to a larger signed
164 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
165 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
166 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
168 if (Subtarget->is64Bit()) {
169 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
170 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
172 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
173 // Expand FP_TO_UINT into a select.
174 // FIXME: We would like to use a Custom expander here eventually to do
175 // the optimal thing for SSE vs. the default expansion in the legalizer.
176 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
178 // With SSE3 we can use fisttpll to convert to a signed i64.
179 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
182 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
183 if (!X86ScalarSSEf64) {
184 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
185 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
188 // Scalar integer divide and remainder are lowered to use operations that
189 // produce two results, to match the available instructions. This exposes
190 // the two-result form to trivial CSE, which is able to combine x/y and x%y
191 // into a single instruction.
193 // Scalar integer multiply-high is also lowered to use two-result
194 // operations, to match the available instructions. However, plain multiply
195 // (low) operations are left as Legal, as there are single-result
196 // instructions for this in x86. Using the two-result multiply instructions
197 // when both high and low results are needed must be arranged by dagcombine.
198 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
199 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
200 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
201 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
202 setOperationAction(ISD::SREM , MVT::i8 , Expand);
203 setOperationAction(ISD::UREM , MVT::i8 , Expand);
204 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
205 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
206 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
207 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
208 setOperationAction(ISD::SREM , MVT::i16 , Expand);
209 setOperationAction(ISD::UREM , MVT::i16 , Expand);
210 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
211 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
212 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
213 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
214 setOperationAction(ISD::SREM , MVT::i32 , Expand);
215 setOperationAction(ISD::UREM , MVT::i32 , Expand);
216 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
217 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
218 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
219 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
220 setOperationAction(ISD::SREM , MVT::i64 , Expand);
221 setOperationAction(ISD::UREM , MVT::i64 , Expand);
223 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
224 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
225 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
226 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
227 if (Subtarget->is64Bit())
228 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
229 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
230 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
231 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
232 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
233 setOperationAction(ISD::FREM , MVT::f32 , Expand);
234 setOperationAction(ISD::FREM , MVT::f64 , Expand);
235 setOperationAction(ISD::FREM , MVT::f80 , Expand);
236 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
238 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
239 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
240 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
241 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
242 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
243 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
244 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
245 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
246 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
247 if (Subtarget->is64Bit()) {
248 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
249 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
250 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
253 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
254 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
256 // These should be promoted to a larger select which is supported.
257 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
258 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
259 // X86 wants to expand cmov itself.
260 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
261 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
262 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
263 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
264 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
265 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
266 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
267 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
268 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
269 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
270 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
271 if (Subtarget->is64Bit()) {
272 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
273 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
275 // X86 ret instruction may pop stack.
276 setOperationAction(ISD::RET , MVT::Other, Custom);
277 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
280 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
281 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
282 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
283 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
284 if (Subtarget->is64Bit())
285 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
286 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
287 if (Subtarget->is64Bit()) {
288 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
289 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
290 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
291 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
293 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
294 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
295 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
296 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
297 if (Subtarget->is64Bit()) {
298 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
299 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
300 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
303 if (Subtarget->hasSSE1())
304 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
306 if (!Subtarget->hasSSE2())
307 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
309 // Expand certain atomics
310 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
311 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
312 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
313 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
315 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
316 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
317 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
318 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
320 if (!Subtarget->is64Bit()) {
321 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
322 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
323 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
324 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
325 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
326 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
327 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
330 // Use the default ISD::DBG_STOPPOINT, ISD::DECLARE expansion.
331 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
332 // FIXME - use subtarget debug flags
333 if (!Subtarget->isTargetDarwin() &&
334 !Subtarget->isTargetELF() &&
335 !Subtarget->isTargetCygMing()) {
336 setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
337 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
340 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
341 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
342 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
343 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
344 if (Subtarget->is64Bit()) {
345 setExceptionPointerRegister(X86::RAX);
346 setExceptionSelectorRegister(X86::RDX);
348 setExceptionPointerRegister(X86::EAX);
349 setExceptionSelectorRegister(X86::EDX);
351 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
352 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
354 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
356 setOperationAction(ISD::TRAP, MVT::Other, Legal);
358 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
359 setOperationAction(ISD::VASTART , MVT::Other, Custom);
360 setOperationAction(ISD::VAEND , MVT::Other, Expand);
361 if (Subtarget->is64Bit()) {
362 setOperationAction(ISD::VAARG , MVT::Other, Custom);
363 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
365 setOperationAction(ISD::VAARG , MVT::Other, Expand);
366 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
369 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
370 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
371 if (Subtarget->is64Bit())
372 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
373 if (Subtarget->isTargetCygMing())
374 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
376 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
378 if (X86ScalarSSEf64) {
379 // f32 and f64 use SSE.
380 // Set up the FP register classes.
381 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
382 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
384 // Use ANDPD to simulate FABS.
385 setOperationAction(ISD::FABS , MVT::f64, Custom);
386 setOperationAction(ISD::FABS , MVT::f32, Custom);
388 // Use XORP to simulate FNEG.
389 setOperationAction(ISD::FNEG , MVT::f64, Custom);
390 setOperationAction(ISD::FNEG , MVT::f32, Custom);
392 // Use ANDPD and ORPD to simulate FCOPYSIGN.
393 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
394 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
396 // We don't support sin/cos/fmod
397 setOperationAction(ISD::FSIN , MVT::f64, Expand);
398 setOperationAction(ISD::FCOS , MVT::f64, Expand);
399 setOperationAction(ISD::FSIN , MVT::f32, Expand);
400 setOperationAction(ISD::FCOS , MVT::f32, Expand);
402 // Expand FP immediates into loads from the stack, except for the special
404 addLegalFPImmediate(APFloat(+0.0)); // xorpd
405 addLegalFPImmediate(APFloat(+0.0f)); // xorps
407 // Floating truncations from f80 and extensions to f80 go through memory.
408 // If optimizing, we lie about this though and handle it in
409 // InstructionSelectPreprocess so that dagcombine2 can hack on these.
411 setConvertAction(MVT::f32, MVT::f80, Expand);
412 setConvertAction(MVT::f64, MVT::f80, Expand);
413 setConvertAction(MVT::f80, MVT::f32, Expand);
414 setConvertAction(MVT::f80, MVT::f64, Expand);
416 } else if (X86ScalarSSEf32) {
417 // Use SSE for f32, x87 for f64.
418 // Set up the FP register classes.
419 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
420 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
422 // Use ANDPS to simulate FABS.
423 setOperationAction(ISD::FABS , MVT::f32, Custom);
425 // Use XORP to simulate FNEG.
426 setOperationAction(ISD::FNEG , MVT::f32, Custom);
428 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
430 // Use ANDPS and ORPS to simulate FCOPYSIGN.
431 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
432 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
434 // We don't support sin/cos/fmod
435 setOperationAction(ISD::FSIN , MVT::f32, Expand);
436 setOperationAction(ISD::FCOS , MVT::f32, Expand);
438 // Special cases we handle for FP constants.
439 addLegalFPImmediate(APFloat(+0.0f)); // xorps
440 addLegalFPImmediate(APFloat(+0.0)); // FLD0
441 addLegalFPImmediate(APFloat(+1.0)); // FLD1
442 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
443 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
445 // SSE <-> X87 conversions go through memory. If optimizing, we lie about
446 // this though and handle it in InstructionSelectPreprocess so that
447 // dagcombine2 can hack on these.
449 setConvertAction(MVT::f32, MVT::f64, Expand);
450 setConvertAction(MVT::f32, MVT::f80, Expand);
451 setConvertAction(MVT::f80, MVT::f32, Expand);
452 setConvertAction(MVT::f64, MVT::f32, Expand);
453 // And x87->x87 truncations also.
454 setConvertAction(MVT::f80, MVT::f64, Expand);
458 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
459 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
462 // f32 and f64 in x87.
463 // Set up the FP register classes.
464 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
465 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
467 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
468 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
469 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
470 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
472 // Floating truncations go through memory. If optimizing, we lie about
473 // this though and handle it in InstructionSelectPreprocess so that
474 // dagcombine2 can hack on these.
476 setConvertAction(MVT::f80, MVT::f32, Expand);
477 setConvertAction(MVT::f64, MVT::f32, Expand);
478 setConvertAction(MVT::f80, MVT::f64, Expand);
482 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
483 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
485 addLegalFPImmediate(APFloat(+0.0)); // FLD0
486 addLegalFPImmediate(APFloat(+1.0)); // FLD1
487 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
488 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
489 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
490 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
491 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
492 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
495 // Long double always uses X87.
496 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
497 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
498 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
501 APFloat TmpFlt(+0.0);
502 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
504 addLegalFPImmediate(TmpFlt); // FLD0
506 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
507 APFloat TmpFlt2(+1.0);
508 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
510 addLegalFPImmediate(TmpFlt2); // FLD1
511 TmpFlt2.changeSign();
512 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
516 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
517 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
520 // Always use a library call for pow.
521 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
522 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
523 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
525 setOperationAction(ISD::FLOG, MVT::f80, Expand);
526 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
527 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
528 setOperationAction(ISD::FEXP, MVT::f80, Expand);
529 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
531 // First set operation action for all vector types to either promote
532 // (for widening) or expand (for scalarization). Then we will selectively
533 // turn on ones that can be effectively codegen'd.
534 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
535 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
536 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
537 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
538 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
539 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
540 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
541 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
542 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
543 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
544 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
545 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
546 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
547 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
548 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
549 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
550 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
551 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
552 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
553 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
554 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
555 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
556 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
557 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
558 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
559 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
560 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
561 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
562 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
563 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
564 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
565 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
566 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
567 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
568 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
569 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
570 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
571 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
572 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
573 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
574 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
575 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
576 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
577 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
578 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
581 if (!DisableMMX && Subtarget->hasMMX()) {
582 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
583 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
584 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
585 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
586 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
588 // FIXME: add MMX packed arithmetics
590 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
591 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
592 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
593 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
595 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
596 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
597 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
598 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
600 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
601 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
603 setOperationAction(ISD::AND, MVT::v8i8, Promote);
604 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
605 setOperationAction(ISD::AND, MVT::v4i16, Promote);
606 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
607 setOperationAction(ISD::AND, MVT::v2i32, Promote);
608 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
609 setOperationAction(ISD::AND, MVT::v1i64, Legal);
611 setOperationAction(ISD::OR, MVT::v8i8, Promote);
612 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
613 setOperationAction(ISD::OR, MVT::v4i16, Promote);
614 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
615 setOperationAction(ISD::OR, MVT::v2i32, Promote);
616 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
617 setOperationAction(ISD::OR, MVT::v1i64, Legal);
619 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
620 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
621 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
622 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
623 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
624 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
625 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
627 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
628 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
629 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
630 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
631 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
632 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
633 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
634 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
635 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
637 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
638 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
639 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
640 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
641 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
643 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
644 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
645 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
646 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
648 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
649 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
650 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
651 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
653 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
655 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
656 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Expand);
657 setOperationAction(ISD::SELECT, MVT::v8i8, Promote);
658 setOperationAction(ISD::SELECT, MVT::v4i16, Promote);
659 setOperationAction(ISD::SELECT, MVT::v2i32, Promote);
660 setOperationAction(ISD::SELECT, MVT::v1i64, Custom);
663 if (Subtarget->hasSSE1()) {
664 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
666 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
667 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
668 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
669 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
670 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
671 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
672 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
673 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
674 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
675 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
676 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
677 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
680 if (Subtarget->hasSSE2()) {
681 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
682 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
683 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
684 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
685 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
687 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
688 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
689 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
690 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
691 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
692 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
693 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
694 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
695 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
696 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
697 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
698 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
699 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
700 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
701 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
702 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
704 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
705 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
706 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
707 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
709 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
710 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
711 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
712 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
713 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
715 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
716 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
717 MVT VT = (MVT::SimpleValueType)i;
718 // Do not attempt to custom lower non-power-of-2 vectors
719 if (!isPowerOf2_32(VT.getVectorNumElements()))
721 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
722 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
723 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
725 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
726 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
727 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
728 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
729 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
730 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
731 if (Subtarget->is64Bit()) {
732 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
733 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
736 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
737 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
738 setOperationAction(ISD::AND, (MVT::SimpleValueType)VT, Promote);
739 AddPromotedToType (ISD::AND, (MVT::SimpleValueType)VT, MVT::v2i64);
740 setOperationAction(ISD::OR, (MVT::SimpleValueType)VT, Promote);
741 AddPromotedToType (ISD::OR, (MVT::SimpleValueType)VT, MVT::v2i64);
742 setOperationAction(ISD::XOR, (MVT::SimpleValueType)VT, Promote);
743 AddPromotedToType (ISD::XOR, (MVT::SimpleValueType)VT, MVT::v2i64);
744 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Promote);
745 AddPromotedToType (ISD::LOAD, (MVT::SimpleValueType)VT, MVT::v2i64);
746 setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
747 AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v2i64);
750 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
752 // Custom lower v2i64 and v2f64 selects.
753 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
754 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
755 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
756 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
760 if (Subtarget->hasSSE41()) {
761 // FIXME: Do we need to handle scalar-to-vector here?
762 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
764 // i8 and i16 vectors are custom , because the source register and source
765 // source memory operand types are not the same width. f32 vectors are
766 // custom since the immediate controlling the insert encodes additional
768 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
769 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
770 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
771 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
773 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
774 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
775 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
776 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
778 if (Subtarget->is64Bit()) {
779 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
780 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
784 if (Subtarget->hasSSE42()) {
785 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
788 // We want to custom lower some of our intrinsics.
789 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
791 // Add/Sub/Mul with overflow operations are custom lowered.
792 setOperationAction(ISD::SADDO, MVT::i32, Custom);
793 setOperationAction(ISD::SADDO, MVT::i64, Custom);
794 setOperationAction(ISD::UADDO, MVT::i32, Custom);
795 setOperationAction(ISD::UADDO, MVT::i64, Custom);
796 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
797 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
798 setOperationAction(ISD::USUBO, MVT::i32, Custom);
799 setOperationAction(ISD::USUBO, MVT::i64, Custom);
800 setOperationAction(ISD::SMULO, MVT::i32, Custom);
801 setOperationAction(ISD::SMULO, MVT::i64, Custom);
802 setOperationAction(ISD::UMULO, MVT::i32, Custom);
803 setOperationAction(ISD::UMULO, MVT::i64, Custom);
805 // We have target-specific dag combine patterns for the following nodes:
806 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
807 setTargetDAGCombine(ISD::BUILD_VECTOR);
808 setTargetDAGCombine(ISD::SELECT);
809 setTargetDAGCombine(ISD::SHL);
810 setTargetDAGCombine(ISD::SRA);
811 setTargetDAGCombine(ISD::SRL);
812 setTargetDAGCombine(ISD::STORE);
814 computeRegisterProperties();
816 // FIXME: These should be based on subtarget info. Plus, the values should
817 // be smaller when we are in optimizing for size mode.
818 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
819 maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
820 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
821 allowUnalignedMemoryAccesses = true; // x86 supports it!
822 setPrefLoopAlignment(16);
826 MVT X86TargetLowering::getSetCCResultType(MVT VT) const {
831 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
832 /// the desired ByVal argument alignment.
833 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
836 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
837 if (VTy->getBitWidth() == 128)
839 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
840 unsigned EltAlign = 0;
841 getMaxByValAlign(ATy->getElementType(), EltAlign);
842 if (EltAlign > MaxAlign)
844 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
845 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
846 unsigned EltAlign = 0;
847 getMaxByValAlign(STy->getElementType(i), EltAlign);
848 if (EltAlign > MaxAlign)
857 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
858 /// function arguments in the caller parameter area. For X86, aggregates
859 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
860 /// are at 4-byte boundaries.
861 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
862 if (Subtarget->is64Bit()) {
863 // Max of 8 and alignment of type.
864 unsigned TyAlign = TD->getABITypeAlignment(Ty);
871 if (Subtarget->hasSSE1())
872 getMaxByValAlign(Ty, Align);
876 /// getOptimalMemOpType - Returns the target specific optimal type for load
877 /// and store operations as a result of memset, memcpy, and memmove
878 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
881 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
882 bool isSrcConst, bool isSrcStr) const {
883 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
884 // linux. This is because the stack realignment code can't handle certain
885 // cases like PR2962. This should be removed when PR2962 is fixed.
886 if (Subtarget->getStackAlignment() >= 16) {
887 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
889 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
892 if (Subtarget->is64Bit() && Size >= 8)
898 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
900 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
901 SelectionDAG &DAG) const {
902 if (usesGlobalOffsetTable())
903 return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
904 if (!Subtarget->isPICStyleRIPRel())
905 return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
909 //===----------------------------------------------------------------------===//
910 // Return Value Calling Convention Implementation
911 //===----------------------------------------------------------------------===//
913 #include "X86GenCallingConv.inc"
915 /// LowerRET - Lower an ISD::RET node.
916 SDValue X86TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
917 DebugLoc dl = Op.getNode()->getDebugLoc();
918 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
920 SmallVector<CCValAssign, 16> RVLocs;
921 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
922 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
923 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
924 CCInfo.AnalyzeReturn(Op.getNode(), RetCC_X86);
926 // If this is the first return lowered for this function, add the regs to the
927 // liveout set for the function.
928 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
929 for (unsigned i = 0; i != RVLocs.size(); ++i)
930 if (RVLocs[i].isRegLoc())
931 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
933 SDValue Chain = Op.getOperand(0);
935 // Handle tail call return.
936 Chain = GetPossiblePreceedingTailCall(Chain, X86ISD::TAILCALL);
937 if (Chain.getOpcode() == X86ISD::TAILCALL) {
938 SDValue TailCall = Chain;
939 SDValue TargetAddress = TailCall.getOperand(1);
940 SDValue StackAdjustment = TailCall.getOperand(2);
941 assert(((TargetAddress.getOpcode() == ISD::Register &&
942 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::EAX ||
943 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
944 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
945 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
946 "Expecting an global address, external symbol, or register");
947 assert(StackAdjustment.getOpcode() == ISD::Constant &&
948 "Expecting a const value");
950 SmallVector<SDValue,8> Operands;
951 Operands.push_back(Chain.getOperand(0));
952 Operands.push_back(TargetAddress);
953 Operands.push_back(StackAdjustment);
954 // Copy registers used by the call. Last operand is a flag so it is not
956 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
957 Operands.push_back(Chain.getOperand(i));
959 return DAG.getNode(X86ISD::TC_RETURN, dl, MVT::Other, &Operands[0],
966 SmallVector<SDValue, 6> RetOps;
967 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
968 // Operand #1 = Bytes To Pop
969 RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
971 // Copy the result values into the output registers.
972 for (unsigned i = 0; i != RVLocs.size(); ++i) {
973 CCValAssign &VA = RVLocs[i];
974 assert(VA.isRegLoc() && "Can only return in registers!");
975 SDValue ValToCopy = Op.getOperand(i*2+1);
977 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
978 // the RET instruction and handled by the FP Stackifier.
979 if (RVLocs[i].getLocReg() == X86::ST0 ||
980 RVLocs[i].getLocReg() == X86::ST1) {
981 // If this is a copy from an xmm register to ST(0), use an FPExtend to
982 // change the value to the FP stack register class.
983 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT()))
984 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
985 RetOps.push_back(ValToCopy);
986 // Don't emit a copytoreg.
990 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), ValToCopy, Flag);
991 Flag = Chain.getValue(1);
994 // The x86-64 ABI for returning structs by value requires that we copy
995 // the sret argument into %rax for the return. We saved the argument into
996 // a virtual register in the entry block, so now we copy the value out
998 if (Subtarget->is64Bit() &&
999 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1000 MachineFunction &MF = DAG.getMachineFunction();
1001 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1002 unsigned Reg = FuncInfo->getSRetReturnReg();
1004 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1005 FuncInfo->setSRetReturnReg(Reg);
1007 SDValue Val = DAG.getCopyFromReg(Chain, Reg, getPointerTy());
1009 Chain = DAG.getCopyToReg(Chain, X86::RAX, Val, Flag);
1010 Flag = Chain.getValue(1);
1013 RetOps[0] = Chain; // Update chain.
1015 // Add the flag if we have it.
1017 RetOps.push_back(Flag);
1019 return DAG.getNode(X86ISD::RET_FLAG, dl,
1020 MVT::Other, &RetOps[0], RetOps.size());
1024 /// LowerCallResult - Lower the result values of an ISD::CALL into the
1025 /// appropriate copies out of appropriate physical registers. This assumes that
1026 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
1027 /// being lowered. The returns a SDNode with the same number of values as the
1029 SDNode *X86TargetLowering::
1030 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall,
1031 unsigned CallingConv, SelectionDAG &DAG) {
1033 DebugLoc dl = TheCall->getDebugLoc();
1034 // Assign locations to each value returned by this call.
1035 SmallVector<CCValAssign, 16> RVLocs;
1036 bool isVarArg = TheCall->isVarArg();
1037 bool Is64Bit = Subtarget->is64Bit();
1038 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
1039 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
1041 SmallVector<SDValue, 8> ResultVals;
1043 // Copy all of the result registers out of their specified physreg.
1044 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1045 MVT CopyVT = RVLocs[i].getValVT();
1047 // If this is x86-64, and we disabled SSE, we can't return FP values
1048 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1049 ((Is64Bit || TheCall->isInreg()) && !Subtarget->hasSSE1())) {
1050 cerr << "SSE register return with SSE disabled\n";
1054 // If this is a call to a function that returns an fp value on the floating
1055 // point stack, but where we prefer to use the value in xmm registers, copy
1056 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1057 if ((RVLocs[i].getLocReg() == X86::ST0 ||
1058 RVLocs[i].getLocReg() == X86::ST1) &&
1059 isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
1063 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
1064 CopyVT, InFlag).getValue(1);
1065 SDValue Val = Chain.getValue(0);
1066 InFlag = Chain.getValue(2);
1068 if (CopyVT != RVLocs[i].getValVT()) {
1069 // Round the F80 the right size, which also moves to the appropriate xmm
1071 Val = DAG.getNode(ISD::FP_ROUND, dl, RVLocs[i].getValVT(), Val,
1072 // This truncation won't change the value.
1073 DAG.getIntPtrConstant(1));
1076 ResultVals.push_back(Val);
1079 // Merge everything together with a MERGE_VALUES node.
1080 ResultVals.push_back(Chain);
1081 return DAG.getNode(ISD::MERGE_VALUES, dl, TheCall->getVTList(),
1082 &ResultVals[0], ResultVals.size()).getNode();
1086 //===----------------------------------------------------------------------===//
1087 // C & StdCall & Fast Calling Convention implementation
1088 //===----------------------------------------------------------------------===//
1089 // StdCall calling convention seems to be standard for many Windows' API
1090 // routines and around. It differs from C calling convention just a little:
1091 // callee should clean up the stack, not caller. Symbols should be also
1092 // decorated in some fancy way :) It doesn't support any vector arguments.
1093 // For info on fast calling convention see Fast Calling Convention (tail call)
1094 // implementation LowerX86_32FastCCCallTo.
1096 /// AddLiveIn - This helper function adds the specified physical register to the
1097 /// MachineFunction as a live in value. It also creates a corresponding virtual
1098 /// register for it.
1099 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
1100 const TargetRegisterClass *RC) {
1101 assert(RC->contains(PReg) && "Not the correct regclass!");
1102 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
1103 MF.getRegInfo().addLiveIn(PReg, VReg);
1107 /// CallIsStructReturn - Determines whether a CALL node uses struct return
1109 static bool CallIsStructReturn(CallSDNode *TheCall) {
1110 unsigned NumOps = TheCall->getNumArgs();
1114 return TheCall->getArgFlags(0).isSRet();
1117 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
1118 /// return semantics.
1119 static bool ArgsAreStructReturn(SDValue Op) {
1120 unsigned NumArgs = Op.getNode()->getNumValues() - 1;
1124 return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
1127 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
1128 /// the callee to pop its own arguments. Callee pop is necessary to support tail
1130 bool X86TargetLowering::IsCalleePop(bool IsVarArg, unsigned CallingConv) {
1134 switch (CallingConv) {
1137 case CallingConv::X86_StdCall:
1138 return !Subtarget->is64Bit();
1139 case CallingConv::X86_FastCall:
1140 return !Subtarget->is64Bit();
1141 case CallingConv::Fast:
1142 return PerformTailCallOpt;
1146 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1147 /// given CallingConvention value.
1148 CCAssignFn *X86TargetLowering::CCAssignFnForNode(unsigned CC) const {
1149 if (Subtarget->is64Bit()) {
1150 if (Subtarget->isTargetWin64())
1151 return CC_X86_Win64_C;
1152 else if (CC == CallingConv::Fast && PerformTailCallOpt)
1153 return CC_X86_64_TailCall;
1158 if (CC == CallingConv::X86_FastCall)
1159 return CC_X86_32_FastCall;
1160 else if (CC == CallingConv::Fast)
1161 return CC_X86_32_FastCC;
1166 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1167 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1169 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDValue Op) {
1170 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1171 if (CC == CallingConv::X86_FastCall)
1173 else if (CC == CallingConv::X86_StdCall)
1179 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1180 /// in a register before calling.
1181 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1182 return !IsTailCall && !Is64Bit &&
1183 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1184 Subtarget->isPICStyleGOT();
1187 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1188 /// address to be loaded in a register.
1190 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1191 return !Is64Bit && IsTailCall &&
1192 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1193 Subtarget->isPICStyleGOT();
1196 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1197 /// by "Src" to address "Dst" with size and alignment information specified by
1198 /// the specific parameter attribute. The copy will be passed as a byval
1199 /// function parameter.
1201 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1202 ISD::ArgFlagsTy Flags, SelectionDAG &DAG) {
1203 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1204 return DAG.getMemcpy(Chain, Dst, Src, SizeNode, Flags.getByValAlign(),
1205 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1208 SDValue X86TargetLowering::LowerMemArgument(SDValue Op, SelectionDAG &DAG,
1209 const CCValAssign &VA,
1210 MachineFrameInfo *MFI,
1212 SDValue Root, unsigned i) {
1213 // Create the nodes corresponding to a load from this parameter slot.
1214 ISD::ArgFlagsTy Flags =
1215 cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1216 bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1217 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1219 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1220 // changed with more analysis.
1221 // In case of tail call optimization mark all arguments mutable. Since they
1222 // could be overwritten by lowering of arguments in case of a tail call.
1223 int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1224 VA.getLocMemOffset(), isImmutable);
1225 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1226 if (Flags.isByVal())
1228 return DAG.getLoad(VA.getValVT(), Op.getNode()->getDebugLoc(), Root, FIN,
1229 PseudoSourceValue::getFixedStack(FI), 0);
1233 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) {
1234 MachineFunction &MF = DAG.getMachineFunction();
1235 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1236 DebugLoc dl = Op.getNode()->getDebugLoc();
1238 const Function* Fn = MF.getFunction();
1239 if (Fn->hasExternalLinkage() &&
1240 Subtarget->isTargetCygMing() &&
1241 Fn->getName() == "main")
1242 FuncInfo->setForceFramePointer(true);
1244 // Decorate the function name.
1245 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1247 MachineFrameInfo *MFI = MF.getFrameInfo();
1248 SDValue Root = Op.getOperand(0);
1249 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
1250 unsigned CC = MF.getFunction()->getCallingConv();
1251 bool Is64Bit = Subtarget->is64Bit();
1252 bool IsWin64 = Subtarget->isTargetWin64();
1254 assert(!(isVarArg && CC == CallingConv::Fast) &&
1255 "Var args not supported with calling convention fastcc");
1257 // Assign locations to all of the incoming arguments.
1258 SmallVector<CCValAssign, 16> ArgLocs;
1259 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1260 CCInfo.AnalyzeFormalArguments(Op.getNode(), CCAssignFnForNode(CC));
1262 SmallVector<SDValue, 8> ArgValues;
1263 unsigned LastVal = ~0U;
1264 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1265 CCValAssign &VA = ArgLocs[i];
1266 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1268 assert(VA.getValNo() != LastVal &&
1269 "Don't support value assigned to multiple locs yet");
1270 LastVal = VA.getValNo();
1272 if (VA.isRegLoc()) {
1273 MVT RegVT = VA.getLocVT();
1274 TargetRegisterClass *RC = NULL;
1275 if (RegVT == MVT::i32)
1276 RC = X86::GR32RegisterClass;
1277 else if (Is64Bit && RegVT == MVT::i64)
1278 RC = X86::GR64RegisterClass;
1279 else if (RegVT == MVT::f32)
1280 RC = X86::FR32RegisterClass;
1281 else if (RegVT == MVT::f64)
1282 RC = X86::FR64RegisterClass;
1283 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1284 RC = X86::VR128RegisterClass;
1285 else if (RegVT.isVector()) {
1286 assert(RegVT.getSizeInBits() == 64);
1288 RC = X86::VR64RegisterClass; // MMX values are passed in MMXs.
1290 // Darwin calling convention passes MMX values in either GPRs or
1291 // XMMs in x86-64. Other targets pass them in memory.
1292 if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1293 RC = X86::VR128RegisterClass; // MMX values are passed in XMMs.
1296 RC = X86::GR64RegisterClass; // v1i64 values are passed in GPRs.
1301 assert(0 && "Unknown argument type!");
1304 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1305 SDValue ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1307 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1308 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1310 if (VA.getLocInfo() == CCValAssign::SExt)
1311 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1312 DAG.getValueType(VA.getValVT()));
1313 else if (VA.getLocInfo() == CCValAssign::ZExt)
1314 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1315 DAG.getValueType(VA.getValVT()));
1317 if (VA.getLocInfo() != CCValAssign::Full)
1318 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1320 // Handle MMX values passed in GPRs.
1321 if (Is64Bit && RegVT != VA.getLocVT()) {
1322 if (RegVT.getSizeInBits() == 64 && RC == X86::GR64RegisterClass)
1323 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1324 else if (RC == X86::VR128RegisterClass) {
1325 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1326 ArgValue, DAG.getConstant(0, MVT::i64));
1327 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1331 ArgValues.push_back(ArgValue);
1333 assert(VA.isMemLoc());
1334 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1338 // The x86-64 ABI for returning structs by value requires that we copy
1339 // the sret argument into %rax for the return. Save the argument into
1340 // a virtual register so that we can access it from the return points.
1341 if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1342 MachineFunction &MF = DAG.getMachineFunction();
1343 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1344 unsigned Reg = FuncInfo->getSRetReturnReg();
1346 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1347 FuncInfo->setSRetReturnReg(Reg);
1349 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), Reg, ArgValues[0]);
1350 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Root);
1353 unsigned StackSize = CCInfo.getNextStackOffset();
1354 // align stack specially for tail calls
1355 if (PerformTailCallOpt && CC == CallingConv::Fast)
1356 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1358 // If the function takes variable number of arguments, make a frame index for
1359 // the start of the first vararg value... for expansion of llvm.va_start.
1361 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1362 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1365 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1367 // FIXME: We should really autogenerate these arrays
1368 static const unsigned GPR64ArgRegsWin64[] = {
1369 X86::RCX, X86::RDX, X86::R8, X86::R9
1371 static const unsigned XMMArgRegsWin64[] = {
1372 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1374 static const unsigned GPR64ArgRegs64Bit[] = {
1375 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1377 static const unsigned XMMArgRegs64Bit[] = {
1378 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1379 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1381 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1384 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1385 GPR64ArgRegs = GPR64ArgRegsWin64;
1386 XMMArgRegs = XMMArgRegsWin64;
1388 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1389 GPR64ArgRegs = GPR64ArgRegs64Bit;
1390 XMMArgRegs = XMMArgRegs64Bit;
1392 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1394 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1397 assert((Subtarget->hasSSE1() || !NumXMMRegs) &&
1398 "SSE register cannot be used when SSE is disabled!");
1399 if (!Subtarget->hasSSE1()) {
1400 // Kernel mode asks for SSE to be disabled, so don't push them
1402 TotalNumXMMRegs = 0;
1404 // For X86-64, if there are vararg parameters that are passed via
1405 // registers, then we must store them to their spots on the stack so they
1406 // may be loaded by deferencing the result of va_next.
1407 VarArgsGPOffset = NumIntRegs * 8;
1408 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1409 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1410 TotalNumXMMRegs * 16, 16);
1412 // Store the integer parameter registers.
1413 SmallVector<SDValue, 8> MemOps;
1414 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1415 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1416 DAG.getIntPtrConstant(VarArgsGPOffset));
1417 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1418 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1419 X86::GR64RegisterClass);
1420 SDValue Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1422 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1423 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1424 MemOps.push_back(Store);
1425 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1426 DAG.getIntPtrConstant(8));
1429 // Now store the XMM (fp + vector) parameter registers.
1430 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1431 DAG.getIntPtrConstant(VarArgsFPOffset));
1432 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1433 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1434 X86::VR128RegisterClass);
1435 SDValue Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1437 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1438 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1439 MemOps.push_back(Store);
1440 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1441 DAG.getIntPtrConstant(16));
1443 if (!MemOps.empty())
1444 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1445 &MemOps[0], MemOps.size());
1449 ArgValues.push_back(Root);
1451 // Some CCs need callee pop.
1452 if (IsCalleePop(isVarArg, CC)) {
1453 BytesToPopOnReturn = StackSize; // Callee pops everything.
1454 BytesCallerReserves = 0;
1456 BytesToPopOnReturn = 0; // Callee pops nothing.
1457 // If this is an sret function, the return should pop the hidden pointer.
1458 if (!Is64Bit && CC != CallingConv::Fast && ArgsAreStructReturn(Op))
1459 BytesToPopOnReturn = 4;
1460 BytesCallerReserves = StackSize;
1464 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1465 if (CC == CallingConv::X86_FastCall)
1466 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1469 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1471 // Return the new list of results.
1472 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(),
1473 &ArgValues[0], ArgValues.size()).getValue(Op.getResNo());
1477 X86TargetLowering::LowerMemOpCallTo(CallSDNode *TheCall, SelectionDAG &DAG,
1478 const SDValue &StackPtr,
1479 const CCValAssign &VA,
1481 SDValue Arg, ISD::ArgFlagsTy Flags) {
1482 DebugLoc dl = TheCall->getDebugLoc();
1483 unsigned LocMemOffset = VA.getLocMemOffset();
1484 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1485 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1486 if (Flags.isByVal()) {
1487 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG);
1489 return DAG.getStore(Chain, dl, Arg, PtrOff,
1490 PseudoSourceValue::getStack(), LocMemOffset);
1493 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1494 /// optimization is performed and it is required.
1496 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1497 SDValue &OutRetAddr,
1503 if (!IsTailCall || FPDiff==0) return Chain;
1505 // Adjust the Return address stack slot.
1506 MVT VT = getPointerTy();
1507 OutRetAddr = getReturnAddressFrameIndex(DAG);
1509 // Load the "old" Return address.
1510 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0);
1511 return SDValue(OutRetAddr.getNode(), 1);
1514 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1515 /// optimization is performed and it is required (FPDiff!=0).
1517 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1518 SDValue Chain, SDValue RetAddrFrIdx,
1519 bool Is64Bit, int FPDiff, DebugLoc dl) {
1520 // Store the return address to the appropriate stack slot.
1521 if (!FPDiff) return Chain;
1522 // Calculate the new stack slot for the return address.
1523 int SlotSize = Is64Bit ? 8 : 4;
1524 int NewReturnAddrFI =
1525 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1526 MVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1527 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1528 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1529 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1533 SDValue X86TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1534 MachineFunction &MF = DAG.getMachineFunction();
1535 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
1536 SDValue Chain = TheCall->getChain();
1537 unsigned CC = TheCall->getCallingConv();
1538 bool isVarArg = TheCall->isVarArg();
1539 bool IsTailCall = TheCall->isTailCall() &&
1540 CC == CallingConv::Fast && PerformTailCallOpt;
1541 SDValue Callee = TheCall->getCallee();
1542 bool Is64Bit = Subtarget->is64Bit();
1543 bool IsStructRet = CallIsStructReturn(TheCall);
1544 DebugLoc dl = TheCall->getDebugLoc();
1546 assert(!(isVarArg && CC == CallingConv::Fast) &&
1547 "Var args not supported with calling convention fastcc");
1549 // Analyze operands of the call, assigning locations to each operand.
1550 SmallVector<CCValAssign, 16> ArgLocs;
1551 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1552 CCInfo.AnalyzeCallOperands(TheCall, CCAssignFnForNode(CC));
1554 // Get a count of how many bytes are to be pushed on the stack.
1555 unsigned NumBytes = CCInfo.getNextStackOffset();
1556 if (PerformTailCallOpt && CC == CallingConv::Fast)
1557 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1561 // Lower arguments at fp - stackoffset + fpdiff.
1562 unsigned NumBytesCallerPushed =
1563 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1564 FPDiff = NumBytesCallerPushed - NumBytes;
1566 // Set the delta of movement of the returnaddr stackslot.
1567 // But only set if delta is greater than previous delta.
1568 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1569 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1572 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1574 SDValue RetAddrFrIdx;
1575 // Load return adress for tail calls.
1576 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1579 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1580 SmallVector<SDValue, 8> MemOpChains;
1583 // Walk the register/memloc assignments, inserting copies/loads. In the case
1584 // of tail call optimization arguments are handle later.
1585 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1586 CCValAssign &VA = ArgLocs[i];
1587 SDValue Arg = TheCall->getArg(i);
1588 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1589 bool isByVal = Flags.isByVal();
1591 // Promote the value if needed.
1592 switch (VA.getLocInfo()) {
1593 default: assert(0 && "Unknown loc info!");
1594 case CCValAssign::Full: break;
1595 case CCValAssign::SExt:
1596 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1598 case CCValAssign::ZExt:
1599 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1601 case CCValAssign::AExt:
1602 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1606 if (VA.isRegLoc()) {
1608 MVT RegVT = VA.getLocVT();
1609 if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1610 switch (VA.getLocReg()) {
1613 case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1615 // Special case: passing MMX values in GPR registers.
1616 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1619 case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1620 case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1621 // Special case: passing MMX values in XMM registers.
1622 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1623 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1624 Arg = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v2i64,
1625 DAG.getNode(ISD::UNDEF, dl, MVT::v2i64), Arg,
1626 getMOVLMask(2, DAG, dl));
1631 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1633 if (!IsTailCall || (IsTailCall && isByVal)) {
1634 assert(VA.isMemLoc());
1635 if (StackPtr.getNode() == 0)
1636 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1638 MemOpChains.push_back(LowerMemOpCallTo(TheCall, DAG, StackPtr, VA,
1639 Chain, Arg, Flags));
1644 if (!MemOpChains.empty())
1645 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1646 &MemOpChains[0], MemOpChains.size());
1648 // Build a sequence of copy-to-reg nodes chained together with token chain
1649 // and flag operands which copy the outgoing args into registers.
1651 // Tail call byval lowering might overwrite argument registers so in case of
1652 // tail call optimization the copies to registers are lowered later.
1654 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1655 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1657 InFlag = Chain.getValue(1);
1660 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1662 if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1663 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1664 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1666 InFlag = Chain.getValue(1);
1668 // If we are tail calling and generating PIC/GOT style code load the address
1669 // of the callee into ecx. The value in ecx is used as target of the tail
1670 // jump. This is done to circumvent the ebx/callee-saved problem for tail
1671 // calls on PIC/GOT architectures. Normally we would just put the address of
1672 // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1673 // restored (since ebx is callee saved) before jumping to the target@PLT.
1674 if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1675 // Note: The actual moving to ecx is done further down.
1676 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1677 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1678 !G->getGlobal()->hasProtectedVisibility())
1679 Callee = LowerGlobalAddress(Callee, DAG);
1680 else if (isa<ExternalSymbolSDNode>(Callee))
1681 Callee = LowerExternalSymbol(Callee,DAG);
1684 if (Is64Bit && isVarArg) {
1685 // From AMD64 ABI document:
1686 // For calls that may call functions that use varargs or stdargs
1687 // (prototype-less calls or calls to functions containing ellipsis (...) in
1688 // the declaration) %al is used as hidden argument to specify the number
1689 // of SSE registers used. The contents of %al do not need to match exactly
1690 // the number of registers, but must be an ubound on the number of SSE
1691 // registers used and is in the range 0 - 8 inclusive.
1693 // FIXME: Verify this on Win64
1694 // Count the number of XMM registers allocated.
1695 static const unsigned XMMArgRegs[] = {
1696 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1697 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1699 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1700 assert((Subtarget->hasSSE1() || !NumXMMRegs)
1701 && "SSE registers cannot be used when SSE is disabled");
1703 Chain = DAG.getCopyToReg(Chain, X86::AL,
1704 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1705 InFlag = Chain.getValue(1);
1709 // For tail calls lower the arguments to the 'real' stack slot.
1711 SmallVector<SDValue, 8> MemOpChains2;
1714 // Do not flag preceeding copytoreg stuff together with the following stuff.
1716 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1717 CCValAssign &VA = ArgLocs[i];
1718 if (!VA.isRegLoc()) {
1719 assert(VA.isMemLoc());
1720 SDValue Arg = TheCall->getArg(i);
1721 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1722 // Create frame index.
1723 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1724 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1725 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1726 FIN = DAG.getFrameIndex(FI, getPointerTy());
1728 if (Flags.isByVal()) {
1729 // Copy relative to framepointer.
1730 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1731 if (StackPtr.getNode() == 0)
1732 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1733 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
1735 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1738 // Store relative to framepointer.
1739 MemOpChains2.push_back(
1740 DAG.getStore(Chain, dl, Arg, FIN,
1741 PseudoSourceValue::getFixedStack(FI), 0));
1746 if (!MemOpChains2.empty())
1747 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1748 &MemOpChains2[0], MemOpChains2.size());
1750 // Copy arguments to their registers.
1751 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1752 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1754 InFlag = Chain.getValue(1);
1758 // Store the return address to the appropriate stack slot.
1759 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1763 // If the callee is a GlobalAddress node (quite common, every direct call is)
1764 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1765 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1766 // We should use extra load for direct calls to dllimported functions in
1768 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1769 getTargetMachine(), true))
1770 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy(),
1772 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1773 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1774 } else if (IsTailCall) {
1775 unsigned Opc = Is64Bit ? X86::R9 : X86::EAX;
1777 Chain = DAG.getCopyToReg(Chain,
1778 DAG.getRegister(Opc, getPointerTy()),
1780 Callee = DAG.getRegister(Opc, getPointerTy());
1781 // Add register as live out.
1782 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1785 // Returns a chain & a flag for retval copy to use.
1786 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1787 SmallVector<SDValue, 8> Ops;
1790 Ops.push_back(Chain);
1791 Ops.push_back(DAG.getIntPtrConstant(NumBytes, true));
1792 Ops.push_back(DAG.getIntPtrConstant(0, true));
1793 if (InFlag.getNode())
1794 Ops.push_back(InFlag);
1795 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1796 InFlag = Chain.getValue(1);
1798 // Returns a chain & a flag for retval copy to use.
1799 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1803 Ops.push_back(Chain);
1804 Ops.push_back(Callee);
1807 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1809 // Add argument registers to the end of the list so that they are known live
1811 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1812 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1813 RegsToPass[i].second.getValueType()));
1815 // Add an implicit use GOT pointer in EBX.
1816 if (!IsTailCall && !Is64Bit &&
1817 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1818 Subtarget->isPICStyleGOT())
1819 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1821 // Add an implicit use of AL for x86 vararg functions.
1822 if (Is64Bit && isVarArg)
1823 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1825 if (InFlag.getNode())
1826 Ops.push_back(InFlag);
1829 assert(InFlag.getNode() &&
1830 "Flag must be set. Depend on flag being set in LowerRET");
1831 Chain = DAG.getNode(X86ISD::TAILCALL, dl,
1832 TheCall->getVTList(), &Ops[0], Ops.size());
1834 return SDValue(Chain.getNode(), Op.getResNo());
1837 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
1838 InFlag = Chain.getValue(1);
1840 // Create the CALLSEQ_END node.
1841 unsigned NumBytesForCalleeToPush;
1842 if (IsCalleePop(isVarArg, CC))
1843 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1844 else if (!Is64Bit && CC != CallingConv::Fast && IsStructRet)
1845 // If this is is a call to a struct-return function, the callee
1846 // pops the hidden struct pointer, so we have to push it back.
1847 // This is common for Darwin/X86, Linux & Mingw32 targets.
1848 NumBytesForCalleeToPush = 4;
1850 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1852 // Returns a flag for retval copy to use.
1853 Chain = DAG.getCALLSEQ_END(Chain,
1854 DAG.getIntPtrConstant(NumBytes, true),
1855 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
1858 InFlag = Chain.getValue(1);
1860 // Handle result values, copying them out of physregs into vregs that we
1862 return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
1867 //===----------------------------------------------------------------------===//
1868 // Fast Calling Convention (tail call) implementation
1869 //===----------------------------------------------------------------------===//
1871 // Like std call, callee cleans arguments, convention except that ECX is
1872 // reserved for storing the tail called function address. Only 2 registers are
1873 // free for argument passing (inreg). Tail call optimization is performed
1875 // * tailcallopt is enabled
1876 // * caller/callee are fastcc
1877 // On X86_64 architecture with GOT-style position independent code only local
1878 // (within module) calls are supported at the moment.
1879 // To keep the stack aligned according to platform abi the function
1880 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1881 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1882 // If a tail called function callee has more arguments than the caller the
1883 // caller needs to make sure that there is room to move the RETADDR to. This is
1884 // achieved by reserving an area the size of the argument delta right after the
1885 // original REtADDR, but before the saved framepointer or the spilled registers
1886 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1898 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1899 /// for a 16 byte align requirement.
1900 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1901 SelectionDAG& DAG) {
1902 MachineFunction &MF = DAG.getMachineFunction();
1903 const TargetMachine &TM = MF.getTarget();
1904 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1905 unsigned StackAlignment = TFI.getStackAlignment();
1906 uint64_t AlignMask = StackAlignment - 1;
1907 int64_t Offset = StackSize;
1908 uint64_t SlotSize = TD->getPointerSize();
1909 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1910 // Number smaller than 12 so just add the difference.
1911 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1913 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1914 Offset = ((~AlignMask) & Offset) + StackAlignment +
1915 (StackAlignment-SlotSize);
1920 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1921 /// following the call is a return. A function is eligible if caller/callee
1922 /// calling conventions match, currently only fastcc supports tail calls, and
1923 /// the function CALL is immediatly followed by a RET.
1924 bool X86TargetLowering::IsEligibleForTailCallOptimization(CallSDNode *TheCall,
1926 SelectionDAG& DAG) const {
1927 if (!PerformTailCallOpt)
1930 if (CheckTailCallReturnConstraints(TheCall, Ret)) {
1931 MachineFunction &MF = DAG.getMachineFunction();
1932 unsigned CallerCC = MF.getFunction()->getCallingConv();
1933 unsigned CalleeCC= TheCall->getCallingConv();
1934 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1935 SDValue Callee = TheCall->getCallee();
1936 // On x86/32Bit PIC/GOT tail calls are supported.
1937 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1938 !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1941 // Can only do local tail calls (in same module, hidden or protected) on
1942 // x86_64 PIC/GOT at the moment.
1943 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1944 return G->getGlobal()->hasHiddenVisibility()
1945 || G->getGlobal()->hasProtectedVisibility();
1953 X86TargetLowering::createFastISel(MachineFunction &mf,
1954 MachineModuleInfo *mmo,
1956 DenseMap<const Value *, unsigned> &vm,
1957 DenseMap<const BasicBlock *,
1958 MachineBasicBlock *> &bm,
1959 DenseMap<const AllocaInst *, int> &am
1961 , SmallSet<Instruction*, 8> &cil
1964 return X86::createFastISel(mf, mmo, dw, vm, bm, am
1972 //===----------------------------------------------------------------------===//
1973 // Other Lowering Hooks
1974 //===----------------------------------------------------------------------===//
1977 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1978 MachineFunction &MF = DAG.getMachineFunction();
1979 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1980 int ReturnAddrIndex = FuncInfo->getRAIndex();
1982 if (ReturnAddrIndex == 0) {
1983 // Set up a frame object for the return address.
1984 uint64_t SlotSize = TD->getPointerSize();
1985 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize);
1986 FuncInfo->setRAIndex(ReturnAddrIndex);
1989 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1993 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
1994 /// specific condition code, returning the condition code and the LHS/RHS of the
1995 /// comparison to make.
1996 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1997 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
1999 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2000 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2001 // X > -1 -> X == 0, jump !sign.
2002 RHS = DAG.getConstant(0, RHS.getValueType());
2003 return X86::COND_NS;
2004 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2005 // X < 0 -> X == 0, jump on sign.
2007 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2009 RHS = DAG.getConstant(0, RHS.getValueType());
2010 return X86::COND_LE;
2014 switch (SetCCOpcode) {
2015 default: assert(0 && "Invalid integer condition!");
2016 case ISD::SETEQ: return X86::COND_E;
2017 case ISD::SETGT: return X86::COND_G;
2018 case ISD::SETGE: return X86::COND_GE;
2019 case ISD::SETLT: return X86::COND_L;
2020 case ISD::SETLE: return X86::COND_LE;
2021 case ISD::SETNE: return X86::COND_NE;
2022 case ISD::SETULT: return X86::COND_B;
2023 case ISD::SETUGT: return X86::COND_A;
2024 case ISD::SETULE: return X86::COND_BE;
2025 case ISD::SETUGE: return X86::COND_AE;
2029 // First determine if it is required or is profitable to flip the operands.
2031 // If LHS is a foldable load, but RHS is not, flip the condition.
2032 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2033 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2034 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2035 std::swap(LHS, RHS);
2038 switch (SetCCOpcode) {
2044 std::swap(LHS, RHS);
2048 // On a floating point condition, the flags are set as follows:
2050 // 0 | 0 | 0 | X > Y
2051 // 0 | 0 | 1 | X < Y
2052 // 1 | 0 | 0 | X == Y
2053 // 1 | 1 | 1 | unordered
2054 switch (SetCCOpcode) {
2055 default: assert(0 && "Condcode should be pre-legalized away");
2057 case ISD::SETEQ: return X86::COND_E;
2058 case ISD::SETOLT: // flipped
2060 case ISD::SETGT: return X86::COND_A;
2061 case ISD::SETOLE: // flipped
2063 case ISD::SETGE: return X86::COND_AE;
2064 case ISD::SETUGT: // flipped
2066 case ISD::SETLT: return X86::COND_B;
2067 case ISD::SETUGE: // flipped
2069 case ISD::SETLE: return X86::COND_BE;
2071 case ISD::SETNE: return X86::COND_NE;
2072 case ISD::SETUO: return X86::COND_P;
2073 case ISD::SETO: return X86::COND_NP;
2077 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2078 /// code. Current x86 isa includes the following FP cmov instructions:
2079 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2080 static bool hasFPCMov(unsigned X86CC) {
2096 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
2097 /// true if Op is undef or if its value falls within the specified range (L, H].
2098 static bool isUndefOrInRange(SDValue Op, unsigned Low, unsigned Hi) {
2099 if (Op.getOpcode() == ISD::UNDEF)
2102 unsigned Val = cast<ConstantSDNode>(Op)->getZExtValue();
2103 return (Val >= Low && Val < Hi);
2106 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
2107 /// true if Op is undef or if its value equal to the specified value.
2108 static bool isUndefOrEqual(SDValue Op, unsigned Val) {
2109 if (Op.getOpcode() == ISD::UNDEF)
2111 return cast<ConstantSDNode>(Op)->getZExtValue() == Val;
2114 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2115 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
2116 bool X86::isPSHUFDMask(SDNode *N) {
2117 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2119 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
2122 // Check if the value doesn't reference the second vector.
2123 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2124 SDValue Arg = N->getOperand(i);
2125 if (Arg.getOpcode() == ISD::UNDEF) continue;
2126 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2127 if (cast<ConstantSDNode>(Arg)->getZExtValue() >= e)
2134 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2135 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2136 bool X86::isPSHUFHWMask(SDNode *N) {
2137 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2139 if (N->getNumOperands() != 8)
2142 // Lower quadword copied in order.
2143 for (unsigned i = 0; i != 4; ++i) {
2144 SDValue Arg = N->getOperand(i);
2145 if (Arg.getOpcode() == ISD::UNDEF) continue;
2146 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2147 if (cast<ConstantSDNode>(Arg)->getZExtValue() != i)
2151 // Upper quadword shuffled.
2152 for (unsigned i = 4; i != 8; ++i) {
2153 SDValue Arg = N->getOperand(i);
2154 if (Arg.getOpcode() == ISD::UNDEF) continue;
2155 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2156 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2157 if (Val < 4 || Val > 7)
2164 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2165 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2166 bool X86::isPSHUFLWMask(SDNode *N) {
2167 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2169 if (N->getNumOperands() != 8)
2172 // Upper quadword copied in order.
2173 for (unsigned i = 4; i != 8; ++i)
2174 if (!isUndefOrEqual(N->getOperand(i), i))
2177 // Lower quadword shuffled.
2178 for (unsigned i = 0; i != 4; ++i)
2179 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2185 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2186 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2187 template<class SDOperand>
2188 static bool isSHUFPMask(SDOperand *Elems, unsigned NumElems) {
2189 if (NumElems != 2 && NumElems != 4) return false;
2191 unsigned Half = NumElems / 2;
2192 for (unsigned i = 0; i < Half; ++i)
2193 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2195 for (unsigned i = Half; i < NumElems; ++i)
2196 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2202 bool X86::isSHUFPMask(SDNode *N) {
2203 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2204 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2207 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2208 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2209 /// half elements to come from vector 1 (which would equal the dest.) and
2210 /// the upper half to come from vector 2.
2211 template<class SDOperand>
2212 static bool isCommutedSHUFP(SDOperand *Ops, unsigned NumOps) {
2213 if (NumOps != 2 && NumOps != 4) return false;
2215 unsigned Half = NumOps / 2;
2216 for (unsigned i = 0; i < Half; ++i)
2217 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2219 for (unsigned i = Half; i < NumOps; ++i)
2220 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2225 static bool isCommutedSHUFP(SDNode *N) {
2226 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2227 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2230 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2231 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2232 bool X86::isMOVHLPSMask(SDNode *N) {
2233 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2235 if (N->getNumOperands() != 4)
2238 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2239 return isUndefOrEqual(N->getOperand(0), 6) &&
2240 isUndefOrEqual(N->getOperand(1), 7) &&
2241 isUndefOrEqual(N->getOperand(2), 2) &&
2242 isUndefOrEqual(N->getOperand(3), 3);
2245 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2246 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2248 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2249 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2251 if (N->getNumOperands() != 4)
2254 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2255 return isUndefOrEqual(N->getOperand(0), 2) &&
2256 isUndefOrEqual(N->getOperand(1), 3) &&
2257 isUndefOrEqual(N->getOperand(2), 2) &&
2258 isUndefOrEqual(N->getOperand(3), 3);
2261 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2262 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2263 bool X86::isMOVLPMask(SDNode *N) {
2264 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2266 unsigned NumElems = N->getNumOperands();
2267 if (NumElems != 2 && NumElems != 4)
2270 for (unsigned i = 0; i < NumElems/2; ++i)
2271 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2274 for (unsigned i = NumElems/2; i < NumElems; ++i)
2275 if (!isUndefOrEqual(N->getOperand(i), i))
2281 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2282 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2284 bool X86::isMOVHPMask(SDNode *N) {
2285 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2287 unsigned NumElems = N->getNumOperands();
2288 if (NumElems != 2 && NumElems != 4)
2291 for (unsigned i = 0; i < NumElems/2; ++i)
2292 if (!isUndefOrEqual(N->getOperand(i), i))
2295 for (unsigned i = 0; i < NumElems/2; ++i) {
2296 SDValue Arg = N->getOperand(i + NumElems/2);
2297 if (!isUndefOrEqual(Arg, i + NumElems))
2304 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2305 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2306 template<class SDOperand>
2307 bool static isUNPCKLMask(SDOperand *Elts, unsigned NumElts,
2308 bool V2IsSplat = false) {
2309 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2312 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2313 SDValue BitI = Elts[i];
2314 SDValue BitI1 = Elts[i+1];
2315 if (!isUndefOrEqual(BitI, j))
2318 if (isUndefOrEqual(BitI1, NumElts))
2321 if (!isUndefOrEqual(BitI1, j + NumElts))
2329 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2330 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2331 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2334 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2335 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2336 template<class SDOperand>
2337 bool static isUNPCKHMask(SDOperand *Elts, unsigned NumElts,
2338 bool V2IsSplat = false) {
2339 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2342 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2343 SDValue BitI = Elts[i];
2344 SDValue BitI1 = Elts[i+1];
2345 if (!isUndefOrEqual(BitI, j + NumElts/2))
2348 if (isUndefOrEqual(BitI1, NumElts))
2351 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2359 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2360 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2361 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2364 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2365 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2367 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2368 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2370 unsigned NumElems = N->getNumOperands();
2371 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2374 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2375 SDValue BitI = N->getOperand(i);
2376 SDValue BitI1 = N->getOperand(i+1);
2378 if (!isUndefOrEqual(BitI, j))
2380 if (!isUndefOrEqual(BitI1, j))
2387 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2388 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2390 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2391 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2393 unsigned NumElems = N->getNumOperands();
2394 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2397 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2398 SDValue BitI = N->getOperand(i);
2399 SDValue BitI1 = N->getOperand(i + 1);
2401 if (!isUndefOrEqual(BitI, j))
2403 if (!isUndefOrEqual(BitI1, j))
2410 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2411 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2412 /// MOVSD, and MOVD, i.e. setting the lowest element.
2413 template<class SDOperand>
2414 static bool isMOVLMask(SDOperand *Elts, unsigned NumElts) {
2415 if (NumElts != 2 && NumElts != 4)
2418 if (!isUndefOrEqual(Elts[0], NumElts))
2421 for (unsigned i = 1; i < NumElts; ++i) {
2422 if (!isUndefOrEqual(Elts[i], i))
2429 bool X86::isMOVLMask(SDNode *N) {
2430 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2431 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2434 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2435 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2436 /// element of vector 2 and the other elements to come from vector 1 in order.
2437 template<class SDOperand>
2438 static bool isCommutedMOVL(SDOperand *Ops, unsigned NumOps,
2439 bool V2IsSplat = false,
2440 bool V2IsUndef = false) {
2441 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2444 if (!isUndefOrEqual(Ops[0], 0))
2447 for (unsigned i = 1; i < NumOps; ++i) {
2448 SDValue Arg = Ops[i];
2449 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2450 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2451 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2458 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2459 bool V2IsUndef = false) {
2460 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2461 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2462 V2IsSplat, V2IsUndef);
2465 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2466 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2467 bool X86::isMOVSHDUPMask(SDNode *N) {
2468 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2470 if (N->getNumOperands() != 4)
2473 // Expect 1, 1, 3, 3
2474 for (unsigned i = 0; i < 2; ++i) {
2475 SDValue Arg = N->getOperand(i);
2476 if (Arg.getOpcode() == ISD::UNDEF) continue;
2477 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2478 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2479 if (Val != 1) return false;
2483 for (unsigned i = 2; i < 4; ++i) {
2484 SDValue Arg = N->getOperand(i);
2485 if (Arg.getOpcode() == ISD::UNDEF) continue;
2486 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2487 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2488 if (Val != 3) return false;
2492 // Don't use movshdup if it can be done with a shufps.
2496 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2497 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2498 bool X86::isMOVSLDUPMask(SDNode *N) {
2499 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2501 if (N->getNumOperands() != 4)
2504 // Expect 0, 0, 2, 2
2505 for (unsigned i = 0; i < 2; ++i) {
2506 SDValue Arg = N->getOperand(i);
2507 if (Arg.getOpcode() == ISD::UNDEF) continue;
2508 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2509 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2510 if (Val != 0) return false;
2514 for (unsigned i = 2; i < 4; ++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 != 2) return false;
2523 // Don't use movshdup if it can be done with a shufps.
2527 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2528 /// specifies a identity operation on the LHS or RHS.
2529 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2530 unsigned NumElems = N->getNumOperands();
2531 for (unsigned i = 0; i < NumElems; ++i)
2532 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2537 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2538 /// a splat of a single element.
2539 static bool isSplatMask(SDNode *N) {
2540 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2542 // This is a splat operation if each element of the permute is the same, and
2543 // if the value doesn't reference the second vector.
2544 unsigned NumElems = N->getNumOperands();
2545 SDValue ElementBase;
2547 for (; i != NumElems; ++i) {
2548 SDValue Elt = N->getOperand(i);
2549 if (isa<ConstantSDNode>(Elt)) {
2555 if (!ElementBase.getNode())
2558 for (; i != NumElems; ++i) {
2559 SDValue Arg = N->getOperand(i);
2560 if (Arg.getOpcode() == ISD::UNDEF) continue;
2561 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2562 if (Arg != ElementBase) return false;
2565 // Make sure it is a splat of the first vector operand.
2566 return cast<ConstantSDNode>(ElementBase)->getZExtValue() < NumElems;
2569 /// getSplatMaskEltNo - Given a splat mask, return the index to the element
2570 /// we want to splat.
2571 static SDValue getSplatMaskEltNo(SDNode *N) {
2572 assert(isSplatMask(N) && "Not a splat mask");
2573 unsigned NumElems = N->getNumOperands();
2574 SDValue ElementBase;
2576 for (; i != NumElems; ++i) {
2577 SDValue Elt = N->getOperand(i);
2578 if (isa<ConstantSDNode>(Elt))
2581 assert(0 && " No splat value found!");
2586 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2587 /// a splat of a single element and it's a 2 or 4 element mask.
2588 bool X86::isSplatMask(SDNode *N) {
2589 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2591 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2592 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2594 return ::isSplatMask(N);
2597 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2598 /// specifies a splat of zero element.
2599 bool X86::isSplatLoMask(SDNode *N) {
2600 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2602 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2603 if (!isUndefOrEqual(N->getOperand(i), 0))
2608 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2609 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2610 bool X86::isMOVDDUPMask(SDNode *N) {
2611 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2613 unsigned e = N->getNumOperands() / 2;
2614 for (unsigned i = 0; i < e; ++i)
2615 if (!isUndefOrEqual(N->getOperand(i), i))
2617 for (unsigned i = 0; i < e; ++i)
2618 if (!isUndefOrEqual(N->getOperand(e+i), i))
2623 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2624 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2626 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2627 unsigned NumOperands = N->getNumOperands();
2628 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2630 for (unsigned i = 0; i < NumOperands; ++i) {
2632 SDValue Arg = N->getOperand(NumOperands-i-1);
2633 if (Arg.getOpcode() != ISD::UNDEF)
2634 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2635 if (Val >= NumOperands) Val -= NumOperands;
2637 if (i != NumOperands - 1)
2644 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2645 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2647 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2649 // 8 nodes, but we only care about the last 4.
2650 for (unsigned i = 7; i >= 4; --i) {
2652 SDValue Arg = N->getOperand(i);
2653 if (Arg.getOpcode() != ISD::UNDEF)
2654 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2663 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2664 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2666 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2668 // 8 nodes, but we only care about the first 4.
2669 for (int i = 3; i >= 0; --i) {
2671 SDValue Arg = N->getOperand(i);
2672 if (Arg.getOpcode() != ISD::UNDEF)
2673 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2682 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2683 /// specifies a 8 element shuffle that can be broken into a pair of
2684 /// PSHUFHW and PSHUFLW.
2685 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2686 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2688 if (N->getNumOperands() != 8)
2691 // Lower quadword shuffled.
2692 for (unsigned i = 0; i != 4; ++i) {
2693 SDValue Arg = N->getOperand(i);
2694 if (Arg.getOpcode() == ISD::UNDEF) continue;
2695 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2696 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2701 // Upper quadword shuffled.
2702 for (unsigned i = 4; i != 8; ++i) {
2703 SDValue Arg = N->getOperand(i);
2704 if (Arg.getOpcode() == ISD::UNDEF) continue;
2705 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2706 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2707 if (Val < 4 || Val > 7)
2714 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2715 /// values in ther permute mask.
2716 static SDValue CommuteVectorShuffle(SDValue Op, SDValue &V1,
2717 SDValue &V2, SDValue &Mask,
2718 SelectionDAG &DAG) {
2719 MVT VT = Op.getValueType();
2720 MVT MaskVT = Mask.getValueType();
2721 MVT EltVT = MaskVT.getVectorElementType();
2722 unsigned NumElems = Mask.getNumOperands();
2723 SmallVector<SDValue, 8> MaskVec;
2724 DebugLoc dl = Op.getNode()->getDebugLoc();
2726 for (unsigned i = 0; i != NumElems; ++i) {
2727 SDValue Arg = Mask.getOperand(i);
2728 if (Arg.getOpcode() == ISD::UNDEF) {
2729 MaskVec.push_back(DAG.getNode(ISD::UNDEF, dl, EltVT));
2732 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2733 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2735 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2737 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2741 Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT, &MaskVec[0], NumElems);
2742 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, Mask);
2745 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2746 /// the two vector operands have swapped position.
2748 SDValue CommuteVectorShuffleMask(SDValue Mask, SelectionDAG &DAG, DebugLoc dl) {
2749 MVT MaskVT = Mask.getValueType();
2750 MVT EltVT = MaskVT.getVectorElementType();
2751 unsigned NumElems = Mask.getNumOperands();
2752 SmallVector<SDValue, 8> MaskVec;
2753 for (unsigned i = 0; i != NumElems; ++i) {
2754 SDValue Arg = Mask.getOperand(i);
2755 if (Arg.getOpcode() == ISD::UNDEF) {
2756 MaskVec.push_back(DAG.getNode(ISD::UNDEF, dl, EltVT));
2759 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2760 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2762 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2764 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2766 return DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT, &MaskVec[0], NumElems);
2770 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2771 /// match movhlps. The lower half elements should come from upper half of
2772 /// V1 (and in order), and the upper half elements should come from the upper
2773 /// half of V2 (and in order).
2774 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2775 unsigned NumElems = Mask->getNumOperands();
2778 for (unsigned i = 0, e = 2; i != e; ++i)
2779 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2781 for (unsigned i = 2; i != 4; ++i)
2782 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2787 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2788 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2790 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2791 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
2793 N = N->getOperand(0).getNode();
2794 if (!ISD::isNON_EXTLoad(N))
2797 *LD = cast<LoadSDNode>(N);
2801 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2802 /// match movlp{s|d}. The lower half elements should come from lower half of
2803 /// V1 (and in order), and the upper half elements should come from the upper
2804 /// half of V2 (and in order). And since V1 will become the source of the
2805 /// MOVLP, it must be either a vector load or a scalar load to vector.
2806 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2807 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2809 // Is V2 is a vector load, don't do this transformation. We will try to use
2810 // load folding shufps op.
2811 if (ISD::isNON_EXTLoad(V2))
2814 unsigned NumElems = Mask->getNumOperands();
2815 if (NumElems != 2 && NumElems != 4)
2817 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2818 if (!isUndefOrEqual(Mask->getOperand(i), i))
2820 for (unsigned i = NumElems/2; i != NumElems; ++i)
2821 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2826 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2828 static bool isSplatVector(SDNode *N) {
2829 if (N->getOpcode() != ISD::BUILD_VECTOR)
2832 SDValue SplatValue = N->getOperand(0);
2833 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2834 if (N->getOperand(i) != SplatValue)
2839 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2841 static bool isUndefShuffle(SDNode *N) {
2842 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2845 SDValue V1 = N->getOperand(0);
2846 SDValue V2 = N->getOperand(1);
2847 SDValue Mask = N->getOperand(2);
2848 unsigned NumElems = Mask.getNumOperands();
2849 for (unsigned i = 0; i != NumElems; ++i) {
2850 SDValue Arg = Mask.getOperand(i);
2851 if (Arg.getOpcode() != ISD::UNDEF) {
2852 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2853 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2855 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2862 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2864 static inline bool isZeroNode(SDValue Elt) {
2865 return ((isa<ConstantSDNode>(Elt) &&
2866 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2867 (isa<ConstantFPSDNode>(Elt) &&
2868 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2871 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2872 /// to an zero vector.
2873 static bool isZeroShuffle(SDNode *N) {
2874 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2877 SDValue V1 = N->getOperand(0);
2878 SDValue V2 = N->getOperand(1);
2879 SDValue Mask = N->getOperand(2);
2880 unsigned NumElems = Mask.getNumOperands();
2881 for (unsigned i = 0; i != NumElems; ++i) {
2882 SDValue Arg = Mask.getOperand(i);
2883 if (Arg.getOpcode() == ISD::UNDEF)
2886 unsigned Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2887 if (Idx < NumElems) {
2888 unsigned Opc = V1.getNode()->getOpcode();
2889 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
2891 if (Opc != ISD::BUILD_VECTOR ||
2892 !isZeroNode(V1.getNode()->getOperand(Idx)))
2894 } else if (Idx >= NumElems) {
2895 unsigned Opc = V2.getNode()->getOpcode();
2896 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
2898 if (Opc != ISD::BUILD_VECTOR ||
2899 !isZeroNode(V2.getNode()->getOperand(Idx - NumElems)))
2906 /// getZeroVector - Returns a vector of specified type with all zero elements.
2908 static SDValue getZeroVector(MVT VT, bool HasSSE2, SelectionDAG &DAG,
2910 assert(VT.isVector() && "Expected a vector type");
2912 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2913 // type. This ensures they get CSE'd.
2915 if (VT.getSizeInBits() == 64) { // MMX
2916 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2917 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2918 } else if (HasSSE2) { // SSE2
2919 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2920 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2922 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2923 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
2925 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2928 /// getOnesVector - Returns a vector of specified type with all bits set.
2930 static SDValue getOnesVector(MVT VT, SelectionDAG &DAG, DebugLoc dl) {
2931 assert(VT.isVector() && "Expected a vector type");
2933 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2934 // type. This ensures they get CSE'd.
2935 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2937 if (VT.getSizeInBits() == 64) // MMX
2938 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
2940 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
2941 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2945 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2946 /// that point to V2 points to its first element.
2947 static SDValue NormalizeMask(SDValue Mask, SelectionDAG &DAG) {
2948 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2950 bool Changed = false;
2951 SmallVector<SDValue, 8> MaskVec;
2952 unsigned NumElems = Mask.getNumOperands();
2953 for (unsigned i = 0; i != NumElems; ++i) {
2954 SDValue Arg = Mask.getOperand(i);
2955 if (Arg.getOpcode() != ISD::UNDEF) {
2956 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2957 if (Val > NumElems) {
2958 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2962 MaskVec.push_back(Arg);
2966 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getNode()->getDebugLoc(),
2967 Mask.getValueType(),
2968 &MaskVec[0], MaskVec.size());
2972 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2973 /// operation of specified width.
2974 static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG, DebugLoc dl) {
2975 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2976 MVT BaseVT = MaskVT.getVectorElementType();
2978 SmallVector<SDValue, 8> MaskVec;
2979 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2980 for (unsigned i = 1; i != NumElems; ++i)
2981 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2982 return DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
2983 &MaskVec[0], MaskVec.size());
2986 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2987 /// of specified width.
2988 static SDValue getUnpacklMask(unsigned NumElems, SelectionDAG &DAG,
2990 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2991 MVT BaseVT = MaskVT.getVectorElementType();
2992 SmallVector<SDValue, 8> MaskVec;
2993 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2994 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2995 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2997 return DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
2998 &MaskVec[0], MaskVec.size());
3001 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
3002 /// of specified width.
3003 static SDValue getUnpackhMask(unsigned NumElems, SelectionDAG &DAG,
3005 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3006 MVT BaseVT = MaskVT.getVectorElementType();
3007 unsigned Half = NumElems/2;
3008 SmallVector<SDValue, 8> MaskVec;
3009 for (unsigned i = 0; i != Half; ++i) {
3010 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
3011 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
3013 return DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3014 &MaskVec[0], MaskVec.size());
3017 /// getSwapEltZeroMask - Returns a vector_shuffle mask for a shuffle that swaps
3018 /// element #0 of a vector with the specified index, leaving the rest of the
3019 /// elements in place.
3020 static SDValue getSwapEltZeroMask(unsigned NumElems, unsigned DestElt,
3021 SelectionDAG &DAG, DebugLoc dl) {
3022 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3023 MVT BaseVT = MaskVT.getVectorElementType();
3024 SmallVector<SDValue, 8> MaskVec;
3025 // Element #0 of the result gets the elt we are replacing.
3026 MaskVec.push_back(DAG.getConstant(DestElt, BaseVT));
3027 for (unsigned i = 1; i != NumElems; ++i)
3028 MaskVec.push_back(DAG.getConstant(i == DestElt ? 0 : i, BaseVT));
3029 return DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3030 &MaskVec[0], MaskVec.size());
3033 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3034 static SDValue PromoteSplat(SDValue Op, SelectionDAG &DAG, bool HasSSE2) {
3035 MVT PVT = HasSSE2 ? MVT::v4i32 : MVT::v4f32;
3036 MVT VT = Op.getValueType();
3039 SDValue V1 = Op.getOperand(0);
3040 SDValue Mask = Op.getOperand(2);
3041 unsigned MaskNumElems = Mask.getNumOperands();
3042 unsigned NumElems = MaskNumElems;
3043 DebugLoc dl = Op.getNode()->getDebugLoc();
3044 // Special handling of v4f32 -> v4i32.
3045 if (VT != MVT::v4f32) {
3046 // Find which element we want to splat.
3047 SDNode* EltNoNode = getSplatMaskEltNo(Mask.getNode()).getNode();
3048 unsigned EltNo = cast<ConstantSDNode>(EltNoNode)->getZExtValue();
3049 // unpack elements to the correct location
3050 while (NumElems > 4) {
3051 if (EltNo < NumElems/2) {
3052 Mask = getUnpacklMask(MaskNumElems, DAG, dl);
3054 Mask = getUnpackhMask(MaskNumElems, DAG, dl);
3055 EltNo -= NumElems/2;
3057 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V1, Mask);
3060 SDValue Cst = DAG.getConstant(EltNo, MVT::i32);
3061 Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3064 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3065 SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, PVT, V1,
3066 DAG.getNode(ISD::UNDEF, PVT), Mask);
3067 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Shuffle);
3070 /// isVectorLoad - Returns true if the node is a vector load, a scalar
3071 /// load that's promoted to vector, or a load bitcasted.
3072 static bool isVectorLoad(SDValue Op) {
3073 assert(Op.getValueType().isVector() && "Expected a vector type");
3074 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR ||
3075 Op.getOpcode() == ISD::BIT_CONVERT) {
3076 return isa<LoadSDNode>(Op.getOperand(0));
3078 return isa<LoadSDNode>(Op);
3082 /// CanonicalizeMovddup - Cannonicalize movddup shuffle to v2f64.
3084 static SDValue CanonicalizeMovddup(SDValue Op, SDValue V1, SDValue Mask,
3085 SelectionDAG &DAG, bool HasSSE3) {
3086 // If we have sse3 and shuffle has more than one use or input is a load, then
3087 // use movddup. Otherwise, use movlhps.
3088 bool UseMovddup = HasSSE3 && (!Op.hasOneUse() || isVectorLoad(V1));
3089 MVT PVT = UseMovddup ? MVT::v2f64 : MVT::v4f32;
3090 MVT VT = Op.getValueType();
3093 DebugLoc dl = Op.getNode()->getDebugLoc();
3094 unsigned NumElems = PVT.getVectorNumElements();
3095 if (NumElems == 2) {
3096 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3097 Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3099 assert(NumElems == 4);
3100 SDValue Cst0 = DAG.getTargetConstant(0, MVT::i32);
3101 SDValue Cst1 = DAG.getTargetConstant(1, MVT::i32);
3102 Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
3103 Cst0, Cst1, Cst0, Cst1);
3106 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3107 SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, PVT, V1,
3108 DAG.getNode(ISD::UNDEF, dl, PVT), Mask);
3109 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Shuffle);
3112 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3113 /// vector of zero or undef vector. This produces a shuffle where the low
3114 /// element of V2 is swizzled into the zero/undef vector, landing at element
3115 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3116 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3117 bool isZero, bool HasSSE2,
3118 SelectionDAG &DAG) {
3119 DebugLoc dl = V2.getNode()->getDebugLoc();
3120 MVT VT = V2.getValueType();
3122 ? getZeroVector(VT, HasSSE2, DAG, dl) : DAG.getNode(ISD::UNDEF, dl, VT);
3123 unsigned NumElems = V2.getValueType().getVectorNumElements();
3124 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3125 MVT EVT = MaskVT.getVectorElementType();
3126 SmallVector<SDValue, 16> MaskVec;
3127 for (unsigned i = 0; i != NumElems; ++i)
3128 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
3129 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
3131 MaskVec.push_back(DAG.getConstant(i, EVT));
3132 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3133 &MaskVec[0], MaskVec.size());
3134 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, Mask);
3137 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3138 /// a shuffle that is zero.
3140 unsigned getNumOfConsecutiveZeros(SDValue Op, SDValue Mask,
3141 unsigned NumElems, bool Low,
3142 SelectionDAG &DAG) {
3143 unsigned NumZeros = 0;
3144 for (unsigned i = 0; i < NumElems; ++i) {
3145 unsigned Index = Low ? i : NumElems-i-1;
3146 SDValue Idx = Mask.getOperand(Index);
3147 if (Idx.getOpcode() == ISD::UNDEF) {
3151 SDValue Elt = DAG.getShuffleScalarElt(Op.getNode(), Index);
3152 if (Elt.getNode() && isZeroNode(Elt))
3160 /// isVectorShift - Returns true if the shuffle can be implemented as a
3161 /// logical left or right shift of a vector.
3162 static bool isVectorShift(SDValue Op, SDValue Mask, SelectionDAG &DAG,
3163 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3164 unsigned NumElems = Mask.getNumOperands();
3167 unsigned NumZeros= getNumOfConsecutiveZeros(Op, Mask, NumElems, true, DAG);
3170 NumZeros = getNumOfConsecutiveZeros(Op, Mask, NumElems, false, DAG);
3175 bool SeenV1 = false;
3176 bool SeenV2 = false;
3177 for (unsigned i = NumZeros; i < NumElems; ++i) {
3178 unsigned Val = isLeft ? (i - NumZeros) : i;
3179 SDValue Idx = Mask.getOperand(isLeft ? i : (i - NumZeros));
3180 if (Idx.getOpcode() == ISD::UNDEF)
3182 unsigned Index = cast<ConstantSDNode>(Idx)->getZExtValue();
3183 if (Index < NumElems)
3192 if (SeenV1 && SeenV2)
3195 ShVal = SeenV1 ? Op.getOperand(0) : Op.getOperand(1);
3201 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3203 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3204 unsigned NumNonZero, unsigned NumZero,
3205 SelectionDAG &DAG, TargetLowering &TLI) {
3209 DebugLoc dl = Op.getNode()->getDebugLoc();
3212 for (unsigned i = 0; i < 16; ++i) {
3213 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3214 if (ThisIsNonZero && First) {
3216 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3218 V = DAG.getNode(ISD::UNDEF, dl, MVT::v8i16);
3223 SDValue ThisElt(0, 0), LastElt(0, 0);
3224 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3225 if (LastIsNonZero) {
3226 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3227 MVT::i16, Op.getOperand(i-1));
3229 if (ThisIsNonZero) {
3230 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3231 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3232 ThisElt, DAG.getConstant(8, MVT::i8));
3234 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3238 if (ThisElt.getNode())
3239 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3240 DAG.getIntPtrConstant(i/2));
3244 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3247 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3249 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3250 unsigned NumNonZero, unsigned NumZero,
3251 SelectionDAG &DAG, TargetLowering &TLI) {
3255 DebugLoc dl = Op.getNode()->getDebugLoc();
3258 for (unsigned i = 0; i < 8; ++i) {
3259 bool isNonZero = (NonZeros & (1 << i)) != 0;
3263 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3265 V = DAG.getNode(ISD::UNDEF, dl, MVT::v8i16);
3268 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3269 MVT::v8i16, V, Op.getOperand(i),
3270 DAG.getIntPtrConstant(i));
3277 /// getVShift - Return a vector logical shift node.
3279 static SDValue getVShift(bool isLeft, MVT VT, SDValue SrcOp,
3280 unsigned NumBits, SelectionDAG &DAG,
3281 const TargetLowering &TLI, DebugLoc dl) {
3282 bool isMMX = VT.getSizeInBits() == 64;
3283 MVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3284 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3285 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3286 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3287 DAG.getNode(Opc, dl, ShVT, SrcOp,
3288 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3292 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3293 DebugLoc dl = Op.getNode()->getDebugLoc();
3294 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3295 if (ISD::isBuildVectorAllZeros(Op.getNode())
3296 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3297 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3298 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3299 // eliminated on x86-32 hosts.
3300 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3303 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3304 return getOnesVector(Op.getValueType(), DAG, dl);
3305 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3308 MVT VT = Op.getValueType();
3309 MVT EVT = VT.getVectorElementType();
3310 unsigned EVTBits = EVT.getSizeInBits();
3312 unsigned NumElems = Op.getNumOperands();
3313 unsigned NumZero = 0;
3314 unsigned NumNonZero = 0;
3315 unsigned NonZeros = 0;
3316 bool IsAllConstants = true;
3317 SmallSet<SDValue, 8> Values;
3318 for (unsigned i = 0; i < NumElems; ++i) {
3319 SDValue Elt = Op.getOperand(i);
3320 if (Elt.getOpcode() == ISD::UNDEF)
3323 if (Elt.getOpcode() != ISD::Constant &&
3324 Elt.getOpcode() != ISD::ConstantFP)
3325 IsAllConstants = false;
3326 if (isZeroNode(Elt))
3329 NonZeros |= (1 << i);
3334 if (NumNonZero == 0) {
3335 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3336 return DAG.getNode(ISD::UNDEF, dl, VT);
3339 // Special case for single non-zero, non-undef, element.
3340 if (NumNonZero == 1 && NumElems <= 4) {
3341 unsigned Idx = CountTrailingZeros_32(NonZeros);
3342 SDValue Item = Op.getOperand(Idx);
3344 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3345 // the value are obviously zero, truncate the value to i32 and do the
3346 // insertion that way. Only do this if the value is non-constant or if the
3347 // value is a constant being inserted into element 0. It is cheaper to do
3348 // a constant pool load than it is to do a movd + shuffle.
3349 if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3350 (!IsAllConstants || Idx == 0)) {
3351 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3352 // Handle MMX and SSE both.
3353 MVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3354 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3356 // Truncate the value (which may itself be a constant) to i32, and
3357 // convert it to a vector with movd (S2V+shuffle to zero extend).
3358 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3359 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3360 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3361 Subtarget->hasSSE2(), DAG);
3363 // Now we have our 32-bit value zero extended in the low element of
3364 // a vector. If Idx != 0, swizzle it into place.
3367 Item, DAG.getNode(ISD::UNDEF, dl, Item.getValueType()),
3368 getSwapEltZeroMask(VecElts, Idx, DAG, dl)
3370 Item = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VecVT, Ops, 3);
3372 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3376 // If we have a constant or non-constant insertion into the low element of
3377 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3378 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3379 // depending on what the source datatype is. Because we can only get here
3380 // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3382 // Don't do this for i64 values on x86-32.
3383 (EVT != MVT::i64 || Subtarget->is64Bit())) {
3384 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3385 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3386 return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3387 Subtarget->hasSSE2(), DAG);
3390 // Is it a vector logical left shift?
3391 if (NumElems == 2 && Idx == 1 &&
3392 isZeroNode(Op.getOperand(0)) && !isZeroNode(Op.getOperand(1))) {
3393 unsigned NumBits = VT.getSizeInBits();
3394 return getVShift(true, VT,
3395 DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(1)),
3396 NumBits/2, DAG, *this, dl);
3399 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3402 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3403 // is a non-constant being inserted into an element other than the low one,
3404 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3405 // movd/movss) to move this into the low element, then shuffle it into
3407 if (EVTBits == 32) {
3408 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3410 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3411 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3412 Subtarget->hasSSE2(), DAG);
3413 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3414 MVT MaskEVT = MaskVT.getVectorElementType();
3415 SmallVector<SDValue, 8> MaskVec;
3416 for (unsigned i = 0; i < NumElems; i++)
3417 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3418 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3419 &MaskVec[0], MaskVec.size());
3420 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, Item,
3421 DAG.getNode(ISD::UNDEF, VT), Mask);
3425 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3426 if (Values.size() == 1)
3429 // A vector full of immediates; various special cases are already
3430 // handled, so this is best done with a single constant-pool load.
3434 // Let legalizer expand 2-wide build_vectors.
3435 if (EVTBits == 64) {
3436 if (NumNonZero == 1) {
3437 // One half is zero or undef.
3438 unsigned Idx = CountTrailingZeros_32(NonZeros);
3439 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3440 Op.getOperand(Idx));
3441 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3442 Subtarget->hasSSE2(), DAG);
3447 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3448 if (EVTBits == 8 && NumElems == 16) {
3449 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3451 if (V.getNode()) return V;
3454 if (EVTBits == 16 && NumElems == 8) {
3455 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3457 if (V.getNode()) return V;
3460 // If element VT is == 32 bits, turn it into a number of shuffles.
3461 SmallVector<SDValue, 8> V;
3463 if (NumElems == 4 && NumZero > 0) {
3464 for (unsigned i = 0; i < 4; ++i) {
3465 bool isZero = !(NonZeros & (1 << i));
3467 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3469 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3472 for (unsigned i = 0; i < 2; ++i) {
3473 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3476 V[i] = V[i*2]; // Must be a zero vector.
3479 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[i*2+1], V[i*2],
3480 getMOVLMask(NumElems, DAG, dl));
3483 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[i*2], V[i*2+1],
3484 getMOVLMask(NumElems, DAG, dl));
3487 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[i*2], V[i*2+1],
3488 getUnpacklMask(NumElems, DAG, dl));
3493 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3494 MVT EVT = MaskVT.getVectorElementType();
3495 SmallVector<SDValue, 8> MaskVec;
3496 bool Reverse = (NonZeros & 0x3) == 2;
3497 for (unsigned i = 0; i < 2; ++i)
3499 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3501 MaskVec.push_back(DAG.getConstant(i, EVT));
3502 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3503 for (unsigned i = 0; i < 2; ++i)
3505 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3507 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3508 SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3509 &MaskVec[0], MaskVec.size());
3510 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[0], V[1], ShufMask);
3513 if (Values.size() > 2) {
3514 // Expand into a number of unpckl*.
3516 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3517 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3518 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3519 SDValue UnpckMask = getUnpacklMask(NumElems, DAG, dl);
3520 for (unsigned i = 0; i < NumElems; ++i)
3521 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3523 while (NumElems != 0) {
3524 for (unsigned i = 0; i < NumElems; ++i)
3525 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[i], V[i + NumElems],
3536 SDValue LowerVECTOR_SHUFFLEv8i16(SDValue V1, SDValue V2,
3537 SDValue PermMask, SelectionDAG &DAG,
3538 TargetLowering &TLI, DebugLoc dl) {
3540 MVT MaskVT = MVT::getIntVectorWithNumElements(8);
3541 MVT MaskEVT = MaskVT.getVectorElementType();
3542 MVT PtrVT = TLI.getPointerTy();
3543 SmallVector<SDValue, 8> MaskElts(PermMask.getNode()->op_begin(),
3544 PermMask.getNode()->op_end());
3546 // First record which half of which vector the low elements come from.
3547 SmallVector<unsigned, 4> LowQuad(4);
3548 for (unsigned i = 0; i < 4; ++i) {
3549 SDValue Elt = MaskElts[i];
3550 if (Elt.getOpcode() == ISD::UNDEF)
3552 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3553 int QuadIdx = EltIdx / 4;
3557 int BestLowQuad = -1;
3558 unsigned MaxQuad = 1;
3559 for (unsigned i = 0; i < 4; ++i) {
3560 if (LowQuad[i] > MaxQuad) {
3562 MaxQuad = LowQuad[i];
3566 // Record which half of which vector the high elements come from.
3567 SmallVector<unsigned, 4> HighQuad(4);
3568 for (unsigned i = 4; i < 8; ++i) {
3569 SDValue Elt = MaskElts[i];
3570 if (Elt.getOpcode() == ISD::UNDEF)
3572 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3573 int QuadIdx = EltIdx / 4;
3574 ++HighQuad[QuadIdx];
3577 int BestHighQuad = -1;
3579 for (unsigned i = 0; i < 4; ++i) {
3580 if (HighQuad[i] > MaxQuad) {
3582 MaxQuad = HighQuad[i];
3586 // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3587 if (BestLowQuad != -1 || BestHighQuad != -1) {
3588 // First sort the 4 chunks in order using shufpd.
3589 SmallVector<SDValue, 8> MaskVec;
3591 if (BestLowQuad != -1)
3592 MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3594 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3596 if (BestHighQuad != -1)
3597 MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3599 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3601 SDValue Mask= DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, &MaskVec[0],2);
3602 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v2i64,
3603 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
3604 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), Mask);
3605 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
3607 // Now sort high and low parts separately.
3608 BitVector InOrder(8);
3609 if (BestLowQuad != -1) {
3610 // Sort lower half in order using PSHUFLW.
3612 bool AnyOutOrder = false;
3614 for (unsigned i = 0; i != 4; ++i) {
3615 SDValue Elt = MaskElts[i];
3616 if (Elt.getOpcode() == ISD::UNDEF) {
3617 MaskVec.push_back(Elt);
3620 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3624 MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3626 // If this element is in the right place after this shuffle, then
3628 if ((int)(EltIdx / 4) == BestLowQuad)
3633 for (unsigned i = 4; i != 8; ++i)
3634 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3635 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3637 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v8i16,
3642 if (BestHighQuad != -1) {
3643 // Sort high half in order using PSHUFHW if possible.
3646 for (unsigned i = 0; i != 4; ++i)
3647 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3649 bool AnyOutOrder = false;
3650 for (unsigned i = 4; i != 8; ++i) {
3651 SDValue Elt = MaskElts[i];
3652 if (Elt.getOpcode() == ISD::UNDEF) {
3653 MaskVec.push_back(Elt);
3656 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3660 MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3662 // If this element is in the right place after this shuffle, then
3664 if ((int)(EltIdx / 4) == BestHighQuad)
3670 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl,
3671 MaskVT, &MaskVec[0], 8);
3672 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v8i16,
3677 // The other elements are put in the right place using pextrw and pinsrw.
3678 for (unsigned i = 0; i != 8; ++i) {
3681 SDValue Elt = MaskElts[i];
3682 if (Elt.getOpcode() == ISD::UNDEF)
3684 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3685 SDValue ExtOp = (EltIdx < 8)
3686 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
3687 DAG.getConstant(EltIdx, PtrVT))
3688 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
3689 DAG.getConstant(EltIdx - 8, PtrVT));
3690 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3691 DAG.getConstant(i, PtrVT));
3697 // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use as
3698 // few as possible. First, let's find out how many elements are already in the
3700 unsigned V1InOrder = 0;
3701 unsigned V1FromV1 = 0;
3702 unsigned V2InOrder = 0;
3703 unsigned V2FromV2 = 0;
3704 SmallVector<SDValue, 8> V1Elts;
3705 SmallVector<SDValue, 8> V2Elts;
3706 for (unsigned i = 0; i < 8; ++i) {
3707 SDValue Elt = MaskElts[i];
3708 if (Elt.getOpcode() == ISD::UNDEF) {
3709 V1Elts.push_back(Elt);
3710 V2Elts.push_back(Elt);
3715 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3717 V1Elts.push_back(Elt);
3718 V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3720 } else if (EltIdx == i+8) {
3721 V1Elts.push_back(Elt);
3722 V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3724 } else if (EltIdx < 8) {
3725 V1Elts.push_back(Elt);
3726 V2Elts.push_back(DAG.getConstant(EltIdx+8, MaskEVT));
3729 V1Elts.push_back(Elt);
3730 V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3735 if (V2InOrder > V1InOrder) {
3736 PermMask = CommuteVectorShuffleMask(PermMask, DAG, dl);
3738 std::swap(V1Elts, V2Elts);
3739 std::swap(V1FromV1, V2FromV2);
3742 if ((V1FromV1 + V1InOrder) != 8) {
3743 // Some elements are from V2.
3745 // If there are elements that are from V1 but out of place,
3746 // then first sort them in place
3747 SmallVector<SDValue, 8> MaskVec;
3748 for (unsigned i = 0; i < 8; ++i) {
3749 SDValue Elt = V1Elts[i];
3750 if (Elt.getOpcode() == ISD::UNDEF) {
3751 MaskVec.push_back(DAG.getNode(ISD::UNDEF, dl, MaskEVT));
3754 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3756 MaskVec.push_back(DAG.getNode(ISD::UNDEF, dl, MaskEVT));
3758 MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3760 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT, &MaskVec[0], 8);
3761 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v8i16, V1, V1, Mask);
3765 for (unsigned i = 0; i < 8; ++i) {
3766 SDValue Elt = V1Elts[i];
3767 if (Elt.getOpcode() == ISD::UNDEF)
3769 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3772 SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
3773 DAG.getConstant(EltIdx - 8, PtrVT));
3774 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3775 DAG.getConstant(i, PtrVT));
3779 // All elements are from V1.
3781 for (unsigned i = 0; i < 8; ++i) {
3782 SDValue Elt = V1Elts[i];
3783 if (Elt.getOpcode() == ISD::UNDEF)
3785 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3786 SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
3787 DAG.getConstant(EltIdx, PtrVT));
3788 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3789 DAG.getConstant(i, PtrVT));
3795 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3796 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3797 /// done when every pair / quad of shuffle mask elements point to elements in
3798 /// the right sequence. e.g.
3799 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3801 SDValue RewriteAsNarrowerShuffle(SDValue V1, SDValue V2,
3803 SDValue PermMask, SelectionDAG &DAG,
3804 TargetLowering &TLI, DebugLoc dl) {
3805 unsigned NumElems = PermMask.getNumOperands();
3806 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3807 MVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3808 MVT MaskEltVT = MaskVT.getVectorElementType();
3810 switch (VT.getSimpleVT()) {
3811 default: assert(false && "Unexpected!");
3812 case MVT::v4f32: NewVT = MVT::v2f64; break;
3813 case MVT::v4i32: NewVT = MVT::v2i64; break;
3814 case MVT::v8i16: NewVT = MVT::v4i32; break;
3815 case MVT::v16i8: NewVT = MVT::v4i32; break;
3818 if (NewWidth == 2) {
3824 unsigned Scale = NumElems / NewWidth;
3825 SmallVector<SDValue, 8> MaskVec;
3826 for (unsigned i = 0; i < NumElems; i += Scale) {
3827 unsigned StartIdx = ~0U;
3828 for (unsigned j = 0; j < Scale; ++j) {
3829 SDValue Elt = PermMask.getOperand(i+j);
3830 if (Elt.getOpcode() == ISD::UNDEF)
3832 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3833 if (StartIdx == ~0U)
3834 StartIdx = EltIdx - (EltIdx % Scale);
3835 if (EltIdx != StartIdx + j)
3838 if (StartIdx == ~0U)
3839 MaskVec.push_back(DAG.getNode(ISD::UNDEF, dl, MaskEltVT));
3841 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MaskEltVT));
3844 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
3845 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
3846 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, NewVT, V1, V2,
3847 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3848 &MaskVec[0], MaskVec.size()));
3851 /// getVZextMovL - Return a zero-extending vector move low node.
3853 static SDValue getVZextMovL(MVT VT, MVT OpVT,
3854 SDValue SrcOp, SelectionDAG &DAG,
3855 const X86Subtarget *Subtarget, DebugLoc dl) {
3856 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3857 LoadSDNode *LD = NULL;
3858 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
3859 LD = dyn_cast<LoadSDNode>(SrcOp);
3861 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3863 MVT EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3864 if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
3865 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3866 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3867 SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
3869 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3870 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3871 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3872 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3880 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3881 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3882 DAG.getNode(ISD::BIT_CONVERT, dl,
3886 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
3889 LowerVECTOR_SHUFFLE_4wide(SDValue V1, SDValue V2,
3890 SDValue PermMask, MVT VT, SelectionDAG &DAG,
3892 MVT MaskVT = PermMask.getValueType();
3893 MVT MaskEVT = MaskVT.getVectorElementType();
3894 SmallVector<std::pair<int, int>, 8> Locs;
3896 SmallVector<SDValue, 8> Mask1(4, DAG.getNode(ISD::UNDEF, dl, MaskEVT));
3899 for (unsigned i = 0; i != 4; ++i) {
3900 SDValue Elt = PermMask.getOperand(i);
3901 if (Elt.getOpcode() == ISD::UNDEF) {
3902 Locs[i] = std::make_pair(-1, -1);
3904 unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
3905 assert(Val < 8 && "Invalid VECTOR_SHUFFLE index!");
3907 Locs[i] = std::make_pair(0, NumLo);
3911 Locs[i] = std::make_pair(1, NumHi);
3913 Mask1[2+NumHi] = Elt;
3919 if (NumLo <= 2 && NumHi <= 2) {
3920 // If no more than two elements come from either vector. This can be
3921 // implemented with two shuffles. First shuffle gather the elements.
3922 // The second shuffle, which takes the first shuffle as both of its
3923 // vector operands, put the elements into the right order.
3924 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
3925 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3926 &Mask1[0], Mask1.size()));
3928 SmallVector<SDValue, 8> Mask2(4, DAG.getNode(ISD::UNDEF, dl, MaskEVT));
3929 for (unsigned i = 0; i != 4; ++i) {
3930 if (Locs[i].first == -1)
3933 unsigned Idx = (i < 2) ? 0 : 4;
3934 Idx += Locs[i].first * 2 + Locs[i].second;
3935 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3939 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V1,
3940 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
3941 &Mask2[0], Mask2.size()));
3942 } else if (NumLo == 3 || NumHi == 3) {
3943 // Otherwise, we must have three elements from one vector, call it X, and
3944 // one element from the other, call it Y. First, use a shufps to build an
3945 // intermediate vector with the one element from Y and the element from X
3946 // that will be in the same half in the final destination (the indexes don't
3947 // matter). Then, use a shufps to build the final vector, taking the half
3948 // containing the element from Y from the intermediate, and the other half
3951 // Normalize it so the 3 elements come from V1.
3952 PermMask = CommuteVectorShuffleMask(PermMask, DAG, dl);
3956 // Find the element from V2.
3958 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
3959 SDValue Elt = PermMask.getOperand(HiIndex);
3960 if (Elt.getOpcode() == ISD::UNDEF)
3962 unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
3967 Mask1[0] = PermMask.getOperand(HiIndex);
3968 Mask1[1] = DAG.getNode(ISD::UNDEF, dl, MaskEVT);
3969 Mask1[2] = PermMask.getOperand(HiIndex^1);
3970 Mask1[3] = DAG.getNode(ISD::UNDEF, dl, MaskEVT);
3971 V2 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
3972 DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3975 Mask1[0] = PermMask.getOperand(0);
3976 Mask1[1] = PermMask.getOperand(1);
3977 Mask1[2] = DAG.getConstant(HiIndex & 1 ? 6 : 4, MaskEVT);
3978 Mask1[3] = DAG.getConstant(HiIndex & 1 ? 4 : 6, MaskEVT);
3979 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
3980 DAG.getNode(ISD::BUILD_VECTOR, dl,
3981 MaskVT, &Mask1[0], 4));
3983 Mask1[0] = DAG.getConstant(HiIndex & 1 ? 2 : 0, MaskEVT);
3984 Mask1[1] = DAG.getConstant(HiIndex & 1 ? 0 : 2, MaskEVT);
3985 Mask1[2] = PermMask.getOperand(2);
3986 Mask1[3] = PermMask.getOperand(3);
3987 if (Mask1[2].getOpcode() != ISD::UNDEF)
3989 DAG.getConstant(cast<ConstantSDNode>(Mask1[2])->getZExtValue()+4,
3991 if (Mask1[3].getOpcode() != ISD::UNDEF)
3993 DAG.getConstant(cast<ConstantSDNode>(Mask1[3])->getZExtValue()+4,
3995 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V2, V1,
3996 DAG.getNode(ISD::BUILD_VECTOR, dl,
3997 MaskVT, &Mask1[0], 4));
4001 // Break it into (shuffle shuffle_hi, shuffle_lo).
4003 SmallVector<SDValue,8> LoMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
4004 SmallVector<SDValue,8> HiMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
4005 SmallVector<SDValue,8> *MaskPtr = &LoMask;
4006 unsigned MaskIdx = 0;
4009 for (unsigned i = 0; i != 4; ++i) {
4016 SDValue Elt = PermMask.getOperand(i);
4017 if (Elt.getOpcode() == ISD::UNDEF) {
4018 Locs[i] = std::make_pair(-1, -1);
4019 } else if (cast<ConstantSDNode>(Elt)->getZExtValue() < 4) {
4020 Locs[i] = std::make_pair(MaskIdx, LoIdx);
4021 (*MaskPtr)[LoIdx] = Elt;
4024 Locs[i] = std::make_pair(MaskIdx, HiIdx);
4025 (*MaskPtr)[HiIdx] = Elt;
4030 SDValue LoShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
4031 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4032 &LoMask[0], LoMask.size()));
4033 SDValue HiShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
4034 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4035 &HiMask[0], HiMask.size()));
4036 SmallVector<SDValue, 8> MaskOps;
4037 for (unsigned i = 0; i != 4; ++i) {
4038 if (Locs[i].first == -1) {
4039 MaskOps.push_back(DAG.getNode(ISD::UNDEF, dl, MaskEVT));
4041 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4042 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
4045 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, LoShuffle, HiShuffle,
4046 DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4047 &MaskOps[0], MaskOps.size()));
4051 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4052 SDValue V1 = Op.getOperand(0);
4053 SDValue V2 = Op.getOperand(1);
4054 SDValue PermMask = Op.getOperand(2);
4055 MVT VT = Op.getValueType();
4056 DebugLoc dl = Op.getNode()->getDebugLoc();
4057 unsigned NumElems = PermMask.getNumOperands();
4058 bool isMMX = VT.getSizeInBits() == 64;
4059 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4060 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4061 bool V1IsSplat = false;
4062 bool V2IsSplat = false;
4064 if (isUndefShuffle(Op.getNode()))
4065 return DAG.getNode(ISD::UNDEF, dl, VT);
4067 if (isZeroShuffle(Op.getNode()))
4068 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4070 if (isIdentityMask(PermMask.getNode()))
4072 else if (isIdentityMask(PermMask.getNode(), true))
4075 // Canonicalize movddup shuffles.
4076 if (V2IsUndef && Subtarget->hasSSE2() &&
4077 VT.getSizeInBits() == 128 &&
4078 X86::isMOVDDUPMask(PermMask.getNode()))
4079 return CanonicalizeMovddup(Op, V1, PermMask, DAG, Subtarget->hasSSE3());
4081 if (isSplatMask(PermMask.getNode())) {
4082 if (isMMX || NumElems < 4) return Op;
4083 // Promote it to a v4{if}32 splat.
4084 return PromoteSplat(Op, DAG, Subtarget->hasSSE2());
4087 // If the shuffle can be profitably rewritten as a narrower shuffle, then
4089 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4090 SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG,
4092 if (NewOp.getNode())
4093 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4094 LowerVECTOR_SHUFFLE(NewOp, DAG));
4095 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4096 // FIXME: Figure out a cleaner way to do this.
4097 // Try to make use of movq to zero out the top part.
4098 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4099 SDValue NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
4101 if (NewOp.getNode()) {
4102 SDValue NewV1 = NewOp.getOperand(0);
4103 SDValue NewV2 = NewOp.getOperand(1);
4104 SDValue NewMask = NewOp.getOperand(2);
4105 if (isCommutedMOVL(NewMask.getNode(), true, false)) {
4106 NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
4107 return getVZextMovL(VT, NewOp.getValueType(), NewV2, DAG, Subtarget,
4111 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4112 SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
4114 if (NewOp.getNode() && X86::isMOVLMask(NewOp.getOperand(2).getNode()))
4115 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4116 DAG, Subtarget, dl);
4120 // Check if this can be converted into a logical shift.
4121 bool isLeft = false;
4124 bool isShift = isVectorShift(Op, PermMask, DAG, isLeft, ShVal, ShAmt);
4125 if (isShift && ShVal.hasOneUse()) {
4126 // If the shifted value has multiple uses, it may be cheaper to use
4127 // v_set0 + movlhps or movhlps, etc.
4128 MVT EVT = VT.getVectorElementType();
4129 ShAmt *= EVT.getSizeInBits();
4130 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4133 if (X86::isMOVLMask(PermMask.getNode())) {
4136 if (ISD::isBuildVectorAllZeros(V1.getNode()))
4137 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4142 if (!isMMX && (X86::isMOVSHDUPMask(PermMask.getNode()) ||
4143 X86::isMOVSLDUPMask(PermMask.getNode()) ||
4144 X86::isMOVHLPSMask(PermMask.getNode()) ||
4145 X86::isMOVHPMask(PermMask.getNode()) ||
4146 X86::isMOVLPMask(PermMask.getNode())))
4149 if (ShouldXformToMOVHLPS(PermMask.getNode()) ||
4150 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), PermMask.getNode()))
4151 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4154 // No better options. Use a vshl / vsrl.
4155 MVT EVT = VT.getVectorElementType();
4156 ShAmt *= EVT.getSizeInBits();
4157 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4160 bool Commuted = false;
4161 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4162 // 1,1,1,1 -> v8i16 though.
4163 V1IsSplat = isSplatVector(V1.getNode());
4164 V2IsSplat = isSplatVector(V2.getNode());
4166 // Canonicalize the splat or undef, if present, to be on the RHS.
4167 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4168 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4169 std::swap(V1IsSplat, V2IsSplat);
4170 std::swap(V1IsUndef, V2IsUndef);
4174 // FIXME: Figure out a cleaner way to do this.
4175 if (isCommutedMOVL(PermMask.getNode(), V2IsSplat, V2IsUndef)) {
4176 if (V2IsUndef) return V1;
4177 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4179 // V2 is a splat, so the mask may be malformed. That is, it may point
4180 // to any V2 element. The instruction selectior won't like this. Get
4181 // a corrected mask and commute to form a proper MOVS{S|D}.
4182 SDValue NewMask = getMOVLMask(NumElems, DAG, dl);
4183 if (NewMask.getNode() != PermMask.getNode())
4184 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, NewMask);
4189 if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
4190 X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
4191 X86::isUNPCKLMask(PermMask.getNode()) ||
4192 X86::isUNPCKHMask(PermMask.getNode()))
4196 // Normalize mask so all entries that point to V2 points to its first
4197 // element then try to match unpck{h|l} again. If match, return a
4198 // new vector_shuffle with the corrected mask.
4199 SDValue NewMask = NormalizeMask(PermMask, DAG);
4200 if (NewMask.getNode() != PermMask.getNode()) {
4201 if (X86::isUNPCKLMask(PermMask.getNode(), true)) {
4202 SDValue NewMask = getUnpacklMask(NumElems, DAG, dl);
4203 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, NewMask);
4204 } else if (X86::isUNPCKHMask(PermMask.getNode(), true)) {
4205 SDValue NewMask = getUnpackhMask(NumElems, DAG, dl);
4206 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, NewMask);
4211 // Normalize the node to match x86 shuffle ops if needed
4212 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.getNode()))
4213 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4216 // Commute is back and try unpck* again.
4217 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4218 if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
4219 X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
4220 X86::isUNPCKLMask(PermMask.getNode()) ||
4221 X86::isUNPCKHMask(PermMask.getNode()))
4225 // Try PSHUF* first, then SHUFP*.
4226 // MMX doesn't have PSHUFD but it does have PSHUFW. While it's theoretically
4227 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
4228 if (isMMX && NumElems == 4 && X86::isPSHUFDMask(PermMask.getNode())) {
4229 if (V2.getOpcode() != ISD::UNDEF)
4230 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1,
4231 DAG.getNode(ISD::UNDEF, VT), PermMask);
4236 if (Subtarget->hasSSE2() &&
4237 (X86::isPSHUFDMask(PermMask.getNode()) ||
4238 X86::isPSHUFHWMask(PermMask.getNode()) ||
4239 X86::isPSHUFLWMask(PermMask.getNode()))) {
4241 if (VT == MVT::v4f32) {
4243 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, RVT,
4244 DAG.getNode(ISD::BIT_CONVERT, dl, RVT, V1),
4245 DAG.getNode(ISD::UNDEF, dl, RVT), PermMask);
4246 } else if (V2.getOpcode() != ISD::UNDEF)
4247 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, RVT, V1,
4248 DAG.getNode(ISD::UNDEF, dl, RVT), PermMask);
4250 Op = DAG.getNode(ISD::BIT_CONVERT, dl, VT, Op);
4254 // Binary or unary shufps.
4255 if (X86::isSHUFPMask(PermMask.getNode()) ||
4256 (V2.getOpcode() == ISD::UNDEF && X86::isPSHUFDMask(PermMask.getNode())))
4260 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4261 if (VT == MVT::v8i16) {
4262 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this, dl);
4263 if (NewOp.getNode())
4267 // Handle all 4 wide cases with a number of shuffles except for MMX.
4268 if (NumElems == 4 && !isMMX)
4269 return LowerVECTOR_SHUFFLE_4wide(V1, V2, PermMask, VT, DAG, dl);
4275 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4276 SelectionDAG &DAG) {
4277 MVT VT = Op.getValueType();
4278 DebugLoc dl = Op.getNode()->getDebugLoc();
4279 if (VT.getSizeInBits() == 8) {
4280 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4281 Op.getOperand(0), Op.getOperand(1));
4282 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4283 DAG.getValueType(VT));
4284 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4285 } else if (VT.getSizeInBits() == 16) {
4286 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4287 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4289 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4290 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4291 DAG.getNode(ISD::BIT_CONVERT, dl,
4295 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4296 Op.getOperand(0), Op.getOperand(1));
4297 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4298 DAG.getValueType(VT));
4299 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4300 } else if (VT == MVT::f32) {
4301 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4302 // the result back to FR32 register. It's only worth matching if the
4303 // result has a single use which is a store or a bitcast to i32. And in
4304 // the case of a store, it's not worth it if the index is a constant 0,
4305 // because a MOVSSmr can be used instead, which is smaller and faster.
4306 if (!Op.hasOneUse())
4308 SDNode *User = *Op.getNode()->use_begin();
4309 if ((User->getOpcode() != ISD::STORE ||
4310 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4311 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4312 (User->getOpcode() != ISD::BIT_CONVERT ||
4313 User->getValueType(0) != MVT::i32))
4315 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4316 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4319 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4320 } else if (VT == MVT::i32) {
4321 // ExtractPS works with constant index.
4322 if (isa<ConstantSDNode>(Op.getOperand(1)))
4330 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4331 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4334 if (Subtarget->hasSSE41()) {
4335 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4340 MVT VT = Op.getValueType();
4341 DebugLoc dl = Op.getNode()->getDebugLoc();
4342 // TODO: handle v16i8.
4343 if (VT.getSizeInBits() == 16) {
4344 SDValue Vec = Op.getOperand(0);
4345 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4347 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4348 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4349 DAG.getNode(ISD::BIT_CONVERT, dl,
4352 // Transform it so it match pextrw which produces a 32-bit result.
4353 MVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT()+1);
4354 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EVT,
4355 Op.getOperand(0), Op.getOperand(1));
4356 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EVT, Extract,
4357 DAG.getValueType(VT));
4358 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4359 } else if (VT.getSizeInBits() == 32) {
4360 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4363 // SHUFPS the element to the lowest double word, then movss.
4364 MVT MaskVT = MVT::getIntVectorWithNumElements(4);
4365 SmallVector<SDValue, 8> IdxVec;
4367 push_back(DAG.getConstant(Idx, MaskVT.getVectorElementType()));
4369 push_back(DAG.getNode(ISD::UNDEF, dl, MaskVT.getVectorElementType()));
4371 push_back(DAG.getNode(ISD::UNDEF, dl, MaskVT.getVectorElementType()));
4373 push_back(DAG.getNode(ISD::UNDEF, dl, MaskVT.getVectorElementType()));
4374 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4375 &IdxVec[0], IdxVec.size());
4376 SDValue Vec = Op.getOperand(0);
4377 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, Vec.getValueType(),
4378 Vec, DAG.getNode(ISD::UNDEF, dl, Vec.getValueType()),
4380 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4381 DAG.getIntPtrConstant(0));
4382 } else if (VT.getSizeInBits() == 64) {
4383 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4384 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4385 // to match extract_elt for f64.
4386 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4390 // UNPCKHPD the element to the lowest double word, then movsd.
4391 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4392 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4393 MVT MaskVT = MVT::getIntVectorWithNumElements(2);
4394 SmallVector<SDValue, 8> IdxVec;
4395 IdxVec.push_back(DAG.getConstant(1, MaskVT.getVectorElementType()));
4397 push_back(DAG.getNode(ISD::UNDEF, dl, MaskVT.getVectorElementType()));
4398 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVT,
4399 &IdxVec[0], IdxVec.size());
4400 SDValue Vec = Op.getOperand(0);
4401 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, Vec.getValueType(),
4402 Vec, DAG.getNode(ISD::UNDEF, dl, Vec.getValueType()),
4404 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4405 DAG.getIntPtrConstant(0));
4412 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4413 MVT VT = Op.getValueType();
4414 MVT EVT = VT.getVectorElementType();
4415 DebugLoc dl = Op.getNode()->getDebugLoc();
4417 SDValue N0 = Op.getOperand(0);
4418 SDValue N1 = Op.getOperand(1);
4419 SDValue N2 = Op.getOperand(2);
4421 if ((EVT.getSizeInBits() == 8 || EVT.getSizeInBits() == 16) &&
4422 isa<ConstantSDNode>(N2)) {
4423 unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4425 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4427 if (N1.getValueType() != MVT::i32)
4428 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4429 if (N2.getValueType() != MVT::i32)
4430 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4431 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4432 } else if (EVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4433 // Bits [7:6] of the constant are the source select. This will always be
4434 // zero here. The DAG Combiner may combine an extract_elt index into these
4435 // bits. For example (insert (extract, 3), 2) could be matched by putting
4436 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4437 // Bits [5:4] of the constant are the destination select. This is the
4438 // value of the incoming immediate.
4439 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4440 // combine either bitwise AND or insert of float 0.0 to set these bits.
4441 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4442 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4443 } else if (EVT == MVT::i32) {
4444 // InsertPS works with constant index.
4445 if (isa<ConstantSDNode>(N2))
4452 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4453 MVT VT = Op.getValueType();
4454 MVT EVT = VT.getVectorElementType();
4456 if (Subtarget->hasSSE41())
4457 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4462 DebugLoc dl = Op.getNode()->getDebugLoc();
4463 SDValue N0 = Op.getOperand(0);
4464 SDValue N1 = Op.getOperand(1);
4465 SDValue N2 = Op.getOperand(2);
4467 if (EVT.getSizeInBits() == 16) {
4468 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4469 // as its second argument.
4470 if (N1.getValueType() != MVT::i32)
4471 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4472 if (N2.getValueType() != MVT::i32)
4473 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4474 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
4480 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4481 DebugLoc dl = Op.getNode()->getDebugLoc();
4482 if (Op.getValueType() == MVT::v2f32)
4483 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4484 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4485 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4486 Op.getOperand(0))));
4488 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4489 MVT VT = MVT::v2i32;
4490 switch (Op.getValueType().getSimpleVT()) {
4497 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4498 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4501 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4502 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4503 // one of the above mentioned nodes. It has to be wrapped because otherwise
4504 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4505 // be used to form addressing mode. These wrapped nodes will be selected
4508 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4509 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4510 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(),
4512 CP->getAlignment());
4513 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4514 // With PIC, the address is actually $g + Offset.
4515 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4516 !Subtarget->isPICStyleRIPRel()) {
4517 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4518 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4526 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV,
4528 SelectionDAG &DAG) const {
4529 bool IsPic = getTargetMachine().getRelocationModel() == Reloc::PIC_;
4530 bool ExtraLoadRequired =
4531 Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false);
4533 // Create the TargetGlobalAddress node, folding in the constant
4534 // offset if it is legal.
4536 if (!IsPic && !ExtraLoadRequired && isInt32(Offset)) {
4537 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4540 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0);
4541 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4543 // With PIC, the address is actually $g + Offset.
4544 if (IsPic && !Subtarget->isPICStyleRIPRel()) {
4545 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4546 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4550 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4551 // load the value at address GV, not the value of GV itself. This means that
4552 // the GlobalAddress must be in the base or index register of the address, not
4553 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4554 // The same applies for external symbols during PIC codegen
4555 if (ExtraLoadRequired)
4556 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
4557 PseudoSourceValue::getGOT(), 0);
4559 // If there was a non-zero offset that we didn't fold, create an explicit
4562 Result = DAG.getNode(ISD::ADD, getPointerTy(), Result,
4563 DAG.getConstant(Offset, getPointerTy()));
4569 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4570 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4571 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4572 return LowerGlobalAddress(GV, Offset, DAG);
4575 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4577 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4580 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
4581 DAG.getNode(X86ISD::GlobalBaseReg,
4583 InFlag = Chain.getValue(1);
4585 // emit leal symbol@TLSGD(,%ebx,1), %eax
4586 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4587 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4588 GA->getValueType(0),
4590 SDValue Ops[] = { Chain, TGA, InFlag };
4591 SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
4592 InFlag = Result.getValue(2);
4593 Chain = Result.getValue(1);
4595 // call ___tls_get_addr. This function receives its argument in
4596 // the register EAX.
4597 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
4598 InFlag = Chain.getValue(1);
4600 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4601 SDValue Ops1[] = { Chain,
4602 DAG.getTargetExternalSymbol("___tls_get_addr",
4604 DAG.getRegister(X86::EAX, PtrVT),
4605 DAG.getRegister(X86::EBX, PtrVT),
4607 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
4608 InFlag = Chain.getValue(1);
4610 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
4613 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4615 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4617 SDValue InFlag, Chain;
4619 // emit leaq symbol@TLSGD(%rip), %rdi
4620 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4621 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4622 GA->getValueType(0),
4624 SDValue Ops[] = { DAG.getEntryNode(), TGA};
4625 SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 2);
4626 Chain = Result.getValue(1);
4627 InFlag = Result.getValue(2);
4629 // call __tls_get_addr. This function receives its argument in
4630 // the register RDI.
4631 Chain = DAG.getCopyToReg(Chain, X86::RDI, Result, InFlag);
4632 InFlag = Chain.getValue(1);
4634 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4635 SDValue Ops1[] = { Chain,
4636 DAG.getTargetExternalSymbol("__tls_get_addr",
4638 DAG.getRegister(X86::RDI, PtrVT),
4640 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 4);
4641 InFlag = Chain.getValue(1);
4643 return DAG.getCopyFromReg(Chain, X86::RAX, PtrVT, InFlag);
4646 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4647 // "local exec" model.
4648 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4650 // Get the Thread Pointer
4651 SDValue ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4652 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4654 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4655 GA->getValueType(0),
4657 SDValue Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4659 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4660 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
4661 PseudoSourceValue::getGOT(), 0);
4663 // The address of the thread local variable is the add of the thread
4664 // pointer with the offset of the variable.
4665 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4669 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4670 // TODO: implement the "local dynamic" model
4671 // TODO: implement the "initial exec"model for pic executables
4672 assert(Subtarget->isTargetELF() &&
4673 "TLS not implemented for non-ELF targets");
4674 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4675 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4676 // otherwise use the "Local Exec"TLS Model
4677 if (Subtarget->is64Bit()) {
4678 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4680 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4681 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4683 return LowerToTLSExecModel(GA, DAG, getPointerTy());
4688 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4689 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4690 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4691 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4692 // With PIC, the address is actually $g + Offset.
4693 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4694 !Subtarget->isPICStyleRIPRel()) {
4695 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4696 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4703 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4704 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4705 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4706 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4707 // With PIC, the address is actually $g + Offset.
4708 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4709 !Subtarget->isPICStyleRIPRel()) {
4710 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4711 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4718 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4719 /// take a 2 x i32 value to shift plus a shift amount.
4720 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4721 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4722 MVT VT = Op.getValueType();
4723 unsigned VTBits = VT.getSizeInBits();
4724 DebugLoc dl = Op.getNode()->getDebugLoc();
4725 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4726 SDValue ShOpLo = Op.getOperand(0);
4727 SDValue ShOpHi = Op.getOperand(1);
4728 SDValue ShAmt = Op.getOperand(2);
4729 SDValue Tmp1 = isSRA ?
4730 DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
4731 DAG.getConstant(VTBits - 1, MVT::i8)) :
4732 DAG.getConstant(0, VT);
4735 if (Op.getOpcode() == ISD::SHL_PARTS) {
4736 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
4737 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4739 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
4740 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
4743 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
4744 DAG.getConstant(VTBits, MVT::i8));
4745 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, VT,
4746 AndNode, DAG.getConstant(0, MVT::i8));
4749 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4750 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4751 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4753 if (Op.getOpcode() == ISD::SHL_PARTS) {
4754 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4755 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4757 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4758 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4761 SDValue Ops[2] = { Lo, Hi };
4762 return DAG.getMergeValues(Ops, 2, dl);
4765 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4766 MVT SrcVT = Op.getOperand(0).getValueType();
4767 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4768 "Unknown SINT_TO_FP to lower!");
4770 // These are really Legal; caller falls through into that case.
4771 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4773 if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 &&
4774 Subtarget->is64Bit())
4777 DebugLoc dl = Op.getNode()->getDebugLoc();
4778 unsigned Size = SrcVT.getSizeInBits()/8;
4779 MachineFunction &MF = DAG.getMachineFunction();
4780 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4781 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4782 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
4784 PseudoSourceValue::getFixedStack(SSFI), 0);
4788 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4790 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4792 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4793 SmallVector<SDValue, 8> Ops;
4794 Ops.push_back(Chain);
4795 Ops.push_back(StackSlot);
4796 Ops.push_back(DAG.getValueType(SrcVT));
4797 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
4798 Tys, &Ops[0], Ops.size());
4801 Chain = Result.getValue(1);
4802 SDValue InFlag = Result.getValue(2);
4804 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4805 // shouldn't be necessary except that RFP cannot be live across
4806 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4807 MachineFunction &MF = DAG.getMachineFunction();
4808 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4809 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4810 Tys = DAG.getVTList(MVT::Other);
4811 SmallVector<SDValue, 8> Ops;
4812 Ops.push_back(Chain);
4813 Ops.push_back(Result);
4814 Ops.push_back(StackSlot);
4815 Ops.push_back(DAG.getValueType(Op.getValueType()));
4816 Ops.push_back(InFlag);
4817 Chain = DAG.getNode(X86ISD::FST, dl, Tys, &Ops[0], Ops.size());
4818 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
4819 PseudoSourceValue::getFixedStack(SSFI), 0);
4825 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
4826 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
4827 // This algorithm is not obvious. Here it is in C code, more or less:
4829 double uint64_to_double( uint32_t hi, uint32_t lo ) {
4830 static const __m128i exp = { 0x4330000045300000ULL, 0 };
4831 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
4833 // Copy ints to xmm registers.
4834 __m128i xh = _mm_cvtsi32_si128( hi );
4835 __m128i xl = _mm_cvtsi32_si128( lo );
4837 // Combine into low half of a single xmm register.
4838 __m128i x = _mm_unpacklo_epi32( xh, xl );
4842 // Merge in appropriate exponents to give the integer bits the right
4844 x = _mm_unpacklo_epi32( x, exp );
4846 // Subtract away the biases to deal with the IEEE-754 double precision
4848 d = _mm_sub_pd( (__m128d) x, bias );
4850 // All conversions up to here are exact. The correctly rounded result is
4851 // calculated using the current rounding mode using the following
4853 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
4854 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
4855 // store doesn't really need to be here (except
4856 // maybe to zero the other double)
4861 DebugLoc dl = Op.getNode()->getDebugLoc();
4863 // Build some magic constants.
4864 std::vector<Constant*> CV0;
4865 CV0.push_back(ConstantInt::get(APInt(32, 0x45300000)));
4866 CV0.push_back(ConstantInt::get(APInt(32, 0x43300000)));
4867 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4868 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4869 Constant *C0 = ConstantVector::get(CV0);
4870 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 4);
4872 std::vector<Constant*> CV1;
4873 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4530000000000000ULL))));
4874 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4330000000000000ULL))));
4875 Constant *C1 = ConstantVector::get(CV1);
4876 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 4);
4878 SmallVector<SDValue, 4> MaskVec;
4879 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
4880 MaskVec.push_back(DAG.getConstant(4, MVT::i32));
4881 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
4882 MaskVec.push_back(DAG.getConstant(5, MVT::i32));
4883 SDValue UnpcklMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
4884 &MaskVec[0], MaskVec.size());
4885 SmallVector<SDValue, 4> MaskVec2;
4886 MaskVec2.push_back(DAG.getConstant(1, MVT::i32));
4887 MaskVec2.push_back(DAG.getConstant(0, MVT::i32));
4888 SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32,
4889 &MaskVec2[0], MaskVec2.size());
4891 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4892 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4894 DAG.getIntPtrConstant(1)));
4895 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4896 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4898 DAG.getIntPtrConstant(0)));
4899 SDValue Unpck1 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v4i32,
4900 XR1, XR2, UnpcklMask);
4901 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
4902 PseudoSourceValue::getConstantPool(), 0,
4904 SDValue Unpck2 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v4i32,
4905 Unpck1, CLod0, UnpcklMask);
4906 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
4907 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
4908 PseudoSourceValue::getConstantPool(), 0,
4910 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
4912 // Add the halves; easiest way is to swap them into another reg first.
4913 SDValue Shuf = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v2f64,
4914 Sub, Sub, ShufMask);
4915 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
4916 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
4917 DAG.getIntPtrConstant(0));
4920 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
4921 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
4922 DebugLoc dl = Op.getNode()->getDebugLoc();
4923 // FP constant to bias correct the final result.
4924 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
4927 // Load the 32-bit value into an XMM register.
4928 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
4929 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
4931 DAG.getIntPtrConstant(0)));
4933 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
4934 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
4935 DAG.getIntPtrConstant(0));
4937 // Or the load with the bias.
4938 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
4939 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4940 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4942 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
4943 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4944 MVT::v2f64, Bias)));
4945 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
4946 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
4947 DAG.getIntPtrConstant(0));
4949 // Subtract the bias.
4950 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
4952 // Handle final rounding.
4953 MVT DestVT = Op.getValueType();
4955 if (DestVT.bitsLT(MVT::f64)) {
4956 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
4957 DAG.getIntPtrConstant(0));
4958 } else if (DestVT.bitsGT(MVT::f64)) {
4959 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
4962 // Handle final rounding.
4966 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4967 SDValue N0 = Op.getOperand(0);
4968 DebugLoc dl = Op.getNode()->getDebugLoc();
4970 // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
4971 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
4972 // the optimization here.
4973 if (DAG.SignBitIsZero(N0))
4974 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
4976 MVT SrcVT = N0.getValueType();
4977 if (SrcVT == MVT::i64) {
4978 // We only handle SSE2 f64 target here; caller can handle the rest.
4979 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
4982 return LowerUINT_TO_FP_i64(Op, DAG);
4983 } else if (SrcVT == MVT::i32) {
4984 return LowerUINT_TO_FP_i32(Op, DAG);
4987 assert(0 && "Unknown UINT_TO_FP to lower!");
4991 std::pair<SDValue,SDValue> X86TargetLowering::
4992 FP_TO_SINTHelper(SDValue Op, SelectionDAG &DAG) {
4993 DebugLoc dl = Op.getNode()->getDebugLoc();
4994 assert(Op.getValueType().getSimpleVT() <= MVT::i64 &&
4995 Op.getValueType().getSimpleVT() >= MVT::i16 &&
4996 "Unknown FP_TO_SINT to lower!");
4998 // These are really Legal.
4999 if (Op.getValueType() == MVT::i32 &&
5000 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5001 return std::make_pair(SDValue(), SDValue());
5002 if (Subtarget->is64Bit() &&
5003 Op.getValueType() == MVT::i64 &&
5004 Op.getOperand(0).getValueType() != MVT::f80)
5005 return std::make_pair(SDValue(), SDValue());
5007 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5009 MachineFunction &MF = DAG.getMachineFunction();
5010 unsigned MemSize = Op.getValueType().getSizeInBits()/8;
5011 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
5012 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5014 switch (Op.getValueType().getSimpleVT()) {
5015 default: assert(0 && "Invalid FP_TO_SINT to lower!");
5016 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5017 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5018 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5021 SDValue Chain = DAG.getEntryNode();
5022 SDValue Value = Op.getOperand(0);
5023 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5024 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5025 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5026 PseudoSourceValue::getFixedStack(SSFI), 0);
5027 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5029 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5031 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5032 Chain = Value.getValue(1);
5033 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
5034 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5037 // Build the FP_TO_INT*_IN_MEM
5038 SDValue Ops[] = { Chain, Value, StackSlot };
5039 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5041 return std::make_pair(FIST, StackSlot);
5044 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
5045 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(Op, DAG);
5046 SDValue FIST = Vals.first, StackSlot = Vals.second;
5047 if (FIST.getNode() == 0) return SDValue();
5050 return DAG.getLoad(Op.getValueType(), Op.getNode()->getDebugLoc(),
5051 FIST, StackSlot, NULL, 0);
5054 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
5055 DebugLoc dl = Op.getNode()->getDebugLoc();
5056 MVT VT = Op.getValueType();
5059 EltVT = VT.getVectorElementType();
5060 std::vector<Constant*> CV;
5061 if (EltVT == MVT::f64) {
5062 Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
5066 Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
5072 Constant *C = ConstantVector::get(CV);
5073 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
5074 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5075 PseudoSourceValue::getConstantPool(), 0,
5077 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5080 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
5081 DebugLoc dl = Op.getNode()->getDebugLoc();
5082 MVT VT = Op.getValueType();
5084 unsigned EltNum = 1;
5085 if (VT.isVector()) {
5086 EltVT = VT.getVectorElementType();
5087 EltNum = VT.getVectorNumElements();
5089 std::vector<Constant*> CV;
5090 if (EltVT == MVT::f64) {
5091 Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
5095 Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
5101 Constant *C = ConstantVector::get(CV);
5102 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
5103 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5104 PseudoSourceValue::getConstantPool(), 0,
5106 if (VT.isVector()) {
5107 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5108 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5109 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5111 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5113 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5117 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5118 SDValue Op0 = Op.getOperand(0);
5119 SDValue Op1 = Op.getOperand(1);
5120 DebugLoc dl = Op.getNode()->getDebugLoc();
5121 MVT VT = Op.getValueType();
5122 MVT SrcVT = Op1.getValueType();
5124 // If second operand is smaller, extend it first.
5125 if (SrcVT.bitsLT(VT)) {
5126 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5129 // And if it is bigger, shrink it first.
5130 if (SrcVT.bitsGT(VT)) {
5131 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5135 // At this point the operands and the result should have the same
5136 // type, and that won't be f80 since that is not custom lowered.
5138 // First get the sign bit of second operand.
5139 std::vector<Constant*> CV;
5140 if (SrcVT == MVT::f64) {
5141 CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
5142 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
5144 CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
5145 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5146 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5147 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5149 Constant *C = ConstantVector::get(CV);
5150 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
5151 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5152 PseudoSourceValue::getConstantPool(), 0,
5154 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5156 // Shift sign bit right or left if the two operands have different types.
5157 if (SrcVT.bitsGT(VT)) {
5158 // Op0 is MVT::f32, Op1 is MVT::f64.
5159 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5160 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5161 DAG.getConstant(32, MVT::i32));
5162 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5163 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5164 DAG.getIntPtrConstant(0));
5167 // Clear first operand sign bit.
5169 if (VT == MVT::f64) {
5170 CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
5171 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
5173 CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
5174 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5175 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5176 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5178 C = ConstantVector::get(CV);
5179 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
5180 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5181 PseudoSourceValue::getConstantPool(), 0,
5183 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5185 // Or the value with the sign bit.
5186 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5189 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5190 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5191 SDValue Op0 = Op.getOperand(0);
5192 SDValue Op1 = Op.getOperand(1);
5193 DebugLoc dl = Op.getNode()->getDebugLoc();
5194 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5196 // Lower (X & (1 << N)) == 0 to BT(X, N).
5197 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5198 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5199 if (Op0.getOpcode() == ISD::AND &&
5201 Op1.getOpcode() == ISD::Constant &&
5202 cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5203 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5205 if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
5206 if (ConstantSDNode *Op010C =
5207 dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
5208 if (Op010C->getZExtValue() == 1) {
5209 LHS = Op0.getOperand(0);
5210 RHS = Op0.getOperand(1).getOperand(1);
5212 } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
5213 if (ConstantSDNode *Op000C =
5214 dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
5215 if (Op000C->getZExtValue() == 1) {
5216 LHS = Op0.getOperand(1);
5217 RHS = Op0.getOperand(0).getOperand(1);
5219 } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
5220 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5221 SDValue AndLHS = Op0.getOperand(0);
5222 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5223 LHS = AndLHS.getOperand(0);
5224 RHS = AndLHS.getOperand(1);
5228 if (LHS.getNode()) {
5229 // If LHS is i8, promote it to i16 with any_extend. There is no i8 BT
5230 // instruction. Since the shift amount is in-range-or-undefined, we know
5231 // that doing a bittest on the i16 value is ok. We extend to i32 because
5232 // the encoding for the i16 version is larger than the i32 version.
5233 if (LHS.getValueType() == MVT::i8)
5234 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5236 // If the operand types disagree, extend the shift amount to match. Since
5237 // BT ignores high bits (like shifts) we can use anyextend.
5238 if (LHS.getValueType() != RHS.getValueType())
5239 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5241 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5242 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5243 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5244 DAG.getConstant(Cond, MVT::i8), BT);
5248 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5249 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5251 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5252 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5253 DAG.getConstant(X86CC, MVT::i8), Cond);
5256 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5258 SDValue Op0 = Op.getOperand(0);
5259 SDValue Op1 = Op.getOperand(1);
5260 SDValue CC = Op.getOperand(2);
5261 MVT VT = Op.getValueType();
5262 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5263 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5264 DebugLoc dl = Op.getNode()->getDebugLoc();
5268 MVT VT0 = Op0.getValueType();
5269 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5270 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5273 switch (SetCCOpcode) {
5276 case ISD::SETEQ: SSECC = 0; break;
5278 case ISD::SETGT: Swap = true; // Fallthrough
5280 case ISD::SETOLT: SSECC = 1; break;
5282 case ISD::SETGE: Swap = true; // Fallthrough
5284 case ISD::SETOLE: SSECC = 2; break;
5285 case ISD::SETUO: SSECC = 3; break;
5287 case ISD::SETNE: SSECC = 4; break;
5288 case ISD::SETULE: Swap = true;
5289 case ISD::SETUGE: SSECC = 5; break;
5290 case ISD::SETULT: Swap = true;
5291 case ISD::SETUGT: SSECC = 6; break;
5292 case ISD::SETO: SSECC = 7; break;
5295 std::swap(Op0, Op1);
5297 // In the two special cases we can't handle, emit two comparisons.
5299 if (SetCCOpcode == ISD::SETUEQ) {
5301 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5302 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5303 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
5305 else if (SetCCOpcode == ISD::SETONE) {
5307 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5308 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5309 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
5311 assert(0 && "Illegal FP comparison");
5313 // Handle all other FP comparisons here.
5314 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5317 // We are handling one of the integer comparisons here. Since SSE only has
5318 // GT and EQ comparisons for integer, swapping operands and multiple
5319 // operations may be required for some comparisons.
5320 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5321 bool Swap = false, Invert = false, FlipSigns = false;
5323 switch (VT.getSimpleVT()) {
5325 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5326 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5327 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5328 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5331 switch (SetCCOpcode) {
5333 case ISD::SETNE: Invert = true;
5334 case ISD::SETEQ: Opc = EQOpc; break;
5335 case ISD::SETLT: Swap = true;
5336 case ISD::SETGT: Opc = GTOpc; break;
5337 case ISD::SETGE: Swap = true;
5338 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
5339 case ISD::SETULT: Swap = true;
5340 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5341 case ISD::SETUGE: Swap = true;
5342 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5345 std::swap(Op0, Op1);
5347 // Since SSE has no unsigned integer comparisons, we need to flip the sign
5348 // bits of the inputs before performing those operations.
5350 MVT EltVT = VT.getVectorElementType();
5351 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
5353 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5354 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
5356 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
5357 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
5360 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
5362 // If the logical-not of the result is required, perform that now.
5364 Result = DAG.getNOT(dl, Result, VT);
5369 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5370 static bool isX86LogicalCmp(unsigned Opc) {
5371 return Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI;
5374 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5375 bool addTest = true;
5376 SDValue Cond = Op.getOperand(0);
5377 DebugLoc dl = Op.getNode()->getDebugLoc();
5380 if (Cond.getOpcode() == ISD::SETCC)
5381 Cond = LowerSETCC(Cond, DAG);
5383 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5384 // setting operand in place of the X86ISD::SETCC.
5385 if (Cond.getOpcode() == X86ISD::SETCC) {
5386 CC = Cond.getOperand(0);
5388 SDValue Cmp = Cond.getOperand(1);
5389 unsigned Opc = Cmp.getOpcode();
5390 MVT VT = Op.getValueType();
5392 bool IllegalFPCMov = false;
5393 if (VT.isFloatingPoint() && !VT.isVector() &&
5394 !isScalarFPTypeInSSEReg(VT)) // FPStack?
5395 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
5397 if ((isX86LogicalCmp(Opc) && !IllegalFPCMov) || Opc == X86ISD::BT) { // FIXME
5404 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5405 Cond= DAG.getNode(X86ISD::CMP, dl, MVT::i32, Cond,
5406 DAG.getConstant(0, MVT::i8));
5409 const MVT *VTs = DAG.getNodeValueTypes(Op.getValueType(),
5411 SmallVector<SDValue, 4> Ops;
5412 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
5413 // condition is true.
5414 Ops.push_back(Op.getOperand(2));
5415 Ops.push_back(Op.getOperand(1));
5417 Ops.push_back(Cond);
5418 return DAG.getNode(X86ISD::CMOV, dl, VTs, 2, &Ops[0], Ops.size());
5421 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
5422 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
5423 // from the AND / OR.
5424 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
5425 Opc = Op.getOpcode();
5426 if (Opc != ISD::OR && Opc != ISD::AND)
5428 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5429 Op.getOperand(0).hasOneUse() &&
5430 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
5431 Op.getOperand(1).hasOneUse());
5434 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
5435 // 1 and that the SETCC node has a single use.
5436 static bool isXor1OfSetCC(SDValue Op) {
5437 if (Op.getOpcode() != ISD::XOR)
5439 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5440 if (N1C && N1C->getAPIntValue() == 1) {
5441 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5442 Op.getOperand(0).hasOneUse();
5447 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
5448 bool addTest = true;
5449 SDValue Chain = Op.getOperand(0);
5450 SDValue Cond = Op.getOperand(1);
5451 SDValue Dest = Op.getOperand(2);
5452 DebugLoc dl = Op.getNode()->getDebugLoc();
5455 if (Cond.getOpcode() == ISD::SETCC)
5456 Cond = LowerSETCC(Cond, DAG);
5458 // FIXME: LowerXALUO doesn't handle these!!
5459 else if (Cond.getOpcode() == X86ISD::ADD ||
5460 Cond.getOpcode() == X86ISD::SUB ||
5461 Cond.getOpcode() == X86ISD::SMUL ||
5462 Cond.getOpcode() == X86ISD::UMUL)
5463 Cond = LowerXALUO(Cond, DAG);
5466 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5467 // setting operand in place of the X86ISD::SETCC.
5468 if (Cond.getOpcode() == X86ISD::SETCC) {
5469 CC = Cond.getOperand(0);
5471 SDValue Cmp = Cond.getOperand(1);
5472 unsigned Opc = Cmp.getOpcode();
5473 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
5474 if (isX86LogicalCmp(Opc) || Opc == X86ISD::BT) {
5478 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
5482 // These can only come from an arithmetic instruction with overflow,
5483 // e.g. SADDO, UADDO.
5484 Cond = Cond.getNode()->getOperand(1);
5491 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
5492 SDValue Cmp = Cond.getOperand(0).getOperand(1);
5493 unsigned Opc = Cmp.getOpcode();
5494 if (CondOpc == ISD::OR) {
5495 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
5496 // two branches instead of an explicit OR instruction with a
5498 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5499 isX86LogicalCmp(Opc)) {
5500 CC = Cond.getOperand(0).getOperand(0);
5501 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5502 Chain, Dest, CC, Cmp);
5503 CC = Cond.getOperand(1).getOperand(0);
5507 } else { // ISD::AND
5508 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
5509 // two branches instead of an explicit AND instruction with a
5510 // separate test. However, we only do this if this block doesn't
5511 // have a fall-through edge, because this requires an explicit
5512 // jmp when the condition is false.
5513 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5514 isX86LogicalCmp(Opc) &&
5515 Op.getNode()->hasOneUse()) {
5516 X86::CondCode CCode =
5517 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5518 CCode = X86::GetOppositeBranchCondition(CCode);
5519 CC = DAG.getConstant(CCode, MVT::i8);
5520 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
5521 // Look for an unconditional branch following this conditional branch.
5522 // We need this because we need to reverse the successors in order
5523 // to implement FCMP_OEQ.
5524 if (User.getOpcode() == ISD::BR) {
5525 SDValue FalseBB = User.getOperand(1);
5527 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
5528 assert(NewBR == User);
5531 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5532 Chain, Dest, CC, Cmp);
5533 X86::CondCode CCode =
5534 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
5535 CCode = X86::GetOppositeBranchCondition(CCode);
5536 CC = DAG.getConstant(CCode, MVT::i8);
5542 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
5543 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
5544 // It should be transformed during dag combiner except when the condition
5545 // is set by a arithmetics with overflow node.
5546 X86::CondCode CCode =
5547 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5548 CCode = X86::GetOppositeBranchCondition(CCode);
5549 CC = DAG.getConstant(CCode, MVT::i8);
5550 Cond = Cond.getOperand(0).getOperand(1);
5556 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5557 Cond= DAG.getNode(X86ISD::CMP, dl, MVT::i32, Cond,
5558 DAG.getConstant(0, MVT::i8));
5560 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5561 Chain, Dest, CC, Cond);
5565 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
5566 // Calls to _alloca is needed to probe the stack when allocating more than 4k
5567 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
5568 // that the guard pages used by the OS virtual memory manager are allocated in
5569 // correct sequence.
5571 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5572 SelectionDAG &DAG) {
5573 assert(Subtarget->isTargetCygMing() &&
5574 "This should be used only on Cygwin/Mingw targets");
5575 DebugLoc dl = Op.getNode()->getDebugLoc();
5578 SDValue Chain = Op.getOperand(0);
5579 SDValue Size = Op.getOperand(1);
5580 // FIXME: Ensure alignment here
5584 MVT IntPtr = getPointerTy();
5585 MVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
5587 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
5589 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
5590 Flag = Chain.getValue(1);
5592 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5593 SDValue Ops[] = { Chain,
5594 DAG.getTargetExternalSymbol("_alloca", IntPtr),
5595 DAG.getRegister(X86::EAX, IntPtr),
5596 DAG.getRegister(X86StackPtr, SPTy),
5598 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops, 5);
5599 Flag = Chain.getValue(1);
5601 Chain = DAG.getCALLSEQ_END(Chain,
5602 DAG.getIntPtrConstant(0, true),
5603 DAG.getIntPtrConstant(0, true),
5606 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
5608 SDValue Ops1[2] = { Chain.getValue(0), Chain };
5609 return DAG.getMergeValues(Ops1, 2, dl);
5613 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG,
5615 SDValue Dst, SDValue Src,
5616 SDValue Size, unsigned Align,
5618 uint64_t DstSVOff) {
5619 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5621 // If not DWORD aligned or size is more than the threshold, call the library.
5622 // The libc version is likely to be faster for these cases. It can use the
5623 // address value and run time information about the CPU.
5624 if ((Align & 3) != 0 ||
5626 ConstantSize->getZExtValue() >
5627 getSubtarget()->getMaxInlineSizeThreshold()) {
5628 SDValue InFlag(0, 0);
5630 // Check to see if there is a specialized entry-point for memory zeroing.
5631 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
5633 if (const char *bzeroEntry = V &&
5634 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
5635 MVT IntPtr = getPointerTy();
5636 const Type *IntPtrTy = TD->getIntPtrType();
5637 TargetLowering::ArgListTy Args;
5638 TargetLowering::ArgListEntry Entry;
5640 Entry.Ty = IntPtrTy;
5641 Args.push_back(Entry);
5643 Args.push_back(Entry);
5644 // FIXME provide DebugLoc info
5645 std::pair<SDValue,SDValue> CallResult =
5646 LowerCallTo(Chain, Type::VoidTy, false, false, false, false,
5647 CallingConv::C, false,
5648 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG,
5649 DebugLoc::getUnknownLoc());
5650 return CallResult.second;
5653 // Otherwise have the target-independent code call memset.
5657 uint64_t SizeVal = ConstantSize->getZExtValue();
5658 SDValue InFlag(0, 0);
5661 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
5662 unsigned BytesLeft = 0;
5663 bool TwoRepStos = false;
5666 uint64_t Val = ValC->getZExtValue() & 255;
5668 // If the value is a constant, then we can potentially use larger sets.
5669 switch (Align & 3) {
5670 case 2: // WORD aligned
5673 Val = (Val << 8) | Val;
5675 case 0: // DWORD aligned
5678 Val = (Val << 8) | Val;
5679 Val = (Val << 16) | Val;
5680 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
5683 Val = (Val << 32) | Val;
5686 default: // Byte aligned
5689 Count = DAG.getIntPtrConstant(SizeVal);
5693 if (AVT.bitsGT(MVT::i8)) {
5694 unsigned UBytes = AVT.getSizeInBits() / 8;
5695 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
5696 BytesLeft = SizeVal % UBytes;
5699 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
5701 InFlag = Chain.getValue(1);
5704 Count = DAG.getIntPtrConstant(SizeVal);
5705 Chain = DAG.getCopyToReg(Chain, X86::AL, Src, InFlag);
5706 InFlag = Chain.getValue(1);
5709 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
5711 InFlag = Chain.getValue(1);
5712 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
5714 InFlag = Chain.getValue(1);
5716 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5717 SmallVector<SDValue, 8> Ops;
5718 Ops.push_back(Chain);
5719 Ops.push_back(DAG.getValueType(AVT));
5720 Ops.push_back(InFlag);
5721 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
5724 InFlag = Chain.getValue(1);
5726 MVT CVT = Count.getValueType();
5727 SDValue Left = DAG.getNode(ISD::AND, CVT, Count,
5728 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
5729 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
5731 InFlag = Chain.getValue(1);
5732 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5734 Ops.push_back(Chain);
5735 Ops.push_back(DAG.getValueType(MVT::i8));
5736 Ops.push_back(InFlag);
5737 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
5738 } else if (BytesLeft) {
5739 // Handle the last 1 - 7 bytes.
5740 unsigned Offset = SizeVal - BytesLeft;
5741 MVT AddrVT = Dst.getValueType();
5742 MVT SizeVT = Size.getValueType();
5744 Chain = DAG.getMemset(Chain,
5745 DAG.getNode(ISD::ADD, AddrVT, Dst,
5746 DAG.getConstant(Offset, AddrVT)),
5748 DAG.getConstant(BytesLeft, SizeVT),
5749 Align, DstSV, DstSVOff + Offset);
5752 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
5757 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG,
5758 SDValue Chain, SDValue Dst, SDValue Src,
5759 SDValue Size, unsigned Align,
5761 const Value *DstSV, uint64_t DstSVOff,
5762 const Value *SrcSV, uint64_t SrcSVOff) {
5763 // This requires the copy size to be a constant, preferrably
5764 // within a subtarget-specific limit.
5765 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5768 uint64_t SizeVal = ConstantSize->getZExtValue();
5769 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
5772 /// If not DWORD aligned, call the library.
5773 if ((Align & 3) != 0)
5778 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
5781 unsigned UBytes = AVT.getSizeInBits() / 8;
5782 unsigned CountVal = SizeVal / UBytes;
5783 SDValue Count = DAG.getIntPtrConstant(CountVal);
5784 unsigned BytesLeft = SizeVal % UBytes;
5786 SDValue InFlag(0, 0);
5787 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
5789 InFlag = Chain.getValue(1);
5790 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
5792 InFlag = Chain.getValue(1);
5793 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
5795 InFlag = Chain.getValue(1);
5797 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5798 SmallVector<SDValue, 8> Ops;
5799 Ops.push_back(Chain);
5800 Ops.push_back(DAG.getValueType(AVT));
5801 Ops.push_back(InFlag);
5802 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
5804 SmallVector<SDValue, 4> Results;
5805 Results.push_back(RepMovs);
5807 // Handle the last 1 - 7 bytes.
5808 unsigned Offset = SizeVal - BytesLeft;
5809 MVT DstVT = Dst.getValueType();
5810 MVT SrcVT = Src.getValueType();
5811 MVT SizeVT = Size.getValueType();
5812 Results.push_back(DAG.getMemcpy(Chain,
5813 DAG.getNode(ISD::ADD, DstVT, Dst,
5814 DAG.getConstant(Offset, DstVT)),
5815 DAG.getNode(ISD::ADD, SrcVT, Src,
5816 DAG.getConstant(Offset, SrcVT)),
5817 DAG.getConstant(BytesLeft, SizeVT),
5818 Align, AlwaysInline,
5819 DstSV, DstSVOff + Offset,
5820 SrcSV, SrcSVOff + Offset));
5823 return DAG.getNode(ISD::TokenFactor, MVT::Other, &Results[0], Results.size());
5826 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
5827 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5828 DebugLoc dl = Op.getNode()->getDebugLoc();
5830 if (!Subtarget->is64Bit()) {
5831 // vastart just stores the address of the VarArgsFrameIndex slot into the
5832 // memory location argument.
5833 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5834 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
5838 // gp_offset (0 - 6 * 8)
5839 // fp_offset (48 - 48 + 8 * 16)
5840 // overflow_arg_area (point to parameters coming in memory).
5842 SmallVector<SDValue, 8> MemOps;
5843 SDValue FIN = Op.getOperand(1);
5845 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
5846 DAG.getConstant(VarArgsGPOffset, MVT::i32),
5848 MemOps.push_back(Store);
5851 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5852 FIN, DAG.getIntPtrConstant(4));
5853 Store = DAG.getStore(Op.getOperand(0), dl,
5854 DAG.getConstant(VarArgsFPOffset, MVT::i32),
5856 MemOps.push_back(Store);
5858 // Store ptr to overflow_arg_area
5859 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5860 FIN, DAG.getIntPtrConstant(4));
5861 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5862 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0);
5863 MemOps.push_back(Store);
5865 // Store ptr to reg_save_area.
5866 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5867 FIN, DAG.getIntPtrConstant(8));
5868 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
5869 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0);
5870 MemOps.push_back(Store);
5871 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5872 &MemOps[0], MemOps.size());
5875 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
5876 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5877 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
5878 SDValue Chain = Op.getOperand(0);
5879 SDValue SrcPtr = Op.getOperand(1);
5880 SDValue SrcSV = Op.getOperand(2);
5882 assert(0 && "VAArgInst is not yet implemented for x86-64!");
5887 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
5888 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5889 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
5890 SDValue Chain = Op.getOperand(0);
5891 SDValue DstPtr = Op.getOperand(1);
5892 SDValue SrcPtr = Op.getOperand(2);
5893 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5894 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5896 return DAG.getMemcpy(Chain, DstPtr, SrcPtr,
5897 DAG.getIntPtrConstant(24), 8, false,
5898 DstSV, 0, SrcSV, 0);
5902 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
5903 DebugLoc dl = Op.getNode()->getDebugLoc();
5904 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5906 default: return SDValue(); // Don't custom lower most intrinsics.
5907 // Comparison intrinsics.
5908 case Intrinsic::x86_sse_comieq_ss:
5909 case Intrinsic::x86_sse_comilt_ss:
5910 case Intrinsic::x86_sse_comile_ss:
5911 case Intrinsic::x86_sse_comigt_ss:
5912 case Intrinsic::x86_sse_comige_ss:
5913 case Intrinsic::x86_sse_comineq_ss:
5914 case Intrinsic::x86_sse_ucomieq_ss:
5915 case Intrinsic::x86_sse_ucomilt_ss:
5916 case Intrinsic::x86_sse_ucomile_ss:
5917 case Intrinsic::x86_sse_ucomigt_ss:
5918 case Intrinsic::x86_sse_ucomige_ss:
5919 case Intrinsic::x86_sse_ucomineq_ss:
5920 case Intrinsic::x86_sse2_comieq_sd:
5921 case Intrinsic::x86_sse2_comilt_sd:
5922 case Intrinsic::x86_sse2_comile_sd:
5923 case Intrinsic::x86_sse2_comigt_sd:
5924 case Intrinsic::x86_sse2_comige_sd:
5925 case Intrinsic::x86_sse2_comineq_sd:
5926 case Intrinsic::x86_sse2_ucomieq_sd:
5927 case Intrinsic::x86_sse2_ucomilt_sd:
5928 case Intrinsic::x86_sse2_ucomile_sd:
5929 case Intrinsic::x86_sse2_ucomigt_sd:
5930 case Intrinsic::x86_sse2_ucomige_sd:
5931 case Intrinsic::x86_sse2_ucomineq_sd: {
5933 ISD::CondCode CC = ISD::SETCC_INVALID;
5936 case Intrinsic::x86_sse_comieq_ss:
5937 case Intrinsic::x86_sse2_comieq_sd:
5941 case Intrinsic::x86_sse_comilt_ss:
5942 case Intrinsic::x86_sse2_comilt_sd:
5946 case Intrinsic::x86_sse_comile_ss:
5947 case Intrinsic::x86_sse2_comile_sd:
5951 case Intrinsic::x86_sse_comigt_ss:
5952 case Intrinsic::x86_sse2_comigt_sd:
5956 case Intrinsic::x86_sse_comige_ss:
5957 case Intrinsic::x86_sse2_comige_sd:
5961 case Intrinsic::x86_sse_comineq_ss:
5962 case Intrinsic::x86_sse2_comineq_sd:
5966 case Intrinsic::x86_sse_ucomieq_ss:
5967 case Intrinsic::x86_sse2_ucomieq_sd:
5968 Opc = X86ISD::UCOMI;
5971 case Intrinsic::x86_sse_ucomilt_ss:
5972 case Intrinsic::x86_sse2_ucomilt_sd:
5973 Opc = X86ISD::UCOMI;
5976 case Intrinsic::x86_sse_ucomile_ss:
5977 case Intrinsic::x86_sse2_ucomile_sd:
5978 Opc = X86ISD::UCOMI;
5981 case Intrinsic::x86_sse_ucomigt_ss:
5982 case Intrinsic::x86_sse2_ucomigt_sd:
5983 Opc = X86ISD::UCOMI;
5986 case Intrinsic::x86_sse_ucomige_ss:
5987 case Intrinsic::x86_sse2_ucomige_sd:
5988 Opc = X86ISD::UCOMI;
5991 case Intrinsic::x86_sse_ucomineq_ss:
5992 case Intrinsic::x86_sse2_ucomineq_sd:
5993 Opc = X86ISD::UCOMI;
5998 SDValue LHS = Op.getOperand(1);
5999 SDValue RHS = Op.getOperand(2);
6000 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6001 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6002 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6003 DAG.getConstant(X86CC, MVT::i8), Cond);
6004 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6007 // Fix vector shift instructions where the last operand is a non-immediate
6009 case Intrinsic::x86_sse2_pslli_w:
6010 case Intrinsic::x86_sse2_pslli_d:
6011 case Intrinsic::x86_sse2_pslli_q:
6012 case Intrinsic::x86_sse2_psrli_w:
6013 case Intrinsic::x86_sse2_psrli_d:
6014 case Intrinsic::x86_sse2_psrli_q:
6015 case Intrinsic::x86_sse2_psrai_w:
6016 case Intrinsic::x86_sse2_psrai_d:
6017 case Intrinsic::x86_mmx_pslli_w:
6018 case Intrinsic::x86_mmx_pslli_d:
6019 case Intrinsic::x86_mmx_pslli_q:
6020 case Intrinsic::x86_mmx_psrli_w:
6021 case Intrinsic::x86_mmx_psrli_d:
6022 case Intrinsic::x86_mmx_psrli_q:
6023 case Intrinsic::x86_mmx_psrai_w:
6024 case Intrinsic::x86_mmx_psrai_d: {
6025 SDValue ShAmt = Op.getOperand(2);
6026 if (isa<ConstantSDNode>(ShAmt))
6029 unsigned NewIntNo = 0;
6030 MVT ShAmtVT = MVT::v4i32;
6032 case Intrinsic::x86_sse2_pslli_w:
6033 NewIntNo = Intrinsic::x86_sse2_psll_w;
6035 case Intrinsic::x86_sse2_pslli_d:
6036 NewIntNo = Intrinsic::x86_sse2_psll_d;
6038 case Intrinsic::x86_sse2_pslli_q:
6039 NewIntNo = Intrinsic::x86_sse2_psll_q;
6041 case Intrinsic::x86_sse2_psrli_w:
6042 NewIntNo = Intrinsic::x86_sse2_psrl_w;
6044 case Intrinsic::x86_sse2_psrli_d:
6045 NewIntNo = Intrinsic::x86_sse2_psrl_d;
6047 case Intrinsic::x86_sse2_psrli_q:
6048 NewIntNo = Intrinsic::x86_sse2_psrl_q;
6050 case Intrinsic::x86_sse2_psrai_w:
6051 NewIntNo = Intrinsic::x86_sse2_psra_w;
6053 case Intrinsic::x86_sse2_psrai_d:
6054 NewIntNo = Intrinsic::x86_sse2_psra_d;
6057 ShAmtVT = MVT::v2i32;
6059 case Intrinsic::x86_mmx_pslli_w:
6060 NewIntNo = Intrinsic::x86_mmx_psll_w;
6062 case Intrinsic::x86_mmx_pslli_d:
6063 NewIntNo = Intrinsic::x86_mmx_psll_d;
6065 case Intrinsic::x86_mmx_pslli_q:
6066 NewIntNo = Intrinsic::x86_mmx_psll_q;
6068 case Intrinsic::x86_mmx_psrli_w:
6069 NewIntNo = Intrinsic::x86_mmx_psrl_w;
6071 case Intrinsic::x86_mmx_psrli_d:
6072 NewIntNo = Intrinsic::x86_mmx_psrl_d;
6074 case Intrinsic::x86_mmx_psrli_q:
6075 NewIntNo = Intrinsic::x86_mmx_psrl_q;
6077 case Intrinsic::x86_mmx_psrai_w:
6078 NewIntNo = Intrinsic::x86_mmx_psra_w;
6080 case Intrinsic::x86_mmx_psrai_d:
6081 NewIntNo = Intrinsic::x86_mmx_psra_d;
6083 default: abort(); // Can't reach here.
6088 MVT VT = Op.getValueType();
6089 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT,
6090 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShAmtVT, ShAmt));
6091 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6092 DAG.getConstant(NewIntNo, MVT::i32),
6093 Op.getOperand(1), ShAmt);
6098 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
6099 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6100 DebugLoc dl = Op.getNode()->getDebugLoc();
6103 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6105 DAG.getConstant(TD->getPointerSize(),
6106 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6107 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6108 DAG.getNode(ISD::ADD, dl, getPointerTy(),
6113 // Just load the return address.
6114 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6115 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6116 RetAddrFI, NULL, 0);
6119 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
6120 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6121 MFI->setFrameAddressIsTaken(true);
6122 MVT VT = Op.getValueType();
6123 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6124 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6125 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), FrameReg, VT);
6127 FrameAddr = DAG.getLoad(VT, DAG.getEntryNode(), FrameAddr, NULL, 0);
6131 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6132 SelectionDAG &DAG) {
6133 return DAG.getIntPtrConstant(2*TD->getPointerSize());
6136 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
6138 MachineFunction &MF = DAG.getMachineFunction();
6139 SDValue Chain = Op.getOperand(0);
6140 SDValue Offset = Op.getOperand(1);
6141 SDValue Handler = Op.getOperand(2);
6142 DebugLoc dl = Op.getNode()->getDebugLoc();
6144 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6146 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6148 SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
6149 DAG.getIntPtrConstant(-TD->getPointerSize()));
6150 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
6151 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0);
6152 Chain = DAG.getCopyToReg(Chain, StoreAddrReg, StoreAddr);
6153 MF.getRegInfo().addLiveOut(StoreAddrReg);
6155 return DAG.getNode(X86ISD::EH_RETURN, dl,
6157 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6160 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6161 SelectionDAG &DAG) {
6162 SDValue Root = Op.getOperand(0);
6163 SDValue Trmp = Op.getOperand(1); // trampoline
6164 SDValue FPtr = Op.getOperand(2); // nested function
6165 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6166 DebugLoc dl = Op.getNode()->getDebugLoc();
6168 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6170 const X86InstrInfo *TII =
6171 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
6173 if (Subtarget->is64Bit()) {
6174 SDValue OutChains[6];
6176 // Large code-model.
6178 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
6179 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
6181 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
6182 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
6184 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
6186 // Load the pointer to the nested function into R11.
6187 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
6188 SDValue Addr = Trmp;
6189 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6192 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6193 DAG.getConstant(2, MVT::i64));
6194 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2, false, 2);
6196 // Load the 'nest' parameter value into R10.
6197 // R10 is specified in X86CallingConv.td
6198 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
6199 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6200 DAG.getConstant(10, MVT::i64));
6201 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6202 Addr, TrmpAddr, 10);
6204 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6205 DAG.getConstant(12, MVT::i64));
6206 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12, false, 2);
6208 // Jump to the nested function.
6209 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
6210 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6211 DAG.getConstant(20, MVT::i64));
6212 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6213 Addr, TrmpAddr, 20);
6215 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
6216 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6217 DAG.getConstant(22, MVT::i64));
6218 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
6222 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
6223 return DAG.getMergeValues(Ops, 2, dl);
6225 const Function *Func =
6226 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
6227 unsigned CC = Func->getCallingConv();
6232 assert(0 && "Unsupported calling convention");
6233 case CallingConv::C:
6234 case CallingConv::X86_StdCall: {
6235 // Pass 'nest' parameter in ECX.
6236 // Must be kept in sync with X86CallingConv.td
6239 // Check that ECX wasn't needed by an 'inreg' parameter.
6240 const FunctionType *FTy = Func->getFunctionType();
6241 const AttrListPtr &Attrs = Func->getAttributes();
6243 if (!Attrs.isEmpty() && !Func->isVarArg()) {
6244 unsigned InRegCount = 0;
6247 for (FunctionType::param_iterator I = FTy->param_begin(),
6248 E = FTy->param_end(); I != E; ++I, ++Idx)
6249 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6250 // FIXME: should only count parameters that are lowered to integers.
6251 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6253 if (InRegCount > 2) {
6254 cerr << "Nest register in use - reduce number of inreg parameters!\n";
6260 case CallingConv::X86_FastCall:
6261 case CallingConv::Fast:
6262 // Pass 'nest' parameter in EAX.
6263 // Must be kept in sync with X86CallingConv.td
6268 SDValue OutChains[4];
6271 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6272 DAG.getConstant(10, MVT::i32));
6273 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
6275 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
6276 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
6277 OutChains[0] = DAG.getStore(Root, dl,
6278 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
6281 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6282 DAG.getConstant(1, MVT::i32));
6283 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1, false, 1);
6285 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
6286 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6287 DAG.getConstant(5, MVT::i32));
6288 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
6289 TrmpAddr, 5, false, 1);
6291 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6292 DAG.getConstant(6, MVT::i32));
6293 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6, false, 1);
6296 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
6297 return DAG.getMergeValues(Ops, 2, dl);
6301 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
6303 The rounding mode is in bits 11:10 of FPSR, and has the following
6310 FLT_ROUNDS, on the other hand, expects the following:
6317 To perform the conversion, we do:
6318 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
6321 MachineFunction &MF = DAG.getMachineFunction();
6322 const TargetMachine &TM = MF.getTarget();
6323 const TargetFrameInfo &TFI = *TM.getFrameInfo();
6324 unsigned StackAlignment = TFI.getStackAlignment();
6325 MVT VT = Op.getValueType();
6326 DebugLoc dl = Op.getNode()->getDebugLoc();
6328 // Save FP Control Word to stack slot
6329 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
6330 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6332 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
6333 DAG.getEntryNode(), StackSlot);
6335 // Load FP Control Word from stack slot
6336 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0);
6338 // Transform as necessary
6340 DAG.getNode(ISD::SRL, dl, MVT::i16,
6341 DAG.getNode(ISD::AND, dl, MVT::i16,
6342 CWD, DAG.getConstant(0x800, MVT::i16)),
6343 DAG.getConstant(11, MVT::i8));
6345 DAG.getNode(ISD::SRL, dl, MVT::i16,
6346 DAG.getNode(ISD::AND, dl, MVT::i16,
6347 CWD, DAG.getConstant(0x400, MVT::i16)),
6348 DAG.getConstant(9, MVT::i8));
6351 DAG.getNode(ISD::AND, dl, MVT::i16,
6352 DAG.getNode(ISD::ADD, dl, MVT::i16,
6353 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
6354 DAG.getConstant(1, MVT::i16)),
6355 DAG.getConstant(3, MVT::i16));
6358 return DAG.getNode((VT.getSizeInBits() < 16 ?
6359 ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
6362 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
6363 MVT VT = Op.getValueType();
6365 unsigned NumBits = VT.getSizeInBits();
6366 DebugLoc dl = Op.getNode()->getDebugLoc();
6368 Op = Op.getOperand(0);
6369 if (VT == MVT::i8) {
6370 // Zero extend to i32 since there is not an i8 bsr.
6372 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6375 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
6376 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6377 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
6379 // If src is zero (i.e. bsr sets ZF), returns NumBits.
6380 SmallVector<SDValue, 4> Ops;
6382 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
6383 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6384 Ops.push_back(Op.getValue(1));
6385 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6387 // Finally xor with NumBits-1.
6388 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
6391 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6395 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
6396 MVT VT = Op.getValueType();
6398 unsigned NumBits = VT.getSizeInBits();
6399 DebugLoc dl = Op.getNode()->getDebugLoc();
6401 Op = Op.getOperand(0);
6402 if (VT == MVT::i8) {
6404 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6407 // Issue a bsf (scan bits forward) which also sets EFLAGS.
6408 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6409 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
6411 // If src is zero (i.e. bsf sets ZF), returns NumBits.
6412 SmallVector<SDValue, 4> Ops;
6414 Ops.push_back(DAG.getConstant(NumBits, OpVT));
6415 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6416 Ops.push_back(Op.getValue(1));
6417 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6420 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6424 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
6425 MVT VT = Op.getValueType();
6426 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
6427 DebugLoc dl = Op.getNode()->getDebugLoc();
6429 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
6430 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
6431 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
6432 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
6433 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
6435 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
6436 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
6437 // return AloBlo + AloBhi + AhiBlo;
6439 SDValue A = Op.getOperand(0);
6440 SDValue B = Op.getOperand(1);
6442 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6443 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6444 A, DAG.getConstant(32, MVT::i32));
6445 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6446 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6447 B, DAG.getConstant(32, MVT::i32));
6448 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6449 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6451 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6452 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6454 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6455 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6457 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6458 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6459 AloBhi, DAG.getConstant(32, MVT::i32));
6460 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6461 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6462 AhiBlo, DAG.getConstant(32, MVT::i32));
6463 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
6464 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
6469 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
6470 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
6471 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
6472 // looks for this combo and may remove the "setcc" instruction if the "setcc"
6473 // has only one use.
6474 SDNode *N = Op.getNode();
6475 SDValue LHS = N->getOperand(0);
6476 SDValue RHS = N->getOperand(1);
6477 unsigned BaseOp = 0;
6479 DebugLoc dl = Op.getNode()->getDebugLoc();
6481 switch (Op.getOpcode()) {
6482 default: assert(0 && "Unknown ovf instruction!");
6484 BaseOp = X86ISD::ADD;
6488 BaseOp = X86ISD::ADD;
6492 BaseOp = X86ISD::SUB;
6496 BaseOp = X86ISD::SUB;
6500 BaseOp = X86ISD::SMUL;
6504 BaseOp = X86ISD::UMUL;
6509 // Also sets EFLAGS.
6510 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
6511 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
6514 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
6515 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
6517 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
6521 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
6522 MVT T = Op.getValueType();
6523 DebugLoc dl = Op.getNode()->getDebugLoc();
6526 switch(T.getSimpleVT()) {
6528 assert(false && "Invalid value type!");
6529 case MVT::i8: Reg = X86::AL; size = 1; break;
6530 case MVT::i16: Reg = X86::AX; size = 2; break;
6531 case MVT::i32: Reg = X86::EAX; size = 4; break;
6533 assert(Subtarget->is64Bit() && "Node not type legal!");
6534 Reg = X86::RAX; size = 8;
6537 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), Reg,
6538 Op.getOperand(2), SDValue());
6539 SDValue Ops[] = { cpIn.getValue(0),
6542 DAG.getTargetConstant(size, MVT::i8),
6544 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6545 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
6547 DAG.getCopyFromReg(Result.getValue(0), Reg, T, Result.getValue(1));
6551 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
6552 SelectionDAG &DAG) {
6553 assert(Subtarget->is64Bit() && "Result not type legalized?");
6554 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6555 SDValue TheChain = Op.getOperand(0);
6556 DebugLoc dl = Op.getNode()->getDebugLoc();
6557 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6558 SDValue rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
6559 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX, MVT::i64,
6561 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
6562 DAG.getConstant(32, MVT::i8));
6564 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
6567 return DAG.getMergeValues(Ops, 2, dl);
6570 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
6571 SDNode *Node = Op.getNode();
6572 DebugLoc dl = Node->getDebugLoc();
6573 MVT T = Node->getValueType(0);
6574 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
6575 DAG.getConstant(0, T), Node->getOperand(2));
6576 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
6577 cast<AtomicSDNode>(Node)->getMemoryVT(),
6578 Node->getOperand(0),
6579 Node->getOperand(1), negOp,
6580 cast<AtomicSDNode>(Node)->getSrcValue(),
6581 cast<AtomicSDNode>(Node)->getAlignment());
6584 /// LowerOperation - Provide custom lowering hooks for some operations.
6586 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
6587 switch (Op.getOpcode()) {
6588 default: assert(0 && "Should not custom lower this!");
6589 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
6590 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
6591 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6592 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6593 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6594 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6595 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6596 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6597 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6598 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6599 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
6600 case ISD::SHL_PARTS:
6601 case ISD::SRA_PARTS:
6602 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
6603 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
6604 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
6605 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
6606 case ISD::FABS: return LowerFABS(Op, DAG);
6607 case ISD::FNEG: return LowerFNEG(Op, DAG);
6608 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6609 case ISD::SETCC: return LowerSETCC(Op, DAG);
6610 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
6611 case ISD::SELECT: return LowerSELECT(Op, DAG);
6612 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
6613 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6614 case ISD::CALL: return LowerCALL(Op, DAG);
6615 case ISD::RET: return LowerRET(Op, DAG);
6616 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
6617 case ISD::VASTART: return LowerVASTART(Op, DAG);
6618 case ISD::VAARG: return LowerVAARG(Op, DAG);
6619 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
6620 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6621 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6622 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6623 case ISD::FRAME_TO_ARGS_OFFSET:
6624 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
6625 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
6626 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
6627 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
6628 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6629 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
6630 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
6631 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
6637 case ISD::UMULO: return LowerXALUO(Op, DAG);
6638 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
6642 void X86TargetLowering::
6643 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
6644 SelectionDAG &DAG, unsigned NewOp) {
6645 MVT T = Node->getValueType(0);
6646 DebugLoc dl = Node->getDebugLoc();
6647 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
6649 SDValue Chain = Node->getOperand(0);
6650 SDValue In1 = Node->getOperand(1);
6651 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6652 Node->getOperand(2), DAG.getIntPtrConstant(0));
6653 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6654 Node->getOperand(2), DAG.getIntPtrConstant(1));
6655 // This is a generalized SDNode, not an AtomicSDNode, so it doesn't
6656 // have a MemOperand. Pass the info through as a normal operand.
6657 SDValue LSI = DAG.getMemOperand(cast<MemSDNode>(Node)->getMemOperand());
6658 SDValue Ops[] = { Chain, In1, In2L, In2H, LSI };
6659 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6660 SDValue Result = DAG.getNode(NewOp, dl, Tys, Ops, 5);
6661 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
6662 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6663 Results.push_back(Result.getValue(2));
6666 /// ReplaceNodeResults - Replace a node with an illegal result type
6667 /// with a new node built out of custom code.
6668 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
6669 SmallVectorImpl<SDValue>&Results,
6670 SelectionDAG &DAG) {
6671 DebugLoc dl = N->getDebugLoc();
6672 switch (N->getOpcode()) {
6674 assert(false && "Do not know how to custom type legalize this operation!");
6676 case ISD::FP_TO_SINT: {
6677 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(SDValue(N, 0), DAG);
6678 SDValue FIST = Vals.first, StackSlot = Vals.second;
6679 if (FIST.getNode() != 0) {
6680 MVT VT = N->getValueType(0);
6681 // Return a load from the stack slot.
6682 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0));
6686 case ISD::READCYCLECOUNTER: {
6687 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6688 SDValue TheChain = N->getOperand(0);
6689 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6690 SDValue eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
6691 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX, MVT::i32,
6693 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
6694 SDValue Ops[] = { eax, edx };
6695 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
6696 Results.push_back(edx.getValue(1));
6699 case ISD::ATOMIC_CMP_SWAP: {
6700 MVT T = N->getValueType(0);
6701 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
6702 SDValue cpInL, cpInH;
6703 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
6704 DAG.getConstant(0, MVT::i32));
6705 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
6706 DAG.getConstant(1, MVT::i32));
6707 cpInL = DAG.getCopyToReg(N->getOperand(0), X86::EAX, cpInL, SDValue());
6708 cpInH = DAG.getCopyToReg(cpInL.getValue(0), X86::EDX, cpInH,
6710 SDValue swapInL, swapInH;
6711 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
6712 DAG.getConstant(0, MVT::i32));
6713 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
6714 DAG.getConstant(1, MVT::i32));
6715 swapInL = DAG.getCopyToReg(cpInH.getValue(0), X86::EBX, swapInL,
6717 swapInH = DAG.getCopyToReg(swapInL.getValue(0), X86::ECX, swapInH,
6718 swapInL.getValue(1));
6719 SDValue Ops[] = { swapInH.getValue(0),
6721 swapInH.getValue(1) };
6722 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6723 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
6724 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), X86::EAX, MVT::i32,
6725 Result.getValue(1));
6726 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), X86::EDX, MVT::i32,
6727 cpOutL.getValue(2));
6728 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
6729 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6730 Results.push_back(cpOutH.getValue(1));
6733 case ISD::ATOMIC_LOAD_ADD:
6734 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
6736 case ISD::ATOMIC_LOAD_AND:
6737 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
6739 case ISD::ATOMIC_LOAD_NAND:
6740 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
6742 case ISD::ATOMIC_LOAD_OR:
6743 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
6745 case ISD::ATOMIC_LOAD_SUB:
6746 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
6748 case ISD::ATOMIC_LOAD_XOR:
6749 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
6751 case ISD::ATOMIC_SWAP:
6752 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
6757 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
6759 default: return NULL;
6760 case X86ISD::BSF: return "X86ISD::BSF";
6761 case X86ISD::BSR: return "X86ISD::BSR";
6762 case X86ISD::SHLD: return "X86ISD::SHLD";
6763 case X86ISD::SHRD: return "X86ISD::SHRD";
6764 case X86ISD::FAND: return "X86ISD::FAND";
6765 case X86ISD::FOR: return "X86ISD::FOR";
6766 case X86ISD::FXOR: return "X86ISD::FXOR";
6767 case X86ISD::FSRL: return "X86ISD::FSRL";
6768 case X86ISD::FILD: return "X86ISD::FILD";
6769 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
6770 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
6771 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
6772 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
6773 case X86ISD::FLD: return "X86ISD::FLD";
6774 case X86ISD::FST: return "X86ISD::FST";
6775 case X86ISD::CALL: return "X86ISD::CALL";
6776 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
6777 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
6778 case X86ISD::BT: return "X86ISD::BT";
6779 case X86ISD::CMP: return "X86ISD::CMP";
6780 case X86ISD::COMI: return "X86ISD::COMI";
6781 case X86ISD::UCOMI: return "X86ISD::UCOMI";
6782 case X86ISD::SETCC: return "X86ISD::SETCC";
6783 case X86ISD::CMOV: return "X86ISD::CMOV";
6784 case X86ISD::BRCOND: return "X86ISD::BRCOND";
6785 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
6786 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
6787 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
6788 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
6789 case X86ISD::Wrapper: return "X86ISD::Wrapper";
6790 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
6791 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
6792 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
6793 case X86ISD::PINSRB: return "X86ISD::PINSRB";
6794 case X86ISD::PINSRW: return "X86ISD::PINSRW";
6795 case X86ISD::FMAX: return "X86ISD::FMAX";
6796 case X86ISD::FMIN: return "X86ISD::FMIN";
6797 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
6798 case X86ISD::FRCP: return "X86ISD::FRCP";
6799 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
6800 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
6801 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
6802 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
6803 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
6804 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
6805 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
6806 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
6807 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
6808 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
6809 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
6810 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
6811 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
6812 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
6813 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
6814 case X86ISD::VSHL: return "X86ISD::VSHL";
6815 case X86ISD::VSRL: return "X86ISD::VSRL";
6816 case X86ISD::CMPPD: return "X86ISD::CMPPD";
6817 case X86ISD::CMPPS: return "X86ISD::CMPPS";
6818 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
6819 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
6820 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
6821 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
6822 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
6823 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
6824 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
6825 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
6826 case X86ISD::ADD: return "X86ISD::ADD";
6827 case X86ISD::SUB: return "X86ISD::SUB";
6828 case X86ISD::SMUL: return "X86ISD::SMUL";
6829 case X86ISD::UMUL: return "X86ISD::UMUL";
6833 // isLegalAddressingMode - Return true if the addressing mode represented
6834 // by AM is legal for this target, for a load/store of the specified type.
6835 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
6836 const Type *Ty) const {
6837 // X86 supports extremely general addressing modes.
6839 // X86 allows a sign-extended 32-bit immediate field as a displacement.
6840 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
6844 // We can only fold this if we don't need an extra load.
6845 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
6847 // If BaseGV requires a register, we cannot also have a BaseReg.
6848 if (Subtarget->GVRequiresRegister(AM.BaseGV, getTargetMachine(), false) &&
6852 // X86-64 only supports addr of globals in small code model.
6853 if (Subtarget->is64Bit()) {
6854 if (getTargetMachine().getCodeModel() != CodeModel::Small)
6856 // If lower 4G is not available, then we must use rip-relative addressing.
6857 if (AM.BaseOffs || AM.Scale > 1)
6868 // These scales always work.
6873 // These scales are formed with basereg+scalereg. Only accept if there is
6878 default: // Other stuff never works.
6886 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
6887 if (!Ty1->isInteger() || !Ty2->isInteger())
6889 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6890 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6891 if (NumBits1 <= NumBits2)
6893 return Subtarget->is64Bit() || NumBits1 < 64;
6896 bool X86TargetLowering::isTruncateFree(MVT VT1, MVT VT2) const {
6897 if (!VT1.isInteger() || !VT2.isInteger())
6899 unsigned NumBits1 = VT1.getSizeInBits();
6900 unsigned NumBits2 = VT2.getSizeInBits();
6901 if (NumBits1 <= NumBits2)
6903 return Subtarget->is64Bit() || NumBits1 < 64;
6906 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6907 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6908 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6909 /// are assumed to be legal.
6911 X86TargetLowering::isShuffleMaskLegal(SDValue Mask, MVT VT) const {
6912 // Only do shuffles on 128-bit vector types for now.
6913 if (VT.getSizeInBits() == 64) return false;
6914 return (Mask.getNode()->getNumOperands() <= 4 ||
6915 isIdentityMask(Mask.getNode()) ||
6916 isIdentityMask(Mask.getNode(), true) ||
6917 isSplatMask(Mask.getNode()) ||
6918 isPSHUFHW_PSHUFLWMask(Mask.getNode()) ||
6919 X86::isUNPCKLMask(Mask.getNode()) ||
6920 X86::isUNPCKHMask(Mask.getNode()) ||
6921 X86::isUNPCKL_v_undef_Mask(Mask.getNode()) ||
6922 X86::isUNPCKH_v_undef_Mask(Mask.getNode()));
6926 X86TargetLowering::isVectorClearMaskLegal(const std::vector<SDValue> &BVOps,
6927 MVT EVT, SelectionDAG &DAG) const {
6928 unsigned NumElts = BVOps.size();
6929 // Only do shuffles on 128-bit vector types for now.
6930 if (EVT.getSizeInBits() * NumElts == 64) return false;
6931 if (NumElts == 2) return true;
6933 return (isMOVLMask(&BVOps[0], 4) ||
6934 isCommutedMOVL(&BVOps[0], 4, true) ||
6935 isSHUFPMask(&BVOps[0], 4) ||
6936 isCommutedSHUFP(&BVOps[0], 4));
6941 //===----------------------------------------------------------------------===//
6942 // X86 Scheduler Hooks
6943 //===----------------------------------------------------------------------===//
6945 // private utility function
6947 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
6948 MachineBasicBlock *MBB,
6956 TargetRegisterClass *RC,
6958 // For the atomic bitwise operator, we generate
6961 // ld t1 = [bitinstr.addr]
6962 // op t2 = t1, [bitinstr.val]
6964 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
6966 // fallthrough -->nextMBB
6967 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6968 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6969 MachineFunction::iterator MBBIter = MBB;
6972 /// First build the CFG
6973 MachineFunction *F = MBB->getParent();
6974 MachineBasicBlock *thisMBB = MBB;
6975 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6976 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6977 F->insert(MBBIter, newMBB);
6978 F->insert(MBBIter, nextMBB);
6980 // Move all successors to thisMBB to nextMBB
6981 nextMBB->transferSuccessors(thisMBB);
6983 // Update thisMBB to fall through to newMBB
6984 thisMBB->addSuccessor(newMBB);
6986 // newMBB jumps to itself and fall through to nextMBB
6987 newMBB->addSuccessor(nextMBB);
6988 newMBB->addSuccessor(newMBB);
6990 // Insert instructions into newMBB based on incoming instruction
6991 assert(bInstr->getNumOperands() < 8 && "unexpected number of operands");
6992 DebugLoc dl = bInstr->getDebugLoc();
6993 MachineOperand& destOper = bInstr->getOperand(0);
6994 MachineOperand* argOpers[6];
6995 int numArgs = bInstr->getNumOperands() - 1;
6996 for (int i=0; i < numArgs; ++i)
6997 argOpers[i] = &bInstr->getOperand(i+1);
6999 // x86 address has 4 operands: base, index, scale, and displacement
7000 int lastAddrIndx = 3; // [0,3]
7003 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7004 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7005 for (int i=0; i <= lastAddrIndx; ++i)
7006 (*MIB).addOperand(*argOpers[i]);
7008 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7010 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7015 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7016 assert((argOpers[valArgIndx]->isReg() ||
7017 argOpers[valArgIndx]->isImm()) &&
7019 if (argOpers[valArgIndx]->isReg())
7020 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7022 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7024 (*MIB).addOperand(*argOpers[valArgIndx]);
7026 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7029 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7030 for (int i=0; i <= lastAddrIndx; ++i)
7031 (*MIB).addOperand(*argOpers[i]);
7033 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7034 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7036 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7040 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7042 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7046 // private utility function: 64 bit atomics on 32 bit host.
7048 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7049 MachineBasicBlock *MBB,
7055 // For the atomic bitwise operator, we generate
7056 // thisMBB (instructions are in pairs, except cmpxchg8b)
7057 // ld t1,t2 = [bitinstr.addr]
7059 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7060 // op t5, t6 <- out1, out2, [bitinstr.val]
7061 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
7062 // mov ECX, EBX <- t5, t6
7063 // mov EAX, EDX <- t1, t2
7064 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
7065 // mov t3, t4 <- EAX, EDX
7067 // result in out1, out2
7068 // fallthrough -->nextMBB
7070 const TargetRegisterClass *RC = X86::GR32RegisterClass;
7071 const unsigned LoadOpc = X86::MOV32rm;
7072 const unsigned copyOpc = X86::MOV32rr;
7073 const unsigned NotOpc = X86::NOT32r;
7074 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7075 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7076 MachineFunction::iterator MBBIter = MBB;
7079 /// First build the CFG
7080 MachineFunction *F = MBB->getParent();
7081 MachineBasicBlock *thisMBB = MBB;
7082 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7083 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7084 F->insert(MBBIter, newMBB);
7085 F->insert(MBBIter, nextMBB);
7087 // Move all successors to thisMBB to nextMBB
7088 nextMBB->transferSuccessors(thisMBB);
7090 // Update thisMBB to fall through to newMBB
7091 thisMBB->addSuccessor(newMBB);
7093 // newMBB jumps to itself and fall through to nextMBB
7094 newMBB->addSuccessor(nextMBB);
7095 newMBB->addSuccessor(newMBB);
7097 DebugLoc dl = bInstr->getDebugLoc();
7098 // Insert instructions into newMBB based on incoming instruction
7099 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7100 assert(bInstr->getNumOperands() < 18 && "unexpected number of operands");
7101 MachineOperand& dest1Oper = bInstr->getOperand(0);
7102 MachineOperand& dest2Oper = bInstr->getOperand(1);
7103 MachineOperand* argOpers[6];
7104 for (int i=0; i < 6; ++i)
7105 argOpers[i] = &bInstr->getOperand(i+2);
7107 // x86 address has 4 operands: base, index, scale, and displacement
7108 int lastAddrIndx = 3; // [0,3]
7110 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7111 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
7112 for (int i=0; i <= lastAddrIndx; ++i)
7113 (*MIB).addOperand(*argOpers[i]);
7114 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7115 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
7116 // add 4 to displacement.
7117 for (int i=0; i <= lastAddrIndx-1; ++i)
7118 (*MIB).addOperand(*argOpers[i]);
7119 MachineOperand newOp3 = *(argOpers[3]);
7121 newOp3.setImm(newOp3.getImm()+4);
7123 newOp3.setOffset(newOp3.getOffset()+4);
7124 (*MIB).addOperand(newOp3);
7126 // t3/4 are defined later, at the bottom of the loop
7127 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
7128 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
7129 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
7130 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
7131 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
7132 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
7134 unsigned tt1 = F->getRegInfo().createVirtualRegister(RC);
7135 unsigned tt2 = F->getRegInfo().createVirtualRegister(RC);
7137 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt1).addReg(t1);
7138 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt2).addReg(t2);
7144 assert((argOpers[4]->isReg() || argOpers[4]->isImm()) &&
7146 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
7147 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
7148 if (argOpers[4]->isReg())
7149 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
7151 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
7152 if (regOpcL != X86::MOV32rr)
7154 (*MIB).addOperand(*argOpers[4]);
7155 assert(argOpers[5]->isReg() == argOpers[4]->isReg());
7156 assert(argOpers[5]->isImm() == argOpers[4]->isImm());
7157 if (argOpers[5]->isReg())
7158 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
7160 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
7161 if (regOpcH != X86::MOV32rr)
7163 (*MIB).addOperand(*argOpers[5]);
7165 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
7167 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
7170 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
7172 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
7175 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
7176 for (int i=0; i <= lastAddrIndx; ++i)
7177 (*MIB).addOperand(*argOpers[i]);
7179 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7180 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7182 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
7183 MIB.addReg(X86::EAX);
7184 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
7185 MIB.addReg(X86::EDX);
7188 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7190 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7194 // private utility function
7196 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
7197 MachineBasicBlock *MBB,
7199 // For the atomic min/max operator, we generate
7202 // ld t1 = [min/max.addr]
7203 // mov t2 = [min/max.val]
7205 // cmov[cond] t2 = t1
7207 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7209 // fallthrough -->nextMBB
7211 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7212 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7213 MachineFunction::iterator MBBIter = MBB;
7216 /// First build the CFG
7217 MachineFunction *F = MBB->getParent();
7218 MachineBasicBlock *thisMBB = MBB;
7219 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7220 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7221 F->insert(MBBIter, newMBB);
7222 F->insert(MBBIter, nextMBB);
7224 // Move all successors to thisMBB to nextMBB
7225 nextMBB->transferSuccessors(thisMBB);
7227 // Update thisMBB to fall through to newMBB
7228 thisMBB->addSuccessor(newMBB);
7230 // newMBB jumps to newMBB and fall through to nextMBB
7231 newMBB->addSuccessor(nextMBB);
7232 newMBB->addSuccessor(newMBB);
7234 DebugLoc dl = mInstr->getDebugLoc();
7235 // Insert instructions into newMBB based on incoming instruction
7236 assert(mInstr->getNumOperands() < 8 && "unexpected number of operands");
7237 MachineOperand& destOper = mInstr->getOperand(0);
7238 MachineOperand* argOpers[6];
7239 int numArgs = mInstr->getNumOperands() - 1;
7240 for (int i=0; i < numArgs; ++i)
7241 argOpers[i] = &mInstr->getOperand(i+1);
7243 // x86 address has 4 operands: base, index, scale, and displacement
7244 int lastAddrIndx = 3; // [0,3]
7247 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7248 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
7249 for (int i=0; i <= lastAddrIndx; ++i)
7250 (*MIB).addOperand(*argOpers[i]);
7252 // We only support register and immediate values
7253 assert((argOpers[valArgIndx]->isReg() ||
7254 argOpers[valArgIndx]->isImm()) &&
7257 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7258 if (argOpers[valArgIndx]->isReg())
7259 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7261 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7262 (*MIB).addOperand(*argOpers[valArgIndx]);
7264 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
7267 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
7272 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7273 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
7277 // Cmp and exchange if none has modified the memory location
7278 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
7279 for (int i=0; i <= lastAddrIndx; ++i)
7280 (*MIB).addOperand(*argOpers[i]);
7282 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7283 (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
7285 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
7286 MIB.addReg(X86::EAX);
7289 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7291 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
7297 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7298 MachineBasicBlock *BB) {
7299 DebugLoc dl = MI->getDebugLoc();
7300 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7301 switch (MI->getOpcode()) {
7302 default: assert(false && "Unexpected instr type to insert");
7303 case X86::CMOV_V1I64:
7304 case X86::CMOV_FR32:
7305 case X86::CMOV_FR64:
7306 case X86::CMOV_V4F32:
7307 case X86::CMOV_V2F64:
7308 case X86::CMOV_V2I64: {
7309 // To "insert" a SELECT_CC instruction, we actually have to insert the
7310 // diamond control-flow pattern. The incoming instruction knows the
7311 // destination vreg to set, the condition code register to branch on, the
7312 // true/false values to select between, and a branch opcode to use.
7313 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7314 MachineFunction::iterator It = BB;
7320 // cmpTY ccX, r1, r2
7322 // fallthrough --> copy0MBB
7323 MachineBasicBlock *thisMBB = BB;
7324 MachineFunction *F = BB->getParent();
7325 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7326 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7328 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
7329 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
7330 F->insert(It, copy0MBB);
7331 F->insert(It, sinkMBB);
7332 // Update machine-CFG edges by transferring all successors of the current
7333 // block to the new block which will contain the Phi node for the select.
7334 sinkMBB->transferSuccessors(BB);
7336 // Add the true and fallthrough blocks as its successors.
7337 BB->addSuccessor(copy0MBB);
7338 BB->addSuccessor(sinkMBB);
7341 // %FalseValue = ...
7342 // # fallthrough to sinkMBB
7345 // Update machine-CFG edges
7346 BB->addSuccessor(sinkMBB);
7349 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7352 BuildMI(BB, dl, TII->get(X86::PHI), MI->getOperand(0).getReg())
7353 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7354 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7356 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7360 case X86::FP32_TO_INT16_IN_MEM:
7361 case X86::FP32_TO_INT32_IN_MEM:
7362 case X86::FP32_TO_INT64_IN_MEM:
7363 case X86::FP64_TO_INT16_IN_MEM:
7364 case X86::FP64_TO_INT32_IN_MEM:
7365 case X86::FP64_TO_INT64_IN_MEM:
7366 case X86::FP80_TO_INT16_IN_MEM:
7367 case X86::FP80_TO_INT32_IN_MEM:
7368 case X86::FP80_TO_INT64_IN_MEM: {
7369 // Change the floating point control register to use "round towards zero"
7370 // mode when truncating to an integer value.
7371 MachineFunction *F = BB->getParent();
7372 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
7373 addFrameReference(BuildMI(BB, dl, TII->get(X86::FNSTCW16m)), CWFrameIdx);
7375 // Load the old value of the high byte of the control word...
7377 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
7378 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16rm), OldCW),
7381 // Set the high part to be round to zero...
7382 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mi)), CWFrameIdx)
7385 // Reload the modified control word now...
7386 addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7388 // Restore the memory image of control word to original value
7389 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mr)), CWFrameIdx)
7392 // Get the X86 opcode to use.
7394 switch (MI->getOpcode()) {
7395 default: assert(0 && "illegal opcode!");
7396 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
7397 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
7398 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
7399 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
7400 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
7401 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
7402 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
7403 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
7404 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
7408 MachineOperand &Op = MI->getOperand(0);
7410 AM.BaseType = X86AddressMode::RegBase;
7411 AM.Base.Reg = Op.getReg();
7413 AM.BaseType = X86AddressMode::FrameIndexBase;
7414 AM.Base.FrameIndex = Op.getIndex();
7416 Op = MI->getOperand(1);
7418 AM.Scale = Op.getImm();
7419 Op = MI->getOperand(2);
7421 AM.IndexReg = Op.getImm();
7422 Op = MI->getOperand(3);
7423 if (Op.isGlobal()) {
7424 AM.GV = Op.getGlobal();
7426 AM.Disp = Op.getImm();
7428 addFullAddress(BuildMI(BB, dl, TII->get(Opc)), AM)
7429 .addReg(MI->getOperand(4).getReg());
7431 // Reload the original control word now.
7432 addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7434 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7437 case X86::ATOMAND32:
7438 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7439 X86::AND32ri, X86::MOV32rm,
7440 X86::LCMPXCHG32, X86::MOV32rr,
7441 X86::NOT32r, X86::EAX,
7442 X86::GR32RegisterClass);
7444 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
7445 X86::OR32ri, X86::MOV32rm,
7446 X86::LCMPXCHG32, X86::MOV32rr,
7447 X86::NOT32r, X86::EAX,
7448 X86::GR32RegisterClass);
7449 case X86::ATOMXOR32:
7450 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
7451 X86::XOR32ri, X86::MOV32rm,
7452 X86::LCMPXCHG32, X86::MOV32rr,
7453 X86::NOT32r, X86::EAX,
7454 X86::GR32RegisterClass);
7455 case X86::ATOMNAND32:
7456 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7457 X86::AND32ri, X86::MOV32rm,
7458 X86::LCMPXCHG32, X86::MOV32rr,
7459 X86::NOT32r, X86::EAX,
7460 X86::GR32RegisterClass, true);
7461 case X86::ATOMMIN32:
7462 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
7463 case X86::ATOMMAX32:
7464 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
7465 case X86::ATOMUMIN32:
7466 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
7467 case X86::ATOMUMAX32:
7468 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
7470 case X86::ATOMAND16:
7471 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7472 X86::AND16ri, X86::MOV16rm,
7473 X86::LCMPXCHG16, X86::MOV16rr,
7474 X86::NOT16r, X86::AX,
7475 X86::GR16RegisterClass);
7477 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
7478 X86::OR16ri, X86::MOV16rm,
7479 X86::LCMPXCHG16, X86::MOV16rr,
7480 X86::NOT16r, X86::AX,
7481 X86::GR16RegisterClass);
7482 case X86::ATOMXOR16:
7483 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
7484 X86::XOR16ri, X86::MOV16rm,
7485 X86::LCMPXCHG16, X86::MOV16rr,
7486 X86::NOT16r, X86::AX,
7487 X86::GR16RegisterClass);
7488 case X86::ATOMNAND16:
7489 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7490 X86::AND16ri, X86::MOV16rm,
7491 X86::LCMPXCHG16, X86::MOV16rr,
7492 X86::NOT16r, X86::AX,
7493 X86::GR16RegisterClass, true);
7494 case X86::ATOMMIN16:
7495 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
7496 case X86::ATOMMAX16:
7497 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
7498 case X86::ATOMUMIN16:
7499 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
7500 case X86::ATOMUMAX16:
7501 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
7504 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7505 X86::AND8ri, X86::MOV8rm,
7506 X86::LCMPXCHG8, X86::MOV8rr,
7507 X86::NOT8r, X86::AL,
7508 X86::GR8RegisterClass);
7510 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
7511 X86::OR8ri, X86::MOV8rm,
7512 X86::LCMPXCHG8, X86::MOV8rr,
7513 X86::NOT8r, X86::AL,
7514 X86::GR8RegisterClass);
7516 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
7517 X86::XOR8ri, X86::MOV8rm,
7518 X86::LCMPXCHG8, X86::MOV8rr,
7519 X86::NOT8r, X86::AL,
7520 X86::GR8RegisterClass);
7521 case X86::ATOMNAND8:
7522 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7523 X86::AND8ri, X86::MOV8rm,
7524 X86::LCMPXCHG8, X86::MOV8rr,
7525 X86::NOT8r, X86::AL,
7526 X86::GR8RegisterClass, true);
7527 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
7528 // This group is for 64-bit host.
7529 case X86::ATOMAND64:
7530 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7531 X86::AND64ri32, X86::MOV64rm,
7532 X86::LCMPXCHG64, X86::MOV64rr,
7533 X86::NOT64r, X86::RAX,
7534 X86::GR64RegisterClass);
7536 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
7537 X86::OR64ri32, X86::MOV64rm,
7538 X86::LCMPXCHG64, X86::MOV64rr,
7539 X86::NOT64r, X86::RAX,
7540 X86::GR64RegisterClass);
7541 case X86::ATOMXOR64:
7542 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
7543 X86::XOR64ri32, X86::MOV64rm,
7544 X86::LCMPXCHG64, X86::MOV64rr,
7545 X86::NOT64r, X86::RAX,
7546 X86::GR64RegisterClass);
7547 case X86::ATOMNAND64:
7548 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7549 X86::AND64ri32, X86::MOV64rm,
7550 X86::LCMPXCHG64, X86::MOV64rr,
7551 X86::NOT64r, X86::RAX,
7552 X86::GR64RegisterClass, true);
7553 case X86::ATOMMIN64:
7554 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
7555 case X86::ATOMMAX64:
7556 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
7557 case X86::ATOMUMIN64:
7558 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
7559 case X86::ATOMUMAX64:
7560 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
7562 // This group does 64-bit operations on a 32-bit host.
7563 case X86::ATOMAND6432:
7564 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7565 X86::AND32rr, X86::AND32rr,
7566 X86::AND32ri, X86::AND32ri,
7568 case X86::ATOMOR6432:
7569 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7570 X86::OR32rr, X86::OR32rr,
7571 X86::OR32ri, X86::OR32ri,
7573 case X86::ATOMXOR6432:
7574 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7575 X86::XOR32rr, X86::XOR32rr,
7576 X86::XOR32ri, X86::XOR32ri,
7578 case X86::ATOMNAND6432:
7579 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7580 X86::AND32rr, X86::AND32rr,
7581 X86::AND32ri, X86::AND32ri,
7583 case X86::ATOMADD6432:
7584 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7585 X86::ADD32rr, X86::ADC32rr,
7586 X86::ADD32ri, X86::ADC32ri,
7588 case X86::ATOMSUB6432:
7589 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7590 X86::SUB32rr, X86::SBB32rr,
7591 X86::SUB32ri, X86::SBB32ri,
7593 case X86::ATOMSWAP6432:
7594 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7595 X86::MOV32rr, X86::MOV32rr,
7596 X86::MOV32ri, X86::MOV32ri,
7601 //===----------------------------------------------------------------------===//
7602 // X86 Optimization Hooks
7603 //===----------------------------------------------------------------------===//
7605 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
7609 const SelectionDAG &DAG,
7610 unsigned Depth) const {
7611 unsigned Opc = Op.getOpcode();
7612 assert((Opc >= ISD::BUILTIN_OP_END ||
7613 Opc == ISD::INTRINSIC_WO_CHAIN ||
7614 Opc == ISD::INTRINSIC_W_CHAIN ||
7615 Opc == ISD::INTRINSIC_VOID) &&
7616 "Should use MaskedValueIsZero if you don't know whether Op"
7617 " is a target node!");
7619 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
7626 // These nodes' second result is a boolean.
7627 if (Op.getResNo() == 0)
7631 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
7632 Mask.getBitWidth() - 1);
7637 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
7638 /// node is a GlobalAddress + offset.
7639 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
7640 GlobalValue* &GA, int64_t &Offset) const{
7641 if (N->getOpcode() == X86ISD::Wrapper) {
7642 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
7643 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
7644 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
7648 return TargetLowering::isGAPlusOffset(N, GA, Offset);
7651 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
7652 const TargetLowering &TLI) {
7655 if (TLI.isGAPlusOffset(Base, GV, Offset))
7656 return (GV->getAlignment() >= N && (Offset % N) == 0);
7657 // DAG combine handles the stack object case.
7661 static bool EltsFromConsecutiveLoads(SDNode *N, SDValue PermMask,
7662 unsigned NumElems, MVT EVT,
7664 SelectionDAG &DAG, MachineFrameInfo *MFI,
7665 const TargetLowering &TLI) {
7667 for (unsigned i = 0; i < NumElems; ++i) {
7668 SDValue Idx = PermMask.getOperand(i);
7669 if (Idx.getOpcode() == ISD::UNDEF) {
7675 SDValue Elt = DAG.getShuffleScalarElt(N, i);
7676 if (!Elt.getNode() ||
7677 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
7680 Base = Elt.getNode();
7681 if (Base->getOpcode() == ISD::UNDEF)
7685 if (Elt.getOpcode() == ISD::UNDEF)
7688 if (!TLI.isConsecutiveLoad(Elt.getNode(), Base,
7689 EVT.getSizeInBits()/8, i, MFI))
7695 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
7696 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
7697 /// if the load addresses are consecutive, non-overlapping, and in the right
7699 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
7700 const TargetLowering &TLI) {
7701 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7702 DebugLoc dl = N->getDebugLoc();
7703 MVT VT = N->getValueType(0);
7704 MVT EVT = VT.getVectorElementType();
7705 SDValue PermMask = N->getOperand(2);
7706 unsigned NumElems = PermMask.getNumOperands();
7707 SDNode *Base = NULL;
7708 if (!EltsFromConsecutiveLoads(N, PermMask, NumElems, EVT, Base,
7712 LoadSDNode *LD = cast<LoadSDNode>(Base);
7713 if (isBaseAlignmentOfN(16, Base->getOperand(1).getNode(), TLI))
7714 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
7715 LD->getSrcValue(), LD->getSrcValueOffset(),
7717 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
7718 LD->getSrcValue(), LD->getSrcValueOffset(),
7719 LD->isVolatile(), LD->getAlignment());
7722 /// PerformBuildVectorCombine - build_vector 0,(load i64 / f64) -> movq / movsd.
7723 static SDValue PerformBuildVectorCombine(SDNode *N, SelectionDAG &DAG,
7724 TargetLowering::DAGCombinerInfo &DCI,
7725 const X86Subtarget *Subtarget,
7726 const TargetLowering &TLI) {
7727 unsigned NumOps = N->getNumOperands();
7728 DebugLoc dl = N->getDebugLoc();
7730 // Ignore single operand BUILD_VECTOR.
7734 MVT VT = N->getValueType(0);
7735 MVT EVT = VT.getVectorElementType();
7736 if ((EVT != MVT::i64 && EVT != MVT::f64) || Subtarget->is64Bit())
7737 // We are looking for load i64 and zero extend. We want to transform
7738 // it before legalizer has a chance to expand it. Also look for i64
7739 // BUILD_PAIR bit casted to f64.
7741 // This must be an insertion into a zero vector.
7742 SDValue HighElt = N->getOperand(1);
7743 if (!isZeroNode(HighElt))
7746 // Value must be a load.
7747 SDNode *Base = N->getOperand(0).getNode();
7748 if (!isa<LoadSDNode>(Base)) {
7749 if (Base->getOpcode() != ISD::BIT_CONVERT)
7751 Base = Base->getOperand(0).getNode();
7752 if (!isa<LoadSDNode>(Base))
7756 // Transform it into VZEXT_LOAD addr.
7757 LoadSDNode *LD = cast<LoadSDNode>(Base);
7759 // Load must not be an extload.
7760 if (LD->getExtensionType() != ISD::NON_EXTLOAD)
7763 // Load type should legal type so we don't have to legalize it.
7764 if (!TLI.isTypeLegal(VT))
7767 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
7768 SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
7769 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
7770 TargetLowering::TargetLoweringOpt TLO(DAG);
7771 TLO.CombineTo(SDValue(Base, 1), ResNode.getValue(1));
7772 DCI.CommitTargetLoweringOpt(TLO);
7776 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
7777 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
7778 const X86Subtarget *Subtarget) {
7779 DebugLoc dl = N->getDebugLoc();
7780 SDValue Cond = N->getOperand(0);
7782 // If we have SSE[12] support, try to form min/max nodes.
7783 if (Subtarget->hasSSE2() &&
7784 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
7785 if (Cond.getOpcode() == ISD::SETCC) {
7786 // Get the LHS/RHS of the select.
7787 SDValue LHS = N->getOperand(1);
7788 SDValue RHS = N->getOperand(2);
7789 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
7791 unsigned Opcode = 0;
7792 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
7795 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
7798 if (!UnsafeFPMath) break;
7800 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
7802 Opcode = X86ISD::FMIN;
7805 case ISD::SETOGT: // (X > Y) ? X : Y -> max
7808 if (!UnsafeFPMath) break;
7810 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
7812 Opcode = X86ISD::FMAX;
7815 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
7818 case ISD::SETOGT: // (X > Y) ? Y : X -> min
7821 if (!UnsafeFPMath) break;
7823 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
7825 Opcode = X86ISD::FMIN;
7828 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
7831 if (!UnsafeFPMath) break;
7833 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
7835 Opcode = X86ISD::FMAX;
7841 return DAG.getNode(Opcode, dl, N->getValueType(0), LHS, RHS);
7849 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
7851 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
7852 const X86Subtarget *Subtarget) {
7853 // On X86 with SSE2 support, we can transform this to a vector shift if
7854 // all elements are shifted by the same amount. We can't do this in legalize
7855 // because the a constant vector is typically transformed to a constant pool
7856 // so we have no knowledge of the shift amount.
7857 if (!Subtarget->hasSSE2())
7860 MVT VT = N->getValueType(0);
7861 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
7864 SDValue ShAmtOp = N->getOperand(1);
7865 MVT EltVT = VT.getVectorElementType();
7866 DebugLoc dl = N->getDebugLoc();
7868 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
7869 unsigned NumElts = VT.getVectorNumElements();
7871 for (; i != NumElts; ++i) {
7872 SDValue Arg = ShAmtOp.getOperand(i);
7873 if (Arg.getOpcode() == ISD::UNDEF) continue;
7877 for (; i != NumElts; ++i) {
7878 SDValue Arg = ShAmtOp.getOperand(i);
7879 if (Arg.getOpcode() == ISD::UNDEF) continue;
7880 if (Arg != BaseShAmt) {
7884 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
7885 isSplatMask(ShAmtOp.getOperand(2).getNode())) {
7886 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, ShAmtOp,
7887 DAG.getIntPtrConstant(0));
7891 if (EltVT.bitsGT(MVT::i32))
7892 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
7893 else if (EltVT.bitsLT(MVT::i32))
7894 BaseShAmt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BaseShAmt);
7896 // The shift amount is identical so we can do a vector shift.
7897 SDValue ValOp = N->getOperand(0);
7898 switch (N->getOpcode()) {
7900 assert(0 && "Unknown shift opcode!");
7903 if (VT == MVT::v2i64)
7904 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7905 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7907 if (VT == MVT::v4i32)
7908 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7909 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
7911 if (VT == MVT::v8i16)
7912 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7913 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
7917 if (VT == MVT::v4i32)
7918 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7919 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
7921 if (VT == MVT::v8i16)
7922 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7923 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
7927 if (VT == MVT::v2i64)
7928 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7929 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7931 if (VT == MVT::v4i32)
7932 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7933 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
7935 if (VT == MVT::v8i16)
7936 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7937 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
7944 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
7945 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
7946 const X86Subtarget *Subtarget) {
7947 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
7948 // the FP state in cases where an emms may be missing.
7949 // A preferable solution to the general problem is to figure out the right
7950 // places to insert EMMS. This qualifies as a quick hack.
7951 StoreSDNode *St = cast<StoreSDNode>(N);
7952 if (St->getValue().getValueType().isVector() &&
7953 St->getValue().getValueType().getSizeInBits() == 64 &&
7954 isa<LoadSDNode>(St->getValue()) &&
7955 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
7956 St->getChain().hasOneUse() && !St->isVolatile()) {
7957 SDNode* LdVal = St->getValue().getNode();
7959 int TokenFactorIndex = -1;
7960 SmallVector<SDValue, 8> Ops;
7961 SDNode* ChainVal = St->getChain().getNode();
7962 // Must be a store of a load. We currently handle two cases: the load
7963 // is a direct child, and it's under an intervening TokenFactor. It is
7964 // possible to dig deeper under nested TokenFactors.
7965 if (ChainVal == LdVal)
7966 Ld = cast<LoadSDNode>(St->getChain());
7967 else if (St->getValue().hasOneUse() &&
7968 ChainVal->getOpcode() == ISD::TokenFactor) {
7969 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
7970 if (ChainVal->getOperand(i).getNode() == LdVal) {
7971 TokenFactorIndex = i;
7972 Ld = cast<LoadSDNode>(St->getValue());
7974 Ops.push_back(ChainVal->getOperand(i));
7978 DebugLoc dl = N->getDebugLoc();
7979 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
7980 if (Subtarget->is64Bit()) {
7981 SDValue NewLd = DAG.getLoad(MVT::i64, dl, Ld->getChain(),
7982 Ld->getBasePtr(), Ld->getSrcValue(),
7983 Ld->getSrcValueOffset(), Ld->isVolatile(),
7984 Ld->getAlignment());
7985 SDValue NewChain = NewLd.getValue(1);
7986 if (TokenFactorIndex != -1) {
7987 Ops.push_back(NewChain);
7988 NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Ops[0],
7991 return DAG.getStore(NewChain, dl, NewLd, St->getBasePtr(),
7992 St->getSrcValue(), St->getSrcValueOffset(),
7993 St->isVolatile(), St->getAlignment());
7996 // Otherwise, lower to two 32-bit copies.
7997 SDValue LoAddr = Ld->getBasePtr();
7998 SDValue HiAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, LoAddr,
7999 DAG.getConstant(4, MVT::i32));
8001 SDValue LoLd = DAG.getLoad(MVT::i32, dl, Ld->getChain(), LoAddr,
8002 Ld->getSrcValue(), Ld->getSrcValueOffset(),
8003 Ld->isVolatile(), Ld->getAlignment());
8004 SDValue HiLd = DAG.getLoad(MVT::i32, dl, Ld->getChain(), HiAddr,
8005 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
8007 MinAlign(Ld->getAlignment(), 4));
8009 SDValue NewChain = LoLd.getValue(1);
8010 if (TokenFactorIndex != -1) {
8011 Ops.push_back(LoLd);
8012 Ops.push_back(HiLd);
8013 NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Ops[0],
8017 LoAddr = St->getBasePtr();
8018 HiAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, LoAddr,
8019 DAG.getConstant(4, MVT::i32));
8021 SDValue LoSt = DAG.getStore(NewChain, dl, LoLd, LoAddr,
8022 St->getSrcValue(), St->getSrcValueOffset(),
8023 St->isVolatile(), St->getAlignment());
8024 SDValue HiSt = DAG.getStore(NewChain, dl, HiLd, HiAddr,
8026 St->getSrcValueOffset() + 4,
8028 MinAlign(St->getAlignment(), 4));
8029 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoSt, HiSt);
8035 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
8036 /// X86ISD::FXOR nodes.
8037 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
8038 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
8039 // F[X]OR(0.0, x) -> x
8040 // F[X]OR(x, 0.0) -> x
8041 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8042 if (C->getValueAPF().isPosZero())
8043 return N->getOperand(1);
8044 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8045 if (C->getValueAPF().isPosZero())
8046 return N->getOperand(0);
8050 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
8051 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
8052 // FAND(0.0, x) -> 0.0
8053 // FAND(x, 0.0) -> 0.0
8054 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8055 if (C->getValueAPF().isPosZero())
8056 return N->getOperand(0);
8057 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8058 if (C->getValueAPF().isPosZero())
8059 return N->getOperand(1);
8063 static SDValue PerformBTCombine(SDNode *N,
8065 TargetLowering::DAGCombinerInfo &DCI) {
8066 // BT ignores high bits in the bit index operand.
8067 SDValue Op1 = N->getOperand(1);
8068 if (Op1.hasOneUse()) {
8069 unsigned BitWidth = Op1.getValueSizeInBits();
8070 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
8071 APInt KnownZero, KnownOne;
8072 TargetLowering::TargetLoweringOpt TLO(DAG);
8073 TargetLowering &TLI = DAG.getTargetLoweringInfo();
8074 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
8075 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
8076 DCI.CommitTargetLoweringOpt(TLO);
8081 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
8082 DAGCombinerInfo &DCI) const {
8083 SelectionDAG &DAG = DCI.DAG;
8084 switch (N->getOpcode()) {
8086 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
8087 case ISD::BUILD_VECTOR:
8088 return PerformBuildVectorCombine(N, DAG, DCI, Subtarget, *this);
8089 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
8092 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
8093 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
8095 case X86ISD::FOR: return PerformFORCombine(N, DAG);
8096 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
8097 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
8103 //===----------------------------------------------------------------------===//
8104 // X86 Inline Assembly Support
8105 //===----------------------------------------------------------------------===//
8107 /// getConstraintType - Given a constraint letter, return the type of
8108 /// constraint it is for this target.
8109 X86TargetLowering::ConstraintType
8110 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
8111 if (Constraint.size() == 1) {
8112 switch (Constraint[0]) {
8124 return C_RegisterClass;
8129 return TargetLowering::getConstraintType(Constraint);
8132 /// LowerXConstraint - try to replace an X constraint, which matches anything,
8133 /// with another that has more specific requirements based on the type of the
8134 /// corresponding operand.
8135 const char *X86TargetLowering::
8136 LowerXConstraint(MVT ConstraintVT) const {
8137 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
8138 // 'f' like normal targets.
8139 if (ConstraintVT.isFloatingPoint()) {
8140 if (Subtarget->hasSSE2())
8142 if (Subtarget->hasSSE1())
8146 return TargetLowering::LowerXConstraint(ConstraintVT);
8149 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8150 /// vector. If it is invalid, don't add anything to Ops.
8151 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8154 std::vector<SDValue>&Ops,
8155 SelectionDAG &DAG) const {
8156 SDValue Result(0, 0);
8158 switch (Constraint) {
8161 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8162 if (C->getZExtValue() <= 31) {
8163 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8169 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8170 if (C->getZExtValue() <= 63) {
8171 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8177 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8178 if (C->getZExtValue() <= 255) {
8179 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8185 // Literal immediates are always ok.
8186 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
8187 Result = DAG.getTargetConstant(CST->getZExtValue(), Op.getValueType());
8191 // If we are in non-pic codegen mode, we allow the address of a global (with
8192 // an optional displacement) to be used with 'i'.
8193 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
8196 // Match either (GA) or (GA+C)
8198 Offset = GA->getOffset();
8199 } else if (Op.getOpcode() == ISD::ADD) {
8200 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8201 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
8203 Offset = GA->getOffset()+C->getZExtValue();
8205 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8206 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
8208 Offset = GA->getOffset()+C->getZExtValue();
8216 Op = LowerGlobalAddress(GA->getGlobal(), Offset, DAG);
8218 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
8224 // Otherwise, not valid for this mode.
8229 if (Result.getNode()) {
8230 Ops.push_back(Result);
8233 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
8237 std::vector<unsigned> X86TargetLowering::
8238 getRegClassForInlineAsmConstraint(const std::string &Constraint,
8240 if (Constraint.size() == 1) {
8241 // FIXME: not handling fp-stack yet!
8242 switch (Constraint[0]) { // GCC X86 Constraint Letters
8243 default: break; // Unknown constraint letter
8244 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
8247 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
8248 else if (VT == MVT::i16)
8249 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
8250 else if (VT == MVT::i8)
8251 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
8252 else if (VT == MVT::i64)
8253 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
8258 return std::vector<unsigned>();
8261 std::pair<unsigned, const TargetRegisterClass*>
8262 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8264 // First, see if this is a constraint that directly corresponds to an LLVM
8266 if (Constraint.size() == 1) {
8267 // GCC Constraint Letters
8268 switch (Constraint[0]) {
8270 case 'r': // GENERAL_REGS
8271 case 'R': // LEGACY_REGS
8272 case 'l': // INDEX_REGS
8274 return std::make_pair(0U, X86::GR8RegisterClass);
8276 return std::make_pair(0U, X86::GR16RegisterClass);
8277 if (VT == MVT::i32 || !Subtarget->is64Bit())
8278 return std::make_pair(0U, X86::GR32RegisterClass);
8279 return std::make_pair(0U, X86::GR64RegisterClass);
8280 case 'f': // FP Stack registers.
8281 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
8282 // value to the correct fpstack register class.
8283 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
8284 return std::make_pair(0U, X86::RFP32RegisterClass);
8285 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
8286 return std::make_pair(0U, X86::RFP64RegisterClass);
8287 return std::make_pair(0U, X86::RFP80RegisterClass);
8288 case 'y': // MMX_REGS if MMX allowed.
8289 if (!Subtarget->hasMMX()) break;
8290 return std::make_pair(0U, X86::VR64RegisterClass);
8291 case 'Y': // SSE_REGS if SSE2 allowed
8292 if (!Subtarget->hasSSE2()) break;
8294 case 'x': // SSE_REGS if SSE1 allowed
8295 if (!Subtarget->hasSSE1()) break;
8297 switch (VT.getSimpleVT()) {
8299 // Scalar SSE types.
8302 return std::make_pair(0U, X86::FR32RegisterClass);
8305 return std::make_pair(0U, X86::FR64RegisterClass);
8313 return std::make_pair(0U, X86::VR128RegisterClass);
8319 // Use the default implementation in TargetLowering to convert the register
8320 // constraint into a member of a register class.
8321 std::pair<unsigned, const TargetRegisterClass*> Res;
8322 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8324 // Not found as a standard register?
8325 if (Res.second == 0) {
8326 // GCC calls "st(0)" just plain "st".
8327 if (StringsEqualNoCase("{st}", Constraint)) {
8328 Res.first = X86::ST0;
8329 Res.second = X86::RFP80RegisterClass;
8331 // 'A' means EAX + EDX.
8332 if (Constraint == "A") {
8333 Res.first = X86::EAX;
8334 Res.second = X86::GRADRegisterClass;
8339 // Otherwise, check to see if this is a register class of the wrong value
8340 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
8341 // turn into {ax},{dx}.
8342 if (Res.second->hasType(VT))
8343 return Res; // Correct type already, nothing to do.
8345 // All of the single-register GCC register classes map their values onto
8346 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
8347 // really want an 8-bit or 32-bit register, map to the appropriate register
8348 // class and return the appropriate register.
8349 if (Res.second == X86::GR16RegisterClass) {
8350 if (VT == MVT::i8) {
8351 unsigned DestReg = 0;
8352 switch (Res.first) {
8354 case X86::AX: DestReg = X86::AL; break;
8355 case X86::DX: DestReg = X86::DL; break;
8356 case X86::CX: DestReg = X86::CL; break;
8357 case X86::BX: DestReg = X86::BL; break;
8360 Res.first = DestReg;
8361 Res.second = Res.second = X86::GR8RegisterClass;
8363 } else if (VT == MVT::i32) {
8364 unsigned DestReg = 0;
8365 switch (Res.first) {
8367 case X86::AX: DestReg = X86::EAX; break;
8368 case X86::DX: DestReg = X86::EDX; break;
8369 case X86::CX: DestReg = X86::ECX; break;
8370 case X86::BX: DestReg = X86::EBX; break;
8371 case X86::SI: DestReg = X86::ESI; break;
8372 case X86::DI: DestReg = X86::EDI; break;
8373 case X86::BP: DestReg = X86::EBP; break;
8374 case X86::SP: DestReg = X86::ESP; break;
8377 Res.first = DestReg;
8378 Res.second = Res.second = X86::GR32RegisterClass;
8380 } else if (VT == MVT::i64) {
8381 unsigned DestReg = 0;
8382 switch (Res.first) {
8384 case X86::AX: DestReg = X86::RAX; break;
8385 case X86::DX: DestReg = X86::RDX; break;
8386 case X86::CX: DestReg = X86::RCX; break;
8387 case X86::BX: DestReg = X86::RBX; break;
8388 case X86::SI: DestReg = X86::RSI; break;
8389 case X86::DI: DestReg = X86::RDI; break;
8390 case X86::BP: DestReg = X86::RBP; break;
8391 case X86::SP: DestReg = X86::RSP; break;
8394 Res.first = DestReg;
8395 Res.second = Res.second = X86::GR64RegisterClass;
8398 } else if (Res.second == X86::FR32RegisterClass ||
8399 Res.second == X86::FR64RegisterClass ||
8400 Res.second == X86::VR128RegisterClass) {
8401 // Handle references to XMM physical registers that got mapped into the
8402 // wrong class. This can happen with constraints like {xmm0} where the
8403 // target independent register mapper will just pick the first match it can
8404 // find, ignoring the required type.
8406 Res.second = X86::FR32RegisterClass;
8407 else if (VT == MVT::f64)
8408 Res.second = X86::FR64RegisterClass;
8409 else if (X86::VR128RegisterClass->hasType(VT))
8410 Res.second = X86::VR128RegisterClass;
8416 //===----------------------------------------------------------------------===//
8417 // X86 Widen vector type
8418 //===----------------------------------------------------------------------===//
8420 /// getWidenVectorType: given a vector type, returns the type to widen
8421 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
8422 /// If there is no vector type that we want to widen to, returns MVT::Other
8423 /// When and where to widen is target dependent based on the cost of
8424 /// scalarizing vs using the wider vector type.
8426 MVT X86TargetLowering::getWidenVectorType(MVT VT) const {
8427 assert(VT.isVector());
8428 if (isTypeLegal(VT))
8431 // TODO: In computeRegisterProperty, we can compute the list of legal vector
8432 // type based on element type. This would speed up our search (though
8433 // it may not be worth it since the size of the list is relatively
8435 MVT EltVT = VT.getVectorElementType();
8436 unsigned NElts = VT.getVectorNumElements();
8438 // On X86, it make sense to widen any vector wider than 1
8442 for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
8443 nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
8444 MVT SVT = (MVT::SimpleValueType)nVT;
8446 if (isTypeLegal(SVT) &&
8447 SVT.getVectorElementType() == EltVT &&
8448 SVT.getVectorNumElements() > NElts)