1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
16 #include "X86InstrBuilder.h"
17 #include "X86ISelLowering.h"
18 #include "X86MachineFunctionInfo.h"
19 #include "X86TargetMachine.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Function.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/ADT/BitVector.h"
27 #include "llvm/ADT/VectorExtras.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/PseudoSourceValue.h"
35 #include "llvm/CodeGen/SelectionDAG.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/ADT/SmallSet.h"
40 #include "llvm/ADT/StringExtras.h"
41 #include "llvm/Support/CommandLine.h"
45 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
47 // Forward declarations.
48 static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG, DebugLoc dl);
50 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
51 : TargetLowering(TM) {
52 Subtarget = &TM.getSubtarget<X86Subtarget>();
53 X86ScalarSSEf64 = Subtarget->hasSSE2();
54 X86ScalarSSEf32 = Subtarget->hasSSE1();
55 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
59 RegInfo = TM.getRegisterInfo();
62 // Set up the TargetLowering object.
64 // X86 is weird, it always uses i8 for shift amounts and setcc results.
65 setShiftAmountType(MVT::i8);
66 setBooleanContents(ZeroOrOneBooleanContent);
67 setSchedulingPreference(SchedulingForRegPressure);
68 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
69 setStackPointerRegisterToSaveRestore(X86StackPtr);
71 if (Subtarget->isTargetDarwin()) {
72 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
73 setUseUnderscoreSetJmp(false);
74 setUseUnderscoreLongJmp(false);
75 } else if (Subtarget->isTargetMingw()) {
76 // MS runtime is weird: it exports _setjmp, but longjmp!
77 setUseUnderscoreSetJmp(true);
78 setUseUnderscoreLongJmp(false);
80 setUseUnderscoreSetJmp(true);
81 setUseUnderscoreLongJmp(true);
84 // Set up the register classes.
85 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
86 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
87 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
88 if (Subtarget->is64Bit())
89 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
91 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
93 // We don't accept any truncstore of integer registers.
94 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
95 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
96 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
97 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
98 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
99 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
101 // SETOEQ and SETUNE require checking two conditions.
102 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
103 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
104 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
105 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
106 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
107 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
109 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
111 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
112 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
113 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
115 if (Subtarget->is64Bit()) {
116 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
117 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
119 if (X86ScalarSSEf64) {
120 // We have an impenetrably clever algorithm for ui64->double only.
121 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
123 // We have faster algorithm for ui32->single only.
124 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
126 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
129 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
131 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
132 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
133 // SSE has no i16 to fp conversion, only i32
134 if (X86ScalarSSEf32) {
135 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
136 // f32 and f64 cases are Legal, f80 case is not
137 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
139 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
140 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
143 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
144 // are Legal, f80 is custom lowered.
145 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
146 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
148 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
150 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
151 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
153 if (X86ScalarSSEf32) {
154 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
155 // f32 and f64 cases are Legal, f80 case is not
156 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
158 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
159 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
162 // Handle FP_TO_UINT by promoting the destination to a larger signed
164 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
165 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
166 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
168 if (Subtarget->is64Bit()) {
169 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
170 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
172 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
173 // Expand FP_TO_UINT into a select.
174 // FIXME: We would like to use a Custom expander here eventually to do
175 // the optimal thing for SSE vs. the default expansion in the legalizer.
176 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
178 // With SSE3 we can use fisttpll to convert to a signed i64.
179 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
182 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
183 if (!X86ScalarSSEf64) {
184 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
185 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
188 // Scalar integer divide and remainder are lowered to use operations that
189 // produce two results, to match the available instructions. This exposes
190 // the two-result form to trivial CSE, which is able to combine x/y and x%y
191 // into a single instruction.
193 // Scalar integer multiply-high is also lowered to use two-result
194 // operations, to match the available instructions. However, plain multiply
195 // (low) operations are left as Legal, as there are single-result
196 // instructions for this in x86. Using the two-result multiply instructions
197 // when both high and low results are needed must be arranged by dagcombine.
198 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
199 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
200 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
201 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
202 setOperationAction(ISD::SREM , MVT::i8 , Expand);
203 setOperationAction(ISD::UREM , MVT::i8 , Expand);
204 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
205 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
206 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
207 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
208 setOperationAction(ISD::SREM , MVT::i16 , Expand);
209 setOperationAction(ISD::UREM , MVT::i16 , Expand);
210 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
211 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
212 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
213 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
214 setOperationAction(ISD::SREM , MVT::i32 , Expand);
215 setOperationAction(ISD::UREM , MVT::i32 , Expand);
216 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
217 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
218 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
219 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
220 setOperationAction(ISD::SREM , MVT::i64 , Expand);
221 setOperationAction(ISD::UREM , MVT::i64 , Expand);
223 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
224 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
225 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
226 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
227 if (Subtarget->is64Bit())
228 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
229 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
230 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
231 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
232 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
233 setOperationAction(ISD::FREM , MVT::f32 , Expand);
234 setOperationAction(ISD::FREM , MVT::f64 , Expand);
235 setOperationAction(ISD::FREM , MVT::f80 , Expand);
236 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
238 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
239 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
240 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
241 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
242 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
243 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
244 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
245 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
246 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
247 if (Subtarget->is64Bit()) {
248 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
249 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
250 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
253 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
254 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
256 // These should be promoted to a larger select which is supported.
257 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
258 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
259 // X86 wants to expand cmov itself.
260 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
261 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
262 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
263 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
264 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
265 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
266 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
267 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
268 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
269 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
270 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
271 if (Subtarget->is64Bit()) {
272 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
273 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
275 // X86 ret instruction may pop stack.
276 setOperationAction(ISD::RET , MVT::Other, Custom);
277 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
280 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
281 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
282 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
283 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
284 if (Subtarget->is64Bit())
285 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
286 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
287 if (Subtarget->is64Bit()) {
288 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
289 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
290 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
291 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
293 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
294 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
295 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
296 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
297 if (Subtarget->is64Bit()) {
298 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
299 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
300 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
303 if (Subtarget->hasSSE1())
304 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
306 if (!Subtarget->hasSSE2())
307 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
309 // Expand certain atomics
310 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
311 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
312 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
313 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
315 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
316 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
317 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
318 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
320 if (!Subtarget->is64Bit()) {
321 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
322 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
323 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
324 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
325 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
326 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
327 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
330 // Use the default ISD::DBG_STOPPOINT, ISD::DECLARE expansion.
331 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
332 // FIXME - use subtarget debug flags
333 if (!Subtarget->isTargetDarwin() &&
334 !Subtarget->isTargetELF() &&
335 !Subtarget->isTargetCygMing()) {
336 setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
337 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
340 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
341 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
342 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
343 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
344 if (Subtarget->is64Bit()) {
345 setExceptionPointerRegister(X86::RAX);
346 setExceptionSelectorRegister(X86::RDX);
348 setExceptionPointerRegister(X86::EAX);
349 setExceptionSelectorRegister(X86::EDX);
351 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
352 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
354 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
356 setOperationAction(ISD::TRAP, MVT::Other, Legal);
358 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
359 setOperationAction(ISD::VASTART , MVT::Other, Custom);
360 setOperationAction(ISD::VAEND , MVT::Other, Expand);
361 if (Subtarget->is64Bit()) {
362 setOperationAction(ISD::VAARG , MVT::Other, Custom);
363 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
365 setOperationAction(ISD::VAARG , MVT::Other, Expand);
366 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
369 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
370 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
371 if (Subtarget->is64Bit())
372 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
373 if (Subtarget->isTargetCygMing())
374 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
376 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
378 if (!UseSoftFloat && X86ScalarSSEf64) {
379 // f32 and f64 use SSE.
380 // Set up the FP register classes.
381 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
382 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
384 // Use ANDPD to simulate FABS.
385 setOperationAction(ISD::FABS , MVT::f64, Custom);
386 setOperationAction(ISD::FABS , MVT::f32, Custom);
388 // Use XORP to simulate FNEG.
389 setOperationAction(ISD::FNEG , MVT::f64, Custom);
390 setOperationAction(ISD::FNEG , MVT::f32, Custom);
392 // Use ANDPD and ORPD to simulate FCOPYSIGN.
393 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
394 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
396 // We don't support sin/cos/fmod
397 setOperationAction(ISD::FSIN , MVT::f64, Expand);
398 setOperationAction(ISD::FCOS , MVT::f64, Expand);
399 setOperationAction(ISD::FSIN , MVT::f32, Expand);
400 setOperationAction(ISD::FCOS , MVT::f32, Expand);
402 // Expand FP immediates into loads from the stack, except for the special
404 addLegalFPImmediate(APFloat(+0.0)); // xorpd
405 addLegalFPImmediate(APFloat(+0.0f)); // xorps
407 // Floating truncations from f80 and extensions to f80 go through memory.
408 // If optimizing, we lie about this though and handle it in
409 // InstructionSelectPreprocess so that dagcombine2 can hack on these.
411 setConvertAction(MVT::f32, MVT::f80, Expand);
412 setConvertAction(MVT::f64, MVT::f80, Expand);
413 setConvertAction(MVT::f80, MVT::f32, Expand);
414 setConvertAction(MVT::f80, MVT::f64, Expand);
416 } else if (!UseSoftFloat && X86ScalarSSEf32) {
417 // Use SSE for f32, x87 for f64.
418 // Set up the FP register classes.
419 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
420 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
422 // Use ANDPS to simulate FABS.
423 setOperationAction(ISD::FABS , MVT::f32, Custom);
425 // Use XORP to simulate FNEG.
426 setOperationAction(ISD::FNEG , MVT::f32, Custom);
428 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
430 // Use ANDPS and ORPS to simulate FCOPYSIGN.
431 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
432 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
434 // We don't support sin/cos/fmod
435 setOperationAction(ISD::FSIN , MVT::f32, Expand);
436 setOperationAction(ISD::FCOS , MVT::f32, Expand);
438 // Special cases we handle for FP constants.
439 addLegalFPImmediate(APFloat(+0.0f)); // xorps
440 addLegalFPImmediate(APFloat(+0.0)); // FLD0
441 addLegalFPImmediate(APFloat(+1.0)); // FLD1
442 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
443 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
445 // SSE <-> X87 conversions go through memory. If optimizing, we lie about
446 // this though and handle it in InstructionSelectPreprocess so that
447 // dagcombine2 can hack on these.
449 setConvertAction(MVT::f32, MVT::f64, Expand);
450 setConvertAction(MVT::f32, MVT::f80, Expand);
451 setConvertAction(MVT::f80, MVT::f32, Expand);
452 setConvertAction(MVT::f64, MVT::f32, Expand);
453 // And x87->x87 truncations also.
454 setConvertAction(MVT::f80, MVT::f64, Expand);
458 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
459 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
461 } else if (!UseSoftFloat) {
462 // f32 and f64 in x87.
463 // Set up the FP register classes.
464 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
465 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
467 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
468 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
469 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
470 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
472 // Floating truncations go through memory. If optimizing, we lie about
473 // this though and handle it in InstructionSelectPreprocess so that
474 // dagcombine2 can hack on these.
476 setConvertAction(MVT::f80, MVT::f32, Expand);
477 setConvertAction(MVT::f64, MVT::f32, Expand);
478 setConvertAction(MVT::f80, MVT::f64, Expand);
482 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
483 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
485 addLegalFPImmediate(APFloat(+0.0)); // FLD0
486 addLegalFPImmediate(APFloat(+1.0)); // FLD1
487 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
488 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
489 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
490 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
491 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
492 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
495 // Long double always uses X87.
497 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
498 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
499 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
502 APFloat TmpFlt(+0.0);
503 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
505 addLegalFPImmediate(TmpFlt); // FLD0
507 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
508 APFloat TmpFlt2(+1.0);
509 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
511 addLegalFPImmediate(TmpFlt2); // FLD1
512 TmpFlt2.changeSign();
513 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
517 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
518 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
522 // Always use a library call for pow.
523 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
524 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
525 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
527 setOperationAction(ISD::FLOG, MVT::f80, Expand);
528 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
529 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
530 setOperationAction(ISD::FEXP, MVT::f80, Expand);
531 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
533 // First set operation action for all vector types to either promote
534 // (for widening) or expand (for scalarization). Then we will selectively
535 // turn on ones that can be effectively codegen'd.
536 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
537 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
538 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
539 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
540 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
541 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
542 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
543 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
544 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
545 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
546 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
547 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
548 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
549 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
550 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
551 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
552 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
553 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
554 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
555 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
556 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
557 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
558 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
559 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
560 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
561 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
562 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
563 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
564 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
565 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
566 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
567 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
568 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
569 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
570 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
571 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
572 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
573 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
574 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
575 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
576 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
577 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
578 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
579 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
580 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
583 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
584 // with -msoft-float, disable use of MMX as well.
585 if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
586 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
587 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
588 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
589 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
590 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
592 // FIXME: add MMX packed arithmetics
594 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
595 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
596 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
597 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
599 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
600 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
601 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
602 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
604 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
605 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
607 setOperationAction(ISD::AND, MVT::v8i8, Promote);
608 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
609 setOperationAction(ISD::AND, MVT::v4i16, Promote);
610 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
611 setOperationAction(ISD::AND, MVT::v2i32, Promote);
612 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
613 setOperationAction(ISD::AND, MVT::v1i64, Legal);
615 setOperationAction(ISD::OR, MVT::v8i8, Promote);
616 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
617 setOperationAction(ISD::OR, MVT::v4i16, Promote);
618 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
619 setOperationAction(ISD::OR, MVT::v2i32, Promote);
620 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
621 setOperationAction(ISD::OR, MVT::v1i64, Legal);
623 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
624 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
625 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
626 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
627 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
628 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
629 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
631 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
632 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
633 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
634 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
635 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
636 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
637 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
638 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
639 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
641 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
642 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
643 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
644 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
645 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
647 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
648 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
649 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
650 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
652 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
653 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
654 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
655 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
657 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
659 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
660 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Expand);
661 setOperationAction(ISD::SELECT, MVT::v8i8, Promote);
662 setOperationAction(ISD::SELECT, MVT::v4i16, Promote);
663 setOperationAction(ISD::SELECT, MVT::v2i32, Promote);
664 setOperationAction(ISD::SELECT, MVT::v1i64, Custom);
667 if (!UseSoftFloat && Subtarget->hasSSE1()) {
668 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
670 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
671 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
672 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
673 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
674 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
675 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
676 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
677 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
678 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
679 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
680 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
681 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
684 if (!UseSoftFloat && Subtarget->hasSSE2()) {
685 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
687 // FIXME: Unfortunately -soft-float means XMM registers cannot be used even
688 // for integer operations.
689 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
690 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
691 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
692 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
694 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
695 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
696 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
697 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
698 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
699 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
700 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
701 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
702 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
703 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
704 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
705 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
706 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
707 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
708 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
709 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
711 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
712 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
713 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
714 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
716 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
717 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
718 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
719 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
720 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
722 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
723 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
724 MVT VT = (MVT::SimpleValueType)i;
725 // Do not attempt to custom lower non-power-of-2 vectors
726 if (!isPowerOf2_32(VT.getVectorNumElements()))
728 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
729 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
730 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
732 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
733 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
734 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
735 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
736 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
737 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
738 if (Subtarget->is64Bit()) {
739 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
740 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
743 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
744 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
745 setOperationAction(ISD::AND, (MVT::SimpleValueType)VT, Promote);
746 AddPromotedToType (ISD::AND, (MVT::SimpleValueType)VT, MVT::v2i64);
747 setOperationAction(ISD::OR, (MVT::SimpleValueType)VT, Promote);
748 AddPromotedToType (ISD::OR, (MVT::SimpleValueType)VT, MVT::v2i64);
749 setOperationAction(ISD::XOR, (MVT::SimpleValueType)VT, Promote);
750 AddPromotedToType (ISD::XOR, (MVT::SimpleValueType)VT, MVT::v2i64);
751 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Promote);
752 AddPromotedToType (ISD::LOAD, (MVT::SimpleValueType)VT, MVT::v2i64);
753 setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
754 AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v2i64);
757 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
759 // Custom lower v2i64 and v2f64 selects.
760 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
761 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
762 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
763 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
767 if (Subtarget->hasSSE41()) {
768 // FIXME: Do we need to handle scalar-to-vector here?
769 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
771 // i8 and i16 vectors are custom , because the source register and source
772 // source memory operand types are not the same width. f32 vectors are
773 // custom since the immediate controlling the insert encodes additional
775 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
776 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
777 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
778 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
780 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
781 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
782 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
783 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
785 if (Subtarget->is64Bit()) {
786 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
787 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
791 if (Subtarget->hasSSE42()) {
792 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
795 // We want to custom lower some of our intrinsics.
796 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
798 // Add/Sub/Mul with overflow operations are custom lowered.
799 setOperationAction(ISD::SADDO, MVT::i32, Custom);
800 setOperationAction(ISD::SADDO, MVT::i64, Custom);
801 setOperationAction(ISD::UADDO, MVT::i32, Custom);
802 setOperationAction(ISD::UADDO, MVT::i64, Custom);
803 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
804 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
805 setOperationAction(ISD::USUBO, MVT::i32, Custom);
806 setOperationAction(ISD::USUBO, MVT::i64, Custom);
807 setOperationAction(ISD::SMULO, MVT::i32, Custom);
808 setOperationAction(ISD::SMULO, MVT::i64, Custom);
809 setOperationAction(ISD::UMULO, MVT::i32, Custom);
810 setOperationAction(ISD::UMULO, MVT::i64, Custom);
812 // We have target-specific dag combine patterns for the following nodes:
813 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
814 setTargetDAGCombine(ISD::BUILD_VECTOR);
815 setTargetDAGCombine(ISD::SELECT);
816 setTargetDAGCombine(ISD::SHL);
817 setTargetDAGCombine(ISD::SRA);
818 setTargetDAGCombine(ISD::SRL);
819 setTargetDAGCombine(ISD::STORE);
821 computeRegisterProperties();
823 // FIXME: These should be based on subtarget info. Plus, the values should
824 // be smaller when we are in optimizing for size mode.
825 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
826 maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
827 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
828 allowUnalignedMemoryAccesses = true; // x86 supports it!
829 setPrefLoopAlignment(16);
833 MVT X86TargetLowering::getSetCCResultType(MVT VT) const {
838 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
839 /// the desired ByVal argument alignment.
840 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
843 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
844 if (VTy->getBitWidth() == 128)
846 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
847 unsigned EltAlign = 0;
848 getMaxByValAlign(ATy->getElementType(), EltAlign);
849 if (EltAlign > MaxAlign)
851 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
852 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
853 unsigned EltAlign = 0;
854 getMaxByValAlign(STy->getElementType(i), EltAlign);
855 if (EltAlign > MaxAlign)
864 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
865 /// function arguments in the caller parameter area. For X86, aggregates
866 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
867 /// are at 4-byte boundaries.
868 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
869 if (Subtarget->is64Bit()) {
870 // Max of 8 and alignment of type.
871 unsigned TyAlign = TD->getABITypeAlignment(Ty);
878 if (Subtarget->hasSSE1())
879 getMaxByValAlign(Ty, Align);
883 /// getOptimalMemOpType - Returns the target specific optimal type for load
884 /// and store operations as a result of memset, memcpy, and memmove
885 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
888 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
889 bool isSrcConst, bool isSrcStr) const {
890 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
891 // linux. This is because the stack realignment code can't handle certain
892 // cases like PR2962. This should be removed when PR2962 is fixed.
893 if (Subtarget->getStackAlignment() >= 16) {
894 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
896 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
899 if (Subtarget->is64Bit() && Size >= 8)
905 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
907 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
908 SelectionDAG &DAG) const {
909 if (usesGlobalOffsetTable())
910 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy());
911 if (!Subtarget->isPICStyleRIPRel())
912 // This doesn't have DebugLoc associated with it, but is not really the
913 // same as a Register.
914 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc::getUnknownLoc(),
919 //===----------------------------------------------------------------------===//
920 // Return Value Calling Convention Implementation
921 //===----------------------------------------------------------------------===//
923 #include "X86GenCallingConv.inc"
925 /// LowerRET - Lower an ISD::RET node.
926 SDValue X86TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
927 DebugLoc dl = Op.getDebugLoc();
928 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
930 SmallVector<CCValAssign, 16> RVLocs;
931 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
932 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
933 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
934 CCInfo.AnalyzeReturn(Op.getNode(), RetCC_X86);
936 // If this is the first return lowered for this function, add the regs to the
937 // liveout set for the function.
938 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
939 for (unsigned i = 0; i != RVLocs.size(); ++i)
940 if (RVLocs[i].isRegLoc())
941 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
943 SDValue Chain = Op.getOperand(0);
945 // Handle tail call return.
946 Chain = GetPossiblePreceedingTailCall(Chain, X86ISD::TAILCALL);
947 if (Chain.getOpcode() == X86ISD::TAILCALL) {
948 SDValue TailCall = Chain;
949 SDValue TargetAddress = TailCall.getOperand(1);
950 SDValue StackAdjustment = TailCall.getOperand(2);
951 assert(((TargetAddress.getOpcode() == ISD::Register &&
952 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::EAX ||
953 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
954 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
955 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
956 "Expecting an global address, external symbol, or register");
957 assert(StackAdjustment.getOpcode() == ISD::Constant &&
958 "Expecting a const value");
960 SmallVector<SDValue,8> Operands;
961 Operands.push_back(Chain.getOperand(0));
962 Operands.push_back(TargetAddress);
963 Operands.push_back(StackAdjustment);
964 // Copy registers used by the call. Last operand is a flag so it is not
966 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
967 Operands.push_back(Chain.getOperand(i));
969 return DAG.getNode(X86ISD::TC_RETURN, dl, MVT::Other, &Operands[0],
976 SmallVector<SDValue, 6> RetOps;
977 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
978 // Operand #1 = Bytes To Pop
979 RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
981 // Copy the result values into the output registers.
982 for (unsigned i = 0; i != RVLocs.size(); ++i) {
983 CCValAssign &VA = RVLocs[i];
984 assert(VA.isRegLoc() && "Can only return in registers!");
985 SDValue ValToCopy = Op.getOperand(i*2+1);
987 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
988 // the RET instruction and handled by the FP Stackifier.
989 if (VA.getLocReg() == X86::ST0 ||
990 VA.getLocReg() == X86::ST1) {
991 // If this is a copy from an xmm register to ST(0), use an FPExtend to
992 // change the value to the FP stack register class.
993 if (isScalarFPTypeInSSEReg(VA.getValVT()))
994 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
995 RetOps.push_back(ValToCopy);
996 // Don't emit a copytoreg.
1000 // 64-bit vector (MMX) values are returned in RAX.
1001 if (Subtarget->is64Bit()) {
1002 MVT ValVT = ValToCopy.getValueType();
1003 if (VA.getLocReg() == X86::RAX &&
1004 ValVT.isVector() && ValVT.getSizeInBits() == 64)
1005 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1008 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1009 Flag = Chain.getValue(1);
1012 // The x86-64 ABI for returning structs by value requires that we copy
1013 // the sret argument into %rax for the return. We saved the argument into
1014 // a virtual register in the entry block, so now we copy the value out
1016 if (Subtarget->is64Bit() &&
1017 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1018 MachineFunction &MF = DAG.getMachineFunction();
1019 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1020 unsigned Reg = FuncInfo->getSRetReturnReg();
1022 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1023 FuncInfo->setSRetReturnReg(Reg);
1025 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1027 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1028 Flag = Chain.getValue(1);
1031 RetOps[0] = Chain; // Update chain.
1033 // Add the flag if we have it.
1035 RetOps.push_back(Flag);
1037 return DAG.getNode(X86ISD::RET_FLAG, dl,
1038 MVT::Other, &RetOps[0], RetOps.size());
1042 /// LowerCallResult - Lower the result values of an ISD::CALL into the
1043 /// appropriate copies out of appropriate physical registers. This assumes that
1044 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
1045 /// being lowered. The returns a SDNode with the same number of values as the
1047 SDNode *X86TargetLowering::
1048 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall,
1049 unsigned CallingConv, SelectionDAG &DAG) {
1051 DebugLoc dl = TheCall->getDebugLoc();
1052 // Assign locations to each value returned by this call.
1053 SmallVector<CCValAssign, 16> RVLocs;
1054 bool isVarArg = TheCall->isVarArg();
1055 bool Is64Bit = Subtarget->is64Bit();
1056 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
1057 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
1059 SmallVector<SDValue, 8> ResultVals;
1061 // Copy all of the result registers out of their specified physreg.
1062 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1063 CCValAssign &VA = RVLocs[i];
1064 MVT CopyVT = VA.getValVT();
1066 // If this is x86-64, and we disabled SSE, we can't return FP values
1067 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1068 ((Is64Bit || TheCall->isInreg()) && !Subtarget->hasSSE1())) {
1069 cerr << "SSE register return with SSE disabled\n";
1073 // If this is a call to a function that returns an fp value on the floating
1074 // point stack, but where we prefer to use the value in xmm registers, copy
1075 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1076 if ((VA.getLocReg() == X86::ST0 ||
1077 VA.getLocReg() == X86::ST1) &&
1078 isScalarFPTypeInSSEReg(VA.getValVT())) {
1083 if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1084 // For x86-64, MMX values are returned in RAX.
1085 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1086 MVT::i64, InFlag).getValue(1);
1087 Val = Chain.getValue(0);
1088 Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1090 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1091 CopyVT, InFlag).getValue(1);
1092 Val = Chain.getValue(0);
1094 InFlag = Chain.getValue(2);
1096 if (CopyVT != VA.getValVT()) {
1097 // Round the F80 the right size, which also moves to the appropriate xmm
1099 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1100 // This truncation won't change the value.
1101 DAG.getIntPtrConstant(1));
1104 ResultVals.push_back(Val);
1107 // Merge everything together with a MERGE_VALUES node.
1108 ResultVals.push_back(Chain);
1109 return DAG.getNode(ISD::MERGE_VALUES, dl, TheCall->getVTList(),
1110 &ResultVals[0], ResultVals.size()).getNode();
1114 //===----------------------------------------------------------------------===//
1115 // C & StdCall & Fast Calling Convention implementation
1116 //===----------------------------------------------------------------------===//
1117 // StdCall calling convention seems to be standard for many Windows' API
1118 // routines and around. It differs from C calling convention just a little:
1119 // callee should clean up the stack, not caller. Symbols should be also
1120 // decorated in some fancy way :) It doesn't support any vector arguments.
1121 // For info on fast calling convention see Fast Calling Convention (tail call)
1122 // implementation LowerX86_32FastCCCallTo.
1124 /// AddLiveIn - This helper function adds the specified physical register to the
1125 /// MachineFunction as a live in value. It also creates a corresponding virtual
1126 /// register for it.
1127 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
1128 const TargetRegisterClass *RC) {
1129 assert(RC->contains(PReg) && "Not the correct regclass!");
1130 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
1131 MF.getRegInfo().addLiveIn(PReg, VReg);
1135 /// CallIsStructReturn - Determines whether a CALL node uses struct return
1137 static bool CallIsStructReturn(CallSDNode *TheCall) {
1138 unsigned NumOps = TheCall->getNumArgs();
1142 return TheCall->getArgFlags(0).isSRet();
1145 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
1146 /// return semantics.
1147 static bool ArgsAreStructReturn(SDValue Op) {
1148 unsigned NumArgs = Op.getNode()->getNumValues() - 1;
1152 return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
1155 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
1156 /// the callee to pop its own arguments. Callee pop is necessary to support tail
1158 bool X86TargetLowering::IsCalleePop(bool IsVarArg, unsigned CallingConv) {
1162 switch (CallingConv) {
1165 case CallingConv::X86_StdCall:
1166 return !Subtarget->is64Bit();
1167 case CallingConv::X86_FastCall:
1168 return !Subtarget->is64Bit();
1169 case CallingConv::Fast:
1170 return PerformTailCallOpt;
1174 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1175 /// given CallingConvention value.
1176 CCAssignFn *X86TargetLowering::CCAssignFnForNode(unsigned CC) const {
1177 if (Subtarget->is64Bit()) {
1178 if (Subtarget->isTargetWin64())
1179 return CC_X86_Win64_C;
1180 else if (CC == CallingConv::Fast && PerformTailCallOpt)
1181 return CC_X86_64_TailCall;
1186 if (CC == CallingConv::X86_FastCall)
1187 return CC_X86_32_FastCall;
1188 else if (CC == CallingConv::Fast)
1189 return CC_X86_32_FastCC;
1194 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1195 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1197 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDValue Op) {
1198 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1199 if (CC == CallingConv::X86_FastCall)
1201 else if (CC == CallingConv::X86_StdCall)
1207 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1208 /// in a register before calling.
1209 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1210 return !IsTailCall && !Is64Bit &&
1211 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1212 Subtarget->isPICStyleGOT();
1215 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1216 /// address to be loaded in a register.
1218 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1219 return !Is64Bit && IsTailCall &&
1220 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1221 Subtarget->isPICStyleGOT();
1224 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1225 /// by "Src" to address "Dst" with size and alignment information specified by
1226 /// the specific parameter attribute. The copy will be passed as a byval
1227 /// function parameter.
1229 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1230 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1232 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1233 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1234 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1237 SDValue X86TargetLowering::LowerMemArgument(SDValue Op, SelectionDAG &DAG,
1238 const CCValAssign &VA,
1239 MachineFrameInfo *MFI,
1241 SDValue Root, unsigned i) {
1242 // Create the nodes corresponding to a load from this parameter slot.
1243 ISD::ArgFlagsTy Flags =
1244 cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1245 bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1246 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1248 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1249 // changed with more analysis.
1250 // In case of tail call optimization mark all arguments mutable. Since they
1251 // could be overwritten by lowering of arguments in case of a tail call.
1252 int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1253 VA.getLocMemOffset(), isImmutable);
1254 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1255 if (Flags.isByVal())
1257 return DAG.getLoad(VA.getValVT(), Op.getDebugLoc(), Root, FIN,
1258 PseudoSourceValue::getFixedStack(FI), 0);
1262 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) {
1263 MachineFunction &MF = DAG.getMachineFunction();
1264 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1265 DebugLoc dl = Op.getDebugLoc();
1267 const Function* Fn = MF.getFunction();
1268 if (Fn->hasExternalLinkage() &&
1269 Subtarget->isTargetCygMing() &&
1270 Fn->getName() == "main")
1271 FuncInfo->setForceFramePointer(true);
1273 // Decorate the function name.
1274 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1276 MachineFrameInfo *MFI = MF.getFrameInfo();
1277 SDValue Root = Op.getOperand(0);
1278 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
1279 unsigned CC = MF.getFunction()->getCallingConv();
1280 bool Is64Bit = Subtarget->is64Bit();
1281 bool IsWin64 = Subtarget->isTargetWin64();
1283 assert(!(isVarArg && CC == CallingConv::Fast) &&
1284 "Var args not supported with calling convention fastcc");
1286 // Assign locations to all of the incoming arguments.
1287 SmallVector<CCValAssign, 16> ArgLocs;
1288 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1289 CCInfo.AnalyzeFormalArguments(Op.getNode(), CCAssignFnForNode(CC));
1291 SmallVector<SDValue, 8> ArgValues;
1292 unsigned LastVal = ~0U;
1293 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1294 CCValAssign &VA = ArgLocs[i];
1295 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1297 assert(VA.getValNo() != LastVal &&
1298 "Don't support value assigned to multiple locs yet");
1299 LastVal = VA.getValNo();
1301 if (VA.isRegLoc()) {
1302 MVT RegVT = VA.getLocVT();
1303 TargetRegisterClass *RC = NULL;
1304 if (RegVT == MVT::i32)
1305 RC = X86::GR32RegisterClass;
1306 else if (Is64Bit && RegVT == MVT::i64)
1307 RC = X86::GR64RegisterClass;
1308 else if (RegVT == MVT::f32)
1309 RC = X86::FR32RegisterClass;
1310 else if (RegVT == MVT::f64)
1311 RC = X86::FR64RegisterClass;
1312 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1313 RC = X86::VR128RegisterClass;
1314 else if (RegVT.isVector()) {
1315 assert(RegVT.getSizeInBits() == 64);
1317 RC = X86::VR64RegisterClass; // MMX values are passed in MMXs.
1319 // Darwin calling convention passes MMX values in either GPRs or
1320 // XMMs in x86-64. Other targets pass them in memory.
1321 if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1322 RC = X86::VR128RegisterClass; // MMX values are passed in XMMs.
1325 RC = X86::GR64RegisterClass; // v1i64 values are passed in GPRs.
1330 assert(0 && "Unknown argument type!");
1333 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1334 SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, RegVT);
1336 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1337 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1339 if (VA.getLocInfo() == CCValAssign::SExt)
1340 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1341 DAG.getValueType(VA.getValVT()));
1342 else if (VA.getLocInfo() == CCValAssign::ZExt)
1343 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1344 DAG.getValueType(VA.getValVT()));
1346 if (VA.getLocInfo() != CCValAssign::Full)
1347 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1349 // Handle MMX values passed in GPRs.
1350 if (Is64Bit && RegVT != VA.getLocVT()) {
1351 if (RegVT.getSizeInBits() == 64 && RC == X86::GR64RegisterClass)
1352 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1353 else if (RC == X86::VR128RegisterClass) {
1354 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1355 ArgValue, DAG.getConstant(0, MVT::i64));
1356 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getLocVT(), ArgValue);
1360 ArgValues.push_back(ArgValue);
1362 assert(VA.isMemLoc());
1363 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1367 // The x86-64 ABI for returning structs by value requires that we copy
1368 // the sret argument into %rax for the return. Save the argument into
1369 // a virtual register so that we can access it from the return points.
1370 if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1371 MachineFunction &MF = DAG.getMachineFunction();
1372 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1373 unsigned Reg = FuncInfo->getSRetReturnReg();
1375 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1376 FuncInfo->setSRetReturnReg(Reg);
1378 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, ArgValues[0]);
1379 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Root);
1382 unsigned StackSize = CCInfo.getNextStackOffset();
1383 // align stack specially for tail calls
1384 if (PerformTailCallOpt && CC == CallingConv::Fast)
1385 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1387 // If the function takes variable number of arguments, make a frame index for
1388 // the start of the first vararg value... for expansion of llvm.va_start.
1390 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1391 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1394 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1396 // FIXME: We should really autogenerate these arrays
1397 static const unsigned GPR64ArgRegsWin64[] = {
1398 X86::RCX, X86::RDX, X86::R8, X86::R9
1400 static const unsigned XMMArgRegsWin64[] = {
1401 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1403 static const unsigned GPR64ArgRegs64Bit[] = {
1404 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1406 static const unsigned XMMArgRegs64Bit[] = {
1407 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1408 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1410 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1413 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1414 GPR64ArgRegs = GPR64ArgRegsWin64;
1415 XMMArgRegs = XMMArgRegsWin64;
1417 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1418 GPR64ArgRegs = GPR64ArgRegs64Bit;
1419 XMMArgRegs = XMMArgRegs64Bit;
1421 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1423 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1426 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1427 "SSE register cannot be used when SSE is disabled!");
1428 assert(!(NumXMMRegs && UseSoftFloat) &&
1429 "SSE register cannot be used when SSE is disabled!");
1430 if (UseSoftFloat || !Subtarget->hasSSE1()) {
1431 // Kernel mode asks for SSE to be disabled, so don't push them
1433 TotalNumXMMRegs = 0;
1435 // For X86-64, if there are vararg parameters that are passed via
1436 // registers, then we must store them to their spots on the stack so they
1437 // may be loaded by deferencing the result of va_next.
1438 VarArgsGPOffset = NumIntRegs * 8;
1439 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1440 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1441 TotalNumXMMRegs * 16, 16);
1443 // Store the integer parameter registers.
1444 SmallVector<SDValue, 8> MemOps;
1445 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1446 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1447 DAG.getIntPtrConstant(VarArgsGPOffset));
1448 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1449 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1450 X86::GR64RegisterClass);
1451 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::i64);
1453 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1454 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1455 MemOps.push_back(Store);
1456 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1457 DAG.getIntPtrConstant(8));
1460 // Now store the XMM (fp + vector) parameter registers.
1461 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1462 DAG.getIntPtrConstant(VarArgsFPOffset));
1463 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1464 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1465 X86::VR128RegisterClass);
1466 SDValue Val = DAG.getCopyFromReg(Root, dl, VReg, MVT::v4f32);
1468 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1469 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1470 MemOps.push_back(Store);
1471 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), FIN,
1472 DAG.getIntPtrConstant(16));
1474 if (!MemOps.empty())
1475 Root = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1476 &MemOps[0], MemOps.size());
1480 ArgValues.push_back(Root);
1482 // Some CCs need callee pop.
1483 if (IsCalleePop(isVarArg, CC)) {
1484 BytesToPopOnReturn = StackSize; // Callee pops everything.
1485 BytesCallerReserves = 0;
1487 BytesToPopOnReturn = 0; // Callee pops nothing.
1488 // If this is an sret function, the return should pop the hidden pointer.
1489 if (!Is64Bit && CC != CallingConv::Fast && ArgsAreStructReturn(Op))
1490 BytesToPopOnReturn = 4;
1491 BytesCallerReserves = StackSize;
1495 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1496 if (CC == CallingConv::X86_FastCall)
1497 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1500 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1502 // Return the new list of results.
1503 return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getNode()->getVTList(),
1504 &ArgValues[0], ArgValues.size()).getValue(Op.getResNo());
1508 X86TargetLowering::LowerMemOpCallTo(CallSDNode *TheCall, SelectionDAG &DAG,
1509 const SDValue &StackPtr,
1510 const CCValAssign &VA,
1512 SDValue Arg, ISD::ArgFlagsTy Flags) {
1513 DebugLoc dl = TheCall->getDebugLoc();
1514 unsigned LocMemOffset = VA.getLocMemOffset();
1515 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1516 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1517 if (Flags.isByVal()) {
1518 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1520 return DAG.getStore(Chain, dl, Arg, PtrOff,
1521 PseudoSourceValue::getStack(), LocMemOffset);
1524 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1525 /// optimization is performed and it is required.
1527 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1528 SDValue &OutRetAddr,
1534 if (!IsTailCall || FPDiff==0) return Chain;
1536 // Adjust the Return address stack slot.
1537 MVT VT = getPointerTy();
1538 OutRetAddr = getReturnAddressFrameIndex(DAG);
1540 // Load the "old" Return address.
1541 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0);
1542 return SDValue(OutRetAddr.getNode(), 1);
1545 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1546 /// optimization is performed and it is required (FPDiff!=0).
1548 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1549 SDValue Chain, SDValue RetAddrFrIdx,
1550 bool Is64Bit, int FPDiff, DebugLoc dl) {
1551 // Store the return address to the appropriate stack slot.
1552 if (!FPDiff) return Chain;
1553 // Calculate the new stack slot for the return address.
1554 int SlotSize = Is64Bit ? 8 : 4;
1555 int NewReturnAddrFI =
1556 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1557 MVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1558 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1559 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1560 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1564 SDValue X86TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1565 MachineFunction &MF = DAG.getMachineFunction();
1566 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
1567 SDValue Chain = TheCall->getChain();
1568 unsigned CC = TheCall->getCallingConv();
1569 bool isVarArg = TheCall->isVarArg();
1570 bool IsTailCall = TheCall->isTailCall() &&
1571 CC == CallingConv::Fast && PerformTailCallOpt;
1572 SDValue Callee = TheCall->getCallee();
1573 bool Is64Bit = Subtarget->is64Bit();
1574 bool IsStructRet = CallIsStructReturn(TheCall);
1575 DebugLoc dl = TheCall->getDebugLoc();
1577 assert(!(isVarArg && CC == CallingConv::Fast) &&
1578 "Var args not supported with calling convention fastcc");
1580 // Analyze operands of the call, assigning locations to each operand.
1581 SmallVector<CCValAssign, 16> ArgLocs;
1582 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1583 CCInfo.AnalyzeCallOperands(TheCall, CCAssignFnForNode(CC));
1585 // Get a count of how many bytes are to be pushed on the stack.
1586 unsigned NumBytes = CCInfo.getNextStackOffset();
1587 if (PerformTailCallOpt && CC == CallingConv::Fast)
1588 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1592 // Lower arguments at fp - stackoffset + fpdiff.
1593 unsigned NumBytesCallerPushed =
1594 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1595 FPDiff = NumBytesCallerPushed - NumBytes;
1597 // Set the delta of movement of the returnaddr stackslot.
1598 // But only set if delta is greater than previous delta.
1599 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1600 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1603 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1605 SDValue RetAddrFrIdx;
1606 // Load return adress for tail calls.
1607 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1610 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1611 SmallVector<SDValue, 8> MemOpChains;
1614 // Walk the register/memloc assignments, inserting copies/loads. In the case
1615 // of tail call optimization arguments are handle later.
1616 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1617 CCValAssign &VA = ArgLocs[i];
1618 SDValue Arg = TheCall->getArg(i);
1619 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1620 bool isByVal = Flags.isByVal();
1622 // Promote the value if needed.
1623 switch (VA.getLocInfo()) {
1624 default: assert(0 && "Unknown loc info!");
1625 case CCValAssign::Full: break;
1626 case CCValAssign::SExt:
1627 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1629 case CCValAssign::ZExt:
1630 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1632 case CCValAssign::AExt:
1633 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1637 if (VA.isRegLoc()) {
1639 MVT RegVT = VA.getLocVT();
1640 if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1641 switch (VA.getLocReg()) {
1644 case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1646 // Special case: passing MMX values in GPR registers.
1647 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1650 case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1651 case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1652 // Special case: passing MMX values in XMM registers.
1653 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1654 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1655 Arg = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v2i64,
1656 DAG.getUNDEF(MVT::v2i64), Arg,
1657 getMOVLMask(2, DAG, dl));
1662 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1664 if (!IsTailCall || (IsTailCall && isByVal)) {
1665 assert(VA.isMemLoc());
1666 if (StackPtr.getNode() == 0)
1667 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1669 MemOpChains.push_back(LowerMemOpCallTo(TheCall, DAG, StackPtr, VA,
1670 Chain, Arg, Flags));
1675 if (!MemOpChains.empty())
1676 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1677 &MemOpChains[0], MemOpChains.size());
1679 // Build a sequence of copy-to-reg nodes chained together with token chain
1680 // and flag operands which copy the outgoing args into registers.
1682 // Tail call byval lowering might overwrite argument registers so in case of
1683 // tail call optimization the copies to registers are lowered later.
1685 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1686 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1687 RegsToPass[i].second, InFlag);
1688 InFlag = Chain.getValue(1);
1691 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1693 if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1694 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1695 DAG.getNode(X86ISD::GlobalBaseReg,
1696 DebugLoc::getUnknownLoc(),
1699 InFlag = Chain.getValue(1);
1701 // If we are tail calling and generating PIC/GOT style code load the address
1702 // of the callee into ecx. The value in ecx is used as target of the tail
1703 // jump. This is done to circumvent the ebx/callee-saved problem for tail
1704 // calls on PIC/GOT architectures. Normally we would just put the address of
1705 // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1706 // restored (since ebx is callee saved) before jumping to the target@PLT.
1707 if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1708 // Note: The actual moving to ecx is done further down.
1709 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1710 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1711 !G->getGlobal()->hasProtectedVisibility())
1712 Callee = LowerGlobalAddress(Callee, DAG);
1713 else if (isa<ExternalSymbolSDNode>(Callee))
1714 Callee = LowerExternalSymbol(Callee,DAG);
1717 if (Is64Bit && isVarArg) {
1718 // From AMD64 ABI document:
1719 // For calls that may call functions that use varargs or stdargs
1720 // (prototype-less calls or calls to functions containing ellipsis (...) in
1721 // the declaration) %al is used as hidden argument to specify the number
1722 // of SSE registers used. The contents of %al do not need to match exactly
1723 // the number of registers, but must be an ubound on the number of SSE
1724 // registers used and is in the range 0 - 8 inclusive.
1726 // FIXME: Verify this on Win64
1727 // Count the number of XMM registers allocated.
1728 static const unsigned XMMArgRegs[] = {
1729 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1730 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1732 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1733 assert((Subtarget->hasSSE1() || !NumXMMRegs)
1734 && "SSE registers cannot be used when SSE is disabled");
1736 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1737 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1738 InFlag = Chain.getValue(1);
1742 // For tail calls lower the arguments to the 'real' stack slot.
1744 SmallVector<SDValue, 8> MemOpChains2;
1747 // Do not flag preceeding copytoreg stuff together with the following stuff.
1749 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1750 CCValAssign &VA = ArgLocs[i];
1751 if (!VA.isRegLoc()) {
1752 assert(VA.isMemLoc());
1753 SDValue Arg = TheCall->getArg(i);
1754 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1755 // Create frame index.
1756 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1757 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1758 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1759 FIN = DAG.getFrameIndex(FI, getPointerTy());
1761 if (Flags.isByVal()) {
1762 // Copy relative to framepointer.
1763 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1764 if (StackPtr.getNode() == 0)
1765 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
1767 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
1769 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1772 // Store relative to framepointer.
1773 MemOpChains2.push_back(
1774 DAG.getStore(Chain, dl, Arg, FIN,
1775 PseudoSourceValue::getFixedStack(FI), 0));
1780 if (!MemOpChains2.empty())
1781 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1782 &MemOpChains2[0], MemOpChains2.size());
1784 // Copy arguments to their registers.
1785 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1786 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1787 RegsToPass[i].second, InFlag);
1788 InFlag = Chain.getValue(1);
1792 // Store the return address to the appropriate stack slot.
1793 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1797 // If the callee is a GlobalAddress node (quite common, every direct call is)
1798 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1799 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1800 // We should use extra load for direct calls to dllimported functions in
1802 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1803 getTargetMachine(), true))
1804 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy(),
1806 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1807 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1808 } else if (IsTailCall) {
1809 unsigned Opc = Is64Bit ? X86::R9 : X86::EAX;
1811 Chain = DAG.getCopyToReg(Chain, dl,
1812 DAG.getRegister(Opc, getPointerTy()),
1814 Callee = DAG.getRegister(Opc, getPointerTy());
1815 // Add register as live out.
1816 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1819 // Returns a chain & a flag for retval copy to use.
1820 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1821 SmallVector<SDValue, 8> Ops;
1824 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
1825 DAG.getIntPtrConstant(0, true), InFlag);
1826 InFlag = Chain.getValue(1);
1828 // Returns a chain & a flag for retval copy to use.
1829 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1833 Ops.push_back(Chain);
1834 Ops.push_back(Callee);
1837 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1839 // Add argument registers to the end of the list so that they are known live
1841 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1842 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1843 RegsToPass[i].second.getValueType()));
1845 // Add an implicit use GOT pointer in EBX.
1846 if (!IsTailCall && !Is64Bit &&
1847 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1848 Subtarget->isPICStyleGOT())
1849 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1851 // Add an implicit use of AL for x86 vararg functions.
1852 if (Is64Bit && isVarArg)
1853 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1855 if (InFlag.getNode())
1856 Ops.push_back(InFlag);
1859 assert(InFlag.getNode() &&
1860 "Flag must be set. Depend on flag being set in LowerRET");
1861 Chain = DAG.getNode(X86ISD::TAILCALL, dl,
1862 TheCall->getVTList(), &Ops[0], Ops.size());
1864 return SDValue(Chain.getNode(), Op.getResNo());
1867 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
1868 InFlag = Chain.getValue(1);
1870 // Create the CALLSEQ_END node.
1871 unsigned NumBytesForCalleeToPush;
1872 if (IsCalleePop(isVarArg, CC))
1873 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1874 else if (!Is64Bit && CC != CallingConv::Fast && IsStructRet)
1875 // If this is is a call to a struct-return function, the callee
1876 // pops the hidden struct pointer, so we have to push it back.
1877 // This is common for Darwin/X86, Linux & Mingw32 targets.
1878 NumBytesForCalleeToPush = 4;
1880 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1882 // Returns a flag for retval copy to use.
1883 Chain = DAG.getCALLSEQ_END(Chain,
1884 DAG.getIntPtrConstant(NumBytes, true),
1885 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
1888 InFlag = Chain.getValue(1);
1890 // Handle result values, copying them out of physregs into vregs that we
1892 return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
1897 //===----------------------------------------------------------------------===//
1898 // Fast Calling Convention (tail call) implementation
1899 //===----------------------------------------------------------------------===//
1901 // Like std call, callee cleans arguments, convention except that ECX is
1902 // reserved for storing the tail called function address. Only 2 registers are
1903 // free for argument passing (inreg). Tail call optimization is performed
1905 // * tailcallopt is enabled
1906 // * caller/callee are fastcc
1907 // On X86_64 architecture with GOT-style position independent code only local
1908 // (within module) calls are supported at the moment.
1909 // To keep the stack aligned according to platform abi the function
1910 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1911 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1912 // If a tail called function callee has more arguments than the caller the
1913 // caller needs to make sure that there is room to move the RETADDR to. This is
1914 // achieved by reserving an area the size of the argument delta right after the
1915 // original REtADDR, but before the saved framepointer or the spilled registers
1916 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1928 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1929 /// for a 16 byte align requirement.
1930 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1931 SelectionDAG& DAG) {
1932 MachineFunction &MF = DAG.getMachineFunction();
1933 const TargetMachine &TM = MF.getTarget();
1934 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1935 unsigned StackAlignment = TFI.getStackAlignment();
1936 uint64_t AlignMask = StackAlignment - 1;
1937 int64_t Offset = StackSize;
1938 uint64_t SlotSize = TD->getPointerSize();
1939 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1940 // Number smaller than 12 so just add the difference.
1941 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1943 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1944 Offset = ((~AlignMask) & Offset) + StackAlignment +
1945 (StackAlignment-SlotSize);
1950 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1951 /// following the call is a return. A function is eligible if caller/callee
1952 /// calling conventions match, currently only fastcc supports tail calls, and
1953 /// the function CALL is immediatly followed by a RET.
1954 bool X86TargetLowering::IsEligibleForTailCallOptimization(CallSDNode *TheCall,
1956 SelectionDAG& DAG) const {
1957 if (!PerformTailCallOpt)
1960 if (CheckTailCallReturnConstraints(TheCall, Ret)) {
1961 MachineFunction &MF = DAG.getMachineFunction();
1962 unsigned CallerCC = MF.getFunction()->getCallingConv();
1963 unsigned CalleeCC= TheCall->getCallingConv();
1964 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1965 SDValue Callee = TheCall->getCallee();
1966 // On x86/32Bit PIC/GOT tail calls are supported.
1967 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1968 !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1971 // Can only do local tail calls (in same module, hidden or protected) on
1972 // x86_64 PIC/GOT at the moment.
1973 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1974 return G->getGlobal()->hasHiddenVisibility()
1975 || G->getGlobal()->hasProtectedVisibility();
1983 X86TargetLowering::createFastISel(MachineFunction &mf,
1984 MachineModuleInfo *mmo,
1986 DenseMap<const Value *, unsigned> &vm,
1987 DenseMap<const BasicBlock *,
1988 MachineBasicBlock *> &bm,
1989 DenseMap<const AllocaInst *, int> &am
1991 , SmallSet<Instruction*, 8> &cil
1994 return X86::createFastISel(mf, mmo, dw, vm, bm, am
2002 //===----------------------------------------------------------------------===//
2003 // Other Lowering Hooks
2004 //===----------------------------------------------------------------------===//
2007 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2008 MachineFunction &MF = DAG.getMachineFunction();
2009 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2010 int ReturnAddrIndex = FuncInfo->getRAIndex();
2012 if (ReturnAddrIndex == 0) {
2013 // Set up a frame object for the return address.
2014 uint64_t SlotSize = TD->getPointerSize();
2015 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize);
2016 FuncInfo->setRAIndex(ReturnAddrIndex);
2019 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2023 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2024 /// specific condition code, returning the condition code and the LHS/RHS of the
2025 /// comparison to make.
2026 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2027 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2029 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2030 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2031 // X > -1 -> X == 0, jump !sign.
2032 RHS = DAG.getConstant(0, RHS.getValueType());
2033 return X86::COND_NS;
2034 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2035 // X < 0 -> X == 0, jump on sign.
2037 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2039 RHS = DAG.getConstant(0, RHS.getValueType());
2040 return X86::COND_LE;
2044 switch (SetCCOpcode) {
2045 default: assert(0 && "Invalid integer condition!");
2046 case ISD::SETEQ: return X86::COND_E;
2047 case ISD::SETGT: return X86::COND_G;
2048 case ISD::SETGE: return X86::COND_GE;
2049 case ISD::SETLT: return X86::COND_L;
2050 case ISD::SETLE: return X86::COND_LE;
2051 case ISD::SETNE: return X86::COND_NE;
2052 case ISD::SETULT: return X86::COND_B;
2053 case ISD::SETUGT: return X86::COND_A;
2054 case ISD::SETULE: return X86::COND_BE;
2055 case ISD::SETUGE: return X86::COND_AE;
2059 // First determine if it is required or is profitable to flip the operands.
2061 // If LHS is a foldable load, but RHS is not, flip the condition.
2062 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2063 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2064 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2065 std::swap(LHS, RHS);
2068 switch (SetCCOpcode) {
2074 std::swap(LHS, RHS);
2078 // On a floating point condition, the flags are set as follows:
2080 // 0 | 0 | 0 | X > Y
2081 // 0 | 0 | 1 | X < Y
2082 // 1 | 0 | 0 | X == Y
2083 // 1 | 1 | 1 | unordered
2084 switch (SetCCOpcode) {
2085 default: assert(0 && "Condcode should be pre-legalized away");
2087 case ISD::SETEQ: return X86::COND_E;
2088 case ISD::SETOLT: // flipped
2090 case ISD::SETGT: return X86::COND_A;
2091 case ISD::SETOLE: // flipped
2093 case ISD::SETGE: return X86::COND_AE;
2094 case ISD::SETUGT: // flipped
2096 case ISD::SETLT: return X86::COND_B;
2097 case ISD::SETUGE: // flipped
2099 case ISD::SETLE: return X86::COND_BE;
2101 case ISD::SETNE: return X86::COND_NE;
2102 case ISD::SETUO: return X86::COND_P;
2103 case ISD::SETO: return X86::COND_NP;
2107 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2108 /// code. Current x86 isa includes the following FP cmov instructions:
2109 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2110 static bool hasFPCMov(unsigned X86CC) {
2126 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
2127 /// true if Op is undef or if its value falls within the specified range (L, H].
2128 static bool isUndefOrInRange(SDValue Op, unsigned Low, unsigned Hi) {
2129 if (Op.getOpcode() == ISD::UNDEF)
2132 unsigned Val = cast<ConstantSDNode>(Op)->getZExtValue();
2133 return (Val >= Low && Val < Hi);
2136 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
2137 /// true if Op is undef or if its value equal to the specified value.
2138 static bool isUndefOrEqual(SDValue Op, unsigned Val) {
2139 if (Op.getOpcode() == ISD::UNDEF)
2141 return cast<ConstantSDNode>(Op)->getZExtValue() == Val;
2144 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2145 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
2146 bool X86::isPSHUFDMask(SDNode *N) {
2147 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2149 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
2152 // Check if the value doesn't reference the second vector.
2153 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2154 SDValue Arg = N->getOperand(i);
2155 if (Arg.getOpcode() == ISD::UNDEF) continue;
2156 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2157 if (cast<ConstantSDNode>(Arg)->getZExtValue() >= e)
2164 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2165 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2166 bool X86::isPSHUFHWMask(SDNode *N) {
2167 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2169 if (N->getNumOperands() != 8)
2172 // Lower quadword copied in order.
2173 for (unsigned i = 0; i != 4; ++i) {
2174 SDValue Arg = N->getOperand(i);
2175 if (Arg.getOpcode() == ISD::UNDEF) continue;
2176 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2177 if (cast<ConstantSDNode>(Arg)->getZExtValue() != i)
2181 // Upper quadword shuffled.
2182 for (unsigned i = 4; i != 8; ++i) {
2183 SDValue Arg = N->getOperand(i);
2184 if (Arg.getOpcode() == ISD::UNDEF) continue;
2185 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2186 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2187 if (Val < 4 || Val > 7)
2194 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2195 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2196 bool X86::isPSHUFLWMask(SDNode *N) {
2197 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2199 if (N->getNumOperands() != 8)
2202 // Upper quadword copied in order.
2203 for (unsigned i = 4; i != 8; ++i)
2204 if (!isUndefOrEqual(N->getOperand(i), i))
2207 // Lower quadword shuffled.
2208 for (unsigned i = 0; i != 4; ++i)
2209 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2215 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2216 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2217 template<class SDOperand>
2218 static bool isSHUFPMask(SDOperand *Elems, unsigned NumElems) {
2219 if (NumElems != 2 && NumElems != 4) return false;
2221 unsigned Half = NumElems / 2;
2222 for (unsigned i = 0; i < Half; ++i)
2223 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2225 for (unsigned i = Half; i < NumElems; ++i)
2226 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2232 bool X86::isSHUFPMask(SDNode *N) {
2233 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2234 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2237 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2238 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2239 /// half elements to come from vector 1 (which would equal the dest.) and
2240 /// the upper half to come from vector 2.
2241 template<class SDOperand>
2242 static bool isCommutedSHUFP(SDOperand *Ops, unsigned NumOps) {
2243 if (NumOps != 2 && NumOps != 4) return false;
2245 unsigned Half = NumOps / 2;
2246 for (unsigned i = 0; i < Half; ++i)
2247 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2249 for (unsigned i = Half; i < NumOps; ++i)
2250 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2255 static bool isCommutedSHUFP(SDNode *N) {
2256 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2257 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2260 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2261 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2262 bool X86::isMOVHLPSMask(SDNode *N) {
2263 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2265 if (N->getNumOperands() != 4)
2268 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2269 return isUndefOrEqual(N->getOperand(0), 6) &&
2270 isUndefOrEqual(N->getOperand(1), 7) &&
2271 isUndefOrEqual(N->getOperand(2), 2) &&
2272 isUndefOrEqual(N->getOperand(3), 3);
2275 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2276 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2278 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2279 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2281 if (N->getNumOperands() != 4)
2284 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2285 return isUndefOrEqual(N->getOperand(0), 2) &&
2286 isUndefOrEqual(N->getOperand(1), 3) &&
2287 isUndefOrEqual(N->getOperand(2), 2) &&
2288 isUndefOrEqual(N->getOperand(3), 3);
2291 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2292 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2293 bool X86::isMOVLPMask(SDNode *N) {
2294 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2296 unsigned NumElems = N->getNumOperands();
2297 if (NumElems != 2 && NumElems != 4)
2300 for (unsigned i = 0; i < NumElems/2; ++i)
2301 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2304 for (unsigned i = NumElems/2; i < NumElems; ++i)
2305 if (!isUndefOrEqual(N->getOperand(i), i))
2311 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2312 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2314 bool X86::isMOVHPMask(SDNode *N) {
2315 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2317 unsigned NumElems = N->getNumOperands();
2318 if (NumElems != 2 && NumElems != 4)
2321 for (unsigned i = 0; i < NumElems/2; ++i)
2322 if (!isUndefOrEqual(N->getOperand(i), i))
2325 for (unsigned i = 0; i < NumElems/2; ++i) {
2326 SDValue Arg = N->getOperand(i + NumElems/2);
2327 if (!isUndefOrEqual(Arg, i + NumElems))
2334 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2335 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2336 template<class SDOperand>
2337 bool static isUNPCKLMask(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))
2348 if (!isUndefOrEqual(BitI1, NumElts))
2351 if (!isUndefOrEqual(BitI1, j + NumElts))
2359 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2360 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2361 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2364 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2365 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2366 template<class SDOperand>
2367 bool static isUNPCKHMask(SDOperand *Elts, unsigned NumElts,
2368 bool V2IsSplat = false) {
2369 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2372 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2373 SDValue BitI = Elts[i];
2374 SDValue BitI1 = Elts[i+1];
2375 if (!isUndefOrEqual(BitI, j + NumElts/2))
2378 if (isUndefOrEqual(BitI1, NumElts))
2381 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2389 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2390 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2391 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2394 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2395 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2397 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2398 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2400 unsigned NumElems = N->getNumOperands();
2401 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2404 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2405 SDValue BitI = N->getOperand(i);
2406 SDValue BitI1 = N->getOperand(i+1);
2408 if (!isUndefOrEqual(BitI, j))
2410 if (!isUndefOrEqual(BitI1, j))
2417 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2418 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2420 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2421 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2423 unsigned NumElems = N->getNumOperands();
2424 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2427 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2428 SDValue BitI = N->getOperand(i);
2429 SDValue BitI1 = N->getOperand(i + 1);
2431 if (!isUndefOrEqual(BitI, j))
2433 if (!isUndefOrEqual(BitI1, j))
2440 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2441 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2442 /// MOVSD, and MOVD, i.e. setting the lowest element.
2443 template<class SDOperand>
2444 static bool isMOVLMask(SDOperand *Elts, unsigned NumElts) {
2445 if (NumElts != 2 && NumElts != 4)
2448 if (!isUndefOrEqual(Elts[0], NumElts))
2451 for (unsigned i = 1; i < NumElts; ++i) {
2452 if (!isUndefOrEqual(Elts[i], i))
2459 bool X86::isMOVLMask(SDNode *N) {
2460 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2461 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2464 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2465 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2466 /// element of vector 2 and the other elements to come from vector 1 in order.
2467 template<class SDOperand>
2468 static bool isCommutedMOVL(SDOperand *Ops, unsigned NumOps,
2469 bool V2IsSplat = false,
2470 bool V2IsUndef = false) {
2471 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2474 if (!isUndefOrEqual(Ops[0], 0))
2477 for (unsigned i = 1; i < NumOps; ++i) {
2478 SDValue Arg = Ops[i];
2479 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2480 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2481 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2488 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2489 bool V2IsUndef = false) {
2490 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2491 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2492 V2IsSplat, V2IsUndef);
2495 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2496 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2497 bool X86::isMOVSHDUPMask(SDNode *N) {
2498 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2500 if (N->getNumOperands() != 4)
2503 // Expect 1, 1, 3, 3
2504 for (unsigned i = 0; i < 2; ++i) {
2505 SDValue Arg = N->getOperand(i);
2506 if (Arg.getOpcode() == ISD::UNDEF) continue;
2507 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2508 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2509 if (Val != 1) return false;
2513 for (unsigned i = 2; i < 4; ++i) {
2514 SDValue Arg = N->getOperand(i);
2515 if (Arg.getOpcode() == ISD::UNDEF) continue;
2516 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2517 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2518 if (Val != 3) return false;
2522 // Don't use movshdup if it can be done with a shufps.
2526 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2527 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2528 bool X86::isMOVSLDUPMask(SDNode *N) {
2529 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2531 if (N->getNumOperands() != 4)
2534 // Expect 0, 0, 2, 2
2535 for (unsigned i = 0; i < 2; ++i) {
2536 SDValue Arg = N->getOperand(i);
2537 if (Arg.getOpcode() == ISD::UNDEF) continue;
2538 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2539 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2540 if (Val != 0) return false;
2544 for (unsigned i = 2; i < 4; ++i) {
2545 SDValue Arg = N->getOperand(i);
2546 if (Arg.getOpcode() == ISD::UNDEF) continue;
2547 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2548 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2549 if (Val != 2) return false;
2553 // Don't use movshdup if it can be done with a shufps.
2557 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2558 /// specifies a identity operation on the LHS or RHS.
2559 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2560 unsigned NumElems = N->getNumOperands();
2561 for (unsigned i = 0; i < NumElems; ++i)
2562 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2567 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2568 /// a splat of a single element.
2569 static bool isSplatMask(SDNode *N) {
2570 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2572 // This is a splat operation if each element of the permute is the same, and
2573 // if the value doesn't reference the second vector.
2574 unsigned NumElems = N->getNumOperands();
2575 SDValue ElementBase;
2577 for (; i != NumElems; ++i) {
2578 SDValue Elt = N->getOperand(i);
2579 if (isa<ConstantSDNode>(Elt)) {
2585 if (!ElementBase.getNode())
2588 for (; i != NumElems; ++i) {
2589 SDValue Arg = N->getOperand(i);
2590 if (Arg.getOpcode() == ISD::UNDEF) continue;
2591 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2592 if (Arg != ElementBase) return false;
2595 // Make sure it is a splat of the first vector operand.
2596 return cast<ConstantSDNode>(ElementBase)->getZExtValue() < NumElems;
2599 /// getSplatMaskEltNo - Given a splat mask, return the index to the element
2600 /// we want to splat.
2601 static SDValue getSplatMaskEltNo(SDNode *N) {
2602 assert(isSplatMask(N) && "Not a splat mask");
2603 unsigned NumElems = N->getNumOperands();
2604 SDValue ElementBase;
2606 for (; i != NumElems; ++i) {
2607 SDValue Elt = N->getOperand(i);
2608 if (isa<ConstantSDNode>(Elt))
2611 assert(0 && " No splat value found!");
2616 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2617 /// a splat of a single element and it's a 2 or 4 element mask.
2618 bool X86::isSplatMask(SDNode *N) {
2619 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2621 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2622 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2624 return ::isSplatMask(N);
2627 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2628 /// specifies a splat of zero element.
2629 bool X86::isSplatLoMask(SDNode *N) {
2630 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2632 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2633 if (!isUndefOrEqual(N->getOperand(i), 0))
2638 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2639 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2640 bool X86::isMOVDDUPMask(SDNode *N) {
2641 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2643 unsigned e = N->getNumOperands() / 2;
2644 for (unsigned i = 0; i < e; ++i)
2645 if (!isUndefOrEqual(N->getOperand(i), i))
2647 for (unsigned i = 0; i < e; ++i)
2648 if (!isUndefOrEqual(N->getOperand(e+i), i))
2653 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2654 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2656 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2657 unsigned NumOperands = N->getNumOperands();
2658 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2660 for (unsigned i = 0; i < NumOperands; ++i) {
2662 SDValue Arg = N->getOperand(NumOperands-i-1);
2663 if (Arg.getOpcode() != ISD::UNDEF)
2664 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2665 if (Val >= NumOperands) Val -= NumOperands;
2667 if (i != NumOperands - 1)
2674 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2675 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2677 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2679 // 8 nodes, but we only care about the last 4.
2680 for (unsigned i = 7; i >= 4; --i) {
2682 SDValue Arg = N->getOperand(i);
2683 if (Arg.getOpcode() != ISD::UNDEF) {
2684 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2694 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2695 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2697 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2699 // 8 nodes, but we only care about the first 4.
2700 for (int i = 3; i >= 0; --i) {
2702 SDValue Arg = N->getOperand(i);
2703 if (Arg.getOpcode() != ISD::UNDEF)
2704 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2713 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2714 /// values in ther permute mask.
2715 static SDValue CommuteVectorShuffle(SDValue Op, SDValue &V1,
2716 SDValue &V2, SDValue &Mask,
2717 SelectionDAG &DAG) {
2718 MVT VT = Op.getValueType();
2719 MVT MaskVT = Mask.getValueType();
2720 MVT EltVT = MaskVT.getVectorElementType();
2721 unsigned NumElems = Mask.getNumOperands();
2722 SmallVector<SDValue, 8> MaskVec;
2723 DebugLoc dl = Op.getDebugLoc();
2725 for (unsigned i = 0; i != NumElems; ++i) {
2726 SDValue Arg = Mask.getOperand(i);
2727 if (Arg.getOpcode() == ISD::UNDEF) {
2728 MaskVec.push_back(DAG.getUNDEF(EltVT));
2731 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2732 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2734 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2736 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2740 Mask = DAG.getBUILD_VECTOR(MaskVT, dl, &MaskVec[0], NumElems);
2741 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, Mask);
2744 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2745 /// the two vector operands have swapped position.
2747 SDValue CommuteVectorShuffleMask(SDValue Mask, SelectionDAG &DAG, DebugLoc dl) {
2748 MVT MaskVT = Mask.getValueType();
2749 MVT EltVT = MaskVT.getVectorElementType();
2750 unsigned NumElems = Mask.getNumOperands();
2751 SmallVector<SDValue, 8> MaskVec;
2752 for (unsigned i = 0; i != NumElems; ++i) {
2753 SDValue Arg = Mask.getOperand(i);
2754 if (Arg.getOpcode() == ISD::UNDEF) {
2755 MaskVec.push_back(DAG.getUNDEF(EltVT));
2758 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2759 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2761 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2763 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2765 return DAG.getBUILD_VECTOR(MaskVT, dl, &MaskVec[0], NumElems);
2769 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2770 /// match movhlps. The lower half elements should come from upper half of
2771 /// V1 (and in order), and the upper half elements should come from the upper
2772 /// half of V2 (and in order).
2773 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2774 unsigned NumElems = Mask->getNumOperands();
2777 for (unsigned i = 0, e = 2; i != e; ++i)
2778 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2780 for (unsigned i = 2; i != 4; ++i)
2781 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2786 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2787 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2789 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2790 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
2792 N = N->getOperand(0).getNode();
2793 if (!ISD::isNON_EXTLoad(N))
2796 *LD = cast<LoadSDNode>(N);
2800 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2801 /// match movlp{s|d}. The lower half elements should come from lower half of
2802 /// V1 (and in order), and the upper half elements should come from the upper
2803 /// half of V2 (and in order). And since V1 will become the source of the
2804 /// MOVLP, it must be either a vector load or a scalar load to vector.
2805 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2806 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2808 // Is V2 is a vector load, don't do this transformation. We will try to use
2809 // load folding shufps op.
2810 if (ISD::isNON_EXTLoad(V2))
2813 unsigned NumElems = Mask->getNumOperands();
2814 if (NumElems != 2 && NumElems != 4)
2816 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2817 if (!isUndefOrEqual(Mask->getOperand(i), i))
2819 for (unsigned i = NumElems/2; i != NumElems; ++i)
2820 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2825 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2827 static bool isSplatVector(SDNode *N) {
2828 if (N->getOpcode() != ISD::BUILD_VECTOR)
2831 SDValue SplatValue = N->getOperand(0);
2832 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2833 if (N->getOperand(i) != SplatValue)
2838 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2840 static bool isUndefShuffle(SDNode *N) {
2841 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2844 SDValue V1 = N->getOperand(0);
2845 SDValue V2 = N->getOperand(1);
2846 SDValue Mask = N->getOperand(2);
2847 unsigned NumElems = Mask.getNumOperands();
2848 for (unsigned i = 0; i != NumElems; ++i) {
2849 SDValue Arg = Mask.getOperand(i);
2850 if (Arg.getOpcode() != ISD::UNDEF) {
2851 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2852 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2854 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2861 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2863 static inline bool isZeroNode(SDValue Elt) {
2864 return ((isa<ConstantSDNode>(Elt) &&
2865 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2866 (isa<ConstantFPSDNode>(Elt) &&
2867 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2870 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2871 /// to an zero vector.
2872 static bool isZeroShuffle(SDNode *N) {
2873 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2876 SDValue V1 = N->getOperand(0);
2877 SDValue V2 = N->getOperand(1);
2878 SDValue Mask = N->getOperand(2);
2879 unsigned NumElems = Mask.getNumOperands();
2880 for (unsigned i = 0; i != NumElems; ++i) {
2881 SDValue Arg = Mask.getOperand(i);
2882 if (Arg.getOpcode() == ISD::UNDEF)
2885 unsigned Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2886 if (Idx < NumElems) {
2887 unsigned Opc = V1.getNode()->getOpcode();
2888 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
2890 if (Opc != ISD::BUILD_VECTOR ||
2891 !isZeroNode(V1.getNode()->getOperand(Idx)))
2893 } else if (Idx >= NumElems) {
2894 unsigned Opc = V2.getNode()->getOpcode();
2895 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
2897 if (Opc != ISD::BUILD_VECTOR ||
2898 !isZeroNode(V2.getNode()->getOperand(Idx - NumElems)))
2905 /// getZeroVector - Returns a vector of specified type with all zero elements.
2907 static SDValue getZeroVector(MVT VT, bool HasSSE2, SelectionDAG &DAG,
2909 assert(VT.isVector() && "Expected a vector type");
2911 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2912 // type. This ensures they get CSE'd.
2914 if (VT.getSizeInBits() == 64) { // MMX
2915 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2916 Vec = DAG.getBUILD_VECTOR(MVT::v2i32, dl, Cst, Cst);
2917 } else if (HasSSE2) { // SSE2
2918 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2919 Vec = DAG.getBUILD_VECTOR(MVT::v4i32, dl, Cst, Cst, Cst, Cst);
2921 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2922 Vec = DAG.getBUILD_VECTOR(MVT::v4f32, dl, Cst, Cst, Cst, Cst);
2924 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2927 /// getOnesVector - Returns a vector of specified type with all bits set.
2929 static SDValue getOnesVector(MVT VT, SelectionDAG &DAG, DebugLoc dl) {
2930 assert(VT.isVector() && "Expected a vector type");
2932 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2933 // type. This ensures they get CSE'd.
2934 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2936 if (VT.getSizeInBits() == 64) // MMX
2937 Vec = DAG.getBUILD_VECTOR(MVT::v2i32, dl, Cst, Cst);
2939 Vec = DAG.getBUILD_VECTOR(MVT::v4i32, dl, Cst, Cst, Cst, Cst);
2940 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
2944 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2945 /// that point to V2 points to its first element.
2946 static SDValue NormalizeMask(SDValue Mask, SelectionDAG &DAG) {
2947 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2949 bool Changed = false;
2950 SmallVector<SDValue, 8> MaskVec;
2951 unsigned NumElems = Mask.getNumOperands();
2952 for (unsigned i = 0; i != NumElems; ++i) {
2953 SDValue Arg = Mask.getOperand(i);
2954 if (Arg.getOpcode() != ISD::UNDEF) {
2955 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2956 if (Val > NumElems) {
2957 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2961 MaskVec.push_back(Arg);
2965 Mask = DAG.getBUILD_VECTOR(Mask.getValueType(), Mask.getDebugLoc(),
2966 &MaskVec[0], MaskVec.size());
2970 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2971 /// operation of specified width.
2972 static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG, DebugLoc dl) {
2973 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2974 MVT BaseVT = MaskVT.getVectorElementType();
2976 SmallVector<SDValue, 8> MaskVec;
2977 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2978 for (unsigned i = 1; i != NumElems; ++i)
2979 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2980 return DAG.getBUILD_VECTOR(MaskVT, dl, &MaskVec[0], MaskVec.size());
2983 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2984 /// of specified width.
2985 static SDValue getUnpacklMask(unsigned NumElems, SelectionDAG &DAG,
2987 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2988 MVT BaseVT = MaskVT.getVectorElementType();
2989 SmallVector<SDValue, 8> MaskVec;
2990 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2991 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2992 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2994 return DAG.getBUILD_VECTOR(MaskVT, dl, &MaskVec[0], MaskVec.size());
2997 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2998 /// of specified width.
2999 static SDValue getUnpackhMask(unsigned NumElems, SelectionDAG &DAG,
3001 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3002 MVT BaseVT = MaskVT.getVectorElementType();
3003 unsigned Half = NumElems/2;
3004 SmallVector<SDValue, 8> MaskVec;
3005 for (unsigned i = 0; i != Half; ++i) {
3006 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
3007 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
3009 return DAG.getBUILD_VECTOR(MaskVT, dl, &MaskVec[0], MaskVec.size());
3012 /// getSwapEltZeroMask - Returns a vector_shuffle mask for a shuffle that swaps
3013 /// element #0 of a vector with the specified index, leaving the rest of the
3014 /// elements in place.
3015 static SDValue getSwapEltZeroMask(unsigned NumElems, unsigned DestElt,
3016 SelectionDAG &DAG, DebugLoc dl) {
3017 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3018 MVT BaseVT = MaskVT.getVectorElementType();
3019 SmallVector<SDValue, 8> MaskVec;
3020 // Element #0 of the result gets the elt we are replacing.
3021 MaskVec.push_back(DAG.getConstant(DestElt, BaseVT));
3022 for (unsigned i = 1; i != NumElems; ++i)
3023 MaskVec.push_back(DAG.getConstant(i == DestElt ? 0 : i, BaseVT));
3024 return DAG.getBUILD_VECTOR(MaskVT, dl, &MaskVec[0], MaskVec.size());
3027 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3028 static SDValue PromoteSplat(SDValue Op, SelectionDAG &DAG, bool HasSSE2) {
3029 MVT PVT = HasSSE2 ? MVT::v4i32 : MVT::v4f32;
3030 MVT VT = Op.getValueType();
3033 SDValue V1 = Op.getOperand(0);
3034 SDValue Mask = Op.getOperand(2);
3035 unsigned MaskNumElems = Mask.getNumOperands();
3036 unsigned NumElems = MaskNumElems;
3037 DebugLoc dl = Op.getDebugLoc();
3038 // Special handling of v4f32 -> v4i32.
3039 if (VT != MVT::v4f32) {
3040 // Find which element we want to splat.
3041 SDNode* EltNoNode = getSplatMaskEltNo(Mask.getNode()).getNode();
3042 unsigned EltNo = cast<ConstantSDNode>(EltNoNode)->getZExtValue();
3043 // unpack elements to the correct location
3044 while (NumElems > 4) {
3045 if (EltNo < NumElems/2) {
3046 Mask = getUnpacklMask(MaskNumElems, DAG, dl);
3048 Mask = getUnpackhMask(MaskNumElems, DAG, dl);
3049 EltNo -= NumElems/2;
3051 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V1, Mask);
3054 SDValue Cst = DAG.getConstant(EltNo, MVT::i32);
3055 Mask = DAG.getBUILD_VECTOR(MVT::v4i32, dl, Cst, Cst, Cst, Cst);
3058 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3059 SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, PVT, V1,
3060 DAG.getUNDEF(PVT), Mask);
3061 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Shuffle);
3064 /// isVectorLoad - Returns true if the node is a vector load, a scalar
3065 /// load that's promoted to vector, or a load bitcasted.
3066 static bool isVectorLoad(SDValue Op) {
3067 assert(Op.getValueType().isVector() && "Expected a vector type");
3068 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR ||
3069 Op.getOpcode() == ISD::BIT_CONVERT) {
3070 return isa<LoadSDNode>(Op.getOperand(0));
3072 return isa<LoadSDNode>(Op);
3076 /// CanonicalizeMovddup - Cannonicalize movddup shuffle to v2f64.
3078 static SDValue CanonicalizeMovddup(SDValue Op, SDValue V1, SDValue Mask,
3079 SelectionDAG &DAG, bool HasSSE3) {
3080 // If we have sse3 and shuffle has more than one use or input is a load, then
3081 // use movddup. Otherwise, use movlhps.
3082 bool UseMovddup = HasSSE3 && (!Op.hasOneUse() || isVectorLoad(V1));
3083 MVT PVT = UseMovddup ? MVT::v2f64 : MVT::v4f32;
3084 MVT VT = Op.getValueType();
3087 DebugLoc dl = Op.getDebugLoc();
3088 unsigned NumElems = PVT.getVectorNumElements();
3089 if (NumElems == 2) {
3090 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3091 Mask = DAG.getBUILD_VECTOR(MVT::v2i32, dl, Cst, Cst);
3093 assert(NumElems == 4);
3094 SDValue Cst0 = DAG.getTargetConstant(0, MVT::i32);
3095 SDValue Cst1 = DAG.getTargetConstant(1, MVT::i32);
3096 Mask = DAG.getBUILD_VECTOR(MVT::v4i32, dl, Cst0, Cst1, Cst0, Cst1);
3099 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3100 SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, PVT, V1,
3101 DAG.getUNDEF(PVT), Mask);
3102 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Shuffle);
3105 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3106 /// vector of zero or undef vector. This produces a shuffle where the low
3107 /// element of V2 is swizzled into the zero/undef vector, landing at element
3108 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3109 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3110 bool isZero, bool HasSSE2,
3111 SelectionDAG &DAG) {
3112 DebugLoc dl = V2.getDebugLoc();
3113 MVT VT = V2.getValueType();
3115 ? getZeroVector(VT, HasSSE2, DAG, dl) : DAG.getUNDEF(VT);
3116 unsigned NumElems = V2.getValueType().getVectorNumElements();
3117 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3118 MVT EVT = MaskVT.getVectorElementType();
3119 SmallVector<SDValue, 16> MaskVec;
3120 for (unsigned i = 0; i != NumElems; ++i)
3121 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
3122 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
3124 MaskVec.push_back(DAG.getConstant(i, EVT));
3125 SDValue Mask = DAG.getBUILD_VECTOR(MaskVT, dl, &MaskVec[0], MaskVec.size());
3126 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, Mask);
3129 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3130 /// a shuffle that is zero.
3132 unsigned getNumOfConsecutiveZeros(SDValue Op, SDValue Mask,
3133 unsigned NumElems, bool Low,
3134 SelectionDAG &DAG) {
3135 unsigned NumZeros = 0;
3136 for (unsigned i = 0; i < NumElems; ++i) {
3137 unsigned Index = Low ? i : NumElems-i-1;
3138 SDValue Idx = Mask.getOperand(Index);
3139 if (Idx.getOpcode() == ISD::UNDEF) {
3143 SDValue Elt = DAG.getShuffleScalarElt(Op.getNode(), Index);
3144 if (Elt.getNode() && isZeroNode(Elt))
3152 /// isVectorShift - Returns true if the shuffle can be implemented as a
3153 /// logical left or right shift of a vector.
3154 static bool isVectorShift(SDValue Op, SDValue Mask, SelectionDAG &DAG,
3155 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3156 unsigned NumElems = Mask.getNumOperands();
3159 unsigned NumZeros= getNumOfConsecutiveZeros(Op, Mask, NumElems, true, DAG);
3162 NumZeros = getNumOfConsecutiveZeros(Op, Mask, NumElems, false, DAG);
3167 bool SeenV1 = false;
3168 bool SeenV2 = false;
3169 for (unsigned i = NumZeros; i < NumElems; ++i) {
3170 unsigned Val = isLeft ? (i - NumZeros) : i;
3171 SDValue Idx = Mask.getOperand(isLeft ? i : (i - NumZeros));
3172 if (Idx.getOpcode() == ISD::UNDEF)
3174 unsigned Index = cast<ConstantSDNode>(Idx)->getZExtValue();
3175 if (Index < NumElems)
3184 if (SeenV1 && SeenV2)
3187 ShVal = SeenV1 ? Op.getOperand(0) : Op.getOperand(1);
3193 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3195 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3196 unsigned NumNonZero, unsigned NumZero,
3197 SelectionDAG &DAG, TargetLowering &TLI) {
3201 DebugLoc dl = Op.getDebugLoc();
3204 for (unsigned i = 0; i < 16; ++i) {
3205 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3206 if (ThisIsNonZero && First) {
3208 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3210 V = DAG.getUNDEF(MVT::v8i16);
3215 SDValue ThisElt(0, 0), LastElt(0, 0);
3216 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3217 if (LastIsNonZero) {
3218 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3219 MVT::i16, Op.getOperand(i-1));
3221 if (ThisIsNonZero) {
3222 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3223 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3224 ThisElt, DAG.getConstant(8, MVT::i8));
3226 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3230 if (ThisElt.getNode())
3231 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3232 DAG.getIntPtrConstant(i/2));
3236 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3239 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3241 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3242 unsigned NumNonZero, unsigned NumZero,
3243 SelectionDAG &DAG, TargetLowering &TLI) {
3247 DebugLoc dl = Op.getDebugLoc();
3250 for (unsigned i = 0; i < 8; ++i) {
3251 bool isNonZero = (NonZeros & (1 << i)) != 0;
3255 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3257 V = DAG.getUNDEF(MVT::v8i16);
3260 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3261 MVT::v8i16, V, Op.getOperand(i),
3262 DAG.getIntPtrConstant(i));
3269 /// getVShift - Return a vector logical shift node.
3271 static SDValue getVShift(bool isLeft, MVT VT, SDValue SrcOp,
3272 unsigned NumBits, SelectionDAG &DAG,
3273 const TargetLowering &TLI, DebugLoc dl) {
3274 bool isMMX = VT.getSizeInBits() == 64;
3275 MVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3276 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3277 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3278 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3279 DAG.getNode(Opc, dl, ShVT, SrcOp,
3280 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3284 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3285 DebugLoc dl = Op.getDebugLoc();
3286 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3287 if (ISD::isBuildVectorAllZeros(Op.getNode())
3288 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3289 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3290 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3291 // eliminated on x86-32 hosts.
3292 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3295 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3296 return getOnesVector(Op.getValueType(), DAG, dl);
3297 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3300 MVT VT = Op.getValueType();
3301 MVT EVT = VT.getVectorElementType();
3302 unsigned EVTBits = EVT.getSizeInBits();
3304 unsigned NumElems = Op.getNumOperands();
3305 unsigned NumZero = 0;
3306 unsigned NumNonZero = 0;
3307 unsigned NonZeros = 0;
3308 bool IsAllConstants = true;
3309 SmallSet<SDValue, 8> Values;
3310 for (unsigned i = 0; i < NumElems; ++i) {
3311 SDValue Elt = Op.getOperand(i);
3312 if (Elt.getOpcode() == ISD::UNDEF)
3315 if (Elt.getOpcode() != ISD::Constant &&
3316 Elt.getOpcode() != ISD::ConstantFP)
3317 IsAllConstants = false;
3318 if (isZeroNode(Elt))
3321 NonZeros |= (1 << i);
3326 if (NumNonZero == 0) {
3327 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3328 return DAG.getUNDEF(VT);
3331 // Special case for single non-zero, non-undef, element.
3332 if (NumNonZero == 1 && NumElems <= 4) {
3333 unsigned Idx = CountTrailingZeros_32(NonZeros);
3334 SDValue Item = Op.getOperand(Idx);
3336 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3337 // the value are obviously zero, truncate the value to i32 and do the
3338 // insertion that way. Only do this if the value is non-constant or if the
3339 // value is a constant being inserted into element 0. It is cheaper to do
3340 // a constant pool load than it is to do a movd + shuffle.
3341 if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3342 (!IsAllConstants || Idx == 0)) {
3343 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3344 // Handle MMX and SSE both.
3345 MVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3346 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3348 // Truncate the value (which may itself be a constant) to i32, and
3349 // convert it to a vector with movd (S2V+shuffle to zero extend).
3350 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3351 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3352 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3353 Subtarget->hasSSE2(), DAG);
3355 // Now we have our 32-bit value zero extended in the low element of
3356 // a vector. If Idx != 0, swizzle it into place.
3359 Item, DAG.getUNDEF(Item.getValueType()),
3360 getSwapEltZeroMask(VecElts, Idx, DAG, dl)
3362 Item = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VecVT, Ops, 3);
3364 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3368 // If we have a constant or non-constant insertion into the low element of
3369 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3370 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3371 // depending on what the source datatype is. Because we can only get here
3372 // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3374 // Don't do this for i64 values on x86-32.
3375 (EVT != MVT::i64 || Subtarget->is64Bit())) {
3376 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3377 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3378 return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3379 Subtarget->hasSSE2(), DAG);
3382 // Is it a vector logical left shift?
3383 if (NumElems == 2 && Idx == 1 &&
3384 isZeroNode(Op.getOperand(0)) && !isZeroNode(Op.getOperand(1))) {
3385 unsigned NumBits = VT.getSizeInBits();
3386 return getVShift(true, VT,
3387 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3388 VT, Op.getOperand(1)),
3389 NumBits/2, DAG, *this, dl);
3392 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3395 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3396 // is a non-constant being inserted into an element other than the low one,
3397 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3398 // movd/movss) to move this into the low element, then shuffle it into
3400 if (EVTBits == 32) {
3401 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3403 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3404 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3405 Subtarget->hasSSE2(), DAG);
3406 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3407 MVT MaskEVT = MaskVT.getVectorElementType();
3408 SmallVector<SDValue, 8> MaskVec;
3409 for (unsigned i = 0; i < NumElems; i++)
3410 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3411 SDValue Mask = DAG.getBUILD_VECTOR(MaskVT, dl, &MaskVec[0], MaskVec.size());
3412 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, Item,
3413 DAG.getUNDEF(VT), Mask);
3417 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3418 if (Values.size() == 1)
3421 // A vector full of immediates; various special cases are already
3422 // handled, so this is best done with a single constant-pool load.
3426 // Let legalizer expand 2-wide build_vectors.
3427 if (EVTBits == 64) {
3428 if (NumNonZero == 1) {
3429 // One half is zero or undef.
3430 unsigned Idx = CountTrailingZeros_32(NonZeros);
3431 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3432 Op.getOperand(Idx));
3433 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3434 Subtarget->hasSSE2(), DAG);
3439 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3440 if (EVTBits == 8 && NumElems == 16) {
3441 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3443 if (V.getNode()) return V;
3446 if (EVTBits == 16 && NumElems == 8) {
3447 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3449 if (V.getNode()) return V;
3452 // If element VT is == 32 bits, turn it into a number of shuffles.
3453 SmallVector<SDValue, 8> V;
3455 if (NumElems == 4 && NumZero > 0) {
3456 for (unsigned i = 0; i < 4; ++i) {
3457 bool isZero = !(NonZeros & (1 << i));
3459 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3461 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3464 for (unsigned i = 0; i < 2; ++i) {
3465 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3468 V[i] = V[i*2]; // Must be a zero vector.
3471 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[i*2+1], V[i*2],
3472 getMOVLMask(NumElems, DAG, dl));
3475 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[i*2], V[i*2+1],
3476 getMOVLMask(NumElems, DAG, dl));
3479 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[i*2], V[i*2+1],
3480 getUnpacklMask(NumElems, DAG, dl));
3485 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3486 MVT EVT = MaskVT.getVectorElementType();
3487 SmallVector<SDValue, 8> MaskVec;
3488 bool Reverse = (NonZeros & 0x3) == 2;
3489 for (unsigned i = 0; i < 2; ++i)
3491 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3493 MaskVec.push_back(DAG.getConstant(i, EVT));
3494 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3495 for (unsigned i = 0; i < 2; ++i)
3497 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3499 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3500 SDValue ShufMask = DAG.getBUILD_VECTOR(MaskVT, dl,
3501 &MaskVec[0], MaskVec.size());
3502 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[0], V[1], ShufMask);
3505 if (Values.size() > 2) {
3506 // Expand into a number of unpckl*.
3508 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3509 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3510 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3511 SDValue UnpckMask = getUnpacklMask(NumElems, DAG, dl);
3512 for (unsigned i = 0; i < NumElems; ++i)
3513 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3515 while (NumElems != 0) {
3516 for (unsigned i = 0; i < NumElems; ++i)
3517 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V[i], V[i + NumElems],
3527 // v8i16 shuffles - Prefer shuffles in the following order:
3528 // 1. [all] pshuflw, pshufhw, optional move
3529 // 2. [ssse3] 1 x pshufb
3530 // 3. [ssse3] 2 x pshufb + 1 x por
3531 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
3533 SDValue LowerVECTOR_SHUFFLEv8i16(SDValue V1, SDValue V2,
3534 SDValue PermMask, SelectionDAG &DAG,
3535 X86TargetLowering &TLI, DebugLoc dl) {
3536 SmallVector<SDValue, 8> MaskElts(PermMask.getNode()->op_begin(),
3537 PermMask.getNode()->op_end());
3538 SmallVector<int, 8> MaskVals;
3540 // Determine if more than 1 of the words in each of the low and high quadwords
3541 // of the result come from the same quadword of one of the two inputs. Undef
3542 // mask values count as coming from any quadword, for better codegen.
3543 SmallVector<unsigned, 4> LoQuad(4);
3544 SmallVector<unsigned, 4> HiQuad(4);
3545 BitVector InputQuads(4);
3546 for (unsigned i = 0; i < 8; ++i) {
3547 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
3548 SDValue Elt = MaskElts[i];
3549 int EltIdx = Elt.getOpcode() == ISD::UNDEF ? -1 :
3550 cast<ConstantSDNode>(Elt)->getZExtValue();
3551 MaskVals.push_back(EltIdx);
3560 InputQuads.set(EltIdx / 4);
3563 int BestLoQuad = -1;
3564 unsigned MaxQuad = 1;
3565 for (unsigned i = 0; i < 4; ++i) {
3566 if (LoQuad[i] > MaxQuad) {
3568 MaxQuad = LoQuad[i];
3572 int BestHiQuad = -1;
3574 for (unsigned i = 0; i < 4; ++i) {
3575 if (HiQuad[i] > MaxQuad) {
3577 MaxQuad = HiQuad[i];
3581 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
3582 // of the two input vectors, shuffle them into one input vector so only a
3583 // single pshufb instruction is necessary. If There are more than 2 input
3584 // quads, disable the next transformation since it does not help SSSE3.
3585 bool V1Used = InputQuads[0] || InputQuads[1];
3586 bool V2Used = InputQuads[2] || InputQuads[3];
3587 if (TLI.getSubtarget()->hasSSSE3()) {
3588 if (InputQuads.count() == 2 && V1Used && V2Used) {
3589 BestLoQuad = InputQuads.find_first();
3590 BestHiQuad = InputQuads.find_next(BestLoQuad);
3592 if (InputQuads.count() > 2) {
3598 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
3599 // the shuffle mask. If a quad is scored as -1, that means that it contains
3600 // words from all 4 input quadwords.
3602 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
3603 SmallVector<SDValue,8> MaskV;
3604 MaskV.push_back(DAG.getConstant(BestLoQuad < 0 ? 0 : BestLoQuad, MVT::i64));
3605 MaskV.push_back(DAG.getConstant(BestHiQuad < 0 ? 1 : BestHiQuad, MVT::i64));
3606 SDValue Mask = DAG.getBUILD_VECTOR(MVT::v2i64, dl, &MaskV[0], 2);
3608 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v2i64,
3609 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
3610 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), Mask);
3611 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
3613 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
3614 // source words for the shuffle, to aid later transformations.
3615 bool AllWordsInNewV = true;
3616 for (unsigned i = 0; i != 8; ++i) {
3617 int idx = MaskVals[i];
3618 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
3620 AllWordsInNewV = false;
3624 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
3625 if (AllWordsInNewV) {
3626 for (int i = 0; i != 8; ++i) {
3627 int idx = MaskVals[i];
3630 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
3631 if ((idx != i) && idx < 4)
3633 if ((idx != i) && idx > 3)
3642 // If we've eliminated the use of V2, and the new mask is a pshuflw or
3643 // pshufhw, that's as cheap as it gets. Return the new shuffle.
3644 if (pshufhw || pshuflw) {
3646 for (unsigned i = 0; i != 8; ++i)
3647 MaskV.push_back((MaskVals[i] < 0) ? DAG.getUNDEF(MVT::i16)
3648 : DAG.getConstant(MaskVals[i],
3650 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v8i16, NewV,
3651 DAG.getUNDEF(MVT::v8i16),
3652 DAG.getBUILD_VECTOR(MVT::v8i16, dl, &MaskV[0], 8));
3656 // If we have SSSE3, and all words of the result are from 1 input vector,
3657 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
3658 // is present, fall back to case 4.
3659 if (TLI.getSubtarget()->hasSSSE3()) {
3660 SmallVector<SDValue,16> pshufbMask;
3662 // If we have elements from both input vectors, set the high bit of the
3663 // shuffle mask element to zero out elements that come from V2 in the V1
3664 // mask, and elements that come from V1 in the V2 mask, so that the two
3665 // results can be OR'd together.
3666 bool TwoInputs = V1Used && V2Used;
3667 for (unsigned i = 0; i != 8; ++i) {
3668 int EltIdx = MaskVals[i] * 2;
3669 if (TwoInputs && (EltIdx >= 16)) {
3670 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3671 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3674 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3675 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
3677 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
3678 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3679 DAG.getBUILD_VECTOR(MVT::v16i8, dl, &pshufbMask[0], 16));
3681 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3683 // Calculate the shuffle mask for the second input, shuffle it, and
3684 // OR it with the first shuffled input.
3686 for (unsigned i = 0; i != 8; ++i) {
3687 int EltIdx = MaskVals[i] * 2;
3689 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3690 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3693 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3694 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
3696 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
3697 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3698 DAG.getBUILD_VECTOR(MVT::v16i8, dl, &pshufbMask[0], 16));
3699 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3700 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3703 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
3704 // and update MaskVals with new element order.
3705 BitVector InOrder(8);
3706 if (BestLoQuad >= 0) {
3707 SmallVector<SDValue, 8> MaskV;
3708 for (int i = 0; i != 4; ++i) {
3709 int idx = MaskVals[i];
3711 MaskV.push_back(DAG.getUNDEF(MVT::i16));
3713 } else if ((idx / 4) == BestLoQuad) {
3714 MaskV.push_back(DAG.getConstant(idx & 3, MVT::i16));
3717 MaskV.push_back(DAG.getUNDEF(MVT::i16));
3720 for (unsigned i = 4; i != 8; ++i)
3721 MaskV.push_back(DAG.getConstant(i, MVT::i16));
3722 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v8i16, NewV,
3723 DAG.getUNDEF(MVT::v8i16),
3724 DAG.getBUILD_VECTOR(MVT::v8i16, dl, &MaskV[0], 8));
3727 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
3728 // and update MaskVals with the new element order.
3729 if (BestHiQuad >= 0) {
3730 SmallVector<SDValue, 8> MaskV;
3731 for (unsigned i = 0; i != 4; ++i)
3732 MaskV.push_back(DAG.getConstant(i, MVT::i16));
3733 for (unsigned i = 4; i != 8; ++i) {
3734 int idx = MaskVals[i];
3736 MaskV.push_back(DAG.getUNDEF(MVT::i16));
3738 } else if ((idx / 4) == BestHiQuad) {
3739 MaskV.push_back(DAG.getConstant((idx & 3) + 4, MVT::i16));
3742 MaskV.push_back(DAG.getUNDEF(MVT::i16));
3745 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v8i16, NewV,
3746 DAG.getUNDEF(MVT::v8i16),
3747 DAG.getBUILD_VECTOR(MVT::v8i16, dl, &MaskV[0], 8));
3750 // In case BestHi & BestLo were both -1, which means each quadword has a word
3751 // from each of the four input quadwords, calculate the InOrder bitvector now
3752 // before falling through to the insert/extract cleanup.
3753 if (BestLoQuad == -1 && BestHiQuad == -1) {
3755 for (int i = 0; i != 8; ++i)
3756 if (MaskVals[i] < 0 || MaskVals[i] == i)
3760 // The other elements are put in the right place using pextrw and pinsrw.
3761 for (unsigned i = 0; i != 8; ++i) {
3764 int EltIdx = MaskVals[i];
3767 SDValue ExtOp = (EltIdx < 8)
3768 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
3769 DAG.getIntPtrConstant(EltIdx))
3770 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
3771 DAG.getIntPtrConstant(EltIdx - 8));
3772 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3773 DAG.getIntPtrConstant(i));
3778 // v16i8 shuffles - Prefer shuffles in the following order:
3779 // 1. [ssse3] 1 x pshufb
3780 // 2. [ssse3] 2 x pshufb + 1 x por
3781 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
3783 SDValue LowerVECTOR_SHUFFLEv16i8(SDValue V1, SDValue V2,
3784 SDValue PermMask, SelectionDAG &DAG,
3785 X86TargetLowering &TLI, DebugLoc dl) {
3786 SmallVector<SDValue, 16> MaskElts(PermMask.getNode()->op_begin(),
3787 PermMask.getNode()->op_end());
3788 SmallVector<int, 16> MaskVals;
3790 // If we have SSSE3, case 1 is generated when all result bytes come from
3791 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
3792 // present, fall back to case 3.
3793 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
3796 for (unsigned i = 0; i < 16; ++i) {
3797 SDValue Elt = MaskElts[i];
3798 int EltIdx = Elt.getOpcode() == ISD::UNDEF ? -1 :
3799 cast<ConstantSDNode>(Elt)->getZExtValue();
3800 MaskVals.push_back(EltIdx);
3809 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
3810 if (TLI.getSubtarget()->hasSSSE3()) {
3811 SmallVector<SDValue,16> pshufbMask;
3813 // If all result elements are from one input vector, then only translate
3814 // undef mask values to 0x80 (zero out result) in the pshufb mask.
3816 // Otherwise, we have elements from both input vectors, and must zero out
3817 // elements that come from V2 in the first mask, and V1 in the second mask
3818 // so that we can OR them together.
3819 bool TwoInputs = !(V1Only || V2Only);
3820 for (unsigned i = 0; i != 16; ++i) {
3821 int EltIdx = MaskVals[i];
3822 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
3823 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3826 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3828 // If all the elements are from V2, assign it to V1 and return after
3829 // building the first pshufb.
3832 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3833 DAG.getBUILD_VECTOR(MVT::v16i8, dl, &pshufbMask[0], 16));
3837 // Calculate the shuffle mask for the second input, shuffle it, and
3838 // OR it with the first shuffled input.
3840 for (unsigned i = 0; i != 16; ++i) {
3841 int EltIdx = MaskVals[i];
3843 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3846 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3848 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3849 DAG.getBUILD_VECTOR(MVT::v16i8, dl, &pshufbMask[0], 16));
3850 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3853 // No SSSE3 - Calculate in place words and then fix all out of place words
3854 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
3855 // the 16 different words that comprise the two doublequadword input vectors.
3856 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3857 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
3858 SDValue NewV = V2Only ? V2 : V1;
3859 for (int i = 0; i != 8; ++i) {
3860 int Elt0 = MaskVals[i*2];
3861 int Elt1 = MaskVals[i*2+1];
3863 // This word of the result is all undef, skip it.
3864 if (Elt0 < 0 && Elt1 < 0)
3867 // This word of the result is already in the correct place, skip it.
3868 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
3870 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
3873 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
3874 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
3877 // If Elt1 is defined, extract it from the appropriate source. If the
3878 // source byte is not also odd, shift the extracted word left 8 bits.
3880 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3881 DAG.getIntPtrConstant(Elt1 / 2));
3882 if ((Elt1 & 1) == 0)
3883 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
3884 DAG.getConstant(8, TLI.getShiftAmountTy()));
3886 // If Elt0 is defined, extract it from the appropriate source. If the
3887 // source byte is not also even, shift the extracted word right 8 bits. If
3888 // Elt1 was also defined, OR the extracted values together before
3889 // inserting them in the result.
3891 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
3892 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
3893 if ((Elt0 & 1) != 0)
3894 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
3895 DAG.getConstant(8, TLI.getShiftAmountTy()));
3896 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
3899 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3900 DAG.getIntPtrConstant(i));
3902 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
3905 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3906 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3907 /// done when every pair / quad of shuffle mask elements point to elements in
3908 /// the right sequence. e.g.
3909 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3911 SDValue RewriteAsNarrowerShuffle(SDValue V1, SDValue V2,
3913 SDValue PermMask, SelectionDAG &DAG,
3914 TargetLowering &TLI, DebugLoc dl) {
3915 unsigned NumElems = PermMask.getNumOperands();
3916 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3917 MVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3918 MVT MaskEltVT = MaskVT.getVectorElementType();
3920 switch (VT.getSimpleVT()) {
3921 default: assert(false && "Unexpected!");
3922 case MVT::v4f32: NewVT = MVT::v2f64; break;
3923 case MVT::v4i32: NewVT = MVT::v2i64; break;
3924 case MVT::v8i16: NewVT = MVT::v4i32; break;
3925 case MVT::v16i8: NewVT = MVT::v4i32; break;
3928 if (NewWidth == 2) {
3934 unsigned Scale = NumElems / NewWidth;
3935 SmallVector<SDValue, 8> MaskVec;
3936 for (unsigned i = 0; i < NumElems; i += Scale) {
3937 unsigned StartIdx = ~0U;
3938 for (unsigned j = 0; j < Scale; ++j) {
3939 SDValue Elt = PermMask.getOperand(i+j);
3940 if (Elt.getOpcode() == ISD::UNDEF)
3942 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3943 if (StartIdx == ~0U)
3944 StartIdx = EltIdx - (EltIdx % Scale);
3945 if (EltIdx != StartIdx + j)
3948 if (StartIdx == ~0U)
3949 MaskVec.push_back(DAG.getUNDEF(MaskEltVT));
3951 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MaskEltVT));
3954 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
3955 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
3956 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, NewVT, V1, V2,
3957 DAG.getBUILD_VECTOR(MaskVT, dl, &MaskVec[0], MaskVec.size()));
3960 /// getVZextMovL - Return a zero-extending vector move low node.
3962 static SDValue getVZextMovL(MVT VT, MVT OpVT,
3963 SDValue SrcOp, SelectionDAG &DAG,
3964 const X86Subtarget *Subtarget, DebugLoc dl) {
3965 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3966 LoadSDNode *LD = NULL;
3967 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
3968 LD = dyn_cast<LoadSDNode>(SrcOp);
3970 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3972 MVT EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3973 if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
3974 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3975 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3976 SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
3978 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3979 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3980 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3981 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3989 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3990 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
3991 DAG.getNode(ISD::BIT_CONVERT, dl,
3995 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
3998 LowerVECTOR_SHUFFLE_4wide(SDValue V1, SDValue V2,
3999 SDValue PermMask, MVT VT, SelectionDAG &DAG,
4001 MVT MaskVT = PermMask.getValueType();
4002 MVT MaskEVT = MaskVT.getVectorElementType();
4003 SmallVector<std::pair<int, int>, 8> Locs;
4005 SmallVector<SDValue, 8> Mask1(4, DAG.getUNDEF(MaskEVT));
4008 for (unsigned i = 0; i != 4; ++i) {
4009 SDValue Elt = PermMask.getOperand(i);
4010 if (Elt.getOpcode() == ISD::UNDEF) {
4011 Locs[i] = std::make_pair(-1, -1);
4013 unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
4014 assert(Val < 8 && "Invalid VECTOR_SHUFFLE index!");
4016 Locs[i] = std::make_pair(0, NumLo);
4020 Locs[i] = std::make_pair(1, NumHi);
4022 Mask1[2+NumHi] = Elt;
4028 if (NumLo <= 2 && NumHi <= 2) {
4029 // If no more than two elements come from either vector. This can be
4030 // implemented with two shuffles. First shuffle gather the elements.
4031 // The second shuffle, which takes the first shuffle as both of its
4032 // vector operands, put the elements into the right order.
4033 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
4034 DAG.getBUILD_VECTOR(MaskVT, dl, &Mask1[0], Mask1.size()));
4036 SmallVector<SDValue, 8> Mask2(4, DAG.getUNDEF(MaskEVT));
4037 for (unsigned i = 0; i != 4; ++i) {
4038 if (Locs[i].first == -1)
4041 unsigned Idx = (i < 2) ? 0 : 4;
4042 Idx += Locs[i].first * 2 + Locs[i].second;
4043 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
4047 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V1,
4048 DAG.getBUILD_VECTOR(MaskVT, dl,
4049 &Mask2[0], Mask2.size()));
4050 } else if (NumLo == 3 || NumHi == 3) {
4051 // Otherwise, we must have three elements from one vector, call it X, and
4052 // one element from the other, call it Y. First, use a shufps to build an
4053 // intermediate vector with the one element from Y and the element from X
4054 // that will be in the same half in the final destination (the indexes don't
4055 // matter). Then, use a shufps to build the final vector, taking the half
4056 // containing the element from Y from the intermediate, and the other half
4059 // Normalize it so the 3 elements come from V1.
4060 PermMask = CommuteVectorShuffleMask(PermMask, DAG, dl);
4064 // Find the element from V2.
4066 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4067 SDValue Elt = PermMask.getOperand(HiIndex);
4068 if (Elt.getOpcode() == ISD::UNDEF)
4070 unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
4075 Mask1[0] = PermMask.getOperand(HiIndex);
4076 Mask1[1] = DAG.getUNDEF(MaskEVT);
4077 Mask1[2] = PermMask.getOperand(HiIndex^1);
4078 Mask1[3] = DAG.getUNDEF(MaskEVT);
4079 V2 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
4080 DAG.getBUILD_VECTOR(MaskVT, dl, &Mask1[0], 4));
4083 Mask1[0] = PermMask.getOperand(0);
4084 Mask1[1] = PermMask.getOperand(1);
4085 Mask1[2] = DAG.getConstant(HiIndex & 1 ? 6 : 4, MaskEVT);
4086 Mask1[3] = DAG.getConstant(HiIndex & 1 ? 4 : 6, MaskEVT);
4087 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
4088 DAG.getBUILD_VECTOR(MaskVT, dl, &Mask1[0], 4));
4090 Mask1[0] = DAG.getConstant(HiIndex & 1 ? 2 : 0, MaskEVT);
4091 Mask1[1] = DAG.getConstant(HiIndex & 1 ? 0 : 2, MaskEVT);
4092 Mask1[2] = PermMask.getOperand(2);
4093 Mask1[3] = PermMask.getOperand(3);
4094 if (Mask1[2].getOpcode() != ISD::UNDEF)
4096 DAG.getConstant(cast<ConstantSDNode>(Mask1[2])->getZExtValue()+4,
4098 if (Mask1[3].getOpcode() != ISD::UNDEF)
4100 DAG.getConstant(cast<ConstantSDNode>(Mask1[3])->getZExtValue()+4,
4102 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V2, V1,
4103 DAG.getBUILD_VECTOR(MaskVT, dl, &Mask1[0], 4));
4107 // Break it into (shuffle shuffle_hi, shuffle_lo).
4109 SmallVector<SDValue,8> LoMask(4, DAG.getUNDEF(MaskEVT));
4110 SmallVector<SDValue,8> HiMask(4, DAG.getUNDEF(MaskEVT));
4111 SmallVector<SDValue,8> *MaskPtr = &LoMask;
4112 unsigned MaskIdx = 0;
4115 for (unsigned i = 0; i != 4; ++i) {
4122 SDValue Elt = PermMask.getOperand(i);
4123 if (Elt.getOpcode() == ISD::UNDEF) {
4124 Locs[i] = std::make_pair(-1, -1);
4125 } else if (cast<ConstantSDNode>(Elt)->getZExtValue() < 4) {
4126 Locs[i] = std::make_pair(MaskIdx, LoIdx);
4127 (*MaskPtr)[LoIdx] = Elt;
4130 Locs[i] = std::make_pair(MaskIdx, HiIdx);
4131 (*MaskPtr)[HiIdx] = Elt;
4136 SDValue LoShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
4137 DAG.getBUILD_VECTOR(MaskVT, dl,
4138 &LoMask[0], LoMask.size()));
4139 SDValue HiShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2,
4140 DAG.getBUILD_VECTOR(MaskVT, dl,
4141 &HiMask[0], HiMask.size()));
4142 SmallVector<SDValue, 8> MaskOps;
4143 for (unsigned i = 0; i != 4; ++i) {
4144 if (Locs[i].first == -1) {
4145 MaskOps.push_back(DAG.getUNDEF(MaskEVT));
4147 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4148 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
4151 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, LoShuffle, HiShuffle,
4152 DAG.getBUILD_VECTOR(MaskVT, dl, &MaskOps[0], MaskOps.size()));
4156 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4157 SDValue V1 = Op.getOperand(0);
4158 SDValue V2 = Op.getOperand(1);
4159 SDValue PermMask = Op.getOperand(2);
4160 MVT VT = Op.getValueType();
4161 DebugLoc dl = Op.getDebugLoc();
4162 unsigned NumElems = PermMask.getNumOperands();
4163 bool isMMX = VT.getSizeInBits() == 64;
4164 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4165 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4166 bool V1IsSplat = false;
4167 bool V2IsSplat = false;
4169 // FIXME: Check for legal shuffle and return?
4171 if (isUndefShuffle(Op.getNode()))
4172 return DAG.getUNDEF(VT);
4174 if (isZeroShuffle(Op.getNode()))
4175 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4177 if (isIdentityMask(PermMask.getNode()))
4179 else if (isIdentityMask(PermMask.getNode(), true))
4182 // Canonicalize movddup shuffles.
4183 if (V2IsUndef && Subtarget->hasSSE2() &&
4184 VT.getSizeInBits() == 128 &&
4185 X86::isMOVDDUPMask(PermMask.getNode()))
4186 return CanonicalizeMovddup(Op, V1, PermMask, DAG, Subtarget->hasSSE3());
4188 if (isSplatMask(PermMask.getNode())) {
4189 if (isMMX || NumElems < 4) return Op;
4190 // Promote it to a v4{if}32 splat.
4191 return PromoteSplat(Op, DAG, Subtarget->hasSSE2());
4194 // If the shuffle can be profitably rewritten as a narrower shuffle, then
4196 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4197 SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG,
4199 if (NewOp.getNode())
4200 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4201 LowerVECTOR_SHUFFLE(NewOp, DAG));
4202 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4203 // FIXME: Figure out a cleaner way to do this.
4204 // Try to make use of movq to zero out the top part.
4205 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4206 SDValue NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
4208 if (NewOp.getNode()) {
4209 SDValue NewV1 = NewOp.getOperand(0);
4210 SDValue NewV2 = NewOp.getOperand(1);
4211 SDValue NewMask = NewOp.getOperand(2);
4212 if (isCommutedMOVL(NewMask.getNode(), true, false)) {
4213 NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
4214 return getVZextMovL(VT, NewOp.getValueType(), NewV2, DAG, Subtarget,
4218 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4219 SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
4221 if (NewOp.getNode() && X86::isMOVLMask(NewOp.getOperand(2).getNode()))
4222 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4223 DAG, Subtarget, dl);
4227 // Check if this can be converted into a logical shift.
4228 bool isLeft = false;
4231 bool isShift = isVectorShift(Op, PermMask, DAG, isLeft, ShVal, ShAmt);
4232 if (isShift && ShVal.hasOneUse()) {
4233 // If the shifted value has multiple uses, it may be cheaper to use
4234 // v_set0 + movlhps or movhlps, etc.
4235 MVT EVT = VT.getVectorElementType();
4236 ShAmt *= EVT.getSizeInBits();
4237 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4240 if (X86::isMOVLMask(PermMask.getNode())) {
4243 if (ISD::isBuildVectorAllZeros(V1.getNode()))
4244 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4249 if (!isMMX && (X86::isMOVSHDUPMask(PermMask.getNode()) ||
4250 X86::isMOVSLDUPMask(PermMask.getNode()) ||
4251 X86::isMOVHLPSMask(PermMask.getNode()) ||
4252 X86::isMOVHPMask(PermMask.getNode()) ||
4253 X86::isMOVLPMask(PermMask.getNode())))
4256 if (ShouldXformToMOVHLPS(PermMask.getNode()) ||
4257 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), PermMask.getNode()))
4258 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4261 // No better options. Use a vshl / vsrl.
4262 MVT EVT = VT.getVectorElementType();
4263 ShAmt *= EVT.getSizeInBits();
4264 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4267 bool Commuted = false;
4268 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4269 // 1,1,1,1 -> v8i16 though.
4270 V1IsSplat = isSplatVector(V1.getNode());
4271 V2IsSplat = isSplatVector(V2.getNode());
4273 // Canonicalize the splat or undef, if present, to be on the RHS.
4274 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4275 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4276 std::swap(V1IsSplat, V2IsSplat);
4277 std::swap(V1IsUndef, V2IsUndef);
4281 // FIXME: Figure out a cleaner way to do this.
4282 if (isCommutedMOVL(PermMask.getNode(), V2IsSplat, V2IsUndef)) {
4283 if (V2IsUndef) return V1;
4284 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4286 // V2 is a splat, so the mask may be malformed. That is, it may point
4287 // to any V2 element. The instruction selectior won't like this. Get
4288 // a corrected mask and commute to form a proper MOVS{S|D}.
4289 SDValue NewMask = getMOVLMask(NumElems, DAG, dl);
4290 if (NewMask.getNode() != PermMask.getNode())
4291 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, NewMask);
4296 if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
4297 X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
4298 X86::isUNPCKLMask(PermMask.getNode()) ||
4299 X86::isUNPCKHMask(PermMask.getNode()))
4303 // Normalize mask so all entries that point to V2 points to its first
4304 // element then try to match unpck{h|l} again. If match, return a
4305 // new vector_shuffle with the corrected mask.
4306 SDValue NewMask = NormalizeMask(PermMask, DAG);
4307 if (NewMask.getNode() != PermMask.getNode()) {
4308 if (X86::isUNPCKLMask(NewMask.getNode(), true)) {
4309 SDValue NewMask = getUnpacklMask(NumElems, DAG, dl);
4310 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, NewMask);
4311 } else if (X86::isUNPCKHMask(NewMask.getNode(), true)) {
4312 SDValue NewMask = getUnpackhMask(NumElems, DAG, dl);
4313 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1, V2, NewMask);
4318 // Normalize the node to match x86 shuffle ops if needed
4319 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.getNode()))
4320 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4323 // Commute is back and try unpck* again.
4324 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4325 if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
4326 X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
4327 X86::isUNPCKLMask(PermMask.getNode()) ||
4328 X86::isUNPCKHMask(PermMask.getNode()))
4332 // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4333 // Try PSHUF* first, then SHUFP*.
4334 // MMX doesn't have PSHUFD but it does have PSHUFW. While it's theoretically
4335 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
4336 if (isMMX && NumElems == 4 && X86::isPSHUFDMask(PermMask.getNode())) {
4337 if (V2.getOpcode() != ISD::UNDEF)
4338 return DAG.getNode(ISD::VECTOR_SHUFFLE, dl, VT, V1,
4339 DAG.getUNDEF(VT), PermMask);
4344 if (Subtarget->hasSSE2() &&
4345 (X86::isPSHUFDMask(PermMask.getNode()) ||
4346 X86::isPSHUFHWMask(PermMask.getNode()) ||
4347 X86::isPSHUFLWMask(PermMask.getNode()))) {
4349 if (VT == MVT::v4f32) {
4351 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, RVT,
4352 DAG.getNode(ISD::BIT_CONVERT, dl, RVT, V1),
4353 DAG.getUNDEF(RVT), PermMask);
4354 } else if (V2.getOpcode() != ISD::UNDEF)
4355 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, RVT, V1,
4356 DAG.getUNDEF(RVT), PermMask);
4358 Op = DAG.getNode(ISD::BIT_CONVERT, dl, VT, Op);
4362 // Binary or unary shufps.
4363 if (X86::isSHUFPMask(PermMask.getNode()) ||
4364 (V2.getOpcode() == ISD::UNDEF && X86::isPSHUFDMask(PermMask.getNode())))
4368 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4369 if (VT == MVT::v8i16) {
4370 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this, dl);
4371 if (NewOp.getNode())
4375 if (VT == MVT::v16i8) {
4376 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(V1, V2, PermMask, DAG, *this, dl);
4377 if (NewOp.getNode())
4381 // Handle all 4 wide cases with a number of shuffles except for MMX.
4382 if (NumElems == 4 && !isMMX)
4383 return LowerVECTOR_SHUFFLE_4wide(V1, V2, PermMask, VT, DAG, dl);
4389 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4390 SelectionDAG &DAG) {
4391 MVT VT = Op.getValueType();
4392 DebugLoc dl = Op.getDebugLoc();
4393 if (VT.getSizeInBits() == 8) {
4394 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4395 Op.getOperand(0), Op.getOperand(1));
4396 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4397 DAG.getValueType(VT));
4398 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4399 } else if (VT.getSizeInBits() == 16) {
4400 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4401 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4403 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4404 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4405 DAG.getNode(ISD::BIT_CONVERT, dl,
4409 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4410 Op.getOperand(0), Op.getOperand(1));
4411 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4412 DAG.getValueType(VT));
4413 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4414 } else if (VT == MVT::f32) {
4415 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4416 // the result back to FR32 register. It's only worth matching if the
4417 // result has a single use which is a store or a bitcast to i32. And in
4418 // the case of a store, it's not worth it if the index is a constant 0,
4419 // because a MOVSSmr can be used instead, which is smaller and faster.
4420 if (!Op.hasOneUse())
4422 SDNode *User = *Op.getNode()->use_begin();
4423 if ((User->getOpcode() != ISD::STORE ||
4424 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4425 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4426 (User->getOpcode() != ISD::BIT_CONVERT ||
4427 User->getValueType(0) != MVT::i32))
4429 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4430 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4433 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4434 } else if (VT == MVT::i32) {
4435 // ExtractPS works with constant index.
4436 if (isa<ConstantSDNode>(Op.getOperand(1)))
4444 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4445 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4448 if (Subtarget->hasSSE41()) {
4449 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4454 MVT VT = Op.getValueType();
4455 DebugLoc dl = Op.getDebugLoc();
4456 // TODO: handle v16i8.
4457 if (VT.getSizeInBits() == 16) {
4458 SDValue Vec = Op.getOperand(0);
4459 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4461 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4462 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4463 DAG.getNode(ISD::BIT_CONVERT, dl,
4466 // Transform it so it match pextrw which produces a 32-bit result.
4467 MVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT()+1);
4468 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EVT,
4469 Op.getOperand(0), Op.getOperand(1));
4470 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EVT, Extract,
4471 DAG.getValueType(VT));
4472 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4473 } else if (VT.getSizeInBits() == 32) {
4474 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4477 // SHUFPS the element to the lowest double word, then movss.
4478 MVT MaskVT = MVT::getIntVectorWithNumElements(4);
4479 SmallVector<SDValue, 8> IdxVec;
4481 push_back(DAG.getConstant(Idx, MaskVT.getVectorElementType()));
4483 push_back(DAG.getUNDEF(MaskVT.getVectorElementType()));
4485 push_back(DAG.getUNDEF(MaskVT.getVectorElementType()));
4487 push_back(DAG.getUNDEF(MaskVT.getVectorElementType()));
4488 SDValue Mask = DAG.getBUILD_VECTOR(MaskVT, dl, &IdxVec[0], IdxVec.size());
4489 SDValue Vec = Op.getOperand(0);
4490 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, Vec.getValueType(),
4491 Vec, DAG.getUNDEF(Vec.getValueType()), Mask);
4492 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4493 DAG.getIntPtrConstant(0));
4494 } else if (VT.getSizeInBits() == 64) {
4495 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4496 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4497 // to match extract_elt for f64.
4498 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4502 // UNPCKHPD the element to the lowest double word, then movsd.
4503 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4504 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4505 MVT MaskVT = MVT::getIntVectorWithNumElements(2);
4506 SmallVector<SDValue, 8> IdxVec;
4507 IdxVec.push_back(DAG.getConstant(1, MaskVT.getVectorElementType()));
4509 push_back(DAG.getUNDEF(MaskVT.getVectorElementType()));
4510 SDValue Mask = DAG.getBUILD_VECTOR(MaskVT, dl, &IdxVec[0], IdxVec.size());
4511 SDValue Vec = Op.getOperand(0);
4512 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, Vec.getValueType(),
4513 Vec, DAG.getUNDEF(Vec.getValueType()),
4515 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4516 DAG.getIntPtrConstant(0));
4523 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4524 MVT VT = Op.getValueType();
4525 MVT EVT = VT.getVectorElementType();
4526 DebugLoc dl = Op.getDebugLoc();
4528 SDValue N0 = Op.getOperand(0);
4529 SDValue N1 = Op.getOperand(1);
4530 SDValue N2 = Op.getOperand(2);
4532 if ((EVT.getSizeInBits() == 8 || EVT.getSizeInBits() == 16) &&
4533 isa<ConstantSDNode>(N2)) {
4534 unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4536 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4538 if (N1.getValueType() != MVT::i32)
4539 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4540 if (N2.getValueType() != MVT::i32)
4541 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4542 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4543 } else if (EVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4544 // Bits [7:6] of the constant are the source select. This will always be
4545 // zero here. The DAG Combiner may combine an extract_elt index into these
4546 // bits. For example (insert (extract, 3), 2) could be matched by putting
4547 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4548 // Bits [5:4] of the constant are the destination select. This is the
4549 // value of the incoming immediate.
4550 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4551 // combine either bitwise AND or insert of float 0.0 to set these bits.
4552 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4553 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4554 } else if (EVT == MVT::i32) {
4555 // InsertPS works with constant index.
4556 if (isa<ConstantSDNode>(N2))
4563 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4564 MVT VT = Op.getValueType();
4565 MVT EVT = VT.getVectorElementType();
4567 if (Subtarget->hasSSE41())
4568 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4573 DebugLoc dl = Op.getDebugLoc();
4574 SDValue N0 = Op.getOperand(0);
4575 SDValue N1 = Op.getOperand(1);
4576 SDValue N2 = Op.getOperand(2);
4578 if (EVT.getSizeInBits() == 16) {
4579 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4580 // as its second argument.
4581 if (N1.getValueType() != MVT::i32)
4582 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4583 if (N2.getValueType() != MVT::i32)
4584 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4585 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
4591 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4592 DebugLoc dl = Op.getDebugLoc();
4593 if (Op.getValueType() == MVT::v2f32)
4594 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4595 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4596 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4597 Op.getOperand(0))));
4599 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4600 MVT VT = MVT::v2i32;
4601 switch (Op.getValueType().getSimpleVT()) {
4608 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4609 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4612 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4613 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4614 // one of the above mentioned nodes. It has to be wrapped because otherwise
4615 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4616 // be used to form addressing mode. These wrapped nodes will be selected
4619 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4620 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4621 // FIXME there isn't really any debug info here, should come from the parent
4622 DebugLoc dl = CP->getDebugLoc();
4623 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(),
4625 CP->getAlignment());
4626 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4627 // With PIC, the address is actually $g + Offset.
4628 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4629 !Subtarget->isPICStyleRIPRel()) {
4630 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4631 DAG.getNode(X86ISD::GlobalBaseReg,
4632 DebugLoc::getUnknownLoc(),
4641 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
4643 SelectionDAG &DAG) const {
4644 bool IsPic = getTargetMachine().getRelocationModel() == Reloc::PIC_;
4645 bool ExtraLoadRequired =
4646 Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false);
4648 // Create the TargetGlobalAddress node, folding in the constant
4649 // offset if it is legal.
4651 if (!IsPic && !ExtraLoadRequired && isInt32(Offset)) {
4652 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4655 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0);
4656 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4658 // With PIC, the address is actually $g + Offset.
4659 if (IsPic && !Subtarget->isPICStyleRIPRel()) {
4660 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4661 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4665 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4666 // load the value at address GV, not the value of GV itself. This means that
4667 // the GlobalAddress must be in the base or index register of the address, not
4668 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4669 // The same applies for external symbols during PIC codegen
4670 if (ExtraLoadRequired)
4671 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
4672 PseudoSourceValue::getGOT(), 0);
4674 // If there was a non-zero offset that we didn't fold, create an explicit
4677 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
4678 DAG.getConstant(Offset, getPointerTy()));
4684 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4685 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4686 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4687 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
4690 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4692 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4695 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
4696 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
4697 DAG.getNode(X86ISD::GlobalBaseReg,
4698 DebugLoc::getUnknownLoc(),
4700 InFlag = Chain.getValue(1);
4702 // emit leal symbol@TLSGD(,%ebx,1), %eax
4703 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4704 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4705 GA->getValueType(0),
4707 SDValue Ops[] = { Chain, TGA, InFlag };
4708 SDValue Result = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
4709 InFlag = Result.getValue(2);
4710 Chain = Result.getValue(1);
4712 // call ___tls_get_addr. This function receives its argument in
4713 // the register EAX.
4714 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Result, InFlag);
4715 InFlag = Chain.getValue(1);
4717 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4718 SDValue Ops1[] = { Chain,
4719 DAG.getTargetExternalSymbol("___tls_get_addr",
4721 DAG.getRegister(X86::EAX, PtrVT),
4722 DAG.getRegister(X86::EBX, PtrVT),
4724 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops1, 5);
4725 InFlag = Chain.getValue(1);
4727 return DAG.getCopyFromReg(Chain, dl, X86::EAX, PtrVT, InFlag);
4730 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4732 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4734 SDValue InFlag, Chain;
4735 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
4737 // emit leaq symbol@TLSGD(%rip), %rdi
4738 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4739 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4740 GA->getValueType(0),
4742 SDValue Ops[] = { DAG.getEntryNode(), TGA};
4743 SDValue Result = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
4744 Chain = Result.getValue(1);
4745 InFlag = Result.getValue(2);
4747 // call __tls_get_addr. This function receives its argument in
4748 // the register RDI.
4749 Chain = DAG.getCopyToReg(Chain, dl, X86::RDI, Result, InFlag);
4750 InFlag = Chain.getValue(1);
4752 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4753 SDValue Ops1[] = { Chain,
4754 DAG.getTargetExternalSymbol("__tls_get_addr",
4756 DAG.getRegister(X86::RDI, PtrVT),
4758 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops1, 4);
4759 InFlag = Chain.getValue(1);
4761 return DAG.getCopyFromReg(Chain, dl, X86::RAX, PtrVT, InFlag);
4764 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4765 // "local exec" model.
4766 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4768 DebugLoc dl = GA->getDebugLoc();
4769 // Get the Thread Pointer
4770 SDValue ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER,
4771 DebugLoc::getUnknownLoc(), PtrVT);
4772 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4774 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4775 GA->getValueType(0),
4777 SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
4779 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4780 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
4781 PseudoSourceValue::getGOT(), 0);
4783 // The address of the thread local variable is the add of the thread
4784 // pointer with the offset of the variable.
4785 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
4789 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4790 // TODO: implement the "local dynamic" model
4791 // TODO: implement the "initial exec"model for pic executables
4792 assert(Subtarget->isTargetELF() &&
4793 "TLS not implemented for non-ELF targets");
4794 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4795 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4796 // otherwise use the "Local Exec"TLS Model
4797 if (Subtarget->is64Bit()) {
4798 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4800 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4801 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4803 return LowerToTLSExecModel(GA, DAG, getPointerTy());
4808 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4809 // FIXME there isn't really any debug info here
4810 DebugLoc dl = Op.getDebugLoc();
4811 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4812 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4813 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4814 // With PIC, the address is actually $g + Offset.
4815 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4816 !Subtarget->isPICStyleRIPRel()) {
4817 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4818 DAG.getNode(X86ISD::GlobalBaseReg,
4819 DebugLoc::getUnknownLoc(),
4827 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4828 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4829 // FIXME there isn't really any debug into here
4830 DebugLoc dl = JT->getDebugLoc();
4831 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4832 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4833 // With PIC, the address is actually $g + Offset.
4834 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4835 !Subtarget->isPICStyleRIPRel()) {
4836 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4837 DAG.getNode(X86ISD::GlobalBaseReg,
4838 DebugLoc::getUnknownLoc(),
4846 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4847 /// take a 2 x i32 value to shift plus a shift amount.
4848 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4849 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4850 MVT VT = Op.getValueType();
4851 unsigned VTBits = VT.getSizeInBits();
4852 DebugLoc dl = Op.getDebugLoc();
4853 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4854 SDValue ShOpLo = Op.getOperand(0);
4855 SDValue ShOpHi = Op.getOperand(1);
4856 SDValue ShAmt = Op.getOperand(2);
4857 SDValue Tmp1 = isSRA ?
4858 DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
4859 DAG.getConstant(VTBits - 1, MVT::i8)) :
4860 DAG.getConstant(0, VT);
4863 if (Op.getOpcode() == ISD::SHL_PARTS) {
4864 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
4865 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4867 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
4868 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
4871 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
4872 DAG.getConstant(VTBits, MVT::i8));
4873 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, VT,
4874 AndNode, DAG.getConstant(0, MVT::i8));
4877 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4878 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4879 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4881 if (Op.getOpcode() == ISD::SHL_PARTS) {
4882 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4883 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4885 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4886 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4889 SDValue Ops[2] = { Lo, Hi };
4890 return DAG.getMergeValues(Ops, 2, dl);
4893 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4894 MVT SrcVT = Op.getOperand(0).getValueType();
4895 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4896 "Unknown SINT_TO_FP to lower!");
4898 // These are really Legal; caller falls through into that case.
4899 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4901 if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 &&
4902 Subtarget->is64Bit())
4905 DebugLoc dl = Op.getDebugLoc();
4906 unsigned Size = SrcVT.getSizeInBits()/8;
4907 MachineFunction &MF = DAG.getMachineFunction();
4908 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4909 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4910 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
4912 PseudoSourceValue::getFixedStack(SSFI), 0);
4916 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4918 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4920 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4921 SmallVector<SDValue, 8> Ops;
4922 Ops.push_back(Chain);
4923 Ops.push_back(StackSlot);
4924 Ops.push_back(DAG.getValueType(SrcVT));
4925 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
4926 Tys, &Ops[0], Ops.size());
4929 Chain = Result.getValue(1);
4930 SDValue InFlag = Result.getValue(2);
4932 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4933 // shouldn't be necessary except that RFP cannot be live across
4934 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4935 MachineFunction &MF = DAG.getMachineFunction();
4936 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4937 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4938 Tys = DAG.getVTList(MVT::Other);
4939 SmallVector<SDValue, 8> Ops;
4940 Ops.push_back(Chain);
4941 Ops.push_back(Result);
4942 Ops.push_back(StackSlot);
4943 Ops.push_back(DAG.getValueType(Op.getValueType()));
4944 Ops.push_back(InFlag);
4945 Chain = DAG.getNode(X86ISD::FST, dl, Tys, &Ops[0], Ops.size());
4946 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
4947 PseudoSourceValue::getFixedStack(SSFI), 0);
4953 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
4954 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
4955 // This algorithm is not obvious. Here it is in C code, more or less:
4957 double uint64_to_double( uint32_t hi, uint32_t lo ) {
4958 static const __m128i exp = { 0x4330000045300000ULL, 0 };
4959 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
4961 // Copy ints to xmm registers.
4962 __m128i xh = _mm_cvtsi32_si128( hi );
4963 __m128i xl = _mm_cvtsi32_si128( lo );
4965 // Combine into low half of a single xmm register.
4966 __m128i x = _mm_unpacklo_epi32( xh, xl );
4970 // Merge in appropriate exponents to give the integer bits the right
4972 x = _mm_unpacklo_epi32( x, exp );
4974 // Subtract away the biases to deal with the IEEE-754 double precision
4976 d = _mm_sub_pd( (__m128d) x, bias );
4978 // All conversions up to here are exact. The correctly rounded result is
4979 // calculated using the current rounding mode using the following
4981 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
4982 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
4983 // store doesn't really need to be here (except
4984 // maybe to zero the other double)
4989 DebugLoc dl = Op.getDebugLoc();
4991 // Build some magic constants.
4992 std::vector<Constant*> CV0;
4993 CV0.push_back(ConstantInt::get(APInt(32, 0x45300000)));
4994 CV0.push_back(ConstantInt::get(APInt(32, 0x43300000)));
4995 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4996 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4997 Constant *C0 = ConstantVector::get(CV0);
4998 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 4);
5000 std::vector<Constant*> CV1;
5001 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4530000000000000ULL))));
5002 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4330000000000000ULL))));
5003 Constant *C1 = ConstantVector::get(CV1);
5004 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 4);
5006 SmallVector<SDValue, 4> MaskVec;
5007 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
5008 MaskVec.push_back(DAG.getConstant(4, MVT::i32));
5009 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
5010 MaskVec.push_back(DAG.getConstant(5, MVT::i32));
5011 SDValue UnpcklMask = DAG.getBUILD_VECTOR(MVT::v4i32, dl,
5012 &MaskVec[0], MaskVec.size());
5013 SmallVector<SDValue, 4> MaskVec2;
5014 MaskVec2.push_back(DAG.getConstant(1, MVT::i32));
5015 MaskVec2.push_back(DAG.getConstant(0, MVT::i32));
5016 SDValue ShufMask = DAG.getBUILD_VECTOR(MVT::v2i32, dl,
5017 &MaskVec2[0], MaskVec2.size());
5019 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5020 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5022 DAG.getIntPtrConstant(1)));
5023 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5024 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5026 DAG.getIntPtrConstant(0)));
5027 SDValue Unpck1 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v4i32,
5028 XR1, XR2, UnpcklMask);
5029 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5030 PseudoSourceValue::getConstantPool(), 0,
5032 SDValue Unpck2 = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v4i32,
5033 Unpck1, CLod0, UnpcklMask);
5034 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5035 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5036 PseudoSourceValue::getConstantPool(), 0,
5038 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5040 // Add the halves; easiest way is to swap them into another reg first.
5041 SDValue Shuf = DAG.getNode(ISD::VECTOR_SHUFFLE, dl, MVT::v2f64,
5042 Sub, Sub, ShufMask);
5043 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5044 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5045 DAG.getIntPtrConstant(0));
5048 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5049 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
5050 DebugLoc dl = Op.getDebugLoc();
5051 // FP constant to bias correct the final result.
5052 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5055 // Load the 32-bit value into an XMM register.
5056 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5057 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5059 DAG.getIntPtrConstant(0)));
5061 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5062 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5063 DAG.getIntPtrConstant(0));
5065 // Or the load with the bias.
5066 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5067 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5068 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5070 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5071 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5072 MVT::v2f64, Bias)));
5073 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5074 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5075 DAG.getIntPtrConstant(0));
5077 // Subtract the bias.
5078 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5080 // Handle final rounding.
5081 MVT DestVT = Op.getValueType();
5083 if (DestVT.bitsLT(MVT::f64)) {
5084 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5085 DAG.getIntPtrConstant(0));
5086 } else if (DestVT.bitsGT(MVT::f64)) {
5087 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5090 // Handle final rounding.
5094 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5095 SDValue N0 = Op.getOperand(0);
5096 DebugLoc dl = Op.getDebugLoc();
5098 // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
5099 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5100 // the optimization here.
5101 if (DAG.SignBitIsZero(N0))
5102 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5104 MVT SrcVT = N0.getValueType();
5105 if (SrcVT == MVT::i64) {
5106 // We only handle SSE2 f64 target here; caller can handle the rest.
5107 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
5110 return LowerUINT_TO_FP_i64(Op, DAG);
5111 } else if (SrcVT == MVT::i32) {
5112 return LowerUINT_TO_FP_i32(Op, DAG);
5115 assert(0 && "Unknown UINT_TO_FP to lower!");
5119 std::pair<SDValue,SDValue> X86TargetLowering::
5120 FP_TO_SINTHelper(SDValue Op, SelectionDAG &DAG) {
5121 DebugLoc dl = Op.getDebugLoc();
5122 assert(Op.getValueType().getSimpleVT() <= MVT::i64 &&
5123 Op.getValueType().getSimpleVT() >= MVT::i16 &&
5124 "Unknown FP_TO_SINT to lower!");
5126 // These are really Legal.
5127 if (Op.getValueType() == MVT::i32 &&
5128 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5129 return std::make_pair(SDValue(), SDValue());
5130 if (Subtarget->is64Bit() &&
5131 Op.getValueType() == MVT::i64 &&
5132 Op.getOperand(0).getValueType() != MVT::f80)
5133 return std::make_pair(SDValue(), SDValue());
5135 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5137 MachineFunction &MF = DAG.getMachineFunction();
5138 unsigned MemSize = Op.getValueType().getSizeInBits()/8;
5139 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
5140 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5142 switch (Op.getValueType().getSimpleVT()) {
5143 default: assert(0 && "Invalid FP_TO_SINT to lower!");
5144 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5145 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5146 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5149 SDValue Chain = DAG.getEntryNode();
5150 SDValue Value = Op.getOperand(0);
5151 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5152 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5153 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5154 PseudoSourceValue::getFixedStack(SSFI), 0);
5155 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5157 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5159 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5160 Chain = Value.getValue(1);
5161 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
5162 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5165 // Build the FP_TO_INT*_IN_MEM
5166 SDValue Ops[] = { Chain, Value, StackSlot };
5167 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5169 return std::make_pair(FIST, StackSlot);
5172 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
5173 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(Op, DAG);
5174 SDValue FIST = Vals.first, StackSlot = Vals.second;
5175 if (FIST.getNode() == 0) return SDValue();
5178 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5179 FIST, StackSlot, NULL, 0);
5182 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
5183 DebugLoc dl = Op.getDebugLoc();
5184 MVT VT = Op.getValueType();
5187 EltVT = VT.getVectorElementType();
5188 std::vector<Constant*> CV;
5189 if (EltVT == MVT::f64) {
5190 Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
5194 Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
5200 Constant *C = ConstantVector::get(CV);
5201 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
5202 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5203 PseudoSourceValue::getConstantPool(), 0,
5205 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5208 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
5209 DebugLoc dl = Op.getDebugLoc();
5210 MVT VT = Op.getValueType();
5212 unsigned EltNum = 1;
5213 if (VT.isVector()) {
5214 EltVT = VT.getVectorElementType();
5215 EltNum = VT.getVectorNumElements();
5217 std::vector<Constant*> CV;
5218 if (EltVT == MVT::f64) {
5219 Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
5223 Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
5229 Constant *C = ConstantVector::get(CV);
5230 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
5231 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5232 PseudoSourceValue::getConstantPool(), 0,
5234 if (VT.isVector()) {
5235 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5236 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5237 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5239 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5241 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5245 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5246 SDValue Op0 = Op.getOperand(0);
5247 SDValue Op1 = Op.getOperand(1);
5248 DebugLoc dl = Op.getDebugLoc();
5249 MVT VT = Op.getValueType();
5250 MVT SrcVT = Op1.getValueType();
5252 // If second operand is smaller, extend it first.
5253 if (SrcVT.bitsLT(VT)) {
5254 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5257 // And if it is bigger, shrink it first.
5258 if (SrcVT.bitsGT(VT)) {
5259 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5263 // At this point the operands and the result should have the same
5264 // type, and that won't be f80 since that is not custom lowered.
5266 // First get the sign bit of second operand.
5267 std::vector<Constant*> CV;
5268 if (SrcVT == MVT::f64) {
5269 CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
5270 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
5272 CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
5273 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5274 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5275 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5277 Constant *C = ConstantVector::get(CV);
5278 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
5279 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5280 PseudoSourceValue::getConstantPool(), 0,
5282 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5284 // Shift sign bit right or left if the two operands have different types.
5285 if (SrcVT.bitsGT(VT)) {
5286 // Op0 is MVT::f32, Op1 is MVT::f64.
5287 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5288 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5289 DAG.getConstant(32, MVT::i32));
5290 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5291 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5292 DAG.getIntPtrConstant(0));
5295 // Clear first operand sign bit.
5297 if (VT == MVT::f64) {
5298 CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
5299 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
5301 CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
5302 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5303 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5304 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
5306 C = ConstantVector::get(CV);
5307 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
5308 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5309 PseudoSourceValue::getConstantPool(), 0,
5311 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5313 // Or the value with the sign bit.
5314 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5317 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5318 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5319 SDValue Op0 = Op.getOperand(0);
5320 SDValue Op1 = Op.getOperand(1);
5321 DebugLoc dl = Op.getDebugLoc();
5322 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5324 // Lower (X & (1 << N)) == 0 to BT(X, N).
5325 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5326 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5327 if (Op0.getOpcode() == ISD::AND &&
5329 Op1.getOpcode() == ISD::Constant &&
5330 cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5331 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5333 if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
5334 if (ConstantSDNode *Op010C =
5335 dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
5336 if (Op010C->getZExtValue() == 1) {
5337 LHS = Op0.getOperand(0);
5338 RHS = Op0.getOperand(1).getOperand(1);
5340 } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
5341 if (ConstantSDNode *Op000C =
5342 dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
5343 if (Op000C->getZExtValue() == 1) {
5344 LHS = Op0.getOperand(1);
5345 RHS = Op0.getOperand(0).getOperand(1);
5347 } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
5348 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5349 SDValue AndLHS = Op0.getOperand(0);
5350 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5351 LHS = AndLHS.getOperand(0);
5352 RHS = AndLHS.getOperand(1);
5356 if (LHS.getNode()) {
5357 // If LHS is i8, promote it to i16 with any_extend. There is no i8 BT
5358 // instruction. Since the shift amount is in-range-or-undefined, we know
5359 // that doing a bittest on the i16 value is ok. We extend to i32 because
5360 // the encoding for the i16 version is larger than the i32 version.
5361 if (LHS.getValueType() == MVT::i8)
5362 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5364 // If the operand types disagree, extend the shift amount to match. Since
5365 // BT ignores high bits (like shifts) we can use anyextend.
5366 if (LHS.getValueType() != RHS.getValueType())
5367 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5369 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5370 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5371 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5372 DAG.getConstant(Cond, MVT::i8), BT);
5376 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5377 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5379 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5380 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5381 DAG.getConstant(X86CC, MVT::i8), Cond);
5384 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5386 SDValue Op0 = Op.getOperand(0);
5387 SDValue Op1 = Op.getOperand(1);
5388 SDValue CC = Op.getOperand(2);
5389 MVT VT = Op.getValueType();
5390 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5391 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5392 DebugLoc dl = Op.getDebugLoc();
5396 MVT VT0 = Op0.getValueType();
5397 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5398 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5401 switch (SetCCOpcode) {
5404 case ISD::SETEQ: SSECC = 0; break;
5406 case ISD::SETGT: Swap = true; // Fallthrough
5408 case ISD::SETOLT: SSECC = 1; break;
5410 case ISD::SETGE: Swap = true; // Fallthrough
5412 case ISD::SETOLE: SSECC = 2; break;
5413 case ISD::SETUO: SSECC = 3; break;
5415 case ISD::SETNE: SSECC = 4; break;
5416 case ISD::SETULE: Swap = true;
5417 case ISD::SETUGE: SSECC = 5; break;
5418 case ISD::SETULT: Swap = true;
5419 case ISD::SETUGT: SSECC = 6; break;
5420 case ISD::SETO: SSECC = 7; break;
5423 std::swap(Op0, Op1);
5425 // In the two special cases we can't handle, emit two comparisons.
5427 if (SetCCOpcode == ISD::SETUEQ) {
5429 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5430 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5431 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
5433 else if (SetCCOpcode == ISD::SETONE) {
5435 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5436 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5437 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
5439 assert(0 && "Illegal FP comparison");
5441 // Handle all other FP comparisons here.
5442 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5445 // We are handling one of the integer comparisons here. Since SSE only has
5446 // GT and EQ comparisons for integer, swapping operands and multiple
5447 // operations may be required for some comparisons.
5448 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5449 bool Swap = false, Invert = false, FlipSigns = false;
5451 switch (VT.getSimpleVT()) {
5453 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5454 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5455 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5456 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5459 switch (SetCCOpcode) {
5461 case ISD::SETNE: Invert = true;
5462 case ISD::SETEQ: Opc = EQOpc; break;
5463 case ISD::SETLT: Swap = true;
5464 case ISD::SETGT: Opc = GTOpc; break;
5465 case ISD::SETGE: Swap = true;
5466 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
5467 case ISD::SETULT: Swap = true;
5468 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5469 case ISD::SETUGE: Swap = true;
5470 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5473 std::swap(Op0, Op1);
5475 // Since SSE has no unsigned integer comparisons, we need to flip the sign
5476 // bits of the inputs before performing those operations.
5478 MVT EltVT = VT.getVectorElementType();
5479 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
5481 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5482 SDValue SignVec = DAG.getBUILD_VECTOR(VT, dl, &SignBits[0], SignBits.size());
5483 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
5484 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
5487 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
5489 // If the logical-not of the result is required, perform that now.
5491 Result = DAG.getNOT(dl, Result, VT);
5496 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5497 static bool isX86LogicalCmp(unsigned Opc) {
5498 return Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI;
5501 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5502 bool addTest = true;
5503 SDValue Cond = Op.getOperand(0);
5504 DebugLoc dl = Op.getDebugLoc();
5507 if (Cond.getOpcode() == ISD::SETCC)
5508 Cond = LowerSETCC(Cond, DAG);
5510 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5511 // setting operand in place of the X86ISD::SETCC.
5512 if (Cond.getOpcode() == X86ISD::SETCC) {
5513 CC = Cond.getOperand(0);
5515 SDValue Cmp = Cond.getOperand(1);
5516 unsigned Opc = Cmp.getOpcode();
5517 MVT VT = Op.getValueType();
5519 bool IllegalFPCMov = false;
5520 if (VT.isFloatingPoint() && !VT.isVector() &&
5521 !isScalarFPTypeInSSEReg(VT)) // FPStack?
5522 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
5524 if ((isX86LogicalCmp(Opc) && !IllegalFPCMov) || Opc == X86ISD::BT) { // FIXME
5531 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5532 Cond= DAG.getNode(X86ISD::CMP, dl, MVT::i32, Cond,
5533 DAG.getConstant(0, MVT::i8));
5536 const MVT *VTs = DAG.getNodeValueTypes(Op.getValueType(),
5538 SmallVector<SDValue, 4> Ops;
5539 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
5540 // condition is true.
5541 Ops.push_back(Op.getOperand(2));
5542 Ops.push_back(Op.getOperand(1));
5544 Ops.push_back(Cond);
5545 return DAG.getNode(X86ISD::CMOV, dl, VTs, 2, &Ops[0], Ops.size());
5548 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
5549 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
5550 // from the AND / OR.
5551 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
5552 Opc = Op.getOpcode();
5553 if (Opc != ISD::OR && Opc != ISD::AND)
5555 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5556 Op.getOperand(0).hasOneUse() &&
5557 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
5558 Op.getOperand(1).hasOneUse());
5561 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
5562 // 1 and that the SETCC node has a single use.
5563 static bool isXor1OfSetCC(SDValue Op) {
5564 if (Op.getOpcode() != ISD::XOR)
5566 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5567 if (N1C && N1C->getAPIntValue() == 1) {
5568 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5569 Op.getOperand(0).hasOneUse();
5574 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
5575 bool addTest = true;
5576 SDValue Chain = Op.getOperand(0);
5577 SDValue Cond = Op.getOperand(1);
5578 SDValue Dest = Op.getOperand(2);
5579 DebugLoc dl = Op.getDebugLoc();
5582 if (Cond.getOpcode() == ISD::SETCC)
5583 Cond = LowerSETCC(Cond, DAG);
5585 // FIXME: LowerXALUO doesn't handle these!!
5586 else if (Cond.getOpcode() == X86ISD::ADD ||
5587 Cond.getOpcode() == X86ISD::SUB ||
5588 Cond.getOpcode() == X86ISD::SMUL ||
5589 Cond.getOpcode() == X86ISD::UMUL)
5590 Cond = LowerXALUO(Cond, DAG);
5593 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5594 // setting operand in place of the X86ISD::SETCC.
5595 if (Cond.getOpcode() == X86ISD::SETCC) {
5596 CC = Cond.getOperand(0);
5598 SDValue Cmp = Cond.getOperand(1);
5599 unsigned Opc = Cmp.getOpcode();
5600 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
5601 if (isX86LogicalCmp(Opc) || Opc == X86ISD::BT) {
5605 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
5609 // These can only come from an arithmetic instruction with overflow,
5610 // e.g. SADDO, UADDO.
5611 Cond = Cond.getNode()->getOperand(1);
5618 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
5619 SDValue Cmp = Cond.getOperand(0).getOperand(1);
5620 unsigned Opc = Cmp.getOpcode();
5621 if (CondOpc == ISD::OR) {
5622 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
5623 // two branches instead of an explicit OR instruction with a
5625 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5626 isX86LogicalCmp(Opc)) {
5627 CC = Cond.getOperand(0).getOperand(0);
5628 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5629 Chain, Dest, CC, Cmp);
5630 CC = Cond.getOperand(1).getOperand(0);
5634 } else { // ISD::AND
5635 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
5636 // two branches instead of an explicit AND instruction with a
5637 // separate test. However, we only do this if this block doesn't
5638 // have a fall-through edge, because this requires an explicit
5639 // jmp when the condition is false.
5640 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5641 isX86LogicalCmp(Opc) &&
5642 Op.getNode()->hasOneUse()) {
5643 X86::CondCode CCode =
5644 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5645 CCode = X86::GetOppositeBranchCondition(CCode);
5646 CC = DAG.getConstant(CCode, MVT::i8);
5647 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
5648 // Look for an unconditional branch following this conditional branch.
5649 // We need this because we need to reverse the successors in order
5650 // to implement FCMP_OEQ.
5651 if (User.getOpcode() == ISD::BR) {
5652 SDValue FalseBB = User.getOperand(1);
5654 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
5655 assert(NewBR == User);
5658 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5659 Chain, Dest, CC, Cmp);
5660 X86::CondCode CCode =
5661 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
5662 CCode = X86::GetOppositeBranchCondition(CCode);
5663 CC = DAG.getConstant(CCode, MVT::i8);
5669 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
5670 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
5671 // It should be transformed during dag combiner except when the condition
5672 // is set by a arithmetics with overflow node.
5673 X86::CondCode CCode =
5674 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5675 CCode = X86::GetOppositeBranchCondition(CCode);
5676 CC = DAG.getConstant(CCode, MVT::i8);
5677 Cond = Cond.getOperand(0).getOperand(1);
5683 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5684 Cond= DAG.getNode(X86ISD::CMP, dl, MVT::i32, Cond,
5685 DAG.getConstant(0, MVT::i8));
5687 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5688 Chain, Dest, CC, Cond);
5692 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
5693 // Calls to _alloca is needed to probe the stack when allocating more than 4k
5694 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
5695 // that the guard pages used by the OS virtual memory manager are allocated in
5696 // correct sequence.
5698 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5699 SelectionDAG &DAG) {
5700 assert(Subtarget->isTargetCygMing() &&
5701 "This should be used only on Cygwin/Mingw targets");
5702 DebugLoc dl = Op.getDebugLoc();
5705 SDValue Chain = Op.getOperand(0);
5706 SDValue Size = Op.getOperand(1);
5707 // FIXME: Ensure alignment here
5711 MVT IntPtr = getPointerTy();
5712 MVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
5714 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
5716 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
5717 Flag = Chain.getValue(1);
5719 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5720 SDValue Ops[] = { Chain,
5721 DAG.getTargetExternalSymbol("_alloca", IntPtr),
5722 DAG.getRegister(X86::EAX, IntPtr),
5723 DAG.getRegister(X86StackPtr, SPTy),
5725 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops, 5);
5726 Flag = Chain.getValue(1);
5728 Chain = DAG.getCALLSEQ_END(Chain,
5729 DAG.getIntPtrConstant(0, true),
5730 DAG.getIntPtrConstant(0, true),
5733 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
5735 SDValue Ops1[2] = { Chain.getValue(0), Chain };
5736 return DAG.getMergeValues(Ops1, 2, dl);
5740 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
5742 SDValue Dst, SDValue Src,
5743 SDValue Size, unsigned Align,
5745 uint64_t DstSVOff) {
5746 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5748 // If not DWORD aligned or size is more than the threshold, call the library.
5749 // The libc version is likely to be faster for these cases. It can use the
5750 // address value and run time information about the CPU.
5751 if ((Align & 3) != 0 ||
5753 ConstantSize->getZExtValue() >
5754 getSubtarget()->getMaxInlineSizeThreshold()) {
5755 SDValue InFlag(0, 0);
5757 // Check to see if there is a specialized entry-point for memory zeroing.
5758 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
5760 if (const char *bzeroEntry = V &&
5761 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
5762 MVT IntPtr = getPointerTy();
5763 const Type *IntPtrTy = TD->getIntPtrType();
5764 TargetLowering::ArgListTy Args;
5765 TargetLowering::ArgListEntry Entry;
5767 Entry.Ty = IntPtrTy;
5768 Args.push_back(Entry);
5770 Args.push_back(Entry);
5771 std::pair<SDValue,SDValue> CallResult =
5772 LowerCallTo(Chain, Type::VoidTy, false, false, false, false,
5773 CallingConv::C, false,
5774 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl);
5775 return CallResult.second;
5778 // Otherwise have the target-independent code call memset.
5782 uint64_t SizeVal = ConstantSize->getZExtValue();
5783 SDValue InFlag(0, 0);
5786 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
5787 unsigned BytesLeft = 0;
5788 bool TwoRepStos = false;
5791 uint64_t Val = ValC->getZExtValue() & 255;
5793 // If the value is a constant, then we can potentially use larger sets.
5794 switch (Align & 3) {
5795 case 2: // WORD aligned
5798 Val = (Val << 8) | Val;
5800 case 0: // DWORD aligned
5803 Val = (Val << 8) | Val;
5804 Val = (Val << 16) | Val;
5805 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
5808 Val = (Val << 32) | Val;
5811 default: // Byte aligned
5814 Count = DAG.getIntPtrConstant(SizeVal);
5818 if (AVT.bitsGT(MVT::i8)) {
5819 unsigned UBytes = AVT.getSizeInBits() / 8;
5820 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
5821 BytesLeft = SizeVal % UBytes;
5824 Chain = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
5826 InFlag = Chain.getValue(1);
5829 Count = DAG.getIntPtrConstant(SizeVal);
5830 Chain = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
5831 InFlag = Chain.getValue(1);
5834 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
5837 InFlag = Chain.getValue(1);
5838 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
5841 InFlag = Chain.getValue(1);
5843 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5844 SmallVector<SDValue, 8> Ops;
5845 Ops.push_back(Chain);
5846 Ops.push_back(DAG.getValueType(AVT));
5847 Ops.push_back(InFlag);
5848 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
5851 InFlag = Chain.getValue(1);
5853 MVT CVT = Count.getValueType();
5854 SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
5855 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
5856 Chain = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
5859 InFlag = Chain.getValue(1);
5860 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5862 Ops.push_back(Chain);
5863 Ops.push_back(DAG.getValueType(MVT::i8));
5864 Ops.push_back(InFlag);
5865 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
5866 } else if (BytesLeft) {
5867 // Handle the last 1 - 7 bytes.
5868 unsigned Offset = SizeVal - BytesLeft;
5869 MVT AddrVT = Dst.getValueType();
5870 MVT SizeVT = Size.getValueType();
5872 Chain = DAG.getMemset(Chain, dl,
5873 DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
5874 DAG.getConstant(Offset, AddrVT)),
5876 DAG.getConstant(BytesLeft, SizeVT),
5877 Align, DstSV, DstSVOff + Offset);
5880 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
5885 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
5886 SDValue Chain, SDValue Dst, SDValue Src,
5887 SDValue Size, unsigned Align,
5889 const Value *DstSV, uint64_t DstSVOff,
5890 const Value *SrcSV, uint64_t SrcSVOff) {
5891 // This requires the copy size to be a constant, preferrably
5892 // within a subtarget-specific limit.
5893 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5896 uint64_t SizeVal = ConstantSize->getZExtValue();
5897 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
5900 /// If not DWORD aligned, call the library.
5901 if ((Align & 3) != 0)
5906 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
5909 unsigned UBytes = AVT.getSizeInBits() / 8;
5910 unsigned CountVal = SizeVal / UBytes;
5911 SDValue Count = DAG.getIntPtrConstant(CountVal);
5912 unsigned BytesLeft = SizeVal % UBytes;
5914 SDValue InFlag(0, 0);
5915 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
5918 InFlag = Chain.getValue(1);
5919 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
5922 InFlag = Chain.getValue(1);
5923 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
5926 InFlag = Chain.getValue(1);
5928 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5929 SmallVector<SDValue, 8> Ops;
5930 Ops.push_back(Chain);
5931 Ops.push_back(DAG.getValueType(AVT));
5932 Ops.push_back(InFlag);
5933 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, &Ops[0], Ops.size());
5935 SmallVector<SDValue, 4> Results;
5936 Results.push_back(RepMovs);
5938 // Handle the last 1 - 7 bytes.
5939 unsigned Offset = SizeVal - BytesLeft;
5940 MVT DstVT = Dst.getValueType();
5941 MVT SrcVT = Src.getValueType();
5942 MVT SizeVT = Size.getValueType();
5943 Results.push_back(DAG.getMemcpy(Chain, dl,
5944 DAG.getNode(ISD::ADD, dl, DstVT, Dst,
5945 DAG.getConstant(Offset, DstVT)),
5946 DAG.getNode(ISD::ADD, dl, SrcVT, Src,
5947 DAG.getConstant(Offset, SrcVT)),
5948 DAG.getConstant(BytesLeft, SizeVT),
5949 Align, AlwaysInline,
5950 DstSV, DstSVOff + Offset,
5951 SrcSV, SrcSVOff + Offset));
5954 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5955 &Results[0], Results.size());
5958 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
5959 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5960 DebugLoc dl = Op.getDebugLoc();
5962 if (!Subtarget->is64Bit()) {
5963 // vastart just stores the address of the VarArgsFrameIndex slot into the
5964 // memory location argument.
5965 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5966 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
5970 // gp_offset (0 - 6 * 8)
5971 // fp_offset (48 - 48 + 8 * 16)
5972 // overflow_arg_area (point to parameters coming in memory).
5974 SmallVector<SDValue, 8> MemOps;
5975 SDValue FIN = Op.getOperand(1);
5977 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
5978 DAG.getConstant(VarArgsGPOffset, MVT::i32),
5980 MemOps.push_back(Store);
5983 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5984 FIN, DAG.getIntPtrConstant(4));
5985 Store = DAG.getStore(Op.getOperand(0), dl,
5986 DAG.getConstant(VarArgsFPOffset, MVT::i32),
5988 MemOps.push_back(Store);
5990 // Store ptr to overflow_arg_area
5991 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5992 FIN, DAG.getIntPtrConstant(4));
5993 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5994 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0);
5995 MemOps.push_back(Store);
5997 // Store ptr to reg_save_area.
5998 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5999 FIN, DAG.getIntPtrConstant(8));
6000 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
6001 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0);
6002 MemOps.push_back(Store);
6003 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6004 &MemOps[0], MemOps.size());
6007 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
6008 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6009 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6010 SDValue Chain = Op.getOperand(0);
6011 SDValue SrcPtr = Op.getOperand(1);
6012 SDValue SrcSV = Op.getOperand(2);
6014 assert(0 && "VAArgInst is not yet implemented for x86-64!");
6019 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
6020 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6021 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6022 SDValue Chain = Op.getOperand(0);
6023 SDValue DstPtr = Op.getOperand(1);
6024 SDValue SrcPtr = Op.getOperand(2);
6025 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6026 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6027 DebugLoc dl = Op.getDebugLoc();
6029 return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6030 DAG.getIntPtrConstant(24), 8, false,
6031 DstSV, 0, SrcSV, 0);
6035 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
6036 DebugLoc dl = Op.getDebugLoc();
6037 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6039 default: return SDValue(); // Don't custom lower most intrinsics.
6040 // Comparison intrinsics.
6041 case Intrinsic::x86_sse_comieq_ss:
6042 case Intrinsic::x86_sse_comilt_ss:
6043 case Intrinsic::x86_sse_comile_ss:
6044 case Intrinsic::x86_sse_comigt_ss:
6045 case Intrinsic::x86_sse_comige_ss:
6046 case Intrinsic::x86_sse_comineq_ss:
6047 case Intrinsic::x86_sse_ucomieq_ss:
6048 case Intrinsic::x86_sse_ucomilt_ss:
6049 case Intrinsic::x86_sse_ucomile_ss:
6050 case Intrinsic::x86_sse_ucomigt_ss:
6051 case Intrinsic::x86_sse_ucomige_ss:
6052 case Intrinsic::x86_sse_ucomineq_ss:
6053 case Intrinsic::x86_sse2_comieq_sd:
6054 case Intrinsic::x86_sse2_comilt_sd:
6055 case Intrinsic::x86_sse2_comile_sd:
6056 case Intrinsic::x86_sse2_comigt_sd:
6057 case Intrinsic::x86_sse2_comige_sd:
6058 case Intrinsic::x86_sse2_comineq_sd:
6059 case Intrinsic::x86_sse2_ucomieq_sd:
6060 case Intrinsic::x86_sse2_ucomilt_sd:
6061 case Intrinsic::x86_sse2_ucomile_sd:
6062 case Intrinsic::x86_sse2_ucomigt_sd:
6063 case Intrinsic::x86_sse2_ucomige_sd:
6064 case Intrinsic::x86_sse2_ucomineq_sd: {
6066 ISD::CondCode CC = ISD::SETCC_INVALID;
6069 case Intrinsic::x86_sse_comieq_ss:
6070 case Intrinsic::x86_sse2_comieq_sd:
6074 case Intrinsic::x86_sse_comilt_ss:
6075 case Intrinsic::x86_sse2_comilt_sd:
6079 case Intrinsic::x86_sse_comile_ss:
6080 case Intrinsic::x86_sse2_comile_sd:
6084 case Intrinsic::x86_sse_comigt_ss:
6085 case Intrinsic::x86_sse2_comigt_sd:
6089 case Intrinsic::x86_sse_comige_ss:
6090 case Intrinsic::x86_sse2_comige_sd:
6094 case Intrinsic::x86_sse_comineq_ss:
6095 case Intrinsic::x86_sse2_comineq_sd:
6099 case Intrinsic::x86_sse_ucomieq_ss:
6100 case Intrinsic::x86_sse2_ucomieq_sd:
6101 Opc = X86ISD::UCOMI;
6104 case Intrinsic::x86_sse_ucomilt_ss:
6105 case Intrinsic::x86_sse2_ucomilt_sd:
6106 Opc = X86ISD::UCOMI;
6109 case Intrinsic::x86_sse_ucomile_ss:
6110 case Intrinsic::x86_sse2_ucomile_sd:
6111 Opc = X86ISD::UCOMI;
6114 case Intrinsic::x86_sse_ucomigt_ss:
6115 case Intrinsic::x86_sse2_ucomigt_sd:
6116 Opc = X86ISD::UCOMI;
6119 case Intrinsic::x86_sse_ucomige_ss:
6120 case Intrinsic::x86_sse2_ucomige_sd:
6121 Opc = X86ISD::UCOMI;
6124 case Intrinsic::x86_sse_ucomineq_ss:
6125 case Intrinsic::x86_sse2_ucomineq_sd:
6126 Opc = X86ISD::UCOMI;
6131 SDValue LHS = Op.getOperand(1);
6132 SDValue RHS = Op.getOperand(2);
6133 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6134 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6135 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6136 DAG.getConstant(X86CC, MVT::i8), Cond);
6137 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6140 // Fix vector shift instructions where the last operand is a non-immediate
6142 case Intrinsic::x86_sse2_pslli_w:
6143 case Intrinsic::x86_sse2_pslli_d:
6144 case Intrinsic::x86_sse2_pslli_q:
6145 case Intrinsic::x86_sse2_psrli_w:
6146 case Intrinsic::x86_sse2_psrli_d:
6147 case Intrinsic::x86_sse2_psrli_q:
6148 case Intrinsic::x86_sse2_psrai_w:
6149 case Intrinsic::x86_sse2_psrai_d:
6150 case Intrinsic::x86_mmx_pslli_w:
6151 case Intrinsic::x86_mmx_pslli_d:
6152 case Intrinsic::x86_mmx_pslli_q:
6153 case Intrinsic::x86_mmx_psrli_w:
6154 case Intrinsic::x86_mmx_psrli_d:
6155 case Intrinsic::x86_mmx_psrli_q:
6156 case Intrinsic::x86_mmx_psrai_w:
6157 case Intrinsic::x86_mmx_psrai_d: {
6158 SDValue ShAmt = Op.getOperand(2);
6159 if (isa<ConstantSDNode>(ShAmt))
6162 unsigned NewIntNo = 0;
6163 MVT ShAmtVT = MVT::v4i32;
6165 case Intrinsic::x86_sse2_pslli_w:
6166 NewIntNo = Intrinsic::x86_sse2_psll_w;
6168 case Intrinsic::x86_sse2_pslli_d:
6169 NewIntNo = Intrinsic::x86_sse2_psll_d;
6171 case Intrinsic::x86_sse2_pslli_q:
6172 NewIntNo = Intrinsic::x86_sse2_psll_q;
6174 case Intrinsic::x86_sse2_psrli_w:
6175 NewIntNo = Intrinsic::x86_sse2_psrl_w;
6177 case Intrinsic::x86_sse2_psrli_d:
6178 NewIntNo = Intrinsic::x86_sse2_psrl_d;
6180 case Intrinsic::x86_sse2_psrli_q:
6181 NewIntNo = Intrinsic::x86_sse2_psrl_q;
6183 case Intrinsic::x86_sse2_psrai_w:
6184 NewIntNo = Intrinsic::x86_sse2_psra_w;
6186 case Intrinsic::x86_sse2_psrai_d:
6187 NewIntNo = Intrinsic::x86_sse2_psra_d;
6190 ShAmtVT = MVT::v2i32;
6192 case Intrinsic::x86_mmx_pslli_w:
6193 NewIntNo = Intrinsic::x86_mmx_psll_w;
6195 case Intrinsic::x86_mmx_pslli_d:
6196 NewIntNo = Intrinsic::x86_mmx_psll_d;
6198 case Intrinsic::x86_mmx_pslli_q:
6199 NewIntNo = Intrinsic::x86_mmx_psll_q;
6201 case Intrinsic::x86_mmx_psrli_w:
6202 NewIntNo = Intrinsic::x86_mmx_psrl_w;
6204 case Intrinsic::x86_mmx_psrli_d:
6205 NewIntNo = Intrinsic::x86_mmx_psrl_d;
6207 case Intrinsic::x86_mmx_psrli_q:
6208 NewIntNo = Intrinsic::x86_mmx_psrl_q;
6210 case Intrinsic::x86_mmx_psrai_w:
6211 NewIntNo = Intrinsic::x86_mmx_psra_w;
6213 case Intrinsic::x86_mmx_psrai_d:
6214 NewIntNo = Intrinsic::x86_mmx_psra_d;
6216 default: abort(); // Can't reach here.
6221 MVT VT = Op.getValueType();
6222 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT,
6223 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, ShAmtVT, ShAmt));
6224 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6225 DAG.getConstant(NewIntNo, MVT::i32),
6226 Op.getOperand(1), ShAmt);
6231 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
6232 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6233 DebugLoc dl = Op.getDebugLoc();
6236 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6238 DAG.getConstant(TD->getPointerSize(),
6239 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6240 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6241 DAG.getNode(ISD::ADD, dl, getPointerTy(),
6246 // Just load the return address.
6247 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6248 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6249 RetAddrFI, NULL, 0);
6252 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
6253 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6254 MFI->setFrameAddressIsTaken(true);
6255 MVT VT = Op.getValueType();
6256 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
6257 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6258 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6259 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6261 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
6265 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6266 SelectionDAG &DAG) {
6267 return DAG.getIntPtrConstant(2*TD->getPointerSize());
6270 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
6272 MachineFunction &MF = DAG.getMachineFunction();
6273 SDValue Chain = Op.getOperand(0);
6274 SDValue Offset = Op.getOperand(1);
6275 SDValue Handler = Op.getOperand(2);
6276 DebugLoc dl = Op.getDebugLoc();
6278 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6280 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6282 SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
6283 DAG.getIntPtrConstant(-TD->getPointerSize()));
6284 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
6285 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0);
6286 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
6287 MF.getRegInfo().addLiveOut(StoreAddrReg);
6289 return DAG.getNode(X86ISD::EH_RETURN, dl,
6291 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6294 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6295 SelectionDAG &DAG) {
6296 SDValue Root = Op.getOperand(0);
6297 SDValue Trmp = Op.getOperand(1); // trampoline
6298 SDValue FPtr = Op.getOperand(2); // nested function
6299 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6300 DebugLoc dl = Op.getDebugLoc();
6302 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6304 const X86InstrInfo *TII =
6305 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
6307 if (Subtarget->is64Bit()) {
6308 SDValue OutChains[6];
6310 // Large code-model.
6312 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
6313 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
6315 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
6316 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
6318 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
6320 // Load the pointer to the nested function into R11.
6321 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
6322 SDValue Addr = Trmp;
6323 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6326 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6327 DAG.getConstant(2, MVT::i64));
6328 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2, false, 2);
6330 // Load the 'nest' parameter value into R10.
6331 // R10 is specified in X86CallingConv.td
6332 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
6333 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6334 DAG.getConstant(10, MVT::i64));
6335 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6336 Addr, TrmpAddr, 10);
6338 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6339 DAG.getConstant(12, MVT::i64));
6340 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12, false, 2);
6342 // Jump to the nested function.
6343 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
6344 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6345 DAG.getConstant(20, MVT::i64));
6346 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6347 Addr, TrmpAddr, 20);
6349 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
6350 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6351 DAG.getConstant(22, MVT::i64));
6352 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
6356 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
6357 return DAG.getMergeValues(Ops, 2, dl);
6359 const Function *Func =
6360 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
6361 unsigned CC = Func->getCallingConv();
6366 assert(0 && "Unsupported calling convention");
6367 case CallingConv::C:
6368 case CallingConv::X86_StdCall: {
6369 // Pass 'nest' parameter in ECX.
6370 // Must be kept in sync with X86CallingConv.td
6373 // Check that ECX wasn't needed by an 'inreg' parameter.
6374 const FunctionType *FTy = Func->getFunctionType();
6375 const AttrListPtr &Attrs = Func->getAttributes();
6377 if (!Attrs.isEmpty() && !Func->isVarArg()) {
6378 unsigned InRegCount = 0;
6381 for (FunctionType::param_iterator I = FTy->param_begin(),
6382 E = FTy->param_end(); I != E; ++I, ++Idx)
6383 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6384 // FIXME: should only count parameters that are lowered to integers.
6385 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6387 if (InRegCount > 2) {
6388 cerr << "Nest register in use - reduce number of inreg parameters!\n";
6394 case CallingConv::X86_FastCall:
6395 case CallingConv::Fast:
6396 // Pass 'nest' parameter in EAX.
6397 // Must be kept in sync with X86CallingConv.td
6402 SDValue OutChains[4];
6405 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6406 DAG.getConstant(10, MVT::i32));
6407 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
6409 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
6410 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
6411 OutChains[0] = DAG.getStore(Root, dl,
6412 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
6415 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6416 DAG.getConstant(1, MVT::i32));
6417 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1, false, 1);
6419 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
6420 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6421 DAG.getConstant(5, MVT::i32));
6422 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
6423 TrmpAddr, 5, false, 1);
6425 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6426 DAG.getConstant(6, MVT::i32));
6427 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6, false, 1);
6430 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
6431 return DAG.getMergeValues(Ops, 2, dl);
6435 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
6437 The rounding mode is in bits 11:10 of FPSR, and has the following
6444 FLT_ROUNDS, on the other hand, expects the following:
6451 To perform the conversion, we do:
6452 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
6455 MachineFunction &MF = DAG.getMachineFunction();
6456 const TargetMachine &TM = MF.getTarget();
6457 const TargetFrameInfo &TFI = *TM.getFrameInfo();
6458 unsigned StackAlignment = TFI.getStackAlignment();
6459 MVT VT = Op.getValueType();
6460 DebugLoc dl = Op.getDebugLoc();
6462 // Save FP Control Word to stack slot
6463 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
6464 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6466 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
6467 DAG.getEntryNode(), StackSlot);
6469 // Load FP Control Word from stack slot
6470 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0);
6472 // Transform as necessary
6474 DAG.getNode(ISD::SRL, dl, MVT::i16,
6475 DAG.getNode(ISD::AND, dl, MVT::i16,
6476 CWD, DAG.getConstant(0x800, MVT::i16)),
6477 DAG.getConstant(11, MVT::i8));
6479 DAG.getNode(ISD::SRL, dl, MVT::i16,
6480 DAG.getNode(ISD::AND, dl, MVT::i16,
6481 CWD, DAG.getConstant(0x400, MVT::i16)),
6482 DAG.getConstant(9, MVT::i8));
6485 DAG.getNode(ISD::AND, dl, MVT::i16,
6486 DAG.getNode(ISD::ADD, dl, MVT::i16,
6487 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
6488 DAG.getConstant(1, MVT::i16)),
6489 DAG.getConstant(3, MVT::i16));
6492 return DAG.getNode((VT.getSizeInBits() < 16 ?
6493 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6496 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
6497 MVT VT = Op.getValueType();
6499 unsigned NumBits = VT.getSizeInBits();
6500 DebugLoc dl = Op.getDebugLoc();
6502 Op = Op.getOperand(0);
6503 if (VT == MVT::i8) {
6504 // Zero extend to i32 since there is not an i8 bsr.
6506 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6509 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
6510 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6511 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
6513 // If src is zero (i.e. bsr sets ZF), returns NumBits.
6514 SmallVector<SDValue, 4> Ops;
6516 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
6517 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6518 Ops.push_back(Op.getValue(1));
6519 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6521 // Finally xor with NumBits-1.
6522 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
6525 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6529 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
6530 MVT VT = Op.getValueType();
6532 unsigned NumBits = VT.getSizeInBits();
6533 DebugLoc dl = Op.getDebugLoc();
6535 Op = Op.getOperand(0);
6536 if (VT == MVT::i8) {
6538 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6541 // Issue a bsf (scan bits forward) which also sets EFLAGS.
6542 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6543 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
6545 // If src is zero (i.e. bsf sets ZF), returns NumBits.
6546 SmallVector<SDValue, 4> Ops;
6548 Ops.push_back(DAG.getConstant(NumBits, OpVT));
6549 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6550 Ops.push_back(Op.getValue(1));
6551 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6554 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6558 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
6559 MVT VT = Op.getValueType();
6560 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
6561 DebugLoc dl = Op.getDebugLoc();
6563 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
6564 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
6565 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
6566 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
6567 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
6569 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
6570 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
6571 // return AloBlo + AloBhi + AhiBlo;
6573 SDValue A = Op.getOperand(0);
6574 SDValue B = Op.getOperand(1);
6576 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6577 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6578 A, DAG.getConstant(32, MVT::i32));
6579 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6580 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6581 B, DAG.getConstant(32, MVT::i32));
6582 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6583 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6585 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6586 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6588 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6589 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6591 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6592 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6593 AloBhi, DAG.getConstant(32, MVT::i32));
6594 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6595 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6596 AhiBlo, DAG.getConstant(32, MVT::i32));
6597 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
6598 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
6603 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
6604 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
6605 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
6606 // looks for this combo and may remove the "setcc" instruction if the "setcc"
6607 // has only one use.
6608 SDNode *N = Op.getNode();
6609 SDValue LHS = N->getOperand(0);
6610 SDValue RHS = N->getOperand(1);
6611 unsigned BaseOp = 0;
6613 DebugLoc dl = Op.getDebugLoc();
6615 switch (Op.getOpcode()) {
6616 default: assert(0 && "Unknown ovf instruction!");
6618 BaseOp = X86ISD::ADD;
6622 BaseOp = X86ISD::ADD;
6626 BaseOp = X86ISD::SUB;
6630 BaseOp = X86ISD::SUB;
6634 BaseOp = X86ISD::SMUL;
6638 BaseOp = X86ISD::UMUL;
6643 // Also sets EFLAGS.
6644 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
6645 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
6648 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
6649 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
6651 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
6655 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
6656 MVT T = Op.getValueType();
6657 DebugLoc dl = Op.getDebugLoc();
6660 switch(T.getSimpleVT()) {
6662 assert(false && "Invalid value type!");
6663 case MVT::i8: Reg = X86::AL; size = 1; break;
6664 case MVT::i16: Reg = X86::AX; size = 2; break;
6665 case MVT::i32: Reg = X86::EAX; size = 4; break;
6667 assert(Subtarget->is64Bit() && "Node not type legal!");
6668 Reg = X86::RAX; size = 8;
6671 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
6672 Op.getOperand(2), SDValue());
6673 SDValue Ops[] = { cpIn.getValue(0),
6676 DAG.getTargetConstant(size, MVT::i8),
6678 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6679 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
6681 DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
6685 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
6686 SelectionDAG &DAG) {
6687 assert(Subtarget->is64Bit() && "Result not type legalized?");
6688 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6689 SDValue TheChain = Op.getOperand(0);
6690 DebugLoc dl = Op.getDebugLoc();
6691 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6692 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
6693 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
6695 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
6696 DAG.getConstant(32, MVT::i8));
6698 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
6701 return DAG.getMergeValues(Ops, 2, dl);
6704 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
6705 SDNode *Node = Op.getNode();
6706 DebugLoc dl = Node->getDebugLoc();
6707 MVT T = Node->getValueType(0);
6708 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
6709 DAG.getConstant(0, T), Node->getOperand(2));
6710 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
6711 cast<AtomicSDNode>(Node)->getMemoryVT(),
6712 Node->getOperand(0),
6713 Node->getOperand(1), negOp,
6714 cast<AtomicSDNode>(Node)->getSrcValue(),
6715 cast<AtomicSDNode>(Node)->getAlignment());
6718 /// LowerOperation - Provide custom lowering hooks for some operations.
6720 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
6721 switch (Op.getOpcode()) {
6722 default: assert(0 && "Should not custom lower this!");
6723 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
6724 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
6725 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6726 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6727 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6728 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6729 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6730 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6731 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6732 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6733 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
6734 case ISD::SHL_PARTS:
6735 case ISD::SRA_PARTS:
6736 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
6737 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
6738 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
6739 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
6740 case ISD::FABS: return LowerFABS(Op, DAG);
6741 case ISD::FNEG: return LowerFNEG(Op, DAG);
6742 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6743 case ISD::SETCC: return LowerSETCC(Op, DAG);
6744 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
6745 case ISD::SELECT: return LowerSELECT(Op, DAG);
6746 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
6747 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6748 case ISD::CALL: return LowerCALL(Op, DAG);
6749 case ISD::RET: return LowerRET(Op, DAG);
6750 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
6751 case ISD::VASTART: return LowerVASTART(Op, DAG);
6752 case ISD::VAARG: return LowerVAARG(Op, DAG);
6753 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
6754 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6755 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6756 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6757 case ISD::FRAME_TO_ARGS_OFFSET:
6758 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
6759 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
6760 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
6761 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
6762 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6763 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
6764 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
6765 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
6771 case ISD::UMULO: return LowerXALUO(Op, DAG);
6772 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
6776 void X86TargetLowering::
6777 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
6778 SelectionDAG &DAG, unsigned NewOp) {
6779 MVT T = Node->getValueType(0);
6780 DebugLoc dl = Node->getDebugLoc();
6781 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
6783 SDValue Chain = Node->getOperand(0);
6784 SDValue In1 = Node->getOperand(1);
6785 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6786 Node->getOperand(2), DAG.getIntPtrConstant(0));
6787 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6788 Node->getOperand(2), DAG.getIntPtrConstant(1));
6789 // This is a generalized SDNode, not an AtomicSDNode, so it doesn't
6790 // have a MemOperand. Pass the info through as a normal operand.
6791 SDValue LSI = DAG.getMemOperand(cast<MemSDNode>(Node)->getMemOperand());
6792 SDValue Ops[] = { Chain, In1, In2L, In2H, LSI };
6793 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6794 SDValue Result = DAG.getNode(NewOp, dl, Tys, Ops, 5);
6795 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
6796 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6797 Results.push_back(Result.getValue(2));
6800 /// ReplaceNodeResults - Replace a node with an illegal result type
6801 /// with a new node built out of custom code.
6802 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
6803 SmallVectorImpl<SDValue>&Results,
6804 SelectionDAG &DAG) {
6805 DebugLoc dl = N->getDebugLoc();
6806 switch (N->getOpcode()) {
6808 assert(false && "Do not know how to custom type legalize this operation!");
6810 case ISD::FP_TO_SINT: {
6811 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(SDValue(N, 0), DAG);
6812 SDValue FIST = Vals.first, StackSlot = Vals.second;
6813 if (FIST.getNode() != 0) {
6814 MVT VT = N->getValueType(0);
6815 // Return a load from the stack slot.
6816 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0));
6820 case ISD::READCYCLECOUNTER: {
6821 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6822 SDValue TheChain = N->getOperand(0);
6823 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
6824 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
6826 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
6828 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
6829 SDValue Ops[] = { eax, edx };
6830 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
6831 Results.push_back(edx.getValue(1));
6834 case ISD::ATOMIC_CMP_SWAP: {
6835 MVT T = N->getValueType(0);
6836 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
6837 SDValue cpInL, cpInH;
6838 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
6839 DAG.getConstant(0, MVT::i32));
6840 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
6841 DAG.getConstant(1, MVT::i32));
6842 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
6843 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
6845 SDValue swapInL, swapInH;
6846 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
6847 DAG.getConstant(0, MVT::i32));
6848 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
6849 DAG.getConstant(1, MVT::i32));
6850 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
6852 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
6853 swapInL.getValue(1));
6854 SDValue Ops[] = { swapInH.getValue(0),
6856 swapInH.getValue(1) };
6857 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6858 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
6859 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
6860 MVT::i32, Result.getValue(1));
6861 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
6862 MVT::i32, cpOutL.getValue(2));
6863 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
6864 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
6865 Results.push_back(cpOutH.getValue(1));
6868 case ISD::ATOMIC_LOAD_ADD:
6869 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
6871 case ISD::ATOMIC_LOAD_AND:
6872 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
6874 case ISD::ATOMIC_LOAD_NAND:
6875 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
6877 case ISD::ATOMIC_LOAD_OR:
6878 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
6880 case ISD::ATOMIC_LOAD_SUB:
6881 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
6883 case ISD::ATOMIC_LOAD_XOR:
6884 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
6886 case ISD::ATOMIC_SWAP:
6887 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
6892 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
6894 default: return NULL;
6895 case X86ISD::BSF: return "X86ISD::BSF";
6896 case X86ISD::BSR: return "X86ISD::BSR";
6897 case X86ISD::SHLD: return "X86ISD::SHLD";
6898 case X86ISD::SHRD: return "X86ISD::SHRD";
6899 case X86ISD::FAND: return "X86ISD::FAND";
6900 case X86ISD::FOR: return "X86ISD::FOR";
6901 case X86ISD::FXOR: return "X86ISD::FXOR";
6902 case X86ISD::FSRL: return "X86ISD::FSRL";
6903 case X86ISD::FILD: return "X86ISD::FILD";
6904 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
6905 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
6906 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
6907 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
6908 case X86ISD::FLD: return "X86ISD::FLD";
6909 case X86ISD::FST: return "X86ISD::FST";
6910 case X86ISD::CALL: return "X86ISD::CALL";
6911 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
6912 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
6913 case X86ISD::BT: return "X86ISD::BT";
6914 case X86ISD::CMP: return "X86ISD::CMP";
6915 case X86ISD::COMI: return "X86ISD::COMI";
6916 case X86ISD::UCOMI: return "X86ISD::UCOMI";
6917 case X86ISD::SETCC: return "X86ISD::SETCC";
6918 case X86ISD::CMOV: return "X86ISD::CMOV";
6919 case X86ISD::BRCOND: return "X86ISD::BRCOND";
6920 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
6921 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
6922 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
6923 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
6924 case X86ISD::Wrapper: return "X86ISD::Wrapper";
6925 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
6926 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
6927 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
6928 case X86ISD::PINSRB: return "X86ISD::PINSRB";
6929 case X86ISD::PINSRW: return "X86ISD::PINSRW";
6930 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
6931 case X86ISD::FMAX: return "X86ISD::FMAX";
6932 case X86ISD::FMIN: return "X86ISD::FMIN";
6933 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
6934 case X86ISD::FRCP: return "X86ISD::FRCP";
6935 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
6936 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
6937 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
6938 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
6939 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
6940 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
6941 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
6942 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
6943 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
6944 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
6945 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
6946 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
6947 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
6948 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
6949 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
6950 case X86ISD::VSHL: return "X86ISD::VSHL";
6951 case X86ISD::VSRL: return "X86ISD::VSRL";
6952 case X86ISD::CMPPD: return "X86ISD::CMPPD";
6953 case X86ISD::CMPPS: return "X86ISD::CMPPS";
6954 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
6955 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
6956 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
6957 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
6958 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
6959 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
6960 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
6961 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
6962 case X86ISD::ADD: return "X86ISD::ADD";
6963 case X86ISD::SUB: return "X86ISD::SUB";
6964 case X86ISD::SMUL: return "X86ISD::SMUL";
6965 case X86ISD::UMUL: return "X86ISD::UMUL";
6969 // isLegalAddressingMode - Return true if the addressing mode represented
6970 // by AM is legal for this target, for a load/store of the specified type.
6971 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
6972 const Type *Ty) const {
6973 // X86 supports extremely general addressing modes.
6975 // X86 allows a sign-extended 32-bit immediate field as a displacement.
6976 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
6980 // We can only fold this if we don't need an extra load.
6981 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
6983 // If BaseGV requires a register, we cannot also have a BaseReg.
6984 if (Subtarget->GVRequiresRegister(AM.BaseGV, getTargetMachine(), false) &&
6988 // X86-64 only supports addr of globals in small code model.
6989 if (Subtarget->is64Bit()) {
6990 if (getTargetMachine().getCodeModel() != CodeModel::Small)
6992 // If lower 4G is not available, then we must use rip-relative addressing.
6993 if (AM.BaseOffs || AM.Scale > 1)
7004 // These scales always work.
7009 // These scales are formed with basereg+scalereg. Only accept if there is
7014 default: // Other stuff never works.
7022 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7023 if (!Ty1->isInteger() || !Ty2->isInteger())
7025 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7026 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7027 if (NumBits1 <= NumBits2)
7029 return Subtarget->is64Bit() || NumBits1 < 64;
7032 bool X86TargetLowering::isTruncateFree(MVT VT1, MVT VT2) const {
7033 if (!VT1.isInteger() || !VT2.isInteger())
7035 unsigned NumBits1 = VT1.getSizeInBits();
7036 unsigned NumBits2 = VT2.getSizeInBits();
7037 if (NumBits1 <= NumBits2)
7039 return Subtarget->is64Bit() || NumBits1 < 64;
7042 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7043 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7044 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7045 /// are assumed to be legal.
7047 X86TargetLowering::isShuffleMaskLegal(SDValue Mask, MVT VT) const {
7048 // Only do shuffles on 128-bit vector types for now.
7049 // FIXME: pshufb, blends
7050 if (VT.getSizeInBits() == 64) return false;
7051 return (Mask.getNode()->getNumOperands() <= 4 ||
7052 isIdentityMask(Mask.getNode()) ||
7053 isIdentityMask(Mask.getNode(), true) ||
7054 isSplatMask(Mask.getNode()) ||
7055 X86::isPSHUFHWMask(Mask.getNode()) ||
7056 X86::isPSHUFLWMask(Mask.getNode()) ||
7057 X86::isUNPCKLMask(Mask.getNode()) ||
7058 X86::isUNPCKHMask(Mask.getNode()) ||
7059 X86::isUNPCKL_v_undef_Mask(Mask.getNode()) ||
7060 X86::isUNPCKH_v_undef_Mask(Mask.getNode()));
7064 X86TargetLowering::isVectorClearMaskLegal(const std::vector<SDValue> &BVOps,
7065 MVT EVT, SelectionDAG &DAG) const {
7066 unsigned NumElts = BVOps.size();
7067 // Only do shuffles on 128-bit vector types for now.
7068 if (EVT.getSizeInBits() * NumElts == 64) return false;
7069 if (NumElts == 2) return true;
7071 return (isMOVLMask(&BVOps[0], 4) ||
7072 isCommutedMOVL(&BVOps[0], 4, true) ||
7073 isSHUFPMask(&BVOps[0], 4) ||
7074 isCommutedSHUFP(&BVOps[0], 4));
7079 //===----------------------------------------------------------------------===//
7080 // X86 Scheduler Hooks
7081 //===----------------------------------------------------------------------===//
7083 // private utility function
7085 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7086 MachineBasicBlock *MBB,
7094 TargetRegisterClass *RC,
7095 bool invSrc) const {
7096 // For the atomic bitwise operator, we generate
7099 // ld t1 = [bitinstr.addr]
7100 // op t2 = t1, [bitinstr.val]
7102 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7104 // fallthrough -->nextMBB
7105 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7106 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7107 MachineFunction::iterator MBBIter = MBB;
7110 /// First build the CFG
7111 MachineFunction *F = MBB->getParent();
7112 MachineBasicBlock *thisMBB = MBB;
7113 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7114 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7115 F->insert(MBBIter, newMBB);
7116 F->insert(MBBIter, nextMBB);
7118 // Move all successors to thisMBB to nextMBB
7119 nextMBB->transferSuccessors(thisMBB);
7121 // Update thisMBB to fall through to newMBB
7122 thisMBB->addSuccessor(newMBB);
7124 // newMBB jumps to itself and fall through to nextMBB
7125 newMBB->addSuccessor(nextMBB);
7126 newMBB->addSuccessor(newMBB);
7128 // Insert instructions into newMBB based on incoming instruction
7129 assert(bInstr->getNumOperands() < 8 && "unexpected number of operands");
7130 DebugLoc dl = bInstr->getDebugLoc();
7131 MachineOperand& destOper = bInstr->getOperand(0);
7132 MachineOperand* argOpers[6];
7133 int numArgs = bInstr->getNumOperands() - 1;
7134 for (int i=0; i < numArgs; ++i)
7135 argOpers[i] = &bInstr->getOperand(i+1);
7137 // x86 address has 4 operands: base, index, scale, and displacement
7138 int lastAddrIndx = 3; // [0,3]
7141 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7142 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7143 for (int i=0; i <= lastAddrIndx; ++i)
7144 (*MIB).addOperand(*argOpers[i]);
7146 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7148 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7153 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7154 assert((argOpers[valArgIndx]->isReg() ||
7155 argOpers[valArgIndx]->isImm()) &&
7157 if (argOpers[valArgIndx]->isReg())
7158 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7160 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7162 (*MIB).addOperand(*argOpers[valArgIndx]);
7164 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7167 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7168 for (int i=0; i <= lastAddrIndx; ++i)
7169 (*MIB).addOperand(*argOpers[i]);
7171 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7172 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7174 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7178 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7180 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7184 // private utility function: 64 bit atomics on 32 bit host.
7186 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7187 MachineBasicBlock *MBB,
7192 bool invSrc) const {
7193 // For the atomic bitwise operator, we generate
7194 // thisMBB (instructions are in pairs, except cmpxchg8b)
7195 // ld t1,t2 = [bitinstr.addr]
7197 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7198 // op t5, t6 <- out1, out2, [bitinstr.val]
7199 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
7200 // mov ECX, EBX <- t5, t6
7201 // mov EAX, EDX <- t1, t2
7202 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
7203 // mov t3, t4 <- EAX, EDX
7205 // result in out1, out2
7206 // fallthrough -->nextMBB
7208 const TargetRegisterClass *RC = X86::GR32RegisterClass;
7209 const unsigned LoadOpc = X86::MOV32rm;
7210 const unsigned copyOpc = X86::MOV32rr;
7211 const unsigned NotOpc = X86::NOT32r;
7212 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7213 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7214 MachineFunction::iterator MBBIter = MBB;
7217 /// First build the CFG
7218 MachineFunction *F = MBB->getParent();
7219 MachineBasicBlock *thisMBB = MBB;
7220 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7221 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7222 F->insert(MBBIter, newMBB);
7223 F->insert(MBBIter, nextMBB);
7225 // Move all successors to thisMBB to nextMBB
7226 nextMBB->transferSuccessors(thisMBB);
7228 // Update thisMBB to fall through to newMBB
7229 thisMBB->addSuccessor(newMBB);
7231 // newMBB jumps to itself and fall through to nextMBB
7232 newMBB->addSuccessor(nextMBB);
7233 newMBB->addSuccessor(newMBB);
7235 DebugLoc dl = bInstr->getDebugLoc();
7236 // Insert instructions into newMBB based on incoming instruction
7237 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7238 assert(bInstr->getNumOperands() < 18 && "unexpected number of operands");
7239 MachineOperand& dest1Oper = bInstr->getOperand(0);
7240 MachineOperand& dest2Oper = bInstr->getOperand(1);
7241 MachineOperand* argOpers[6];
7242 for (int i=0; i < 6; ++i)
7243 argOpers[i] = &bInstr->getOperand(i+2);
7245 // x86 address has 4 operands: base, index, scale, and displacement
7246 int lastAddrIndx = 3; // [0,3]
7248 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7249 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
7250 for (int i=0; i <= lastAddrIndx; ++i)
7251 (*MIB).addOperand(*argOpers[i]);
7252 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7253 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
7254 // add 4 to displacement.
7255 for (int i=0; i <= lastAddrIndx-1; ++i)
7256 (*MIB).addOperand(*argOpers[i]);
7257 MachineOperand newOp3 = *(argOpers[3]);
7259 newOp3.setImm(newOp3.getImm()+4);
7261 newOp3.setOffset(newOp3.getOffset()+4);
7262 (*MIB).addOperand(newOp3);
7264 // t3/4 are defined later, at the bottom of the loop
7265 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
7266 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
7267 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
7268 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
7269 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
7270 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
7272 unsigned tt1 = F->getRegInfo().createVirtualRegister(RC);
7273 unsigned tt2 = F->getRegInfo().createVirtualRegister(RC);
7275 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt1).addReg(t1);
7276 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt2).addReg(t2);
7282 assert((argOpers[4]->isReg() || argOpers[4]->isImm()) &&
7284 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
7285 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
7286 if (argOpers[4]->isReg())
7287 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
7289 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
7290 if (regOpcL != X86::MOV32rr)
7292 (*MIB).addOperand(*argOpers[4]);
7293 assert(argOpers[5]->isReg() == argOpers[4]->isReg());
7294 assert(argOpers[5]->isImm() == argOpers[4]->isImm());
7295 if (argOpers[5]->isReg())
7296 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
7298 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
7299 if (regOpcH != X86::MOV32rr)
7301 (*MIB).addOperand(*argOpers[5]);
7303 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
7305 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
7308 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
7310 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
7313 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
7314 for (int i=0; i <= lastAddrIndx; ++i)
7315 (*MIB).addOperand(*argOpers[i]);
7317 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7318 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
7320 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
7321 MIB.addReg(X86::EAX);
7322 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
7323 MIB.addReg(X86::EDX);
7326 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7328 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7332 // private utility function
7334 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
7335 MachineBasicBlock *MBB,
7336 unsigned cmovOpc) const {
7337 // For the atomic min/max operator, we generate
7340 // ld t1 = [min/max.addr]
7341 // mov t2 = [min/max.val]
7343 // cmov[cond] t2 = t1
7345 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7347 // fallthrough -->nextMBB
7349 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7350 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7351 MachineFunction::iterator MBBIter = MBB;
7354 /// First build the CFG
7355 MachineFunction *F = MBB->getParent();
7356 MachineBasicBlock *thisMBB = MBB;
7357 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7358 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7359 F->insert(MBBIter, newMBB);
7360 F->insert(MBBIter, nextMBB);
7362 // Move all successors to thisMBB to nextMBB
7363 nextMBB->transferSuccessors(thisMBB);
7365 // Update thisMBB to fall through to newMBB
7366 thisMBB->addSuccessor(newMBB);
7368 // newMBB jumps to newMBB and fall through to nextMBB
7369 newMBB->addSuccessor(nextMBB);
7370 newMBB->addSuccessor(newMBB);
7372 DebugLoc dl = mInstr->getDebugLoc();
7373 // Insert instructions into newMBB based on incoming instruction
7374 assert(mInstr->getNumOperands() < 8 && "unexpected number of operands");
7375 MachineOperand& destOper = mInstr->getOperand(0);
7376 MachineOperand* argOpers[6];
7377 int numArgs = mInstr->getNumOperands() - 1;
7378 for (int i=0; i < numArgs; ++i)
7379 argOpers[i] = &mInstr->getOperand(i+1);
7381 // x86 address has 4 operands: base, index, scale, and displacement
7382 int lastAddrIndx = 3; // [0,3]
7385 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7386 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
7387 for (int i=0; i <= lastAddrIndx; ++i)
7388 (*MIB).addOperand(*argOpers[i]);
7390 // We only support register and immediate values
7391 assert((argOpers[valArgIndx]->isReg() ||
7392 argOpers[valArgIndx]->isImm()) &&
7395 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7396 if (argOpers[valArgIndx]->isReg())
7397 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7399 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7400 (*MIB).addOperand(*argOpers[valArgIndx]);
7402 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
7405 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
7410 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7411 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
7415 // Cmp and exchange if none has modified the memory location
7416 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
7417 for (int i=0; i <= lastAddrIndx; ++i)
7418 (*MIB).addOperand(*argOpers[i]);
7420 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7421 (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
7423 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
7424 MIB.addReg(X86::EAX);
7427 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7429 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
7435 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7436 MachineBasicBlock *BB) const {
7437 DebugLoc dl = MI->getDebugLoc();
7438 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7439 switch (MI->getOpcode()) {
7440 default: assert(false && "Unexpected instr type to insert");
7441 case X86::CMOV_V1I64:
7442 case X86::CMOV_FR32:
7443 case X86::CMOV_FR64:
7444 case X86::CMOV_V4F32:
7445 case X86::CMOV_V2F64:
7446 case X86::CMOV_V2I64: {
7447 // To "insert" a SELECT_CC instruction, we actually have to insert the
7448 // diamond control-flow pattern. The incoming instruction knows the
7449 // destination vreg to set, the condition code register to branch on, the
7450 // true/false values to select between, and a branch opcode to use.
7451 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7452 MachineFunction::iterator It = BB;
7458 // cmpTY ccX, r1, r2
7460 // fallthrough --> copy0MBB
7461 MachineBasicBlock *thisMBB = BB;
7462 MachineFunction *F = BB->getParent();
7463 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7464 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7466 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
7467 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
7468 F->insert(It, copy0MBB);
7469 F->insert(It, sinkMBB);
7470 // Update machine-CFG edges by transferring all successors of the current
7471 // block to the new block which will contain the Phi node for the select.
7472 sinkMBB->transferSuccessors(BB);
7474 // Add the true and fallthrough blocks as its successors.
7475 BB->addSuccessor(copy0MBB);
7476 BB->addSuccessor(sinkMBB);
7479 // %FalseValue = ...
7480 // # fallthrough to sinkMBB
7483 // Update machine-CFG edges
7484 BB->addSuccessor(sinkMBB);
7487 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7490 BuildMI(BB, dl, TII->get(X86::PHI), MI->getOperand(0).getReg())
7491 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7492 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7494 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7498 case X86::FP32_TO_INT16_IN_MEM:
7499 case X86::FP32_TO_INT32_IN_MEM:
7500 case X86::FP32_TO_INT64_IN_MEM:
7501 case X86::FP64_TO_INT16_IN_MEM:
7502 case X86::FP64_TO_INT32_IN_MEM:
7503 case X86::FP64_TO_INT64_IN_MEM:
7504 case X86::FP80_TO_INT16_IN_MEM:
7505 case X86::FP80_TO_INT32_IN_MEM:
7506 case X86::FP80_TO_INT64_IN_MEM: {
7507 // Change the floating point control register to use "round towards zero"
7508 // mode when truncating to an integer value.
7509 MachineFunction *F = BB->getParent();
7510 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
7511 addFrameReference(BuildMI(BB, dl, TII->get(X86::FNSTCW16m)), CWFrameIdx);
7513 // Load the old value of the high byte of the control word...
7515 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
7516 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16rm), OldCW),
7519 // Set the high part to be round to zero...
7520 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mi)), CWFrameIdx)
7523 // Reload the modified control word now...
7524 addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7526 // Restore the memory image of control word to original value
7527 addFrameReference(BuildMI(BB, dl, TII->get(X86::MOV16mr)), CWFrameIdx)
7530 // Get the X86 opcode to use.
7532 switch (MI->getOpcode()) {
7533 default: assert(0 && "illegal opcode!");
7534 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
7535 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
7536 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
7537 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
7538 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
7539 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
7540 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
7541 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
7542 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
7546 MachineOperand &Op = MI->getOperand(0);
7548 AM.BaseType = X86AddressMode::RegBase;
7549 AM.Base.Reg = Op.getReg();
7551 AM.BaseType = X86AddressMode::FrameIndexBase;
7552 AM.Base.FrameIndex = Op.getIndex();
7554 Op = MI->getOperand(1);
7556 AM.Scale = Op.getImm();
7557 Op = MI->getOperand(2);
7559 AM.IndexReg = Op.getImm();
7560 Op = MI->getOperand(3);
7561 if (Op.isGlobal()) {
7562 AM.GV = Op.getGlobal();
7564 AM.Disp = Op.getImm();
7566 addFullAddress(BuildMI(BB, dl, TII->get(Opc)), AM)
7567 .addReg(MI->getOperand(4).getReg());
7569 // Reload the original control word now.
7570 addFrameReference(BuildMI(BB, dl, TII->get(X86::FLDCW16m)), CWFrameIdx);
7572 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7575 case X86::ATOMAND32:
7576 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7577 X86::AND32ri, X86::MOV32rm,
7578 X86::LCMPXCHG32, X86::MOV32rr,
7579 X86::NOT32r, X86::EAX,
7580 X86::GR32RegisterClass);
7582 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
7583 X86::OR32ri, X86::MOV32rm,
7584 X86::LCMPXCHG32, X86::MOV32rr,
7585 X86::NOT32r, X86::EAX,
7586 X86::GR32RegisterClass);
7587 case X86::ATOMXOR32:
7588 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
7589 X86::XOR32ri, X86::MOV32rm,
7590 X86::LCMPXCHG32, X86::MOV32rr,
7591 X86::NOT32r, X86::EAX,
7592 X86::GR32RegisterClass);
7593 case X86::ATOMNAND32:
7594 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7595 X86::AND32ri, X86::MOV32rm,
7596 X86::LCMPXCHG32, X86::MOV32rr,
7597 X86::NOT32r, X86::EAX,
7598 X86::GR32RegisterClass, true);
7599 case X86::ATOMMIN32:
7600 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
7601 case X86::ATOMMAX32:
7602 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
7603 case X86::ATOMUMIN32:
7604 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
7605 case X86::ATOMUMAX32:
7606 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
7608 case X86::ATOMAND16:
7609 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7610 X86::AND16ri, X86::MOV16rm,
7611 X86::LCMPXCHG16, X86::MOV16rr,
7612 X86::NOT16r, X86::AX,
7613 X86::GR16RegisterClass);
7615 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
7616 X86::OR16ri, X86::MOV16rm,
7617 X86::LCMPXCHG16, X86::MOV16rr,
7618 X86::NOT16r, X86::AX,
7619 X86::GR16RegisterClass);
7620 case X86::ATOMXOR16:
7621 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
7622 X86::XOR16ri, X86::MOV16rm,
7623 X86::LCMPXCHG16, X86::MOV16rr,
7624 X86::NOT16r, X86::AX,
7625 X86::GR16RegisterClass);
7626 case X86::ATOMNAND16:
7627 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7628 X86::AND16ri, X86::MOV16rm,
7629 X86::LCMPXCHG16, X86::MOV16rr,
7630 X86::NOT16r, X86::AX,
7631 X86::GR16RegisterClass, true);
7632 case X86::ATOMMIN16:
7633 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
7634 case X86::ATOMMAX16:
7635 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
7636 case X86::ATOMUMIN16:
7637 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
7638 case X86::ATOMUMAX16:
7639 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
7642 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7643 X86::AND8ri, X86::MOV8rm,
7644 X86::LCMPXCHG8, X86::MOV8rr,
7645 X86::NOT8r, X86::AL,
7646 X86::GR8RegisterClass);
7648 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
7649 X86::OR8ri, X86::MOV8rm,
7650 X86::LCMPXCHG8, X86::MOV8rr,
7651 X86::NOT8r, X86::AL,
7652 X86::GR8RegisterClass);
7654 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
7655 X86::XOR8ri, X86::MOV8rm,
7656 X86::LCMPXCHG8, X86::MOV8rr,
7657 X86::NOT8r, X86::AL,
7658 X86::GR8RegisterClass);
7659 case X86::ATOMNAND8:
7660 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7661 X86::AND8ri, X86::MOV8rm,
7662 X86::LCMPXCHG8, X86::MOV8rr,
7663 X86::NOT8r, X86::AL,
7664 X86::GR8RegisterClass, true);
7665 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
7666 // This group is for 64-bit host.
7667 case X86::ATOMAND64:
7668 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7669 X86::AND64ri32, X86::MOV64rm,
7670 X86::LCMPXCHG64, X86::MOV64rr,
7671 X86::NOT64r, X86::RAX,
7672 X86::GR64RegisterClass);
7674 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
7675 X86::OR64ri32, X86::MOV64rm,
7676 X86::LCMPXCHG64, X86::MOV64rr,
7677 X86::NOT64r, X86::RAX,
7678 X86::GR64RegisterClass);
7679 case X86::ATOMXOR64:
7680 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
7681 X86::XOR64ri32, X86::MOV64rm,
7682 X86::LCMPXCHG64, X86::MOV64rr,
7683 X86::NOT64r, X86::RAX,
7684 X86::GR64RegisterClass);
7685 case X86::ATOMNAND64:
7686 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7687 X86::AND64ri32, X86::MOV64rm,
7688 X86::LCMPXCHG64, X86::MOV64rr,
7689 X86::NOT64r, X86::RAX,
7690 X86::GR64RegisterClass, true);
7691 case X86::ATOMMIN64:
7692 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
7693 case X86::ATOMMAX64:
7694 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
7695 case X86::ATOMUMIN64:
7696 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
7697 case X86::ATOMUMAX64:
7698 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
7700 // This group does 64-bit operations on a 32-bit host.
7701 case X86::ATOMAND6432:
7702 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7703 X86::AND32rr, X86::AND32rr,
7704 X86::AND32ri, X86::AND32ri,
7706 case X86::ATOMOR6432:
7707 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7708 X86::OR32rr, X86::OR32rr,
7709 X86::OR32ri, X86::OR32ri,
7711 case X86::ATOMXOR6432:
7712 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7713 X86::XOR32rr, X86::XOR32rr,
7714 X86::XOR32ri, X86::XOR32ri,
7716 case X86::ATOMNAND6432:
7717 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7718 X86::AND32rr, X86::AND32rr,
7719 X86::AND32ri, X86::AND32ri,
7721 case X86::ATOMADD6432:
7722 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7723 X86::ADD32rr, X86::ADC32rr,
7724 X86::ADD32ri, X86::ADC32ri,
7726 case X86::ATOMSUB6432:
7727 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7728 X86::SUB32rr, X86::SBB32rr,
7729 X86::SUB32ri, X86::SBB32ri,
7731 case X86::ATOMSWAP6432:
7732 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7733 X86::MOV32rr, X86::MOV32rr,
7734 X86::MOV32ri, X86::MOV32ri,
7739 //===----------------------------------------------------------------------===//
7740 // X86 Optimization Hooks
7741 //===----------------------------------------------------------------------===//
7743 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
7747 const SelectionDAG &DAG,
7748 unsigned Depth) const {
7749 unsigned Opc = Op.getOpcode();
7750 assert((Opc >= ISD::BUILTIN_OP_END ||
7751 Opc == ISD::INTRINSIC_WO_CHAIN ||
7752 Opc == ISD::INTRINSIC_W_CHAIN ||
7753 Opc == ISD::INTRINSIC_VOID) &&
7754 "Should use MaskedValueIsZero if you don't know whether Op"
7755 " is a target node!");
7757 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
7764 // These nodes' second result is a boolean.
7765 if (Op.getResNo() == 0)
7769 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
7770 Mask.getBitWidth() - 1);
7775 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
7776 /// node is a GlobalAddress + offset.
7777 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
7778 GlobalValue* &GA, int64_t &Offset) const{
7779 if (N->getOpcode() == X86ISD::Wrapper) {
7780 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
7781 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
7782 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
7786 return TargetLowering::isGAPlusOffset(N, GA, Offset);
7789 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
7790 const TargetLowering &TLI) {
7793 if (TLI.isGAPlusOffset(Base, GV, Offset))
7794 return (GV->getAlignment() >= N && (Offset % N) == 0);
7795 // DAG combine handles the stack object case.
7799 static bool EltsFromConsecutiveLoads(SDNode *N, SDValue PermMask,
7800 unsigned NumElems, MVT EVT,
7802 SelectionDAG &DAG, MachineFrameInfo *MFI,
7803 const TargetLowering &TLI) {
7805 for (unsigned i = 0; i < NumElems; ++i) {
7806 SDValue Idx = PermMask.getOperand(i);
7807 if (Idx.getOpcode() == ISD::UNDEF) {
7813 SDValue Elt = DAG.getShuffleScalarElt(N, i);
7814 if (!Elt.getNode() ||
7815 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
7818 Base = Elt.getNode();
7819 if (Base->getOpcode() == ISD::UNDEF)
7823 if (Elt.getOpcode() == ISD::UNDEF)
7826 if (!TLI.isConsecutiveLoad(Elt.getNode(), Base,
7827 EVT.getSizeInBits()/8, i, MFI))
7833 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
7834 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
7835 /// if the load addresses are consecutive, non-overlapping, and in the right
7837 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
7838 const TargetLowering &TLI) {
7839 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7840 DebugLoc dl = N->getDebugLoc();
7841 MVT VT = N->getValueType(0);
7842 MVT EVT = VT.getVectorElementType();
7843 SDValue PermMask = N->getOperand(2);
7844 unsigned NumElems = PermMask.getNumOperands();
7845 SDNode *Base = NULL;
7846 if (!EltsFromConsecutiveLoads(N, PermMask, NumElems, EVT, Base,
7850 LoadSDNode *LD = cast<LoadSDNode>(Base);
7851 if (isBaseAlignmentOfN(16, Base->getOperand(1).getNode(), TLI))
7852 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
7853 LD->getSrcValue(), LD->getSrcValueOffset(),
7855 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
7856 LD->getSrcValue(), LD->getSrcValueOffset(),
7857 LD->isVolatile(), LD->getAlignment());
7860 /// PerformBuildVectorCombine - build_vector 0,(load i64 / f64) -> movq / movsd.
7861 static SDValue PerformBuildVectorCombine(SDNode *N, SelectionDAG &DAG,
7862 TargetLowering::DAGCombinerInfo &DCI,
7863 const X86Subtarget *Subtarget,
7864 const TargetLowering &TLI) {
7865 unsigned NumOps = N->getNumOperands();
7866 DebugLoc dl = N->getDebugLoc();
7868 // Ignore single operand BUILD_VECTOR.
7872 MVT VT = N->getValueType(0);
7873 MVT EVT = VT.getVectorElementType();
7874 if ((EVT != MVT::i64 && EVT != MVT::f64) || Subtarget->is64Bit())
7875 // We are looking for load i64 and zero extend. We want to transform
7876 // it before legalizer has a chance to expand it. Also look for i64
7877 // BUILD_PAIR bit casted to f64.
7879 // This must be an insertion into a zero vector.
7880 SDValue HighElt = N->getOperand(1);
7881 if (!isZeroNode(HighElt))
7884 // Value must be a load.
7885 SDNode *Base = N->getOperand(0).getNode();
7886 if (!isa<LoadSDNode>(Base)) {
7887 if (Base->getOpcode() != ISD::BIT_CONVERT)
7889 Base = Base->getOperand(0).getNode();
7890 if (!isa<LoadSDNode>(Base))
7894 // Transform it into VZEXT_LOAD addr.
7895 LoadSDNode *LD = cast<LoadSDNode>(Base);
7897 // Load must not be an extload.
7898 if (LD->getExtensionType() != ISD::NON_EXTLOAD)
7901 // Load type should legal type so we don't have to legalize it.
7902 if (!TLI.isTypeLegal(VT))
7905 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
7906 SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
7907 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
7908 TargetLowering::TargetLoweringOpt TLO(DAG);
7909 TLO.CombineTo(SDValue(Base, 1), ResNode.getValue(1));
7910 DCI.CommitTargetLoweringOpt(TLO);
7914 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
7915 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
7916 const X86Subtarget *Subtarget) {
7917 DebugLoc dl = N->getDebugLoc();
7918 SDValue Cond = N->getOperand(0);
7920 // If we have SSE[12] support, try to form min/max nodes.
7921 if (Subtarget->hasSSE2() &&
7922 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
7923 if (Cond.getOpcode() == ISD::SETCC) {
7924 // Get the LHS/RHS of the select.
7925 SDValue LHS = N->getOperand(1);
7926 SDValue RHS = N->getOperand(2);
7927 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
7929 unsigned Opcode = 0;
7930 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
7933 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
7936 if (!UnsafeFPMath) break;
7938 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
7940 Opcode = X86ISD::FMIN;
7943 case ISD::SETOGT: // (X > Y) ? X : Y -> max
7946 if (!UnsafeFPMath) break;
7948 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
7950 Opcode = X86ISD::FMAX;
7953 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
7956 case ISD::SETOGT: // (X > Y) ? Y : X -> min
7959 if (!UnsafeFPMath) break;
7961 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
7963 Opcode = X86ISD::FMIN;
7966 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
7969 if (!UnsafeFPMath) break;
7971 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
7973 Opcode = X86ISD::FMAX;
7979 return DAG.getNode(Opcode, dl, N->getValueType(0), LHS, RHS);
7987 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
7989 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
7990 const X86Subtarget *Subtarget) {
7991 // On X86 with SSE2 support, we can transform this to a vector shift if
7992 // all elements are shifted by the same amount. We can't do this in legalize
7993 // because the a constant vector is typically transformed to a constant pool
7994 // so we have no knowledge of the shift amount.
7995 if (!Subtarget->hasSSE2())
7998 MVT VT = N->getValueType(0);
7999 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
8002 SDValue ShAmtOp = N->getOperand(1);
8003 MVT EltVT = VT.getVectorElementType();
8004 DebugLoc dl = N->getDebugLoc();
8006 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
8007 unsigned NumElts = VT.getVectorNumElements();
8009 for (; i != NumElts; ++i) {
8010 SDValue Arg = ShAmtOp.getOperand(i);
8011 if (Arg.getOpcode() == ISD::UNDEF) continue;
8015 for (; i != NumElts; ++i) {
8016 SDValue Arg = ShAmtOp.getOperand(i);
8017 if (Arg.getOpcode() == ISD::UNDEF) continue;
8018 if (Arg != BaseShAmt) {
8022 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
8023 isSplatMask(ShAmtOp.getOperand(2).getNode())) {
8024 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, ShAmtOp,
8025 DAG.getIntPtrConstant(0));
8029 if (EltVT.bitsGT(MVT::i32))
8030 BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
8031 else if (EltVT.bitsLT(MVT::i32))
8032 BaseShAmt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, BaseShAmt);
8034 // The shift amount is identical so we can do a vector shift.
8035 SDValue ValOp = N->getOperand(0);
8036 switch (N->getOpcode()) {
8038 assert(0 && "Unknown shift opcode!");
8041 if (VT == MVT::v2i64)
8042 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8043 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8045 if (VT == MVT::v4i32)
8046 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8047 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8049 if (VT == MVT::v8i16)
8050 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8051 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8055 if (VT == MVT::v4i32)
8056 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8057 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8059 if (VT == MVT::v8i16)
8060 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8061 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8065 if (VT == MVT::v2i64)
8066 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8067 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8069 if (VT == MVT::v4i32)
8070 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8071 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8073 if (VT == MVT::v8i16)
8074 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8075 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8082 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
8083 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
8084 const X86Subtarget *Subtarget) {
8085 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
8086 // the FP state in cases where an emms may be missing.
8087 // A preferable solution to the general problem is to figure out the right
8088 // places to insert EMMS. This qualifies as a quick hack.
8089 StoreSDNode *St = cast<StoreSDNode>(N);
8090 if (St->getValue().getValueType().isVector() &&
8091 St->getValue().getValueType().getSizeInBits() == 64 &&
8092 isa<LoadSDNode>(St->getValue()) &&
8093 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
8094 St->getChain().hasOneUse() && !St->isVolatile()) {
8095 SDNode* LdVal = St->getValue().getNode();
8097 int TokenFactorIndex = -1;
8098 SmallVector<SDValue, 8> Ops;
8099 SDNode* ChainVal = St->getChain().getNode();
8100 // Must be a store of a load. We currently handle two cases: the load
8101 // is a direct child, and it's under an intervening TokenFactor. It is
8102 // possible to dig deeper under nested TokenFactors.
8103 if (ChainVal == LdVal)
8104 Ld = cast<LoadSDNode>(St->getChain());
8105 else if (St->getValue().hasOneUse() &&
8106 ChainVal->getOpcode() == ISD::TokenFactor) {
8107 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
8108 if (ChainVal->getOperand(i).getNode() == LdVal) {
8109 TokenFactorIndex = i;
8110 Ld = cast<LoadSDNode>(St->getValue());
8112 Ops.push_back(ChainVal->getOperand(i));
8116 DebugLoc dl = N->getDebugLoc();
8117 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
8118 if (Subtarget->is64Bit()) {
8119 SDValue NewLd = DAG.getLoad(MVT::i64, dl, Ld->getChain(),
8120 Ld->getBasePtr(), Ld->getSrcValue(),
8121 Ld->getSrcValueOffset(), Ld->isVolatile(),
8122 Ld->getAlignment());
8123 SDValue NewChain = NewLd.getValue(1);
8124 if (TokenFactorIndex != -1) {
8125 Ops.push_back(NewChain);
8126 NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Ops[0],
8129 return DAG.getStore(NewChain, dl, NewLd, St->getBasePtr(),
8130 St->getSrcValue(), St->getSrcValueOffset(),
8131 St->isVolatile(), St->getAlignment());
8134 // Otherwise, lower to two 32-bit copies.
8135 SDValue LoAddr = Ld->getBasePtr();
8136 SDValue HiAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, LoAddr,
8137 DAG.getConstant(4, MVT::i32));
8139 SDValue LoLd = DAG.getLoad(MVT::i32, dl, Ld->getChain(), LoAddr,
8140 Ld->getSrcValue(), Ld->getSrcValueOffset(),
8141 Ld->isVolatile(), Ld->getAlignment());
8142 SDValue HiLd = DAG.getLoad(MVT::i32, dl, Ld->getChain(), HiAddr,
8143 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
8145 MinAlign(Ld->getAlignment(), 4));
8147 SDValue NewChain = LoLd.getValue(1);
8148 if (TokenFactorIndex != -1) {
8149 Ops.push_back(LoLd);
8150 Ops.push_back(HiLd);
8151 NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Ops[0],
8155 LoAddr = St->getBasePtr();
8156 HiAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, LoAddr,
8157 DAG.getConstant(4, MVT::i32));
8159 SDValue LoSt = DAG.getStore(NewChain, dl, LoLd, LoAddr,
8160 St->getSrcValue(), St->getSrcValueOffset(),
8161 St->isVolatile(), St->getAlignment());
8162 SDValue HiSt = DAG.getStore(NewChain, dl, HiLd, HiAddr,
8164 St->getSrcValueOffset() + 4,
8166 MinAlign(St->getAlignment(), 4));
8167 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoSt, HiSt);
8173 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
8174 /// X86ISD::FXOR nodes.
8175 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
8176 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
8177 // F[X]OR(0.0, x) -> x
8178 // F[X]OR(x, 0.0) -> x
8179 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8180 if (C->getValueAPF().isPosZero())
8181 return N->getOperand(1);
8182 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8183 if (C->getValueAPF().isPosZero())
8184 return N->getOperand(0);
8188 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
8189 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
8190 // FAND(0.0, x) -> 0.0
8191 // FAND(x, 0.0) -> 0.0
8192 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
8193 if (C->getValueAPF().isPosZero())
8194 return N->getOperand(0);
8195 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
8196 if (C->getValueAPF().isPosZero())
8197 return N->getOperand(1);
8201 static SDValue PerformBTCombine(SDNode *N,
8203 TargetLowering::DAGCombinerInfo &DCI) {
8204 // BT ignores high bits in the bit index operand.
8205 SDValue Op1 = N->getOperand(1);
8206 if (Op1.hasOneUse()) {
8207 unsigned BitWidth = Op1.getValueSizeInBits();
8208 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
8209 APInt KnownZero, KnownOne;
8210 TargetLowering::TargetLoweringOpt TLO(DAG);
8211 TargetLowering &TLI = DAG.getTargetLoweringInfo();
8212 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
8213 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
8214 DCI.CommitTargetLoweringOpt(TLO);
8219 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
8220 DAGCombinerInfo &DCI) const {
8221 SelectionDAG &DAG = DCI.DAG;
8222 switch (N->getOpcode()) {
8224 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
8225 case ISD::BUILD_VECTOR:
8226 return PerformBuildVectorCombine(N, DAG, DCI, Subtarget, *this);
8227 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
8230 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
8231 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
8233 case X86ISD::FOR: return PerformFORCombine(N, DAG);
8234 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
8235 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
8241 //===----------------------------------------------------------------------===//
8242 // X86 Inline Assembly Support
8243 //===----------------------------------------------------------------------===//
8245 /// getConstraintType - Given a constraint letter, return the type of
8246 /// constraint it is for this target.
8247 X86TargetLowering::ConstraintType
8248 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
8249 if (Constraint.size() == 1) {
8250 switch (Constraint[0]) {
8262 return C_RegisterClass;
8270 return TargetLowering::getConstraintType(Constraint);
8273 /// LowerXConstraint - try to replace an X constraint, which matches anything,
8274 /// with another that has more specific requirements based on the type of the
8275 /// corresponding operand.
8276 const char *X86TargetLowering::
8277 LowerXConstraint(MVT ConstraintVT) const {
8278 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
8279 // 'f' like normal targets.
8280 if (ConstraintVT.isFloatingPoint()) {
8281 if (Subtarget->hasSSE2())
8283 if (Subtarget->hasSSE1())
8287 return TargetLowering::LowerXConstraint(ConstraintVT);
8290 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
8291 /// vector. If it is invalid, don't add anything to Ops.
8292 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
8295 std::vector<SDValue>&Ops,
8296 SelectionDAG &DAG) const {
8297 SDValue Result(0, 0);
8299 switch (Constraint) {
8302 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8303 if (C->getZExtValue() <= 31) {
8304 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8310 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8311 if (C->getZExtValue() <= 63) {
8312 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8318 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8319 if (C->getZExtValue() <= 255) {
8320 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8326 // 32-bit signed value
8327 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8328 const ConstantInt *CI = C->getConstantIntValue();
8329 if (CI->isValueValidForType(Type::Int32Ty, C->getSExtValue())) {
8330 // Widen to 64 bits here to get it sign extended.
8331 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
8334 // FIXME gcc accepts some relocatable values here too, but only in certain
8335 // memory models; it's complicated.
8340 // 32-bit unsigned value
8341 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
8342 const ConstantInt *CI = C->getConstantIntValue();
8343 if (CI->isValueValidForType(Type::Int32Ty, C->getZExtValue())) {
8344 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
8348 // FIXME gcc accepts some relocatable values here too, but only in certain
8349 // memory models; it's complicated.
8353 // Literal immediates are always ok.
8354 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
8355 // Widen to 64 bits here to get it sign extended.
8356 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
8360 // If we are in non-pic codegen mode, we allow the address of a global (with
8361 // an optional displacement) to be used with 'i'.
8362 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
8365 // Match either (GA) or (GA+C)
8367 Offset = GA->getOffset();
8368 } else if (Op.getOpcode() == ISD::ADD) {
8369 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8370 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
8372 Offset = GA->getOffset()+C->getZExtValue();
8374 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8375 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
8377 Offset = GA->getOffset()+C->getZExtValue();
8385 Op = LowerGlobalAddress(GA->getGlobal(), Op.getDebugLoc(),
8388 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
8394 // Otherwise, not valid for this mode.
8399 if (Result.getNode()) {
8400 Ops.push_back(Result);
8403 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
8407 std::vector<unsigned> X86TargetLowering::
8408 getRegClassForInlineAsmConstraint(const std::string &Constraint,
8410 if (Constraint.size() == 1) {
8411 // FIXME: not handling fp-stack yet!
8412 switch (Constraint[0]) { // GCC X86 Constraint Letters
8413 default: break; // Unknown constraint letter
8414 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
8417 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
8418 else if (VT == MVT::i16)
8419 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
8420 else if (VT == MVT::i8)
8421 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
8422 else if (VT == MVT::i64)
8423 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
8428 return std::vector<unsigned>();
8431 std::pair<unsigned, const TargetRegisterClass*>
8432 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
8434 // First, see if this is a constraint that directly corresponds to an LLVM
8436 if (Constraint.size() == 1) {
8437 // GCC Constraint Letters
8438 switch (Constraint[0]) {
8440 case 'r': // GENERAL_REGS
8441 case 'R': // LEGACY_REGS
8442 case 'l': // INDEX_REGS
8444 return std::make_pair(0U, X86::GR8RegisterClass);
8446 return std::make_pair(0U, X86::GR16RegisterClass);
8447 if (VT == MVT::i32 || !Subtarget->is64Bit())
8448 return std::make_pair(0U, X86::GR32RegisterClass);
8449 return std::make_pair(0U, X86::GR64RegisterClass);
8450 case 'f': // FP Stack registers.
8451 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
8452 // value to the correct fpstack register class.
8453 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
8454 return std::make_pair(0U, X86::RFP32RegisterClass);
8455 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
8456 return std::make_pair(0U, X86::RFP64RegisterClass);
8457 return std::make_pair(0U, X86::RFP80RegisterClass);
8458 case 'y': // MMX_REGS if MMX allowed.
8459 if (!Subtarget->hasMMX()) break;
8460 return std::make_pair(0U, X86::VR64RegisterClass);
8461 case 'Y': // SSE_REGS if SSE2 allowed
8462 if (!Subtarget->hasSSE2()) break;
8464 case 'x': // SSE_REGS if SSE1 allowed
8465 if (!Subtarget->hasSSE1()) break;
8467 switch (VT.getSimpleVT()) {
8469 // Scalar SSE types.
8472 return std::make_pair(0U, X86::FR32RegisterClass);
8475 return std::make_pair(0U, X86::FR64RegisterClass);
8483 return std::make_pair(0U, X86::VR128RegisterClass);
8489 // Use the default implementation in TargetLowering to convert the register
8490 // constraint into a member of a register class.
8491 std::pair<unsigned, const TargetRegisterClass*> Res;
8492 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
8494 // Not found as a standard register?
8495 if (Res.second == 0) {
8496 // GCC calls "st(0)" just plain "st".
8497 if (StringsEqualNoCase("{st}", Constraint)) {
8498 Res.first = X86::ST0;
8499 Res.second = X86::RFP80RegisterClass;
8501 // 'A' means EAX + EDX.
8502 if (Constraint == "A") {
8503 Res.first = X86::EAX;
8504 Res.second = X86::GRADRegisterClass;
8509 // Otherwise, check to see if this is a register class of the wrong value
8510 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
8511 // turn into {ax},{dx}.
8512 if (Res.second->hasType(VT))
8513 return Res; // Correct type already, nothing to do.
8515 // All of the single-register GCC register classes map their values onto
8516 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
8517 // really want an 8-bit or 32-bit register, map to the appropriate register
8518 // class and return the appropriate register.
8519 if (Res.second == X86::GR16RegisterClass) {
8520 if (VT == MVT::i8) {
8521 unsigned DestReg = 0;
8522 switch (Res.first) {
8524 case X86::AX: DestReg = X86::AL; break;
8525 case X86::DX: DestReg = X86::DL; break;
8526 case X86::CX: DestReg = X86::CL; break;
8527 case X86::BX: DestReg = X86::BL; break;
8530 Res.first = DestReg;
8531 Res.second = Res.second = X86::GR8RegisterClass;
8533 } else if (VT == MVT::i32) {
8534 unsigned DestReg = 0;
8535 switch (Res.first) {
8537 case X86::AX: DestReg = X86::EAX; break;
8538 case X86::DX: DestReg = X86::EDX; break;
8539 case X86::CX: DestReg = X86::ECX; break;
8540 case X86::BX: DestReg = X86::EBX; break;
8541 case X86::SI: DestReg = X86::ESI; break;
8542 case X86::DI: DestReg = X86::EDI; break;
8543 case X86::BP: DestReg = X86::EBP; break;
8544 case X86::SP: DestReg = X86::ESP; break;
8547 Res.first = DestReg;
8548 Res.second = Res.second = X86::GR32RegisterClass;
8550 } else if (VT == MVT::i64) {
8551 unsigned DestReg = 0;
8552 switch (Res.first) {
8554 case X86::AX: DestReg = X86::RAX; break;
8555 case X86::DX: DestReg = X86::RDX; break;
8556 case X86::CX: DestReg = X86::RCX; break;
8557 case X86::BX: DestReg = X86::RBX; break;
8558 case X86::SI: DestReg = X86::RSI; break;
8559 case X86::DI: DestReg = X86::RDI; break;
8560 case X86::BP: DestReg = X86::RBP; break;
8561 case X86::SP: DestReg = X86::RSP; break;
8564 Res.first = DestReg;
8565 Res.second = Res.second = X86::GR64RegisterClass;
8568 } else if (Res.second == X86::FR32RegisterClass ||
8569 Res.second == X86::FR64RegisterClass ||
8570 Res.second == X86::VR128RegisterClass) {
8571 // Handle references to XMM physical registers that got mapped into the
8572 // wrong class. This can happen with constraints like {xmm0} where the
8573 // target independent register mapper will just pick the first match it can
8574 // find, ignoring the required type.
8576 Res.second = X86::FR32RegisterClass;
8577 else if (VT == MVT::f64)
8578 Res.second = X86::FR64RegisterClass;
8579 else if (X86::VR128RegisterClass->hasType(VT))
8580 Res.second = X86::VR128RegisterClass;
8586 //===----------------------------------------------------------------------===//
8587 // X86 Widen vector type
8588 //===----------------------------------------------------------------------===//
8590 /// getWidenVectorType: given a vector type, returns the type to widen
8591 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
8592 /// If there is no vector type that we want to widen to, returns MVT::Other
8593 /// When and where to widen is target dependent based on the cost of
8594 /// scalarizing vs using the wider vector type.
8596 MVT X86TargetLowering::getWidenVectorType(MVT VT) const {
8597 assert(VT.isVector());
8598 if (isTypeLegal(VT))
8601 // TODO: In computeRegisterProperty, we can compute the list of legal vector
8602 // type based on element type. This would speed up our search (though
8603 // it may not be worth it since the size of the list is relatively
8605 MVT EltVT = VT.getVectorElementType();
8606 unsigned NElts = VT.getVectorNumElements();
8608 // On X86, it make sense to widen any vector wider than 1
8612 for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
8613 nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
8614 MVT SVT = (MVT::SimpleValueType)nVT;
8616 if (isTypeLegal(SVT) &&
8617 SVT.getVectorElementType() == EltVT &&
8618 SVT.getVectorNumElements() > NElts)