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/Analysis/ScalarEvolutionExpressions.h"
29 #include "llvm/CodeGen/CallingConvLower.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/PseudoSourceValue.h"
36 #include "llvm/CodeGen/SelectionDAG.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/ADT/SmallSet.h"
41 #include "llvm/ADT/StringExtras.h"
44 X86TargetLowering::X86TargetLowering(TargetMachine &TM)
45 : TargetLowering(TM) {
46 Subtarget = &TM.getSubtarget<X86Subtarget>();
47 X86ScalarSSEf64 = Subtarget->hasSSE2();
48 X86ScalarSSEf32 = Subtarget->hasSSE1();
49 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
53 RegInfo = TM.getRegisterInfo();
55 // Set up the TargetLowering object.
57 // X86 is weird, it always uses i8 for shift amounts and setcc results.
58 setShiftAmountType(MVT::i8);
59 setSetCCResultContents(ZeroOrOneSetCCResult);
60 setSchedulingPreference(SchedulingForRegPressure);
61 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
62 setStackPointerRegisterToSaveRestore(X86StackPtr);
64 if (Subtarget->isTargetDarwin()) {
65 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
66 setUseUnderscoreSetJmp(false);
67 setUseUnderscoreLongJmp(false);
68 } else if (Subtarget->isTargetMingw()) {
69 // MS runtime is weird: it exports _setjmp, but longjmp!
70 setUseUnderscoreSetJmp(true);
71 setUseUnderscoreLongJmp(false);
73 setUseUnderscoreSetJmp(true);
74 setUseUnderscoreLongJmp(true);
77 // Set up the register classes.
78 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
79 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
80 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
81 if (Subtarget->is64Bit())
82 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
84 setLoadXAction(ISD::SEXTLOAD, MVT::i1, Promote);
86 // We don't accept any truncstore of integer registers.
87 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
88 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
89 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
90 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
91 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
92 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
94 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
96 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
97 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
98 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
100 if (Subtarget->is64Bit()) {
101 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
102 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
105 // If SSE i64 SINT_TO_FP is not available, expand i32 UINT_TO_FP.
106 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Expand);
108 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
111 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
113 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
114 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
115 // SSE has no i16 to fp conversion, only i32
116 if (X86ScalarSSEf32) {
117 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
118 // f32 and f64 cases are Legal, f80 case is not
119 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
121 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
122 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
125 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
126 // are Legal, f80 is custom lowered.
127 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
128 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
130 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
132 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
133 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
135 if (X86ScalarSSEf32) {
136 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
137 // f32 and f64 cases are Legal, f80 case is not
138 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
140 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
141 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
144 // Handle FP_TO_UINT by promoting the destination to a larger signed
146 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
147 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
148 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
150 if (Subtarget->is64Bit()) {
151 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
152 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
154 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
155 // Expand FP_TO_UINT into a select.
156 // FIXME: We would like to use a Custom expander here eventually to do
157 // the optimal thing for SSE vs. the default expansion in the legalizer.
158 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
160 // With SSE3 we can use fisttpll to convert to a signed i64.
161 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
164 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
165 if (!X86ScalarSSEf64) {
166 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
167 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
170 // Scalar integer divide and remainder are lowered to use operations that
171 // produce two results, to match the available instructions. This exposes
172 // the two-result form to trivial CSE, which is able to combine x/y and x%y
173 // into a single instruction.
175 // Scalar integer multiply-high is also lowered to use two-result
176 // operations, to match the available instructions. However, plain multiply
177 // (low) operations are left as Legal, as there are single-result
178 // instructions for this in x86. Using the two-result multiply instructions
179 // when both high and low results are needed must be arranged by dagcombine.
180 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
181 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
182 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
183 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
184 setOperationAction(ISD::SREM , MVT::i8 , Expand);
185 setOperationAction(ISD::UREM , MVT::i8 , Expand);
186 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
187 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
188 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
189 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
190 setOperationAction(ISD::SREM , MVT::i16 , Expand);
191 setOperationAction(ISD::UREM , MVT::i16 , Expand);
192 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
193 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
194 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
195 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
196 setOperationAction(ISD::SREM , MVT::i32 , Expand);
197 setOperationAction(ISD::UREM , MVT::i32 , Expand);
198 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
199 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
200 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
201 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
202 setOperationAction(ISD::SREM , MVT::i64 , Expand);
203 setOperationAction(ISD::UREM , MVT::i64 , Expand);
205 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
206 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
207 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
208 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
209 if (Subtarget->is64Bit())
210 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
211 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
212 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
213 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
214 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
215 setOperationAction(ISD::FREM , MVT::f32 , Expand);
216 setOperationAction(ISD::FREM , MVT::f64 , Expand);
217 setOperationAction(ISD::FREM , MVT::f80 , Expand);
218 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
220 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
221 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
222 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
223 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
224 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
225 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
226 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
227 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
228 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
229 if (Subtarget->is64Bit()) {
230 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
231 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
232 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
235 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
236 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
238 // These should be promoted to a larger select which is supported.
239 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
240 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
241 // X86 wants to expand cmov itself.
242 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
243 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
244 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
245 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
246 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
247 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
248 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
249 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
250 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
251 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
252 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
253 if (Subtarget->is64Bit()) {
254 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
255 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
257 // X86 ret instruction may pop stack.
258 setOperationAction(ISD::RET , MVT::Other, Custom);
259 if (!Subtarget->is64Bit())
260 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
263 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
264 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
265 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
266 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
267 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
268 if (Subtarget->is64Bit()) {
269 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
270 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
271 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
272 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
274 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
275 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
276 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
277 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
278 if (Subtarget->is64Bit()) {
279 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
280 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
281 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
284 if (Subtarget->hasSSE1())
285 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
287 if (!Subtarget->hasSSE2())
288 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
290 setOperationAction(ISD::ATOMIC_LCS , MVT::i8, Custom);
291 setOperationAction(ISD::ATOMIC_LCS , MVT::i16, Custom);
292 setOperationAction(ISD::ATOMIC_LCS , MVT::i32, Custom);
293 setOperationAction(ISD::ATOMIC_LCS , MVT::i64, Custom);
295 // Use the default ISD::LOCATION, ISD::DECLARE expansion.
296 setOperationAction(ISD::LOCATION, MVT::Other, Expand);
297 // FIXME - use subtarget debug flags
298 if (!Subtarget->isTargetDarwin() &&
299 !Subtarget->isTargetELF() &&
300 !Subtarget->isTargetCygMing())
301 setOperationAction(ISD::LABEL, MVT::Other, Expand);
303 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
304 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
305 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
306 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
307 if (Subtarget->is64Bit()) {
309 setExceptionPointerRegister(X86::RAX);
310 setExceptionSelectorRegister(X86::RDX);
312 setExceptionPointerRegister(X86::EAX);
313 setExceptionSelectorRegister(X86::EDX);
315 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
317 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
319 setOperationAction(ISD::TRAP, MVT::Other, Legal);
321 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
322 setOperationAction(ISD::VASTART , MVT::Other, Custom);
323 setOperationAction(ISD::VAARG , MVT::Other, Expand);
324 setOperationAction(ISD::VAEND , MVT::Other, Expand);
325 if (Subtarget->is64Bit())
326 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
328 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
330 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
331 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
332 if (Subtarget->is64Bit())
333 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
334 if (Subtarget->isTargetCygMing())
335 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
337 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
339 if (X86ScalarSSEf64) {
340 // f32 and f64 use SSE.
341 // Set up the FP register classes.
342 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
343 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
345 // Use ANDPD to simulate FABS.
346 setOperationAction(ISD::FABS , MVT::f64, Custom);
347 setOperationAction(ISD::FABS , MVT::f32, Custom);
349 // Use XORP to simulate FNEG.
350 setOperationAction(ISD::FNEG , MVT::f64, Custom);
351 setOperationAction(ISD::FNEG , MVT::f32, Custom);
353 // Use ANDPD and ORPD to simulate FCOPYSIGN.
354 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
355 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
357 // We don't support sin/cos/fmod
358 setOperationAction(ISD::FSIN , MVT::f64, Expand);
359 setOperationAction(ISD::FCOS , MVT::f64, Expand);
360 setOperationAction(ISD::FSIN , MVT::f32, Expand);
361 setOperationAction(ISD::FCOS , MVT::f32, Expand);
363 // Expand FP immediates into loads from the stack, except for the special
365 addLegalFPImmediate(APFloat(+0.0)); // xorpd
366 addLegalFPImmediate(APFloat(+0.0f)); // xorps
368 // Floating truncations from f80 and extensions to f80 go through memory.
369 // If optimizing, we lie about this though and handle it in
370 // InstructionSelectPreprocess so that dagcombine2 can hack on these.
372 setConvertAction(MVT::f32, MVT::f80, Expand);
373 setConvertAction(MVT::f64, MVT::f80, Expand);
374 setConvertAction(MVT::f80, MVT::f32, Expand);
375 setConvertAction(MVT::f80, MVT::f64, Expand);
377 } else if (X86ScalarSSEf32) {
378 // Use SSE for f32, x87 for f64.
379 // Set up the FP register classes.
380 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
381 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
383 // Use ANDPS to simulate FABS.
384 setOperationAction(ISD::FABS , MVT::f32, Custom);
386 // Use XORP to simulate FNEG.
387 setOperationAction(ISD::FNEG , MVT::f32, Custom);
389 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
391 // Use ANDPS and ORPS to simulate FCOPYSIGN.
392 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
393 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
395 // We don't support sin/cos/fmod
396 setOperationAction(ISD::FSIN , MVT::f32, Expand);
397 setOperationAction(ISD::FCOS , MVT::f32, Expand);
399 // Special cases we handle for FP constants.
400 addLegalFPImmediate(APFloat(+0.0f)); // xorps
401 addLegalFPImmediate(APFloat(+0.0)); // FLD0
402 addLegalFPImmediate(APFloat(+1.0)); // FLD1
403 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
404 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
406 // SSE <-> X87 conversions go through memory. If optimizing, we lie about
407 // this though and handle it in InstructionSelectPreprocess so that
408 // dagcombine2 can hack on these.
410 setConvertAction(MVT::f32, MVT::f64, Expand);
411 setConvertAction(MVT::f32, MVT::f80, Expand);
412 setConvertAction(MVT::f80, MVT::f32, Expand);
413 setConvertAction(MVT::f64, MVT::f32, Expand);
414 // And x87->x87 truncations also.
415 setConvertAction(MVT::f80, MVT::f64, Expand);
419 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
420 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
423 // f32 and f64 in x87.
424 // Set up the FP register classes.
425 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
426 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
428 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
429 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
430 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
431 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
433 // Floating truncations go through memory. If optimizing, we lie about
434 // this though and handle it in InstructionSelectPreprocess so that
435 // dagcombine2 can hack on these.
437 setConvertAction(MVT::f80, MVT::f32, Expand);
438 setConvertAction(MVT::f64, MVT::f32, Expand);
439 setConvertAction(MVT::f80, MVT::f64, Expand);
443 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
444 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
446 addLegalFPImmediate(APFloat(+0.0)); // FLD0
447 addLegalFPImmediate(APFloat(+1.0)); // FLD1
448 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
449 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
450 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
451 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
452 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
453 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
456 // Long double always uses X87.
457 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
458 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
459 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
461 APFloat TmpFlt(+0.0);
462 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
463 addLegalFPImmediate(TmpFlt); // FLD0
465 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
466 APFloat TmpFlt2(+1.0);
467 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
468 addLegalFPImmediate(TmpFlt2); // FLD1
469 TmpFlt2.changeSign();
470 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
474 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
475 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
478 // Always use a library call for pow.
479 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
480 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
481 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
483 // First set operation action for all vector types to expand. Then we
484 // will selectively turn on ones that can be effectively codegen'd.
485 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
486 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
487 setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
488 setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
489 setOperationAction(ISD::FADD, (MVT::ValueType)VT, Expand);
490 setOperationAction(ISD::FNEG, (MVT::ValueType)VT, Expand);
491 setOperationAction(ISD::FSUB, (MVT::ValueType)VT, Expand);
492 setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
493 setOperationAction(ISD::FMUL, (MVT::ValueType)VT, Expand);
494 setOperationAction(ISD::SDIV, (MVT::ValueType)VT, Expand);
495 setOperationAction(ISD::UDIV, (MVT::ValueType)VT, Expand);
496 setOperationAction(ISD::FDIV, (MVT::ValueType)VT, Expand);
497 setOperationAction(ISD::SREM, (MVT::ValueType)VT, Expand);
498 setOperationAction(ISD::UREM, (MVT::ValueType)VT, Expand);
499 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
500 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Expand);
501 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
502 setOperationAction(ISD::INSERT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
503 setOperationAction(ISD::FABS, (MVT::ValueType)VT, Expand);
504 setOperationAction(ISD::FSIN, (MVT::ValueType)VT, Expand);
505 setOperationAction(ISD::FCOS, (MVT::ValueType)VT, Expand);
506 setOperationAction(ISD::FREM, (MVT::ValueType)VT, Expand);
507 setOperationAction(ISD::FPOWI, (MVT::ValueType)VT, Expand);
508 setOperationAction(ISD::FSQRT, (MVT::ValueType)VT, Expand);
509 setOperationAction(ISD::FCOPYSIGN, (MVT::ValueType)VT, Expand);
510 setOperationAction(ISD::SMUL_LOHI, (MVT::ValueType)VT, Expand);
511 setOperationAction(ISD::UMUL_LOHI, (MVT::ValueType)VT, Expand);
512 setOperationAction(ISD::SDIVREM, (MVT::ValueType)VT, Expand);
513 setOperationAction(ISD::UDIVREM, (MVT::ValueType)VT, Expand);
514 setOperationAction(ISD::FPOW, (MVT::ValueType)VT, Expand);
515 setOperationAction(ISD::CTPOP, (MVT::ValueType)VT, Expand);
516 setOperationAction(ISD::CTTZ, (MVT::ValueType)VT, Expand);
517 setOperationAction(ISD::CTLZ, (MVT::ValueType)VT, Expand);
518 setOperationAction(ISD::SHL, (MVT::ValueType)VT, Expand);
519 setOperationAction(ISD::SRA, (MVT::ValueType)VT, Expand);
520 setOperationAction(ISD::SRL, (MVT::ValueType)VT, Expand);
521 setOperationAction(ISD::ROTL, (MVT::ValueType)VT, Expand);
522 setOperationAction(ISD::ROTR, (MVT::ValueType)VT, Expand);
523 setOperationAction(ISD::BSWAP, (MVT::ValueType)VT, Expand);
526 if (Subtarget->hasMMX()) {
527 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
528 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
529 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
530 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
532 // FIXME: add MMX packed arithmetics
534 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
535 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
536 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
537 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
539 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
540 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
541 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
542 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
544 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
545 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
547 setOperationAction(ISD::AND, MVT::v8i8, Promote);
548 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
549 setOperationAction(ISD::AND, MVT::v4i16, Promote);
550 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
551 setOperationAction(ISD::AND, MVT::v2i32, Promote);
552 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
553 setOperationAction(ISD::AND, MVT::v1i64, Legal);
555 setOperationAction(ISD::OR, MVT::v8i8, Promote);
556 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
557 setOperationAction(ISD::OR, MVT::v4i16, Promote);
558 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
559 setOperationAction(ISD::OR, MVT::v2i32, Promote);
560 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
561 setOperationAction(ISD::OR, MVT::v1i64, Legal);
563 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
564 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
565 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
566 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
567 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
568 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
569 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
571 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
572 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
573 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
574 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
575 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
576 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
577 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
579 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
580 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
581 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
582 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
584 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
585 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
586 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
587 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
589 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
590 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
591 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
594 if (Subtarget->hasSSE1()) {
595 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
597 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
598 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
599 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
600 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
601 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
602 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
603 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
604 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
605 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
606 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
607 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
610 if (Subtarget->hasSSE2()) {
611 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
612 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
613 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
614 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
615 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
617 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
618 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
619 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
620 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
621 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
622 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
623 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
624 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
625 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
626 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
627 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
628 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
629 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
630 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
631 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
633 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
634 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
635 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
636 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
637 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
639 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
640 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
641 // Do not attempt to custom lower non-power-of-2 vectors
642 if (!isPowerOf2_32(MVT::getVectorNumElements(VT)))
644 setOperationAction(ISD::BUILD_VECTOR, (MVT::ValueType)VT, Custom);
645 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Custom);
646 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Custom);
648 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
649 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
650 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
651 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
652 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
653 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
654 if (Subtarget->is64Bit()) {
655 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
656 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
659 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
660 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
661 setOperationAction(ISD::AND, (MVT::ValueType)VT, Promote);
662 AddPromotedToType (ISD::AND, (MVT::ValueType)VT, MVT::v2i64);
663 setOperationAction(ISD::OR, (MVT::ValueType)VT, Promote);
664 AddPromotedToType (ISD::OR, (MVT::ValueType)VT, MVT::v2i64);
665 setOperationAction(ISD::XOR, (MVT::ValueType)VT, Promote);
666 AddPromotedToType (ISD::XOR, (MVT::ValueType)VT, MVT::v2i64);
667 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Promote);
668 AddPromotedToType (ISD::LOAD, (MVT::ValueType)VT, MVT::v2i64);
669 setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
670 AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v2i64);
673 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
675 // Custom lower v2i64 and v2f64 selects.
676 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
677 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
678 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
679 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
682 if (Subtarget->hasSSE41()) {
683 // FIXME: Do we need to handle scalar-to-vector here?
684 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
686 // i8 and i16 vectors are custom , because the source register and source
687 // source memory operand types are not the same width. f32 vectors are
688 // custom since the immediate controlling the insert encodes additional
690 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
691 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
692 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Legal);
693 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
695 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
696 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
697 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
698 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
700 if (Subtarget->is64Bit()) {
701 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
702 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
706 // We want to custom lower some of our intrinsics.
707 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
709 // We have target-specific dag combine patterns for the following nodes:
710 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
711 setTargetDAGCombine(ISD::SELECT);
712 setTargetDAGCombine(ISD::STORE);
714 computeRegisterProperties();
716 // FIXME: These should be based on subtarget info. Plus, the values should
717 // be smaller when we are in optimizing for size mode.
718 maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
719 maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
720 maxStoresPerMemmove = 16; // For %llvm.memmove -> sequence of stores
721 allowUnalignedMemoryAccesses = true; // x86 supports it!
722 setPrefLoopAlignment(16);
727 X86TargetLowering::getSetCCResultType(const SDOperand &) const {
732 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
733 /// the desired ByVal argument alignment.
734 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
737 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
738 if (VTy->getBitWidth() == 128)
740 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
741 unsigned EltAlign = 0;
742 getMaxByValAlign(ATy->getElementType(), EltAlign);
743 if (EltAlign > MaxAlign)
745 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
746 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
747 unsigned EltAlign = 0;
748 getMaxByValAlign(STy->getElementType(i), EltAlign);
749 if (EltAlign > MaxAlign)
758 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
759 /// function arguments in the caller parameter area. For X86, aggregates
760 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
761 /// are at 4-byte boundaries.
762 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
763 if (Subtarget->is64Bit())
764 return getTargetData()->getABITypeAlignment(Ty);
766 if (Subtarget->hasSSE1())
767 getMaxByValAlign(Ty, Align);
771 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
773 SDOperand X86TargetLowering::getPICJumpTableRelocBase(SDOperand Table,
774 SelectionDAG &DAG) const {
775 if (usesGlobalOffsetTable())
776 return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
777 if (!Subtarget->isPICStyleRIPRel())
778 return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
782 //===----------------------------------------------------------------------===//
783 // Return Value Calling Convention Implementation
784 //===----------------------------------------------------------------------===//
786 #include "X86GenCallingConv.inc"
788 /// GetPossiblePreceedingTailCall - Get preceeding X86ISD::TAILCALL node if it
789 /// exists skip possible ISD:TokenFactor.
790 static SDOperand GetPossiblePreceedingTailCall(SDOperand Chain) {
791 if (Chain.getOpcode() == X86ISD::TAILCALL) {
793 } else if (Chain.getOpcode() == ISD::TokenFactor) {
794 if (Chain.getNumOperands() &&
795 Chain.getOperand(0).getOpcode() == X86ISD::TAILCALL)
796 return Chain.getOperand(0);
801 /// LowerRET - Lower an ISD::RET node.
802 SDOperand X86TargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG) {
803 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
805 SmallVector<CCValAssign, 16> RVLocs;
806 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
807 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
808 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
809 CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
811 // If this is the first return lowered for this function, add the regs to the
812 // liveout set for the function.
813 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
814 for (unsigned i = 0; i != RVLocs.size(); ++i)
815 if (RVLocs[i].isRegLoc())
816 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
818 SDOperand Chain = Op.getOperand(0);
820 // Handle tail call return.
821 Chain = GetPossiblePreceedingTailCall(Chain);
822 if (Chain.getOpcode() == X86ISD::TAILCALL) {
823 SDOperand TailCall = Chain;
824 SDOperand TargetAddress = TailCall.getOperand(1);
825 SDOperand StackAdjustment = TailCall.getOperand(2);
826 assert(((TargetAddress.getOpcode() == ISD::Register &&
827 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::ECX ||
828 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
829 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
830 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
831 "Expecting an global address, external symbol, or register");
832 assert(StackAdjustment.getOpcode() == ISD::Constant &&
833 "Expecting a const value");
835 SmallVector<SDOperand,8> Operands;
836 Operands.push_back(Chain.getOperand(0));
837 Operands.push_back(TargetAddress);
838 Operands.push_back(StackAdjustment);
839 // Copy registers used by the call. Last operand is a flag so it is not
841 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
842 Operands.push_back(Chain.getOperand(i));
844 return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0],
851 SmallVector<SDOperand, 6> RetOps;
852 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
853 // Operand #1 = Bytes To Pop
854 RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
856 // Copy the result values into the output registers.
857 for (unsigned i = 0; i != RVLocs.size(); ++i) {
858 CCValAssign &VA = RVLocs[i];
859 assert(VA.isRegLoc() && "Can only return in registers!");
860 SDOperand ValToCopy = Op.getOperand(i*2+1);
862 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
863 // the RET instruction and handled by the FP Stackifier.
864 if (RVLocs[i].getLocReg() == X86::ST0 ||
865 RVLocs[i].getLocReg() == X86::ST1) {
866 // If this is a copy from an xmm register to ST(0), use an FPExtend to
867 // change the value to the FP stack register class.
868 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT()))
869 ValToCopy = DAG.getNode(ISD::FP_EXTEND, MVT::f80, ValToCopy);
870 RetOps.push_back(ValToCopy);
871 // Don't emit a copytoreg.
875 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), ValToCopy, Flag);
876 Flag = Chain.getValue(1);
879 // The x86-64 ABI for returning structs by value requires that we copy
880 // the sret argument into %rax for the return. We saved the argument into
881 // a virtual register in the entry block, so now we copy the value out
883 if (Subtarget->is64Bit() &&
884 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
885 MachineFunction &MF = DAG.getMachineFunction();
886 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
887 unsigned Reg = FuncInfo->getSRetReturnReg();
889 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
890 FuncInfo->setSRetReturnReg(Reg);
892 SDOperand Val = DAG.getCopyFromReg(Chain, Reg, getPointerTy());
894 Chain = DAG.getCopyToReg(Chain, X86::RAX, Val, Flag);
895 Flag = Chain.getValue(1);
898 RetOps[0] = Chain; // Update chain.
900 // Add the flag if we have it.
902 RetOps.push_back(Flag);
904 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, &RetOps[0], RetOps.size());
908 /// LowerCallResult - Lower the result values of an ISD::CALL into the
909 /// appropriate copies out of appropriate physical registers. This assumes that
910 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
911 /// being lowered. The returns a SDNode with the same number of values as the
913 SDNode *X86TargetLowering::
914 LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall,
915 unsigned CallingConv, SelectionDAG &DAG) {
917 // Assign locations to each value returned by this call.
918 SmallVector<CCValAssign, 16> RVLocs;
919 bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
920 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
921 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
923 SmallVector<SDOperand, 8> ResultVals;
925 // Copy all of the result registers out of their specified physreg.
926 for (unsigned i = 0; i != RVLocs.size(); ++i) {
927 MVT::ValueType CopyVT = RVLocs[i].getValVT();
929 // If this is a call to a function that returns an fp value on the floating
930 // point stack, but where we prefer to use the value in xmm registers, copy
931 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
932 if (RVLocs[i].getLocReg() == X86::ST0 &&
933 isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
937 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
938 CopyVT, InFlag).getValue(1);
939 SDOperand Val = Chain.getValue(0);
940 InFlag = Chain.getValue(2);
942 if (CopyVT != RVLocs[i].getValVT()) {
943 // Round the F80 the right size, which also moves to the appropriate xmm
945 Val = DAG.getNode(ISD::FP_ROUND, RVLocs[i].getValVT(), Val,
946 // This truncation won't change the value.
947 DAG.getIntPtrConstant(1));
950 ResultVals.push_back(Val);
953 // Merge everything together with a MERGE_VALUES node.
954 ResultVals.push_back(Chain);
955 return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
956 &ResultVals[0], ResultVals.size()).Val;
960 //===----------------------------------------------------------------------===//
961 // C & StdCall & Fast Calling Convention implementation
962 //===----------------------------------------------------------------------===//
963 // StdCall calling convention seems to be standard for many Windows' API
964 // routines and around. It differs from C calling convention just a little:
965 // callee should clean up the stack, not caller. Symbols should be also
966 // decorated in some fancy way :) It doesn't support any vector arguments.
967 // For info on fast calling convention see Fast Calling Convention (tail call)
968 // implementation LowerX86_32FastCCCallTo.
970 /// AddLiveIn - This helper function adds the specified physical register to the
971 /// MachineFunction as a live in value. It also creates a corresponding virtual
973 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
974 const TargetRegisterClass *RC) {
975 assert(RC->contains(PReg) && "Not the correct regclass!");
976 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
977 MF.getRegInfo().addLiveIn(PReg, VReg);
981 /// CallIsStructReturn - Determines whether a CALL node uses struct return
983 static bool CallIsStructReturn(SDOperand Op) {
984 unsigned NumOps = (Op.getNumOperands() - 5) / 2;
988 return cast<ARG_FLAGSSDNode>(Op.getOperand(6))->getArgFlags().isSRet();
991 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
992 /// return semantics.
993 static bool ArgsAreStructReturn(SDOperand Op) {
994 unsigned NumArgs = Op.Val->getNumValues() - 1;
998 return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
1001 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
1002 /// the callee to pop its own arguments. Callee pop is necessary to support tail
1004 bool X86TargetLowering::IsCalleePop(SDOperand Op) {
1005 bool IsVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1009 switch (cast<ConstantSDNode>(Op.getOperand(1))->getValue()) {
1012 case CallingConv::X86_StdCall:
1013 return !Subtarget->is64Bit();
1014 case CallingConv::X86_FastCall:
1015 return !Subtarget->is64Bit();
1016 case CallingConv::Fast:
1017 return PerformTailCallOpt;
1021 /// CCAssignFnForNode - Selects the correct CCAssignFn for a CALL or
1022 /// FORMAL_ARGUMENTS node.
1023 CCAssignFn *X86TargetLowering::CCAssignFnForNode(SDOperand Op) const {
1024 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1026 if (Subtarget->is64Bit()) {
1027 if (Subtarget->isTargetWin64())
1028 return CC_X86_Win64_C;
1030 if (CC == CallingConv::Fast && PerformTailCallOpt)
1031 return CC_X86_64_TailCall;
1037 if (CC == CallingConv::X86_FastCall)
1038 return CC_X86_32_FastCall;
1039 else if (CC == CallingConv::Fast && PerformTailCallOpt)
1040 return CC_X86_32_TailCall;
1045 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1046 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1048 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDOperand Op) {
1049 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1050 if (CC == CallingConv::X86_FastCall)
1052 else if (CC == CallingConv::X86_StdCall)
1057 /// IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could
1058 /// possibly be overwritten when lowering the outgoing arguments in a tail
1059 /// call. Currently the implementation of this call is very conservative and
1060 /// assumes all arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with
1061 /// virtual registers would be overwritten by direct lowering.
1062 static bool IsPossiblyOverwrittenArgumentOfTailCall(SDOperand Op,
1063 MachineFrameInfo * MFI) {
1064 RegisterSDNode * OpReg = NULL;
1065 FrameIndexSDNode * FrameIdxNode = NULL;
1067 if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
1068 (Op.getOpcode()== ISD::CopyFromReg &&
1069 (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) &&
1070 (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) ||
1071 (Op.getOpcode() == ISD::LOAD &&
1072 (FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op.getOperand(1))) &&
1073 (MFI->isFixedObjectIndex((FrameIdx = FrameIdxNode->getIndex()))) &&
1074 (MFI->getObjectOffset(FrameIdx) >= 0)))
1079 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1080 /// in a register before calling.
1081 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1082 return !IsTailCall && !Is64Bit &&
1083 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1084 Subtarget->isPICStyleGOT();
1088 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1089 /// address to be loaded in a register.
1091 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1092 return !Is64Bit && IsTailCall &&
1093 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1094 Subtarget->isPICStyleGOT();
1097 /// CopyTailCallClobberedArgumentsToVRegs - Create virtual registers for all
1098 /// arguments to force loading and guarantee that arguments sourcing from
1099 /// incomming parameters are not overwriting each other.
1101 CopyTailCallClobberedArgumentsToVRegs(SDOperand Chain,
1102 SmallVector<std::pair<unsigned, SDOperand>, 8> &TailCallClobberedVRegs,
1104 MachineFunction &MF,
1105 const TargetLowering * TL) {
1108 for (unsigned i = 0, e = TailCallClobberedVRegs.size(); i != e; i++) {
1109 SDOperand Arg = TailCallClobberedVRegs[i].second;
1110 unsigned Idx = TailCallClobberedVRegs[i].first;
1113 createVirtualRegister(TL->getRegClassFor(Arg.getValueType()));
1114 Chain = DAG.getCopyToReg(Chain, VReg, Arg, InFlag);
1115 InFlag = Chain.getValue(1);
1116 Arg = DAG.getCopyFromReg(Chain, VReg, Arg.getValueType(), InFlag);
1117 TailCallClobberedVRegs[i] = std::make_pair(Idx, Arg);
1118 Chain = Arg.getValue(1);
1119 InFlag = Arg.getValue(2);
1124 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1125 /// by "Src" to address "Dst" with size and alignment information specified by
1126 /// the specific parameter attribute. The copy will be passed as a byval
1127 /// function parameter.
1129 CreateCopyOfByValArgument(SDOperand Src, SDOperand Dst, SDOperand Chain,
1130 ISD::ArgFlagsTy Flags, SelectionDAG &DAG) {
1131 SDOperand SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1132 return DAG.getMemcpy(Chain, Dst, Src, SizeNode, Flags.getByValAlign(),
1133 /*AlwaysInline=*/true,
1137 SDOperand X86TargetLowering::LowerMemArgument(SDOperand Op, SelectionDAG &DAG,
1138 const CCValAssign &VA,
1139 MachineFrameInfo *MFI,
1141 SDOperand Root, unsigned i) {
1142 // Create the nodes corresponding to a load from this parameter slot.
1143 ISD::ArgFlagsTy Flags =
1144 cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1145 bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1146 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1148 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1149 // changed with more analysis.
1150 // In case of tail call optimization mark all arguments mutable. Since they
1151 // could be overwritten by lowering of arguments in case of a tail call.
1152 int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
1153 VA.getLocMemOffset(), isImmutable);
1154 SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
1155 if (Flags.isByVal())
1157 return DAG.getLoad(VA.getValVT(), Root, FIN,
1158 PseudoSourceValue::getFixedStack(), FI);
1162 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
1163 MachineFunction &MF = DAG.getMachineFunction();
1164 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1166 const Function* Fn = MF.getFunction();
1167 if (Fn->hasExternalLinkage() &&
1168 Subtarget->isTargetCygMing() &&
1169 Fn->getName() == "main")
1170 FuncInfo->setForceFramePointer(true);
1172 // Decorate the function name.
1173 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1175 MachineFrameInfo *MFI = MF.getFrameInfo();
1176 SDOperand Root = Op.getOperand(0);
1177 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1178 unsigned CC = MF.getFunction()->getCallingConv();
1179 bool Is64Bit = Subtarget->is64Bit();
1181 assert(!(isVarArg && CC == CallingConv::Fast) &&
1182 "Var args not supported with calling convention fastcc");
1184 // Assign locations to all of the incoming arguments.
1185 SmallVector<CCValAssign, 16> ArgLocs;
1186 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1187 CCInfo.AnalyzeFormalArguments(Op.Val, CCAssignFnForNode(Op));
1189 SmallVector<SDOperand, 8> ArgValues;
1190 unsigned LastVal = ~0U;
1191 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1192 CCValAssign &VA = ArgLocs[i];
1193 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1195 assert(VA.getValNo() != LastVal &&
1196 "Don't support value assigned to multiple locs yet");
1197 LastVal = VA.getValNo();
1199 if (VA.isRegLoc()) {
1200 MVT::ValueType RegVT = VA.getLocVT();
1201 TargetRegisterClass *RC;
1202 if (RegVT == MVT::i32)
1203 RC = X86::GR32RegisterClass;
1204 else if (Is64Bit && RegVT == MVT::i64)
1205 RC = X86::GR64RegisterClass;
1206 else if (RegVT == MVT::f32)
1207 RC = X86::FR32RegisterClass;
1208 else if (RegVT == MVT::f64)
1209 RC = X86::FR64RegisterClass;
1210 else if (MVT::isVector(RegVT) && MVT::getSizeInBits(RegVT) == 128)
1211 RC = X86::VR128RegisterClass;
1212 else if (MVT::isVector(RegVT)) {
1213 assert(MVT::getSizeInBits(RegVT) == 64);
1215 RC = X86::VR64RegisterClass; // MMX values are passed in MMXs.
1217 // Darwin calling convention passes MMX values in either GPRs or
1218 // XMMs in x86-64. Other targets pass them in memory.
1219 if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1220 RC = X86::VR128RegisterClass; // MMX values are passed in XMMs.
1223 RC = X86::GR64RegisterClass; // v1i64 values are passed in GPRs.
1228 assert(0 && "Unknown argument type!");
1231 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1232 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1234 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1235 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1237 if (VA.getLocInfo() == CCValAssign::SExt)
1238 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1239 DAG.getValueType(VA.getValVT()));
1240 else if (VA.getLocInfo() == CCValAssign::ZExt)
1241 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1242 DAG.getValueType(VA.getValVT()));
1244 if (VA.getLocInfo() != CCValAssign::Full)
1245 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1247 // Handle MMX values passed in GPRs.
1248 if (Is64Bit && RegVT != VA.getLocVT() && RC == X86::GR64RegisterClass &&
1249 MVT::getSizeInBits(RegVT) == 64)
1250 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1252 ArgValues.push_back(ArgValue);
1254 assert(VA.isMemLoc());
1255 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1259 // The x86-64 ABI for returning structs by value requires that we copy
1260 // the sret argument into %rax for the return. Save the argument into
1261 // a virtual register so that we can access it from the return points.
1262 if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1263 MachineFunction &MF = DAG.getMachineFunction();
1264 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1265 unsigned Reg = FuncInfo->getSRetReturnReg();
1267 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1268 FuncInfo->setSRetReturnReg(Reg);
1270 SDOperand Copy = DAG.getCopyToReg(DAG.getEntryNode(), Reg, ArgValues[0]);
1271 Root = DAG.getNode(ISD::TokenFactor, MVT::Other, Copy, Root);
1274 unsigned StackSize = CCInfo.getNextStackOffset();
1275 // align stack specially for tail calls
1276 if (CC == CallingConv::Fast)
1277 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1279 // If the function takes variable number of arguments, make a frame index for
1280 // the start of the first vararg value... for expansion of llvm.va_start.
1282 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1283 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1286 static const unsigned GPR64ArgRegs[] = {
1287 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1289 static const unsigned XMMArgRegs[] = {
1290 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1291 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1294 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 6);
1295 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1297 // For X86-64, if there are vararg parameters that are passed via
1298 // registers, then we must store them to their spots on the stack so they
1299 // may be loaded by deferencing the result of va_next.
1300 VarArgsGPOffset = NumIntRegs * 8;
1301 VarArgsFPOffset = 6 * 8 + NumXMMRegs * 16;
1302 RegSaveFrameIndex = MFI->CreateStackObject(6 * 8 + 8 * 16, 16);
1304 // Store the integer parameter registers.
1305 SmallVector<SDOperand, 8> MemOps;
1306 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1307 SDOperand FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1308 DAG.getIntPtrConstant(VarArgsGPOffset));
1309 for (; NumIntRegs != 6; ++NumIntRegs) {
1310 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1311 X86::GR64RegisterClass);
1312 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1314 DAG.getStore(Val.getValue(1), Val, FIN,
1315 PseudoSourceValue::getFixedStack(),
1317 MemOps.push_back(Store);
1318 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1319 DAG.getIntPtrConstant(8));
1322 // Now store the XMM (fp + vector) parameter registers.
1323 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1324 DAG.getIntPtrConstant(VarArgsFPOffset));
1325 for (; NumXMMRegs != 8; ++NumXMMRegs) {
1326 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1327 X86::VR128RegisterClass);
1328 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1330 DAG.getStore(Val.getValue(1), Val, FIN,
1331 PseudoSourceValue::getFixedStack(),
1333 MemOps.push_back(Store);
1334 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1335 DAG.getIntPtrConstant(16));
1337 if (!MemOps.empty())
1338 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1339 &MemOps[0], MemOps.size());
1343 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1344 // arguments and the arguments after the retaddr has been pushed are
1346 if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1347 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1348 (StackSize & 7) == 0)
1351 ArgValues.push_back(Root);
1353 // Some CCs need callee pop.
1354 if (IsCalleePop(Op)) {
1355 BytesToPopOnReturn = StackSize; // Callee pops everything.
1356 BytesCallerReserves = 0;
1358 BytesToPopOnReturn = 0; // Callee pops nothing.
1359 // If this is an sret function, the return should pop the hidden pointer.
1360 if (!Is64Bit && ArgsAreStructReturn(Op))
1361 BytesToPopOnReturn = 4;
1362 BytesCallerReserves = StackSize;
1366 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1367 if (CC == CallingConv::X86_FastCall)
1368 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1371 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1373 // Return the new list of results.
1374 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1375 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1379 X86TargetLowering::LowerMemOpCallTo(SDOperand Op, SelectionDAG &DAG,
1380 const SDOperand &StackPtr,
1381 const CCValAssign &VA,
1384 unsigned LocMemOffset = VA.getLocMemOffset();
1385 SDOperand PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1386 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1387 ISD::ArgFlagsTy Flags =
1388 cast<ARG_FLAGSSDNode>(Op.getOperand(6+2*VA.getValNo()))->getArgFlags();
1389 if (Flags.isByVal()) {
1390 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG);
1392 return DAG.getStore(Chain, Arg, PtrOff,
1393 PseudoSourceValue::getStack(), LocMemOffset);
1396 /// EmitTailCallLoadRetAddr - Emit a load of return adress if tail call
1397 /// optimization is performed and it is required.
1399 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1400 SDOperand &OutRetAddr,
1405 if (!IsTailCall || FPDiff==0) return Chain;
1407 // Adjust the Return address stack slot.
1408 MVT::ValueType VT = getPointerTy();
1409 OutRetAddr = getReturnAddressFrameIndex(DAG);
1410 // Load the "old" Return address.
1411 OutRetAddr = DAG.getLoad(VT, Chain,OutRetAddr, NULL, 0);
1412 return SDOperand(OutRetAddr.Val, 1);
1415 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1416 /// optimization is performed and it is required (FPDiff!=0).
1418 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1419 SDOperand Chain, SDOperand RetAddrFrIdx,
1420 bool Is64Bit, int FPDiff) {
1421 // Store the return address to the appropriate stack slot.
1422 if (!FPDiff) return Chain;
1423 // Calculate the new stack slot for the return address.
1424 int SlotSize = Is64Bit ? 8 : 4;
1425 int NewReturnAddrFI =
1426 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1427 MVT::ValueType VT = Is64Bit ? MVT::i64 : MVT::i32;
1428 SDOperand NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1429 Chain = DAG.getStore(Chain, RetAddrFrIdx, NewRetAddrFrIdx,
1430 PseudoSourceValue::getFixedStack(), NewReturnAddrFI);
1434 /// CopyTailCallByValClobberedRegToVirtReg - Copy arguments with register target
1435 /// which might be overwritten by later byval tail call lowering to a virtual
1438 X86TargetLowering::CopyTailCallByValClobberedRegToVirtReg(bool containsByValArg,
1439 SmallVector< std::pair<unsigned, unsigned>, 8> &TailCallByValClobberedVRegs,
1440 SmallVector<MVT::ValueType, 8> &TailCallByValClobberedVRegTypes,
1441 std::pair<unsigned, SDOperand> &RegToPass,
1442 SDOperand &OutChain,
1444 MachineFunction &MF,
1445 SelectionDAG & DAG) {
1446 if (!containsByValArg) return false;
1448 std::pair<unsigned, unsigned> ArgRegVReg;
1449 MVT::ValueType VT = RegToPass.second.getValueType();
1451 ArgRegVReg.first = RegToPass.first;
1452 ArgRegVReg.second = MF.getRegInfo().createVirtualRegister(getRegClassFor(VT));
1454 // Copy Argument to virtual register.
1455 OutChain = DAG.getCopyToReg(OutChain, ArgRegVReg.second,
1456 RegToPass.second, OutFlag);
1457 OutFlag = OutChain.getValue(1);
1458 // Remember virtual register and type.
1459 TailCallByValClobberedVRegs.push_back(ArgRegVReg);
1460 TailCallByValClobberedVRegTypes.push_back(VT);
1465 /// RestoreTailCallByValClobberedReg - Restore registers which were saved to
1466 /// virtual registers to prevent tail call byval lowering from overwriting
1467 /// parameter registers.
1469 RestoreTailCallByValClobberedRegs(SelectionDAG & DAG, SDOperand Chain,
1470 SmallVector< std::pair<unsigned, unsigned>, 8> &TailCallByValClobberedVRegs,
1471 SmallVector<MVT::ValueType, 8> &TailCallByValClobberedVRegTypes) {
1472 if (TailCallByValClobberedVRegs.size()==0) return Chain;
1474 SmallVector<SDOperand, 8> RegOpChains;
1475 for (unsigned i = 0, e=TailCallByValClobberedVRegs.size(); i != e; i++) {
1477 unsigned DestReg = TailCallByValClobberedVRegs[i].first;
1478 unsigned VirtReg = TailCallByValClobberedVRegs[i].second;
1479 MVT::ValueType VT = TailCallByValClobberedVRegTypes[i];
1480 SDOperand Tmp = DAG.getCopyFromReg(Chain, VirtReg, VT, InFlag);
1481 Chain = DAG.getCopyToReg(Chain, DestReg, Tmp, InFlag);
1482 RegOpChains.push_back(Chain);
1484 if (!RegOpChains.empty())
1485 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1486 &RegOpChains[0], RegOpChains.size());
1490 SDOperand X86TargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
1491 MachineFunction &MF = DAG.getMachineFunction();
1492 MachineFrameInfo * MFI = MF.getFrameInfo();
1493 SDOperand Chain = Op.getOperand(0);
1494 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1495 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1496 bool IsTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0
1497 && CC == CallingConv::Fast && PerformTailCallOpt;
1498 SDOperand Callee = Op.getOperand(4);
1499 bool Is64Bit = Subtarget->is64Bit();
1500 bool IsStructRet = CallIsStructReturn(Op);
1502 assert(!(isVarArg && CC == CallingConv::Fast) &&
1503 "Var args not supported with calling convention fastcc");
1505 // Analyze operands of the call, assigning locations to each operand.
1506 SmallVector<CCValAssign, 16> ArgLocs;
1507 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1508 CCInfo.AnalyzeCallOperands(Op.Val, CCAssignFnForNode(Op));
1510 // Get a count of how many bytes are to be pushed on the stack.
1511 unsigned NumBytes = CCInfo.getNextStackOffset();
1512 if (CC == CallingConv::Fast)
1513 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1515 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1516 // arguments and the arguments after the retaddr has been pushed are aligned.
1517 if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1518 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1519 (NumBytes & 7) == 0)
1524 // Lower arguments at fp - stackoffset + fpdiff.
1525 unsigned NumBytesCallerPushed =
1526 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1527 FPDiff = NumBytesCallerPushed - NumBytes;
1529 // Set the delta of movement of the returnaddr stackslot.
1530 // But only set if delta is greater than previous delta.
1531 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1532 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1535 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes));
1537 SDOperand RetAddrFrIdx;
1538 // Load return adress for tail calls.
1539 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1542 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1543 SmallVector<std::pair<unsigned, SDOperand>, 8> TailCallClobberedVRegs;
1545 SmallVector<SDOperand, 8> MemOpChains;
1548 bool containsTailCallByValArg = false;
1549 SmallVector<std::pair<unsigned, unsigned>, 8> TailCallByValClobberedVRegs;
1550 SmallVector<MVT::ValueType, 8> TailCallByValClobberedVRegTypes;
1553 // Walk the register/memloc assignments, inserting copies/loads. For tail
1554 // calls, remember all arguments for later special lowering.
1555 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1556 CCValAssign &VA = ArgLocs[i];
1557 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1558 bool isByVal = cast<ARG_FLAGSSDNode>(Op.getOperand(6+2*VA.getValNo()))->
1559 getArgFlags().isByVal();
1561 // Promote the value if needed.
1562 switch (VA.getLocInfo()) {
1563 default: assert(0 && "Unknown loc info!");
1564 case CCValAssign::Full: break;
1565 case CCValAssign::SExt:
1566 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1568 case CCValAssign::ZExt:
1569 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1571 case CCValAssign::AExt:
1572 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1576 if (VA.isRegLoc()) {
1577 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1579 if (!IsTailCall || (IsTailCall && isByVal)) {
1580 assert(VA.isMemLoc());
1581 if (StackPtr.Val == 0)
1582 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1584 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1586 // Remember fact that this call contains byval arguments.
1587 containsTailCallByValArg |= IsTailCall && isByVal;
1588 } else if (IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
1589 TailCallClobberedVRegs.push_back(std::make_pair(i,Arg));
1594 if (!MemOpChains.empty())
1595 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1596 &MemOpChains[0], MemOpChains.size());
1598 // Build a sequence of copy-to-reg nodes chained together with token chain
1599 // and flag operands which copy the outgoing args into registers.
1601 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1602 // Tail call byval lowering might overwrite argument registers so arguments
1603 // passed to be copied to a virtual register for
1604 // later processing.
1605 if (CopyTailCallByValClobberedRegToVirtReg(containsTailCallByValArg,
1606 TailCallByValClobberedVRegs,
1607 TailCallByValClobberedVRegTypes,
1608 RegsToPass[i], Chain, InFlag, MF,
1612 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1614 InFlag = Chain.getValue(1);
1617 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1619 if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1620 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1621 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1623 InFlag = Chain.getValue(1);
1625 // If we are tail calling and generating PIC/GOT style code load the address
1626 // of the callee into ecx. The value in ecx is used as target of the tail
1627 // jump. This is done to circumvent the ebx/callee-saved problem for tail
1628 // calls on PIC/GOT architectures. Normally we would just put the address of
1629 // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1630 // restored (since ebx is callee saved) before jumping to the target@PLT.
1631 if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1632 // Note: The actual moving to ecx is done further down.
1633 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1634 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1635 !G->getGlobal()->hasProtectedVisibility())
1636 Callee = LowerGlobalAddress(Callee, DAG);
1637 else if (isa<ExternalSymbolSDNode>(Callee))
1638 Callee = LowerExternalSymbol(Callee,DAG);
1641 if (Is64Bit && isVarArg) {
1642 // From AMD64 ABI document:
1643 // For calls that may call functions that use varargs or stdargs
1644 // (prototype-less calls or calls to functions containing ellipsis (...) in
1645 // the declaration) %al is used as hidden argument to specify the number
1646 // of SSE registers used. The contents of %al do not need to match exactly
1647 // the number of registers, but must be an ubound on the number of SSE
1648 // registers used and is in the range 0 - 8 inclusive.
1650 // Count the number of XMM registers allocated.
1651 static const unsigned XMMArgRegs[] = {
1652 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1653 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1655 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1657 Chain = DAG.getCopyToReg(Chain, X86::AL,
1658 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1659 InFlag = Chain.getValue(1);
1663 // For tail calls lower the arguments to the 'real' stack slot.
1665 SmallVector<SDOperand, 8> MemOpChains2;
1668 // Do not flag preceeding copytoreg stuff together with the following stuff.
1669 InFlag = SDOperand();
1671 Chain = CopyTailCallClobberedArgumentsToVRegs(Chain, TailCallClobberedVRegs,
1674 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1675 CCValAssign &VA = ArgLocs[i];
1676 if (!VA.isRegLoc()) {
1677 assert(VA.isMemLoc());
1678 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1679 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1680 ISD::ArgFlagsTy Flags =
1681 cast<ARG_FLAGSSDNode>(FlagsOp)->getArgFlags();
1682 // Create frame index.
1683 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1684 uint32_t OpSize = (MVT::getSizeInBits(VA.getLocVT())+7)/8;
1685 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1686 FIN = DAG.getFrameIndex(FI, getPointerTy());
1688 // Find virtual register for this argument.
1690 for (unsigned idx=0, e= TailCallClobberedVRegs.size(); idx < e; idx++)
1691 if (TailCallClobberedVRegs[idx].first==i) {
1692 Arg = TailCallClobberedVRegs[idx].second;
1696 assert(IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)==false ||
1697 (Found==true && "No corresponding Argument was found"));
1699 if (Flags.isByVal()) {
1700 // Copy relative to framepointer.
1701 SDOperand Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1702 if (StackPtr.Val == 0)
1703 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1704 Source = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, Source);
1706 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1709 // Store relative to framepointer.
1710 MemOpChains2.push_back(
1711 DAG.getStore(Chain, Arg, FIN,
1712 PseudoSourceValue::getFixedStack(), FI));
1717 if (!MemOpChains2.empty())
1718 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1719 &MemOpChains2[0], MemOpChains2.size());
1721 // Restore byval lowering clobbered registers.
1722 Chain = RestoreTailCallByValClobberedRegs(DAG, Chain,
1723 TailCallByValClobberedVRegs,
1724 TailCallByValClobberedVRegTypes);
1726 // Store the return address to the appropriate stack slot.
1727 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1731 // If the callee is a GlobalAddress node (quite common, every direct call is)
1732 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1733 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1734 // We should use extra load for direct calls to dllimported functions in
1736 if ((IsTailCall || !Is64Bit ||
1737 getTargetMachine().getCodeModel() != CodeModel::Large)
1738 && !Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1739 getTargetMachine(), true))
1740 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1741 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1742 if (IsTailCall || !Is64Bit ||
1743 getTargetMachine().getCodeModel() != CodeModel::Large)
1744 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1745 } else if (IsTailCall) {
1746 unsigned Opc = Is64Bit ? X86::R9 : X86::ECX;
1748 Chain = DAG.getCopyToReg(Chain,
1749 DAG.getRegister(Opc, getPointerTy()),
1751 Callee = DAG.getRegister(Opc, getPointerTy());
1752 // Add register as live out.
1753 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1756 // Returns a chain & a flag for retval copy to use.
1757 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1758 SmallVector<SDOperand, 8> Ops;
1761 Ops.push_back(Chain);
1762 Ops.push_back(DAG.getIntPtrConstant(NumBytes));
1763 Ops.push_back(DAG.getIntPtrConstant(0));
1765 Ops.push_back(InFlag);
1766 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1767 InFlag = Chain.getValue(1);
1769 // Returns a chain & a flag for retval copy to use.
1770 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1774 Ops.push_back(Chain);
1775 Ops.push_back(Callee);
1778 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1780 // Add argument registers to the end of the list so that they are known live
1782 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1783 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1784 RegsToPass[i].second.getValueType()));
1786 // Add an implicit use GOT pointer in EBX.
1787 if (!IsTailCall && !Is64Bit &&
1788 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1789 Subtarget->isPICStyleGOT())
1790 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1792 // Add an implicit use of AL for x86 vararg functions.
1793 if (Is64Bit && isVarArg)
1794 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1797 Ops.push_back(InFlag);
1800 assert(InFlag.Val &&
1801 "Flag must be set. Depend on flag being set in LowerRET");
1802 Chain = DAG.getNode(X86ISD::TAILCALL,
1803 Op.Val->getVTList(), &Ops[0], Ops.size());
1805 return SDOperand(Chain.Val, Op.ResNo);
1808 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1809 InFlag = Chain.getValue(1);
1811 // Create the CALLSEQ_END node.
1812 unsigned NumBytesForCalleeToPush;
1813 if (IsCalleePop(Op))
1814 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1815 else if (!Is64Bit && IsStructRet)
1816 // If this is is a call to a struct-return function, the callee
1817 // pops the hidden struct pointer, so we have to push it back.
1818 // This is common for Darwin/X86, Linux & Mingw32 targets.
1819 NumBytesForCalleeToPush = 4;
1821 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1823 // Returns a flag for retval copy to use.
1824 Chain = DAG.getCALLSEQ_END(Chain,
1825 DAG.getIntPtrConstant(NumBytes),
1826 DAG.getIntPtrConstant(NumBytesForCalleeToPush),
1828 InFlag = Chain.getValue(1);
1830 // Handle result values, copying them out of physregs into vregs that we
1832 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1836 //===----------------------------------------------------------------------===//
1837 // Fast Calling Convention (tail call) implementation
1838 //===----------------------------------------------------------------------===//
1840 // Like std call, callee cleans arguments, convention except that ECX is
1841 // reserved for storing the tail called function address. Only 2 registers are
1842 // free for argument passing (inreg). Tail call optimization is performed
1844 // * tailcallopt is enabled
1845 // * caller/callee are fastcc
1846 // On X86_64 architecture with GOT-style position independent code only local
1847 // (within module) calls are supported at the moment.
1848 // To keep the stack aligned according to platform abi the function
1849 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1850 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1851 // If a tail called function callee has more arguments than the caller the
1852 // caller needs to make sure that there is room to move the RETADDR to. This is
1853 // achieved by reserving an area the size of the argument delta right after the
1854 // original REtADDR, but before the saved framepointer or the spilled registers
1855 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1867 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1868 /// for a 16 byte align requirement.
1869 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1870 SelectionDAG& DAG) {
1871 if (PerformTailCallOpt) {
1872 MachineFunction &MF = DAG.getMachineFunction();
1873 const TargetMachine &TM = MF.getTarget();
1874 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1875 unsigned StackAlignment = TFI.getStackAlignment();
1876 uint64_t AlignMask = StackAlignment - 1;
1877 int64_t Offset = StackSize;
1878 unsigned SlotSize = Subtarget->is64Bit() ? 8 : 4;
1879 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1880 // Number smaller than 12 so just add the difference.
1881 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1883 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1884 Offset = ((~AlignMask) & Offset) + StackAlignment +
1885 (StackAlignment-SlotSize);
1892 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1893 /// following the call is a return. A function is eligible if caller/callee
1894 /// calling conventions match, currently only fastcc supports tail calls, and
1895 /// the function CALL is immediatly followed by a RET.
1896 bool X86TargetLowering::IsEligibleForTailCallOptimization(SDOperand Call,
1898 SelectionDAG& DAG) const {
1899 if (!PerformTailCallOpt)
1902 // Check whether CALL node immediatly preceeds the RET node and whether the
1903 // return uses the result of the node or is a void return.
1904 unsigned NumOps = Ret.getNumOperands();
1906 (Ret.getOperand(0) == SDOperand(Call.Val,1) ||
1907 Ret.getOperand(0) == SDOperand(Call.Val,0))) ||
1909 Ret.getOperand(0) == SDOperand(Call.Val,Call.Val->getNumValues()-1) &&
1910 Ret.getOperand(1) == SDOperand(Call.Val,0))) {
1911 MachineFunction &MF = DAG.getMachineFunction();
1912 unsigned CallerCC = MF.getFunction()->getCallingConv();
1913 unsigned CalleeCC = cast<ConstantSDNode>(Call.getOperand(1))->getValue();
1914 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1915 SDOperand Callee = Call.getOperand(4);
1916 // On x86/32Bit PIC/GOT tail calls are supported.
1917 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1918 !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1921 // Can only do local tail calls (in same module, hidden or protected) on
1922 // x86_64 PIC/GOT at the moment.
1923 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1924 return G->getGlobal()->hasHiddenVisibility()
1925 || G->getGlobal()->hasProtectedVisibility();
1932 //===----------------------------------------------------------------------===//
1933 // Other Lowering Hooks
1934 //===----------------------------------------------------------------------===//
1937 SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1938 MachineFunction &MF = DAG.getMachineFunction();
1939 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1940 int ReturnAddrIndex = FuncInfo->getRAIndex();
1942 if (ReturnAddrIndex == 0) {
1943 // Set up a frame object for the return address.
1944 if (Subtarget->is64Bit())
1945 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
1947 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
1949 FuncInfo->setRAIndex(ReturnAddrIndex);
1952 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1957 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1958 /// specific condition code. It returns a false if it cannot do a direct
1959 /// translation. X86CC is the translated CondCode. LHS/RHS are modified as
1961 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1962 unsigned &X86CC, SDOperand &LHS, SDOperand &RHS,
1963 SelectionDAG &DAG) {
1964 X86CC = X86::COND_INVALID;
1966 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1967 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
1968 // X > -1 -> X == 0, jump !sign.
1969 RHS = DAG.getConstant(0, RHS.getValueType());
1970 X86CC = X86::COND_NS;
1972 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
1973 // X < 0 -> X == 0, jump on sign.
1974 X86CC = X86::COND_S;
1976 } else if (SetCCOpcode == ISD::SETLT && RHSC->getValue() == 1) {
1978 RHS = DAG.getConstant(0, RHS.getValueType());
1979 X86CC = X86::COND_LE;
1984 switch (SetCCOpcode) {
1986 case ISD::SETEQ: X86CC = X86::COND_E; break;
1987 case ISD::SETGT: X86CC = X86::COND_G; break;
1988 case ISD::SETGE: X86CC = X86::COND_GE; break;
1989 case ISD::SETLT: X86CC = X86::COND_L; break;
1990 case ISD::SETLE: X86CC = X86::COND_LE; break;
1991 case ISD::SETNE: X86CC = X86::COND_NE; break;
1992 case ISD::SETULT: X86CC = X86::COND_B; break;
1993 case ISD::SETUGT: X86CC = X86::COND_A; break;
1994 case ISD::SETULE: X86CC = X86::COND_BE; break;
1995 case ISD::SETUGE: X86CC = X86::COND_AE; break;
1998 // On a floating point condition, the flags are set as follows:
2000 // 0 | 0 | 0 | X > Y
2001 // 0 | 0 | 1 | X < Y
2002 // 1 | 0 | 0 | X == Y
2003 // 1 | 1 | 1 | unordered
2005 switch (SetCCOpcode) {
2008 case ISD::SETEQ: X86CC = X86::COND_E; break;
2009 case ISD::SETOLT: Flip = true; // Fallthrough
2011 case ISD::SETGT: X86CC = X86::COND_A; break;
2012 case ISD::SETOLE: Flip = true; // Fallthrough
2014 case ISD::SETGE: X86CC = X86::COND_AE; break;
2015 case ISD::SETUGT: Flip = true; // Fallthrough
2017 case ISD::SETLT: X86CC = X86::COND_B; break;
2018 case ISD::SETUGE: Flip = true; // Fallthrough
2020 case ISD::SETLE: X86CC = X86::COND_BE; break;
2022 case ISD::SETNE: X86CC = X86::COND_NE; break;
2023 case ISD::SETUO: X86CC = X86::COND_P; break;
2024 case ISD::SETO: X86CC = X86::COND_NP; break;
2027 std::swap(LHS, RHS);
2030 return X86CC != X86::COND_INVALID;
2033 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2034 /// code. Current x86 isa includes the following FP cmov instructions:
2035 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2036 static bool hasFPCMov(unsigned X86CC) {
2052 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
2053 /// true if Op is undef or if its value falls within the specified range (L, H].
2054 static bool isUndefOrInRange(SDOperand Op, unsigned Low, unsigned Hi) {
2055 if (Op.getOpcode() == ISD::UNDEF)
2058 unsigned Val = cast<ConstantSDNode>(Op)->getValue();
2059 return (Val >= Low && Val < Hi);
2062 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
2063 /// true if Op is undef or if its value equal to the specified value.
2064 static bool isUndefOrEqual(SDOperand Op, unsigned Val) {
2065 if (Op.getOpcode() == ISD::UNDEF)
2067 return cast<ConstantSDNode>(Op)->getValue() == Val;
2070 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2071 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
2072 bool X86::isPSHUFDMask(SDNode *N) {
2073 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2075 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
2078 // Check if the value doesn't reference the second vector.
2079 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2080 SDOperand Arg = N->getOperand(i);
2081 if (Arg.getOpcode() == ISD::UNDEF) continue;
2082 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2083 if (cast<ConstantSDNode>(Arg)->getValue() >= e)
2090 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2091 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2092 bool X86::isPSHUFHWMask(SDNode *N) {
2093 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2095 if (N->getNumOperands() != 8)
2098 // Lower quadword copied in order.
2099 for (unsigned i = 0; i != 4; ++i) {
2100 SDOperand Arg = N->getOperand(i);
2101 if (Arg.getOpcode() == ISD::UNDEF) continue;
2102 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2103 if (cast<ConstantSDNode>(Arg)->getValue() != i)
2107 // Upper quadword shuffled.
2108 for (unsigned i = 4; i != 8; ++i) {
2109 SDOperand Arg = N->getOperand(i);
2110 if (Arg.getOpcode() == ISD::UNDEF) continue;
2111 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2112 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2113 if (Val < 4 || Val > 7)
2120 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2121 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2122 bool X86::isPSHUFLWMask(SDNode *N) {
2123 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2125 if (N->getNumOperands() != 8)
2128 // Upper quadword copied in order.
2129 for (unsigned i = 4; i != 8; ++i)
2130 if (!isUndefOrEqual(N->getOperand(i), i))
2133 // Lower quadword shuffled.
2134 for (unsigned i = 0; i != 4; ++i)
2135 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2141 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2142 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2143 static bool isSHUFPMask(SDOperandPtr Elems, unsigned NumElems) {
2144 if (NumElems != 2 && NumElems != 4) return false;
2146 unsigned Half = NumElems / 2;
2147 for (unsigned i = 0; i < Half; ++i)
2148 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2150 for (unsigned i = Half; i < NumElems; ++i)
2151 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2157 bool X86::isSHUFPMask(SDNode *N) {
2158 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2159 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2162 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2163 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2164 /// half elements to come from vector 1 (which would equal the dest.) and
2165 /// the upper half to come from vector 2.
2166 static bool isCommutedSHUFP(SDOperandPtr Ops, unsigned NumOps) {
2167 if (NumOps != 2 && NumOps != 4) return false;
2169 unsigned Half = NumOps / 2;
2170 for (unsigned i = 0; i < Half; ++i)
2171 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2173 for (unsigned i = Half; i < NumOps; ++i)
2174 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2179 static bool isCommutedSHUFP(SDNode *N) {
2180 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2181 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2184 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2185 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2186 bool X86::isMOVHLPSMask(SDNode *N) {
2187 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2189 if (N->getNumOperands() != 4)
2192 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2193 return isUndefOrEqual(N->getOperand(0), 6) &&
2194 isUndefOrEqual(N->getOperand(1), 7) &&
2195 isUndefOrEqual(N->getOperand(2), 2) &&
2196 isUndefOrEqual(N->getOperand(3), 3);
2199 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2200 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2202 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2203 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2205 if (N->getNumOperands() != 4)
2208 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2209 return isUndefOrEqual(N->getOperand(0), 2) &&
2210 isUndefOrEqual(N->getOperand(1), 3) &&
2211 isUndefOrEqual(N->getOperand(2), 2) &&
2212 isUndefOrEqual(N->getOperand(3), 3);
2215 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2216 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2217 bool X86::isMOVLPMask(SDNode *N) {
2218 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2220 unsigned NumElems = N->getNumOperands();
2221 if (NumElems != 2 && NumElems != 4)
2224 for (unsigned i = 0; i < NumElems/2; ++i)
2225 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2228 for (unsigned i = NumElems/2; i < NumElems; ++i)
2229 if (!isUndefOrEqual(N->getOperand(i), i))
2235 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2236 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2238 bool X86::isMOVHPMask(SDNode *N) {
2239 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2241 unsigned NumElems = N->getNumOperands();
2242 if (NumElems != 2 && NumElems != 4)
2245 for (unsigned i = 0; i < NumElems/2; ++i)
2246 if (!isUndefOrEqual(N->getOperand(i), i))
2249 for (unsigned i = 0; i < NumElems/2; ++i) {
2250 SDOperand Arg = N->getOperand(i + NumElems/2);
2251 if (!isUndefOrEqual(Arg, i + NumElems))
2258 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2259 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2260 bool static isUNPCKLMask(SDOperandPtr Elts, unsigned NumElts,
2261 bool V2IsSplat = false) {
2262 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2265 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2266 SDOperand BitI = Elts[i];
2267 SDOperand BitI1 = Elts[i+1];
2268 if (!isUndefOrEqual(BitI, j))
2271 if (isUndefOrEqual(BitI1, NumElts))
2274 if (!isUndefOrEqual(BitI1, j + NumElts))
2282 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2283 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2284 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2287 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2288 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2289 bool static isUNPCKHMask(SDOperandPtr Elts, unsigned NumElts,
2290 bool V2IsSplat = false) {
2291 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2294 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2295 SDOperand BitI = Elts[i];
2296 SDOperand BitI1 = Elts[i+1];
2297 if (!isUndefOrEqual(BitI, j + NumElts/2))
2300 if (isUndefOrEqual(BitI1, NumElts))
2303 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2311 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2312 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2313 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2316 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2317 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2319 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2320 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2322 unsigned NumElems = N->getNumOperands();
2323 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2326 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2327 SDOperand BitI = N->getOperand(i);
2328 SDOperand BitI1 = N->getOperand(i+1);
2330 if (!isUndefOrEqual(BitI, j))
2332 if (!isUndefOrEqual(BitI1, j))
2339 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2340 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2342 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2343 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2345 unsigned NumElems = N->getNumOperands();
2346 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2349 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2350 SDOperand BitI = N->getOperand(i);
2351 SDOperand BitI1 = N->getOperand(i + 1);
2353 if (!isUndefOrEqual(BitI, j))
2355 if (!isUndefOrEqual(BitI1, j))
2362 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2363 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2364 /// MOVSD, and MOVD, i.e. setting the lowest element.
2365 static bool isMOVLMask(SDOperandPtr Elts, unsigned NumElts) {
2366 if (NumElts != 2 && NumElts != 4)
2369 if (!isUndefOrEqual(Elts[0], NumElts))
2372 for (unsigned i = 1; i < NumElts; ++i) {
2373 if (!isUndefOrEqual(Elts[i], i))
2380 bool X86::isMOVLMask(SDNode *N) {
2381 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2382 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2385 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2386 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2387 /// element of vector 2 and the other elements to come from vector 1 in order.
2388 static bool isCommutedMOVL(SDOperandPtr Ops, unsigned NumOps,
2389 bool V2IsSplat = false,
2390 bool V2IsUndef = false) {
2391 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2394 if (!isUndefOrEqual(Ops[0], 0))
2397 for (unsigned i = 1; i < NumOps; ++i) {
2398 SDOperand Arg = Ops[i];
2399 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2400 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2401 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2408 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2409 bool V2IsUndef = false) {
2410 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2411 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2412 V2IsSplat, V2IsUndef);
2415 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2416 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2417 bool X86::isMOVSHDUPMask(SDNode *N) {
2418 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2420 if (N->getNumOperands() != 4)
2423 // Expect 1, 1, 3, 3
2424 for (unsigned i = 0; i < 2; ++i) {
2425 SDOperand Arg = N->getOperand(i);
2426 if (Arg.getOpcode() == ISD::UNDEF) continue;
2427 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2428 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2429 if (Val != 1) return false;
2433 for (unsigned i = 2; i < 4; ++i) {
2434 SDOperand Arg = N->getOperand(i);
2435 if (Arg.getOpcode() == ISD::UNDEF) continue;
2436 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2437 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2438 if (Val != 3) return false;
2442 // Don't use movshdup if it can be done with a shufps.
2446 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2447 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2448 bool X86::isMOVSLDUPMask(SDNode *N) {
2449 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2451 if (N->getNumOperands() != 4)
2454 // Expect 0, 0, 2, 2
2455 for (unsigned i = 0; i < 2; ++i) {
2456 SDOperand Arg = N->getOperand(i);
2457 if (Arg.getOpcode() == ISD::UNDEF) continue;
2458 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2459 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2460 if (Val != 0) return false;
2464 for (unsigned i = 2; i < 4; ++i) {
2465 SDOperand Arg = N->getOperand(i);
2466 if (Arg.getOpcode() == ISD::UNDEF) continue;
2467 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2468 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2469 if (Val != 2) return false;
2473 // Don't use movshdup if it can be done with a shufps.
2477 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2478 /// specifies a identity operation on the LHS or RHS.
2479 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2480 unsigned NumElems = N->getNumOperands();
2481 for (unsigned i = 0; i < NumElems; ++i)
2482 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2487 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2488 /// a splat of a single element.
2489 static bool isSplatMask(SDNode *N) {
2490 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2492 // This is a splat operation if each element of the permute is the same, and
2493 // if the value doesn't reference the second vector.
2494 unsigned NumElems = N->getNumOperands();
2495 SDOperand ElementBase;
2497 for (; i != NumElems; ++i) {
2498 SDOperand Elt = N->getOperand(i);
2499 if (isa<ConstantSDNode>(Elt)) {
2505 if (!ElementBase.Val)
2508 for (; i != NumElems; ++i) {
2509 SDOperand Arg = N->getOperand(i);
2510 if (Arg.getOpcode() == ISD::UNDEF) continue;
2511 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2512 if (Arg != ElementBase) return false;
2515 // Make sure it is a splat of the first vector operand.
2516 return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
2519 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2520 /// a splat of a single element and it's a 2 or 4 element mask.
2521 bool X86::isSplatMask(SDNode *N) {
2522 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2524 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2525 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2527 return ::isSplatMask(N);
2530 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2531 /// specifies a splat of zero element.
2532 bool X86::isSplatLoMask(SDNode *N) {
2533 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2535 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2536 if (!isUndefOrEqual(N->getOperand(i), 0))
2541 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2542 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2544 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2545 unsigned NumOperands = N->getNumOperands();
2546 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2548 for (unsigned i = 0; i < NumOperands; ++i) {
2550 SDOperand Arg = N->getOperand(NumOperands-i-1);
2551 if (Arg.getOpcode() != ISD::UNDEF)
2552 Val = cast<ConstantSDNode>(Arg)->getValue();
2553 if (Val >= NumOperands) Val -= NumOperands;
2555 if (i != NumOperands - 1)
2562 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2563 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2565 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2567 // 8 nodes, but we only care about the last 4.
2568 for (unsigned i = 7; i >= 4; --i) {
2570 SDOperand Arg = N->getOperand(i);
2571 if (Arg.getOpcode() != ISD::UNDEF)
2572 Val = cast<ConstantSDNode>(Arg)->getValue();
2581 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2582 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2584 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2586 // 8 nodes, but we only care about the first 4.
2587 for (int i = 3; i >= 0; --i) {
2589 SDOperand Arg = N->getOperand(i);
2590 if (Arg.getOpcode() != ISD::UNDEF)
2591 Val = cast<ConstantSDNode>(Arg)->getValue();
2600 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2601 /// specifies a 8 element shuffle that can be broken into a pair of
2602 /// PSHUFHW and PSHUFLW.
2603 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2604 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2606 if (N->getNumOperands() != 8)
2609 // Lower quadword shuffled.
2610 for (unsigned i = 0; i != 4; ++i) {
2611 SDOperand Arg = N->getOperand(i);
2612 if (Arg.getOpcode() == ISD::UNDEF) continue;
2613 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2614 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2619 // Upper quadword shuffled.
2620 for (unsigned i = 4; i != 8; ++i) {
2621 SDOperand Arg = N->getOperand(i);
2622 if (Arg.getOpcode() == ISD::UNDEF) continue;
2623 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2624 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2625 if (Val < 4 || Val > 7)
2632 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2633 /// values in ther permute mask.
2634 static SDOperand CommuteVectorShuffle(SDOperand Op, SDOperand &V1,
2635 SDOperand &V2, SDOperand &Mask,
2636 SelectionDAG &DAG) {
2637 MVT::ValueType VT = Op.getValueType();
2638 MVT::ValueType MaskVT = Mask.getValueType();
2639 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2640 unsigned NumElems = Mask.getNumOperands();
2641 SmallVector<SDOperand, 8> MaskVec;
2643 for (unsigned i = 0; i != NumElems; ++i) {
2644 SDOperand Arg = Mask.getOperand(i);
2645 if (Arg.getOpcode() == ISD::UNDEF) {
2646 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2649 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2650 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2652 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2654 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2658 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2659 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2662 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2663 /// the two vector operands have swapped position.
2665 SDOperand CommuteVectorShuffleMask(SDOperand Mask, SelectionDAG &DAG) {
2666 MVT::ValueType MaskVT = Mask.getValueType();
2667 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2668 unsigned NumElems = Mask.getNumOperands();
2669 SmallVector<SDOperand, 8> MaskVec;
2670 for (unsigned i = 0; i != NumElems; ++i) {
2671 SDOperand Arg = Mask.getOperand(i);
2672 if (Arg.getOpcode() == ISD::UNDEF) {
2673 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2676 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2677 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2679 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2681 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2683 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2687 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2688 /// match movhlps. The lower half elements should come from upper half of
2689 /// V1 (and in order), and the upper half elements should come from the upper
2690 /// half of V2 (and in order).
2691 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2692 unsigned NumElems = Mask->getNumOperands();
2695 for (unsigned i = 0, e = 2; i != e; ++i)
2696 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2698 for (unsigned i = 2; i != 4; ++i)
2699 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2704 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2705 /// is promoted to a vector.
2706 static inline bool isScalarLoadToVector(SDNode *N) {
2707 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2708 N = N->getOperand(0).Val;
2709 return ISD::isNON_EXTLoad(N);
2714 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2715 /// match movlp{s|d}. The lower half elements should come from lower half of
2716 /// V1 (and in order), and the upper half elements should come from the upper
2717 /// half of V2 (and in order). And since V1 will become the source of the
2718 /// MOVLP, it must be either a vector load or a scalar load to vector.
2719 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2720 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2722 // Is V2 is a vector load, don't do this transformation. We will try to use
2723 // load folding shufps op.
2724 if (ISD::isNON_EXTLoad(V2))
2727 unsigned NumElems = Mask->getNumOperands();
2728 if (NumElems != 2 && NumElems != 4)
2730 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2731 if (!isUndefOrEqual(Mask->getOperand(i), i))
2733 for (unsigned i = NumElems/2; i != NumElems; ++i)
2734 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2739 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2741 static bool isSplatVector(SDNode *N) {
2742 if (N->getOpcode() != ISD::BUILD_VECTOR)
2745 SDOperand SplatValue = N->getOperand(0);
2746 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2747 if (N->getOperand(i) != SplatValue)
2752 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2754 static bool isUndefShuffle(SDNode *N) {
2755 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2758 SDOperand V1 = N->getOperand(0);
2759 SDOperand V2 = N->getOperand(1);
2760 SDOperand Mask = N->getOperand(2);
2761 unsigned NumElems = Mask.getNumOperands();
2762 for (unsigned i = 0; i != NumElems; ++i) {
2763 SDOperand Arg = Mask.getOperand(i);
2764 if (Arg.getOpcode() != ISD::UNDEF) {
2765 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2766 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2768 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2775 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2777 static inline bool isZeroNode(SDOperand Elt) {
2778 return ((isa<ConstantSDNode>(Elt) &&
2779 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2780 (isa<ConstantFPSDNode>(Elt) &&
2781 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2784 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2785 /// to an zero vector.
2786 static bool isZeroShuffle(SDNode *N) {
2787 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2790 SDOperand V1 = N->getOperand(0);
2791 SDOperand V2 = N->getOperand(1);
2792 SDOperand Mask = N->getOperand(2);
2793 unsigned NumElems = Mask.getNumOperands();
2794 for (unsigned i = 0; i != NumElems; ++i) {
2795 SDOperand Arg = Mask.getOperand(i);
2796 if (Arg.getOpcode() == ISD::UNDEF)
2799 unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
2800 if (Idx < NumElems) {
2801 unsigned Opc = V1.Val->getOpcode();
2802 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.Val))
2804 if (Opc != ISD::BUILD_VECTOR ||
2805 !isZeroNode(V1.Val->getOperand(Idx)))
2807 } else if (Idx >= NumElems) {
2808 unsigned Opc = V2.Val->getOpcode();
2809 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.Val))
2811 if (Opc != ISD::BUILD_VECTOR ||
2812 !isZeroNode(V2.Val->getOperand(Idx - NumElems)))
2819 /// getZeroVector - Returns a vector of specified type with all zero elements.
2821 static SDOperand getZeroVector(MVT::ValueType VT, SelectionDAG &DAG) {
2822 assert(MVT::isVector(VT) && "Expected a vector type");
2824 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2825 // type. This ensures they get CSE'd.
2826 SDOperand Cst = DAG.getTargetConstant(0, MVT::i32);
2828 if (MVT::getSizeInBits(VT) == 64) // MMX
2829 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2831 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2832 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2835 /// getOnesVector - Returns a vector of specified type with all bits set.
2837 static SDOperand getOnesVector(MVT::ValueType VT, SelectionDAG &DAG) {
2838 assert(MVT::isVector(VT) && "Expected a vector type");
2840 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2841 // type. This ensures they get CSE'd.
2842 SDOperand Cst = DAG.getTargetConstant(~0U, MVT::i32);
2844 if (MVT::getSizeInBits(VT) == 64) // MMX
2845 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2847 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2848 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2852 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2853 /// that point to V2 points to its first element.
2854 static SDOperand NormalizeMask(SDOperand Mask, SelectionDAG &DAG) {
2855 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2857 bool Changed = false;
2858 SmallVector<SDOperand, 8> MaskVec;
2859 unsigned NumElems = Mask.getNumOperands();
2860 for (unsigned i = 0; i != NumElems; ++i) {
2861 SDOperand Arg = Mask.getOperand(i);
2862 if (Arg.getOpcode() != ISD::UNDEF) {
2863 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2864 if (Val > NumElems) {
2865 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2869 MaskVec.push_back(Arg);
2873 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2874 &MaskVec[0], MaskVec.size());
2878 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2879 /// operation of specified width.
2880 static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2881 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2882 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2884 SmallVector<SDOperand, 8> MaskVec;
2885 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2886 for (unsigned i = 1; i != NumElems; ++i)
2887 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2888 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2891 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2892 /// of specified width.
2893 static SDOperand getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2894 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2895 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2896 SmallVector<SDOperand, 8> MaskVec;
2897 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2898 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2899 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2901 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2904 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2905 /// of specified width.
2906 static SDOperand getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2907 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2908 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2909 unsigned Half = NumElems/2;
2910 SmallVector<SDOperand, 8> MaskVec;
2911 for (unsigned i = 0; i != Half; ++i) {
2912 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
2913 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2915 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2918 /// getSwapEltZeroMask - Returns a vector_shuffle mask for a shuffle that swaps
2919 /// element #0 of a vector with the specified index, leaving the rest of the
2920 /// elements in place.
2921 static SDOperand getSwapEltZeroMask(unsigned NumElems, unsigned DestElt,
2922 SelectionDAG &DAG) {
2923 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2924 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2925 SmallVector<SDOperand, 8> MaskVec;
2926 // Element #0 of the result gets the elt we are replacing.
2927 MaskVec.push_back(DAG.getConstant(DestElt, BaseVT));
2928 for (unsigned i = 1; i != NumElems; ++i)
2929 MaskVec.push_back(DAG.getConstant(i == DestElt ? 0 : i, BaseVT));
2930 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2933 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
2934 static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG, bool HasSSE2) {
2935 MVT::ValueType PVT = HasSSE2 ? MVT::v4i32 : MVT::v4f32;
2936 MVT::ValueType VT = Op.getValueType();
2939 SDOperand V1 = Op.getOperand(0);
2940 SDOperand Mask = Op.getOperand(2);
2941 unsigned NumElems = Mask.getNumOperands();
2942 // Special handling of v4f32 -> v4i32.
2943 if (VT != MVT::v4f32) {
2944 Mask = getUnpacklMask(NumElems, DAG);
2945 while (NumElems > 4) {
2946 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2949 Mask = getZeroVector(MVT::v4i32, DAG);
2952 V1 = DAG.getNode(ISD::BIT_CONVERT, PVT, V1);
2953 SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, PVT, V1,
2954 DAG.getNode(ISD::UNDEF, PVT), Mask);
2955 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2958 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2959 /// vector of zero or undef vector. This produces a shuffle where the low
2960 /// element of V2 is swizzled into the zero/undef vector, landing at element
2961 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
2962 static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, unsigned Idx,
2963 bool isZero, SelectionDAG &DAG) {
2964 MVT::ValueType VT = V2.getValueType();
2965 SDOperand V1 = isZero ? getZeroVector(VT, DAG) : DAG.getNode(ISD::UNDEF, VT);
2966 unsigned NumElems = MVT::getVectorNumElements(V2.getValueType());
2967 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2968 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
2969 SmallVector<SDOperand, 16> MaskVec;
2970 for (unsigned i = 0; i != NumElems; ++i)
2971 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
2972 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
2974 MaskVec.push_back(DAG.getConstant(i, EVT));
2975 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2976 &MaskVec[0], MaskVec.size());
2977 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2980 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2982 static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
2983 unsigned NumNonZero, unsigned NumZero,
2984 SelectionDAG &DAG, TargetLowering &TLI) {
2990 for (unsigned i = 0; i < 16; ++i) {
2991 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
2992 if (ThisIsNonZero && First) {
2994 V = getZeroVector(MVT::v8i16, DAG);
2996 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3001 SDOperand ThisElt(0, 0), LastElt(0, 0);
3002 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3003 if (LastIsNonZero) {
3004 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
3006 if (ThisIsNonZero) {
3007 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
3008 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
3009 ThisElt, DAG.getConstant(8, MVT::i8));
3011 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
3016 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
3017 DAG.getIntPtrConstant(i/2));
3021 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
3024 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3026 static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
3027 unsigned NumNonZero, unsigned NumZero,
3028 SelectionDAG &DAG, TargetLowering &TLI) {
3034 for (unsigned i = 0; i < 8; ++i) {
3035 bool isNonZero = (NonZeros & (1 << i)) != 0;
3039 V = getZeroVector(MVT::v8i16, DAG);
3041 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3044 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
3045 DAG.getIntPtrConstant(i));
3053 X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3054 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3055 if (ISD::isBuildVectorAllZeros(Op.Val) || ISD::isBuildVectorAllOnes(Op.Val)) {
3056 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3057 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3058 // eliminated on x86-32 hosts.
3059 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3062 if (ISD::isBuildVectorAllOnes(Op.Val))
3063 return getOnesVector(Op.getValueType(), DAG);
3064 return getZeroVector(Op.getValueType(), DAG);
3067 MVT::ValueType VT = Op.getValueType();
3068 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3069 unsigned EVTBits = MVT::getSizeInBits(EVT);
3071 unsigned NumElems = Op.getNumOperands();
3072 unsigned NumZero = 0;
3073 unsigned NumNonZero = 0;
3074 unsigned NonZeros = 0;
3075 bool IsAllConstants = true;
3076 SmallSet<SDOperand, 8> Values;
3077 for (unsigned i = 0; i < NumElems; ++i) {
3078 SDOperand Elt = Op.getOperand(i);
3079 if (Elt.getOpcode() == ISD::UNDEF)
3082 if (Elt.getOpcode() != ISD::Constant &&
3083 Elt.getOpcode() != ISD::ConstantFP)
3084 IsAllConstants = false;
3085 if (isZeroNode(Elt))
3088 NonZeros |= (1 << i);
3093 if (NumNonZero == 0) {
3094 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3095 return DAG.getNode(ISD::UNDEF, VT);
3098 // Special case for single non-zero, non-undef, element.
3099 if (NumNonZero == 1 && NumElems <= 4) {
3100 unsigned Idx = CountTrailingZeros_32(NonZeros);
3101 SDOperand Item = Op.getOperand(Idx);
3103 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3104 // the value are obviously zero, truncate the value to i32 and do the
3105 // insertion that way. Only do this if the value is non-constant or if the
3106 // value is a constant being inserted into element 0. It is cheaper to do
3107 // a constant pool load than it is to do a movd + shuffle.
3108 if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3109 (!IsAllConstants || Idx == 0)) {
3110 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3111 // Handle MMX and SSE both.
3112 MVT::ValueType VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3113 MVT::ValueType VecElts = VT == MVT::v2i64 ? 4 : 2;
3115 // Truncate the value (which may itself be a constant) to i32, and
3116 // convert it to a vector with movd (S2V+shuffle to zero extend).
3117 Item = DAG.getNode(ISD::TRUNCATE, MVT::i32, Item);
3118 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VecVT, Item);
3119 Item = getShuffleVectorZeroOrUndef(Item, 0, true, DAG);
3121 // Now we have our 32-bit value zero extended in the low element of
3122 // a vector. If Idx != 0, swizzle it into place.
3125 Item, DAG.getNode(ISD::UNDEF, Item.getValueType()),
3126 getSwapEltZeroMask(VecElts, Idx, DAG)
3128 Item = DAG.getNode(ISD::VECTOR_SHUFFLE, VecVT, Ops, 3);
3130 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Item);
3134 // If we have a constant or non-constant insertion into the low element of
3135 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3136 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3137 // depending on what the source datatype is. Because we can only get here
3138 // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3140 // Don't do this for i64 values on x86-32.
3141 (EVT != MVT::i64 || Subtarget->is64Bit())) {
3142 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3143 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3144 return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, DAG);
3147 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3150 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3151 // is a non-constant being inserted into an element other than the low one,
3152 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3153 // movd/movss) to move this into the low element, then shuffle it into
3155 if (EVTBits == 32) {
3156 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3158 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3159 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, DAG);
3160 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3161 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3162 SmallVector<SDOperand, 8> MaskVec;
3163 for (unsigned i = 0; i < NumElems; i++)
3164 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3165 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3166 &MaskVec[0], MaskVec.size());
3167 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3168 DAG.getNode(ISD::UNDEF, VT), Mask);
3172 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3173 if (Values.size() == 1)
3176 // A vector full of immediates; various special cases are already
3177 // handled, so this is best done with a single constant-pool load.
3181 // Let legalizer expand 2-wide build_vectors.
3185 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3186 if (EVTBits == 8 && NumElems == 16) {
3187 SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3189 if (V.Val) return V;
3192 if (EVTBits == 16 && NumElems == 8) {
3193 SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3195 if (V.Val) return V;
3198 // If element VT is == 32 bits, turn it into a number of shuffles.
3199 SmallVector<SDOperand, 8> V;
3201 if (NumElems == 4 && NumZero > 0) {
3202 for (unsigned i = 0; i < 4; ++i) {
3203 bool isZero = !(NonZeros & (1 << i));
3205 V[i] = getZeroVector(VT, DAG);
3207 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3210 for (unsigned i = 0; i < 2; ++i) {
3211 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3214 V[i] = V[i*2]; // Must be a zero vector.
3217 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3218 getMOVLMask(NumElems, DAG));
3221 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3222 getMOVLMask(NumElems, DAG));
3225 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3226 getUnpacklMask(NumElems, DAG));
3231 // Take advantage of the fact GR32 to VR128 scalar_to_vector (i.e. movd)
3232 // clears the upper bits.
3233 // FIXME: we can do the same for v4f32 case when we know both parts of
3234 // the lower half come from scalar_to_vector (loadf32). We should do
3235 // that in post legalizer dag combiner with target specific hooks.
3236 if (MVT::isInteger(EVT) && (NonZeros & (0x3 << 2)) == 0)
3238 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3239 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
3240 SmallVector<SDOperand, 8> MaskVec;
3241 bool Reverse = (NonZeros & 0x3) == 2;
3242 for (unsigned i = 0; i < 2; ++i)
3244 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3246 MaskVec.push_back(DAG.getConstant(i, EVT));
3247 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3248 for (unsigned i = 0; i < 2; ++i)
3250 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3252 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3253 SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3254 &MaskVec[0], MaskVec.size());
3255 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3258 if (Values.size() > 2) {
3259 // Expand into a number of unpckl*.
3261 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3262 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3263 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3264 SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
3265 for (unsigned i = 0; i < NumElems; ++i)
3266 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3268 while (NumElems != 0) {
3269 for (unsigned i = 0; i < NumElems; ++i)
3270 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3281 SDOperand LowerVECTOR_SHUFFLEv8i16(SDOperand V1, SDOperand V2,
3282 SDOperand PermMask, SelectionDAG &DAG,
3283 TargetLowering &TLI) {
3285 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(8);
3286 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3287 MVT::ValueType PtrVT = TLI.getPointerTy();
3288 SmallVector<SDOperand, 8> MaskElts(PermMask.Val->op_begin(),
3289 PermMask.Val->op_end());
3291 // First record which half of which vector the low elements come from.
3292 SmallVector<unsigned, 4> LowQuad(4);
3293 for (unsigned i = 0; i < 4; ++i) {
3294 SDOperand Elt = MaskElts[i];
3295 if (Elt.getOpcode() == ISD::UNDEF)
3297 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3298 int QuadIdx = EltIdx / 4;
3301 int BestLowQuad = -1;
3302 unsigned MaxQuad = 1;
3303 for (unsigned i = 0; i < 4; ++i) {
3304 if (LowQuad[i] > MaxQuad) {
3306 MaxQuad = LowQuad[i];
3310 // Record which half of which vector the high elements come from.
3311 SmallVector<unsigned, 4> HighQuad(4);
3312 for (unsigned i = 4; i < 8; ++i) {
3313 SDOperand Elt = MaskElts[i];
3314 if (Elt.getOpcode() == ISD::UNDEF)
3316 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3317 int QuadIdx = EltIdx / 4;
3318 ++HighQuad[QuadIdx];
3320 int BestHighQuad = -1;
3322 for (unsigned i = 0; i < 4; ++i) {
3323 if (HighQuad[i] > MaxQuad) {
3325 MaxQuad = HighQuad[i];
3329 // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3330 if (BestLowQuad != -1 || BestHighQuad != -1) {
3331 // First sort the 4 chunks in order using shufpd.
3332 SmallVector<SDOperand, 8> MaskVec;
3333 if (BestLowQuad != -1)
3334 MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3336 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3337 if (BestHighQuad != -1)
3338 MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3340 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3341 SDOperand Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3342 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3343 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3344 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3345 NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3347 // Now sort high and low parts separately.
3348 BitVector InOrder(8);
3349 if (BestLowQuad != -1) {
3350 // Sort lower half in order using PSHUFLW.
3352 bool AnyOutOrder = false;
3353 for (unsigned i = 0; i != 4; ++i) {
3354 SDOperand Elt = MaskElts[i];
3355 if (Elt.getOpcode() == ISD::UNDEF) {
3356 MaskVec.push_back(Elt);
3359 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3362 MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3363 // If this element is in the right place after this shuffle, then
3365 if ((int)(EltIdx / 4) == BestLowQuad)
3370 for (unsigned i = 4; i != 8; ++i)
3371 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3372 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3373 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3377 if (BestHighQuad != -1) {
3378 // Sort high half in order using PSHUFHW if possible.
3380 for (unsigned i = 0; i != 4; ++i)
3381 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3382 bool AnyOutOrder = false;
3383 for (unsigned i = 4; i != 8; ++i) {
3384 SDOperand Elt = MaskElts[i];
3385 if (Elt.getOpcode() == ISD::UNDEF) {
3386 MaskVec.push_back(Elt);
3389 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3392 MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3393 // If this element is in the right place after this shuffle, then
3395 if ((int)(EltIdx / 4) == BestHighQuad)
3400 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3401 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3405 // The other elements are put in the right place using pextrw and pinsrw.
3406 for (unsigned i = 0; i != 8; ++i) {
3409 SDOperand Elt = MaskElts[i];
3410 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3413 SDOperand ExtOp = (EltIdx < 8)
3414 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3415 DAG.getConstant(EltIdx, PtrVT))
3416 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3417 DAG.getConstant(EltIdx - 8, PtrVT));
3418 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3419 DAG.getConstant(i, PtrVT));
3424 // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use
3425 ///as few as possible.
3426 // First, let's find out how many elements are already in the right order.
3427 unsigned V1InOrder = 0;
3428 unsigned V1FromV1 = 0;
3429 unsigned V2InOrder = 0;
3430 unsigned V2FromV2 = 0;
3431 SmallVector<SDOperand, 8> V1Elts;
3432 SmallVector<SDOperand, 8> V2Elts;
3433 for (unsigned i = 0; i < 8; ++i) {
3434 SDOperand Elt = MaskElts[i];
3435 if (Elt.getOpcode() == ISD::UNDEF) {
3436 V1Elts.push_back(Elt);
3437 V2Elts.push_back(Elt);
3442 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3444 V1Elts.push_back(Elt);
3445 V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3447 } else if (EltIdx == i+8) {
3448 V1Elts.push_back(Elt);
3449 V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3451 } else if (EltIdx < 8) {
3452 V1Elts.push_back(Elt);
3455 V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3460 if (V2InOrder > V1InOrder) {
3461 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3463 std::swap(V1Elts, V2Elts);
3464 std::swap(V1FromV1, V2FromV2);
3467 if ((V1FromV1 + V1InOrder) != 8) {
3468 // Some elements are from V2.
3470 // If there are elements that are from V1 but out of place,
3471 // then first sort them in place
3472 SmallVector<SDOperand, 8> MaskVec;
3473 for (unsigned i = 0; i < 8; ++i) {
3474 SDOperand Elt = V1Elts[i];
3475 if (Elt.getOpcode() == ISD::UNDEF) {
3476 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3479 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3481 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3483 MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3485 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3486 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3490 for (unsigned i = 0; i < 8; ++i) {
3491 SDOperand Elt = V1Elts[i];
3492 if (Elt.getOpcode() == ISD::UNDEF)
3494 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3497 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3498 DAG.getConstant(EltIdx - 8, PtrVT));
3499 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3500 DAG.getConstant(i, PtrVT));
3504 // All elements are from V1.
3506 for (unsigned i = 0; i < 8; ++i) {
3507 SDOperand Elt = V1Elts[i];
3508 if (Elt.getOpcode() == ISD::UNDEF)
3510 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3511 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3512 DAG.getConstant(EltIdx, PtrVT));
3513 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3514 DAG.getConstant(i, PtrVT));
3520 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3521 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3522 /// done when every pair / quad of shuffle mask elements point to elements in
3523 /// the right sequence. e.g.
3524 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3526 SDOperand RewriteAsNarrowerShuffle(SDOperand V1, SDOperand V2,
3528 SDOperand PermMask, SelectionDAG &DAG,
3529 TargetLowering &TLI) {
3530 unsigned NumElems = PermMask.getNumOperands();
3531 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3532 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3533 MVT::ValueType NewVT = MaskVT;
3535 case MVT::v4f32: NewVT = MVT::v2f64; break;
3536 case MVT::v4i32: NewVT = MVT::v2i64; break;
3537 case MVT::v8i16: NewVT = MVT::v4i32; break;
3538 case MVT::v16i8: NewVT = MVT::v4i32; break;
3539 default: assert(false && "Unexpected!");
3542 if (NewWidth == 2) {
3543 if (MVT::isInteger(VT))
3548 unsigned Scale = NumElems / NewWidth;
3549 SmallVector<SDOperand, 8> MaskVec;
3550 for (unsigned i = 0; i < NumElems; i += Scale) {
3551 unsigned StartIdx = ~0U;
3552 for (unsigned j = 0; j < Scale; ++j) {
3553 SDOperand Elt = PermMask.getOperand(i+j);
3554 if (Elt.getOpcode() == ISD::UNDEF)
3556 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3557 if (StartIdx == ~0U)
3558 StartIdx = EltIdx - (EltIdx % Scale);
3559 if (EltIdx != StartIdx + j)
3562 if (StartIdx == ~0U)
3563 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
3565 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MVT::i32));
3568 V1 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V1);
3569 V2 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V2);
3570 return DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, V1, V2,
3571 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3572 &MaskVec[0], MaskVec.size()));
3576 X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
3577 SDOperand V1 = Op.getOperand(0);
3578 SDOperand V2 = Op.getOperand(1);
3579 SDOperand PermMask = Op.getOperand(2);
3580 MVT::ValueType VT = Op.getValueType();
3581 unsigned NumElems = PermMask.getNumOperands();
3582 bool isMMX = MVT::getSizeInBits(VT) == 64;
3583 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3584 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3585 bool V1IsSplat = false;
3586 bool V2IsSplat = false;
3588 if (isUndefShuffle(Op.Val))
3589 return DAG.getNode(ISD::UNDEF, VT);
3591 if (isZeroShuffle(Op.Val))
3592 return getZeroVector(VT, DAG);
3594 if (isIdentityMask(PermMask.Val))
3596 else if (isIdentityMask(PermMask.Val, true))
3599 if (isSplatMask(PermMask.Val)) {
3600 if (isMMX || NumElems < 4) return Op;
3601 // Promote it to a v4{if}32 splat.
3602 return PromoteSplat(Op, DAG, Subtarget->hasSSE2());
3605 // If the shuffle can be profitably rewritten as a narrower shuffle, then
3607 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3608 SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3610 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3611 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3612 // FIXME: Figure out a cleaner way to do this.
3613 // Try to make use of movq to zero out the top part.
3614 if (ISD::isBuildVectorAllZeros(V2.Val)) {
3615 SDOperand NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3617 SDOperand NewV1 = NewOp.getOperand(0);
3618 SDOperand NewV2 = NewOp.getOperand(1);
3619 SDOperand NewMask = NewOp.getOperand(2);
3620 if (isCommutedMOVL(NewMask.Val, true, false)) {
3621 NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
3622 NewOp = DAG.getNode(ISD::VECTOR_SHUFFLE, NewOp.getValueType(),
3623 NewV1, NewV2, getMOVLMask(2, DAG));
3624 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3627 } else if (ISD::isBuildVectorAllZeros(V1.Val)) {
3628 SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3629 if (NewOp.Val && X86::isMOVLMask(NewOp.getOperand(2).Val))
3630 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3634 if (X86::isMOVLMask(PermMask.Val))
3635 return (V1IsUndef) ? V2 : Op;
3637 if (X86::isMOVSHDUPMask(PermMask.Val) ||
3638 X86::isMOVSLDUPMask(PermMask.Val) ||
3639 X86::isMOVHLPSMask(PermMask.Val) ||
3640 X86::isMOVHPMask(PermMask.Val) ||
3641 X86::isMOVLPMask(PermMask.Val))
3644 if (ShouldXformToMOVHLPS(PermMask.Val) ||
3645 ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
3646 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3648 bool Commuted = false;
3649 // FIXME: This should also accept a bitcast of a splat? Be careful, not
3650 // 1,1,1,1 -> v8i16 though.
3651 V1IsSplat = isSplatVector(V1.Val);
3652 V2IsSplat = isSplatVector(V2.Val);
3654 // Canonicalize the splat or undef, if present, to be on the RHS.
3655 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3656 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3657 std::swap(V1IsSplat, V2IsSplat);
3658 std::swap(V1IsUndef, V2IsUndef);
3662 // FIXME: Figure out a cleaner way to do this.
3663 if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
3664 if (V2IsUndef) return V1;
3665 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3667 // V2 is a splat, so the mask may be malformed. That is, it may point
3668 // to any V2 element. The instruction selectior won't like this. Get
3669 // a corrected mask and commute to form a proper MOVS{S|D}.
3670 SDOperand NewMask = getMOVLMask(NumElems, DAG);
3671 if (NewMask.Val != PermMask.Val)
3672 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3677 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3678 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3679 X86::isUNPCKLMask(PermMask.Val) ||
3680 X86::isUNPCKHMask(PermMask.Val))
3684 // Normalize mask so all entries that point to V2 points to its first
3685 // element then try to match unpck{h|l} again. If match, return a
3686 // new vector_shuffle with the corrected mask.
3687 SDOperand NewMask = NormalizeMask(PermMask, DAG);
3688 if (NewMask.Val != PermMask.Val) {
3689 if (X86::isUNPCKLMask(PermMask.Val, true)) {
3690 SDOperand NewMask = getUnpacklMask(NumElems, DAG);
3691 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3692 } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
3693 SDOperand NewMask = getUnpackhMask(NumElems, DAG);
3694 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3699 // Normalize the node to match x86 shuffle ops if needed
3700 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
3701 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3704 // Commute is back and try unpck* again.
3705 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3706 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3707 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3708 X86::isUNPCKLMask(PermMask.Val) ||
3709 X86::isUNPCKHMask(PermMask.Val))
3713 // Try PSHUF* first, then SHUFP*.
3714 // MMX doesn't have PSHUFD but it does have PSHUFW. While it's theoretically
3715 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
3716 if (isMMX && NumElems == 4 && X86::isPSHUFDMask(PermMask.Val)) {
3717 if (V2.getOpcode() != ISD::UNDEF)
3718 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3719 DAG.getNode(ISD::UNDEF, VT), PermMask);
3724 if (Subtarget->hasSSE2() &&
3725 (X86::isPSHUFDMask(PermMask.Val) ||
3726 X86::isPSHUFHWMask(PermMask.Val) ||
3727 X86::isPSHUFLWMask(PermMask.Val))) {
3728 MVT::ValueType RVT = VT;
3729 if (VT == MVT::v4f32) {
3731 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT,
3732 DAG.getNode(ISD::BIT_CONVERT, RVT, V1),
3733 DAG.getNode(ISD::UNDEF, RVT), PermMask);
3734 } else if (V2.getOpcode() != ISD::UNDEF)
3735 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT, V1,
3736 DAG.getNode(ISD::UNDEF, RVT), PermMask);
3738 Op = DAG.getNode(ISD::BIT_CONVERT, VT, Op);
3742 // Binary or unary shufps.
3743 if (X86::isSHUFPMask(PermMask.Val) ||
3744 (V2.getOpcode() == ISD::UNDEF && X86::isPSHUFDMask(PermMask.Val)))
3748 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
3749 if (VT == MVT::v8i16) {
3750 SDOperand NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
3755 // Handle all 4 wide cases with a number of shuffles.
3756 if (NumElems == 4 && !isMMX) {
3757 // Don't do this for MMX.
3758 MVT::ValueType MaskVT = PermMask.getValueType();
3759 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3760 SmallVector<std::pair<int, int>, 8> Locs;
3761 Locs.reserve(NumElems);
3762 SmallVector<SDOperand, 8> Mask1(NumElems,
3763 DAG.getNode(ISD::UNDEF, MaskEVT));
3764 SmallVector<SDOperand, 8> Mask2(NumElems,
3765 DAG.getNode(ISD::UNDEF, MaskEVT));
3768 // If no more than two elements come from either vector. This can be
3769 // implemented with two shuffles. First shuffle gather the elements.
3770 // The second shuffle, which takes the first shuffle as both of its
3771 // vector operands, put the elements into the right order.
3772 for (unsigned i = 0; i != NumElems; ++i) {
3773 SDOperand Elt = PermMask.getOperand(i);
3774 if (Elt.getOpcode() == ISD::UNDEF) {
3775 Locs[i] = std::make_pair(-1, -1);
3777 unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3778 if (Val < NumElems) {
3779 Locs[i] = std::make_pair(0, NumLo);
3783 Locs[i] = std::make_pair(1, NumHi);
3784 if (2+NumHi < NumElems)
3785 Mask1[2+NumHi] = Elt;
3790 if (NumLo <= 2 && NumHi <= 2) {
3791 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3792 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3793 &Mask1[0], Mask1.size()));
3794 for (unsigned i = 0; i != NumElems; ++i) {
3795 if (Locs[i].first == -1)
3798 unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
3799 Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
3800 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3804 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3805 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3806 &Mask2[0], Mask2.size()));
3809 // Break it into (shuffle shuffle_hi, shuffle_lo).
3811 SmallVector<SDOperand,8> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3812 SmallVector<SDOperand,8> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3813 SmallVector<SDOperand,8> *MaskPtr = &LoMask;
3814 unsigned MaskIdx = 0;
3816 unsigned HiIdx = NumElems/2;
3817 for (unsigned i = 0; i != NumElems; ++i) {
3818 if (i == NumElems/2) {
3824 SDOperand Elt = PermMask.getOperand(i);
3825 if (Elt.getOpcode() == ISD::UNDEF) {
3826 Locs[i] = std::make_pair(-1, -1);
3827 } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
3828 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3829 (*MaskPtr)[LoIdx] = Elt;
3832 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3833 (*MaskPtr)[HiIdx] = Elt;
3838 SDOperand LoShuffle =
3839 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3840 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3841 &LoMask[0], LoMask.size()));
3842 SDOperand HiShuffle =
3843 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3844 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3845 &HiMask[0], HiMask.size()));
3846 SmallVector<SDOperand, 8> MaskOps;
3847 for (unsigned i = 0; i != NumElems; ++i) {
3848 if (Locs[i].first == -1) {
3849 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3851 unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
3852 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3855 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3856 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3857 &MaskOps[0], MaskOps.size()));
3864 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDOperand Op,
3865 SelectionDAG &DAG) {
3866 MVT::ValueType VT = Op.getValueType();
3867 if (MVT::getSizeInBits(VT) == 8) {
3868 SDOperand Extract = DAG.getNode(X86ISD::PEXTRB, MVT::i32,
3869 Op.getOperand(0), Op.getOperand(1));
3870 SDOperand Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
3871 DAG.getValueType(VT));
3872 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3873 } else if (MVT::getSizeInBits(VT) == 16) {
3874 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, MVT::i32,
3875 Op.getOperand(0), Op.getOperand(1));
3876 SDOperand Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
3877 DAG.getValueType(VT));
3878 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3879 } else if (VT == MVT::f32) {
3880 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
3881 // the result back to FR32 register. It's only worth matching if the
3882 // result has a single use which is a store or a bitcast to i32.
3883 if (!Op.hasOneUse())
3885 SDNode *User = Op.Val->use_begin()->getUser();
3886 if (User->getOpcode() != ISD::STORE &&
3887 (User->getOpcode() != ISD::BIT_CONVERT ||
3888 User->getValueType(0) != MVT::i32))
3890 SDOperand Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
3891 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Op.getOperand(0)),
3893 return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, Extract);
3900 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3901 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3904 if (Subtarget->hasSSE41()) {
3905 SDOperand Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
3910 MVT::ValueType VT = Op.getValueType();
3911 // TODO: handle v16i8.
3912 if (MVT::getSizeInBits(VT) == 16) {
3913 SDOperand Vec = Op.getOperand(0);
3914 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3916 return DAG.getNode(ISD::TRUNCATE, MVT::i16,
3917 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
3918 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
3920 // Transform it so it match pextrw which produces a 32-bit result.
3921 MVT::ValueType EVT = (MVT::ValueType)(VT+1);
3922 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
3923 Op.getOperand(0), Op.getOperand(1));
3924 SDOperand Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
3925 DAG.getValueType(VT));
3926 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3927 } else if (MVT::getSizeInBits(VT) == 32) {
3928 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3931 // SHUFPS the element to the lowest double word, then movss.
3932 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3933 SmallVector<SDOperand, 8> IdxVec;
3935 push_back(DAG.getConstant(Idx, MVT::getVectorElementType(MaskVT)));
3937 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3939 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3941 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3942 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3943 &IdxVec[0], IdxVec.size());
3944 SDOperand Vec = Op.getOperand(0);
3945 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3946 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3947 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3948 DAG.getIntPtrConstant(0));
3949 } else if (MVT::getSizeInBits(VT) == 64) {
3950 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
3951 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
3952 // to match extract_elt for f64.
3953 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3957 // UNPCKHPD the element to the lowest double word, then movsd.
3958 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
3959 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
3960 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3961 SmallVector<SDOperand, 8> IdxVec;
3962 IdxVec.push_back(DAG.getConstant(1, MVT::getVectorElementType(MaskVT)));
3964 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3965 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3966 &IdxVec[0], IdxVec.size());
3967 SDOperand Vec = Op.getOperand(0);
3968 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3969 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3970 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3971 DAG.getIntPtrConstant(0));
3978 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDOperand Op, SelectionDAG &DAG){
3979 MVT::ValueType VT = Op.getValueType();
3980 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3982 SDOperand N0 = Op.getOperand(0);
3983 SDOperand N1 = Op.getOperand(1);
3984 SDOperand N2 = Op.getOperand(2);
3986 if ((MVT::getSizeInBits(EVT) == 8) || (MVT::getSizeInBits(EVT) == 16)) {
3987 unsigned Opc = (MVT::getSizeInBits(EVT) == 8) ? X86ISD::PINSRB
3989 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
3991 if (N1.getValueType() != MVT::i32)
3992 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3993 if (N2.getValueType() != MVT::i32)
3994 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
3995 return DAG.getNode(Opc, VT, N0, N1, N2);
3996 } else if (EVT == MVT::f32) {
3997 // Bits [7:6] of the constant are the source select. This will always be
3998 // zero here. The DAG Combiner may combine an extract_elt index into these
3999 // bits. For example (insert (extract, 3), 2) could be matched by putting
4000 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4001 // Bits [5:4] of the constant are the destination select. This is the
4002 // value of the incoming immediate.
4003 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4004 // combine either bitwise AND or insert of float 0.0 to set these bits.
4005 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue() << 4);
4006 return DAG.getNode(X86ISD::INSERTPS, VT, N0, N1, N2);
4012 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
4013 MVT::ValueType VT = Op.getValueType();
4014 MVT::ValueType EVT = MVT::getVectorElementType(VT);
4016 if (Subtarget->hasSSE41())
4017 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4022 SDOperand N0 = Op.getOperand(0);
4023 SDOperand N1 = Op.getOperand(1);
4024 SDOperand N2 = Op.getOperand(2);
4026 if (MVT::getSizeInBits(EVT) == 16) {
4027 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4028 // as its second argument.
4029 if (N1.getValueType() != MVT::i32)
4030 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
4031 if (N2.getValueType() != MVT::i32)
4032 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
4033 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
4039 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
4040 SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
4041 MVT::ValueType VT = MVT::v2i32;
4042 switch (Op.getValueType()) {
4049 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(),
4050 DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, AnyExt));
4053 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4054 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4055 // one of the above mentioned nodes. It has to be wrapped because otherwise
4056 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4057 // be used to form addressing mode. These wrapped nodes will be selected
4060 X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
4061 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4062 SDOperand Result = DAG.getTargetConstantPool(CP->getConstVal(),
4064 CP->getAlignment());
4065 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4066 // With PIC, the address is actually $g + Offset.
4067 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4068 !Subtarget->isPICStyleRIPRel()) {
4069 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4070 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4078 X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
4079 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4080 SDOperand Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
4081 // If it's a debug information descriptor, don't mess with it.
4082 if (DAG.isVerifiedDebugInfoDesc(Op))
4084 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4085 // With PIC, the address is actually $g + Offset.
4086 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4087 !Subtarget->isPICStyleRIPRel()) {
4088 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4089 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4093 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4094 // load the value at address GV, not the value of GV itself. This means that
4095 // the GlobalAddress must be in the base or index register of the address, not
4096 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4097 // The same applies for external symbols during PIC codegen
4098 if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
4099 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
4100 PseudoSourceValue::getGOT(), 0);
4105 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
4107 LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4108 const MVT::ValueType PtrVT) {
4110 SDOperand Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
4111 DAG.getNode(X86ISD::GlobalBaseReg,
4113 InFlag = Chain.getValue(1);
4115 // emit leal symbol@TLSGD(,%ebx,1), %eax
4116 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4117 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4118 GA->getValueType(0),
4120 SDOperand Ops[] = { Chain, TGA, InFlag };
4121 SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
4122 InFlag = Result.getValue(2);
4123 Chain = Result.getValue(1);
4125 // call ___tls_get_addr. This function receives its argument in
4126 // the register EAX.
4127 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
4128 InFlag = Chain.getValue(1);
4130 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4131 SDOperand Ops1[] = { Chain,
4132 DAG.getTargetExternalSymbol("___tls_get_addr",
4134 DAG.getRegister(X86::EAX, PtrVT),
4135 DAG.getRegister(X86::EBX, PtrVT),
4137 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
4138 InFlag = Chain.getValue(1);
4140 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
4143 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4144 // "local exec" model.
4146 LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4147 const MVT::ValueType PtrVT) {
4148 // Get the Thread Pointer
4149 SDOperand ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4150 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4152 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4153 GA->getValueType(0),
4155 SDOperand Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4157 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4158 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
4159 PseudoSourceValue::getGOT(), 0);
4161 // The address of the thread local variable is the add of the thread
4162 // pointer with the offset of the variable.
4163 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4167 X86TargetLowering::LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
4168 // TODO: implement the "local dynamic" model
4169 // TODO: implement the "initial exec"model for pic executables
4170 assert(!Subtarget->is64Bit() && Subtarget->isTargetELF() &&
4171 "TLS not implemented for non-ELF and 64-bit targets");
4172 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4173 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4174 // otherwise use the "Local Exec"TLS Model
4175 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4176 return LowerToTLSGeneralDynamicModel(GA, DAG, getPointerTy());
4178 return LowerToTLSExecModel(GA, DAG, getPointerTy());
4182 X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
4183 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4184 SDOperand Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4185 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4186 // With PIC, the address is actually $g + Offset.
4187 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4188 !Subtarget->isPICStyleRIPRel()) {
4189 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4190 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4197 SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
4198 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4199 SDOperand Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4200 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4201 // With PIC, the address is actually $g + Offset.
4202 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4203 !Subtarget->isPICStyleRIPRel()) {
4204 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4205 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4212 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4213 /// take a 2 x i32 value to shift plus a shift amount.
4214 SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
4215 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4216 MVT::ValueType VT = Op.getValueType();
4217 unsigned VTBits = MVT::getSizeInBits(VT);
4218 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4219 SDOperand ShOpLo = Op.getOperand(0);
4220 SDOperand ShOpHi = Op.getOperand(1);
4221 SDOperand ShAmt = Op.getOperand(2);
4222 SDOperand Tmp1 = isSRA ?
4223 DAG.getNode(ISD::SRA, VT, ShOpHi, DAG.getConstant(VTBits - 1, MVT::i8)) :
4224 DAG.getConstant(0, VT);
4226 SDOperand Tmp2, Tmp3;
4227 if (Op.getOpcode() == ISD::SHL_PARTS) {
4228 Tmp2 = DAG.getNode(X86ISD::SHLD, VT, ShOpHi, ShOpLo, ShAmt);
4229 Tmp3 = DAG.getNode(ISD::SHL, VT, ShOpLo, ShAmt);
4231 Tmp2 = DAG.getNode(X86ISD::SHRD, VT, ShOpLo, ShOpHi, ShAmt);
4232 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, VT, ShOpHi, ShAmt);
4235 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
4236 SDOperand AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4237 DAG.getConstant(VTBits, MVT::i8));
4238 SDOperand Cond = DAG.getNode(X86ISD::CMP, VT,
4239 AndNode, DAG.getConstant(0, MVT::i8));
4242 SDOperand CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4243 VTs = DAG.getNodeValueTypes(VT, MVT::Flag);
4244 SmallVector<SDOperand, 4> Ops;
4245 if (Op.getOpcode() == ISD::SHL_PARTS) {
4246 Ops.push_back(Tmp2);
4247 Ops.push_back(Tmp3);
4249 Ops.push_back(Cond);
4250 Hi = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4253 Ops.push_back(Tmp3);
4254 Ops.push_back(Tmp1);
4256 Ops.push_back(Cond);
4257 Lo = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4259 Ops.push_back(Tmp2);
4260 Ops.push_back(Tmp3);
4262 Ops.push_back(Cond);
4263 Lo = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4266 Ops.push_back(Tmp3);
4267 Ops.push_back(Tmp1);
4269 Ops.push_back(Cond);
4270 Hi = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4273 VTs = DAG.getNodeValueTypes(VT, VT);
4277 return DAG.getNode(ISD::MERGE_VALUES, VTs, 2, &Ops[0], Ops.size());
4280 SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
4281 MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
4282 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
4283 "Unknown SINT_TO_FP to lower!");
4285 // These are really Legal; caller falls through into that case.
4286 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4288 if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 &&
4289 Subtarget->is64Bit())
4292 unsigned Size = MVT::getSizeInBits(SrcVT)/8;
4293 MachineFunction &MF = DAG.getMachineFunction();
4294 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4295 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4296 SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4298 PseudoSourceValue::getFixedStack(),
4303 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4305 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4307 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4308 SmallVector<SDOperand, 8> Ops;
4309 Ops.push_back(Chain);
4310 Ops.push_back(StackSlot);
4311 Ops.push_back(DAG.getValueType(SrcVT));
4312 SDOperand Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD,
4313 Tys, &Ops[0], Ops.size());
4316 Chain = Result.getValue(1);
4317 SDOperand InFlag = Result.getValue(2);
4319 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4320 // shouldn't be necessary except that RFP cannot be live across
4321 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4322 MachineFunction &MF = DAG.getMachineFunction();
4323 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4324 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4325 Tys = DAG.getVTList(MVT::Other);
4326 SmallVector<SDOperand, 8> Ops;
4327 Ops.push_back(Chain);
4328 Ops.push_back(Result);
4329 Ops.push_back(StackSlot);
4330 Ops.push_back(DAG.getValueType(Op.getValueType()));
4331 Ops.push_back(InFlag);
4332 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4333 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
4334 PseudoSourceValue::getFixedStack(), SSFI);
4340 std::pair<SDOperand,SDOperand> X86TargetLowering::
4341 FP_TO_SINTHelper(SDOperand Op, SelectionDAG &DAG) {
4342 assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
4343 "Unknown FP_TO_SINT to lower!");
4345 // These are really Legal.
4346 if (Op.getValueType() == MVT::i32 &&
4347 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4348 return std::make_pair(SDOperand(), SDOperand());
4349 if (Subtarget->is64Bit() &&
4350 Op.getValueType() == MVT::i64 &&
4351 Op.getOperand(0).getValueType() != MVT::f80)
4352 return std::make_pair(SDOperand(), SDOperand());
4354 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4356 MachineFunction &MF = DAG.getMachineFunction();
4357 unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
4358 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4359 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4361 switch (Op.getValueType()) {
4362 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4363 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4364 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4365 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4368 SDOperand Chain = DAG.getEntryNode();
4369 SDOperand Value = Op.getOperand(0);
4370 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4371 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4372 Chain = DAG.getStore(Chain, Value, StackSlot,
4373 PseudoSourceValue::getFixedStack(), SSFI);
4374 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4376 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4378 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4379 Chain = Value.getValue(1);
4380 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4381 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4384 // Build the FP_TO_INT*_IN_MEM
4385 SDOperand Ops[] = { Chain, Value, StackSlot };
4386 SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4388 return std::make_pair(FIST, StackSlot);
4391 SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
4392 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(Op, DAG);
4393 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4394 if (FIST.Val == 0) return SDOperand();
4397 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4400 SDNode *X86TargetLowering::ExpandFP_TO_SINT(SDNode *N, SelectionDAG &DAG) {
4401 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(SDOperand(N, 0), DAG);
4402 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4403 if (FIST.Val == 0) return 0;
4405 // Return an i64 load from the stack slot.
4406 SDOperand Res = DAG.getLoad(MVT::i64, FIST, StackSlot, NULL, 0);
4408 // Use a MERGE_VALUES node to drop the chain result value.
4409 return DAG.getNode(ISD::MERGE_VALUES, MVT::i64, Res).Val;
4412 SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
4413 MVT::ValueType VT = Op.getValueType();
4414 MVT::ValueType EltVT = VT;
4415 if (MVT::isVector(VT))
4416 EltVT = MVT::getVectorElementType(VT);
4417 std::vector<Constant*> CV;
4418 if (EltVT == MVT::f64) {
4419 Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
4423 Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
4429 Constant *C = ConstantVector::get(CV);
4430 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4431 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4432 PseudoSourceValue::getConstantPool(), 0,
4434 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4437 SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
4438 MVT::ValueType VT = Op.getValueType();
4439 MVT::ValueType EltVT = VT;
4440 unsigned EltNum = 1;
4441 if (MVT::isVector(VT)) {
4442 EltVT = MVT::getVectorElementType(VT);
4443 EltNum = MVT::getVectorNumElements(VT);
4445 std::vector<Constant*> CV;
4446 if (EltVT == MVT::f64) {
4447 Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
4451 Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
4457 Constant *C = ConstantVector::get(CV);
4458 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4459 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4460 PseudoSourceValue::getConstantPool(), 0,
4462 if (MVT::isVector(VT)) {
4463 return DAG.getNode(ISD::BIT_CONVERT, VT,
4464 DAG.getNode(ISD::XOR, MVT::v2i64,
4465 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4466 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4468 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4472 SDOperand X86TargetLowering::LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
4473 SDOperand Op0 = Op.getOperand(0);
4474 SDOperand Op1 = Op.getOperand(1);
4475 MVT::ValueType VT = Op.getValueType();
4476 MVT::ValueType SrcVT = Op1.getValueType();
4478 // If second operand is smaller, extend it first.
4479 if (MVT::getSizeInBits(SrcVT) < MVT::getSizeInBits(VT)) {
4480 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4483 // And if it is bigger, shrink it first.
4484 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4485 Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1, DAG.getIntPtrConstant(1));
4489 // At this point the operands and the result should have the same
4490 // type, and that won't be f80 since that is not custom lowered.
4492 // First get the sign bit of second operand.
4493 std::vector<Constant*> CV;
4494 if (SrcVT == MVT::f64) {
4495 CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
4496 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4498 CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
4499 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4500 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4501 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4503 Constant *C = ConstantVector::get(CV);
4504 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4505 SDOperand Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx,
4506 PseudoSourceValue::getConstantPool(), 0,
4508 SDOperand SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4510 // Shift sign bit right or left if the two operands have different types.
4511 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4512 // Op0 is MVT::f32, Op1 is MVT::f64.
4513 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4514 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4515 DAG.getConstant(32, MVT::i32));
4516 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4517 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4518 DAG.getIntPtrConstant(0));
4521 // Clear first operand sign bit.
4523 if (VT == MVT::f64) {
4524 CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
4525 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4527 CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
4528 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4529 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4530 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4532 C = ConstantVector::get(CV);
4533 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4534 SDOperand Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4535 PseudoSourceValue::getConstantPool(), 0,
4537 SDOperand Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4539 // Or the value with the sign bit.
4540 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4543 SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG) {
4544 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
4546 SDOperand Op0 = Op.getOperand(0);
4547 SDOperand Op1 = Op.getOperand(1);
4548 SDOperand CC = Op.getOperand(2);
4549 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4550 bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
4553 if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
4555 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4556 return DAG.getNode(X86ISD::SETCC, MVT::i8,
4557 DAG.getConstant(X86CC, MVT::i8), Cond);
4560 assert(isFP && "Illegal integer SetCC!");
4562 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4563 switch (SetCCOpcode) {
4564 default: assert(false && "Illegal floating point SetCC!");
4565 case ISD::SETOEQ: { // !PF & ZF
4566 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4567 DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
4568 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4569 DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4570 return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4572 case ISD::SETUNE: { // PF | !ZF
4573 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4574 DAG.getConstant(X86::COND_P, MVT::i8), Cond);
4575 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4576 DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4577 return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4583 SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
4584 bool addTest = true;
4585 SDOperand Cond = Op.getOperand(0);
4588 if (Cond.getOpcode() == ISD::SETCC)
4589 Cond = LowerSETCC(Cond, DAG);
4591 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4592 // setting operand in place of the X86ISD::SETCC.
4593 if (Cond.getOpcode() == X86ISD::SETCC) {
4594 CC = Cond.getOperand(0);
4596 SDOperand Cmp = Cond.getOperand(1);
4597 unsigned Opc = Cmp.getOpcode();
4598 MVT::ValueType VT = Op.getValueType();
4600 bool IllegalFPCMov = false;
4601 if (MVT::isFloatingPoint(VT) && !MVT::isVector(VT) &&
4602 !isScalarFPTypeInSSEReg(VT)) // FPStack?
4603 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4605 if ((Opc == X86ISD::CMP ||
4606 Opc == X86ISD::COMI ||
4607 Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
4614 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4615 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4618 const MVT::ValueType *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4620 SmallVector<SDOperand, 4> Ops;
4621 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4622 // condition is true.
4623 Ops.push_back(Op.getOperand(2));
4624 Ops.push_back(Op.getOperand(1));
4626 Ops.push_back(Cond);
4627 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
4630 SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
4631 bool addTest = true;
4632 SDOperand Chain = Op.getOperand(0);
4633 SDOperand Cond = Op.getOperand(1);
4634 SDOperand Dest = Op.getOperand(2);
4637 if (Cond.getOpcode() == ISD::SETCC)
4638 Cond = LowerSETCC(Cond, DAG);
4640 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4641 // setting operand in place of the X86ISD::SETCC.
4642 if (Cond.getOpcode() == X86ISD::SETCC) {
4643 CC = Cond.getOperand(0);
4645 SDOperand Cmp = Cond.getOperand(1);
4646 unsigned Opc = Cmp.getOpcode();
4647 if (Opc == X86ISD::CMP ||
4648 Opc == X86ISD::COMI ||
4649 Opc == X86ISD::UCOMI) {
4656 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4657 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4659 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
4660 Chain, Op.getOperand(2), CC, Cond);
4664 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
4665 // Calls to _alloca is needed to probe the stack when allocating more than 4k
4666 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
4667 // that the guard pages used by the OS virtual memory manager are allocated in
4668 // correct sequence.
4670 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDOperand Op,
4671 SelectionDAG &DAG) {
4672 assert(Subtarget->isTargetCygMing() &&
4673 "This should be used only on Cygwin/Mingw targets");
4676 SDOperand Chain = Op.getOperand(0);
4677 SDOperand Size = Op.getOperand(1);
4678 // FIXME: Ensure alignment here
4682 MVT::ValueType IntPtr = getPointerTy();
4683 MVT::ValueType SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
4685 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
4686 Flag = Chain.getValue(1);
4688 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4689 SDOperand Ops[] = { Chain,
4690 DAG.getTargetExternalSymbol("_alloca", IntPtr),
4691 DAG.getRegister(X86::EAX, IntPtr),
4693 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 4);
4694 Flag = Chain.getValue(1);
4696 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
4698 std::vector<MVT::ValueType> Tys;
4699 Tys.push_back(SPTy);
4700 Tys.push_back(MVT::Other);
4701 SDOperand Ops1[2] = { Chain.getValue(0), Chain };
4702 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops1, 2);
4706 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG,
4708 SDOperand Dst, SDOperand Src,
4709 SDOperand Size, unsigned Align,
4710 const Value *DstSV, uint64_t DstOff) {
4711 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
4713 /// If not DWORD aligned or size is more than the threshold, call the library.
4714 /// The libc version is likely to be faster for these cases. It can use the
4715 /// address value and run time information about the CPU.
4716 if ((Align & 3) == 0 ||
4718 ConstantSize->getValue() > getSubtarget()->getMaxInlineSizeThreshold()) {
4719 SDOperand InFlag(0, 0);
4721 // Check to see if there is a specialized entry-point for memory zeroing.
4722 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
4723 if (const char *bzeroEntry =
4724 V && V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
4725 MVT::ValueType IntPtr = getPointerTy();
4726 const Type *IntPtrTy = getTargetData()->getIntPtrType();
4727 TargetLowering::ArgListTy Args;
4728 TargetLowering::ArgListEntry Entry;
4730 Entry.Ty = IntPtrTy;
4731 Args.push_back(Entry);
4733 Args.push_back(Entry);
4734 std::pair<SDOperand,SDOperand> CallResult =
4735 LowerCallTo(Chain, Type::VoidTy, false, false, false, CallingConv::C,
4736 false, DAG.getExternalSymbol(bzeroEntry, IntPtr),
4738 return CallResult.second;
4741 // Otherwise have the target-independent code call memset.
4745 uint64_t SizeVal = ConstantSize->getValue();
4746 SDOperand InFlag(0, 0);
4749 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
4750 unsigned BytesLeft = 0;
4751 bool TwoRepStos = false;
4754 uint64_t Val = ValC->getValue() & 255;
4756 // If the value is a constant, then we can potentially use larger sets.
4757 switch (Align & 3) {
4758 case 2: // WORD aligned
4761 Val = (Val << 8) | Val;
4763 case 0: // DWORD aligned
4766 Val = (Val << 8) | Val;
4767 Val = (Val << 16) | Val;
4768 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
4771 Val = (Val << 32) | Val;
4774 default: // Byte aligned
4777 Count = DAG.getIntPtrConstant(SizeVal);
4781 if (AVT > MVT::i8) {
4782 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4783 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
4784 BytesLeft = SizeVal % UBytes;
4787 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
4789 InFlag = Chain.getValue(1);
4792 Count = DAG.getIntPtrConstant(SizeVal);
4793 Chain = DAG.getCopyToReg(Chain, X86::AL, Src, InFlag);
4794 InFlag = Chain.getValue(1);
4797 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4799 InFlag = Chain.getValue(1);
4800 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4802 InFlag = Chain.getValue(1);
4804 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4805 SmallVector<SDOperand, 8> Ops;
4806 Ops.push_back(Chain);
4807 Ops.push_back(DAG.getValueType(AVT));
4808 Ops.push_back(InFlag);
4809 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4812 InFlag = Chain.getValue(1);
4814 MVT::ValueType CVT = Count.getValueType();
4815 SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
4816 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
4817 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
4819 InFlag = Chain.getValue(1);
4820 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4822 Ops.push_back(Chain);
4823 Ops.push_back(DAG.getValueType(MVT::i8));
4824 Ops.push_back(InFlag);
4825 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4826 } else if (BytesLeft) {
4827 // Handle the last 1 - 7 bytes.
4828 unsigned Offset = SizeVal - BytesLeft;
4829 MVT::ValueType AddrVT = Dst.getValueType();
4830 MVT::ValueType SizeVT = Size.getValueType();
4832 Chain = DAG.getMemset(Chain,
4833 DAG.getNode(ISD::ADD, AddrVT, Dst,
4834 DAG.getConstant(Offset, AddrVT)),
4836 DAG.getConstant(BytesLeft, SizeVT),
4840 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
4845 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG,
4847 SDOperand Dst, SDOperand Src,
4848 SDOperand Size, unsigned Align,
4850 const Value *DstSV, uint64_t DstOff,
4851 const Value *SrcSV, uint64_t SrcOff){
4853 // This requires the copy size to be a constant, preferrably
4854 // within a subtarget-specific limit.
4855 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
4858 uint64_t SizeVal = ConstantSize->getValue();
4859 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
4863 unsigned BytesLeft = 0;
4864 if (Align >= 8 && Subtarget->is64Bit())
4866 else if (Align >= 4)
4868 else if (Align >= 2)
4873 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4874 unsigned CountVal = SizeVal / UBytes;
4875 SDOperand Count = DAG.getIntPtrConstant(CountVal);
4876 BytesLeft = SizeVal % UBytes;
4878 SDOperand InFlag(0, 0);
4879 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4881 InFlag = Chain.getValue(1);
4882 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4884 InFlag = Chain.getValue(1);
4885 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
4887 InFlag = Chain.getValue(1);
4889 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4890 SmallVector<SDOperand, 8> Ops;
4891 Ops.push_back(Chain);
4892 Ops.push_back(DAG.getValueType(AVT));
4893 Ops.push_back(InFlag);
4894 SDOperand RepMovs = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
4896 SmallVector<SDOperand, 4> Results;
4897 Results.push_back(RepMovs);
4899 // Handle the last 1 - 7 bytes.
4900 unsigned Offset = SizeVal - BytesLeft;
4901 MVT::ValueType DstVT = Dst.getValueType();
4902 MVT::ValueType SrcVT = Src.getValueType();
4903 MVT::ValueType SizeVT = Size.getValueType();
4904 Results.push_back(DAG.getMemcpy(Chain,
4905 DAG.getNode(ISD::ADD, DstVT, Dst,
4906 DAG.getConstant(Offset, DstVT)),
4907 DAG.getNode(ISD::ADD, SrcVT, Src,
4908 DAG.getConstant(Offset, SrcVT)),
4909 DAG.getConstant(BytesLeft, SizeVT),
4910 Align, AlwaysInline,
4911 DstSV, 0, SrcSV, 0));
4914 return DAG.getNode(ISD::TokenFactor, MVT::Other, &Results[0], Results.size());
4917 /// Expand the result of: i64,outchain = READCYCLECOUNTER inchain
4918 SDNode *X86TargetLowering::ExpandREADCYCLECOUNTER(SDNode *N, SelectionDAG &DAG){
4919 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4920 SDOperand TheChain = N->getOperand(0);
4921 SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
4922 if (Subtarget->is64Bit()) {
4923 SDOperand rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
4924 SDOperand rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX,
4925 MVT::i64, rax.getValue(2));
4926 SDOperand Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
4927 DAG.getConstant(32, MVT::i8));
4929 DAG.getNode(ISD::OR, MVT::i64, rax, Tmp), rdx.getValue(1)
4932 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4933 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4936 SDOperand eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
4937 SDOperand edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX,
4938 MVT::i32, eax.getValue(2));
4939 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
4940 SDOperand Ops[] = { eax, edx };
4941 Ops[0] = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2);
4943 // Use a MERGE_VALUES to return the value and chain.
4944 Ops[1] = edx.getValue(1);
4945 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4946 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4949 SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
4950 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4952 if (!Subtarget->is64Bit()) {
4953 // vastart just stores the address of the VarArgsFrameIndex slot into the
4954 // memory location argument.
4955 SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4956 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV, 0);
4960 // gp_offset (0 - 6 * 8)
4961 // fp_offset (48 - 48 + 8 * 16)
4962 // overflow_arg_area (point to parameters coming in memory).
4964 SmallVector<SDOperand, 8> MemOps;
4965 SDOperand FIN = Op.getOperand(1);
4967 SDOperand Store = DAG.getStore(Op.getOperand(0),
4968 DAG.getConstant(VarArgsGPOffset, MVT::i32),
4970 MemOps.push_back(Store);
4973 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
4974 Store = DAG.getStore(Op.getOperand(0),
4975 DAG.getConstant(VarArgsFPOffset, MVT::i32),
4977 MemOps.push_back(Store);
4979 // Store ptr to overflow_arg_area
4980 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
4981 SDOperand OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4982 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV, 0);
4983 MemOps.push_back(Store);
4985 // Store ptr to reg_save_area.
4986 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
4987 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
4988 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV, 0);
4989 MemOps.push_back(Store);
4990 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
4993 SDOperand X86TargetLowering::LowerVACOPY(SDOperand Op, SelectionDAG &DAG) {
4994 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
4995 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
4996 SDOperand Chain = Op.getOperand(0);
4997 SDOperand DstPtr = Op.getOperand(1);
4998 SDOperand SrcPtr = Op.getOperand(2);
4999 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5000 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5002 return DAG.getMemcpy(Chain, DstPtr, SrcPtr,
5003 DAG.getIntPtrConstant(24), 8, false,
5004 DstSV, 0, SrcSV, 0);
5008 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
5009 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
5011 default: return SDOperand(); // Don't custom lower most intrinsics.
5012 // Comparison intrinsics.
5013 case Intrinsic::x86_sse_comieq_ss:
5014 case Intrinsic::x86_sse_comilt_ss:
5015 case Intrinsic::x86_sse_comile_ss:
5016 case Intrinsic::x86_sse_comigt_ss:
5017 case Intrinsic::x86_sse_comige_ss:
5018 case Intrinsic::x86_sse_comineq_ss:
5019 case Intrinsic::x86_sse_ucomieq_ss:
5020 case Intrinsic::x86_sse_ucomilt_ss:
5021 case Intrinsic::x86_sse_ucomile_ss:
5022 case Intrinsic::x86_sse_ucomigt_ss:
5023 case Intrinsic::x86_sse_ucomige_ss:
5024 case Intrinsic::x86_sse_ucomineq_ss:
5025 case Intrinsic::x86_sse2_comieq_sd:
5026 case Intrinsic::x86_sse2_comilt_sd:
5027 case Intrinsic::x86_sse2_comile_sd:
5028 case Intrinsic::x86_sse2_comigt_sd:
5029 case Intrinsic::x86_sse2_comige_sd:
5030 case Intrinsic::x86_sse2_comineq_sd:
5031 case Intrinsic::x86_sse2_ucomieq_sd:
5032 case Intrinsic::x86_sse2_ucomilt_sd:
5033 case Intrinsic::x86_sse2_ucomile_sd:
5034 case Intrinsic::x86_sse2_ucomigt_sd:
5035 case Intrinsic::x86_sse2_ucomige_sd:
5036 case Intrinsic::x86_sse2_ucomineq_sd: {
5038 ISD::CondCode CC = ISD::SETCC_INVALID;
5041 case Intrinsic::x86_sse_comieq_ss:
5042 case Intrinsic::x86_sse2_comieq_sd:
5046 case Intrinsic::x86_sse_comilt_ss:
5047 case Intrinsic::x86_sse2_comilt_sd:
5051 case Intrinsic::x86_sse_comile_ss:
5052 case Intrinsic::x86_sse2_comile_sd:
5056 case Intrinsic::x86_sse_comigt_ss:
5057 case Intrinsic::x86_sse2_comigt_sd:
5061 case Intrinsic::x86_sse_comige_ss:
5062 case Intrinsic::x86_sse2_comige_sd:
5066 case Intrinsic::x86_sse_comineq_ss:
5067 case Intrinsic::x86_sse2_comineq_sd:
5071 case Intrinsic::x86_sse_ucomieq_ss:
5072 case Intrinsic::x86_sse2_ucomieq_sd:
5073 Opc = X86ISD::UCOMI;
5076 case Intrinsic::x86_sse_ucomilt_ss:
5077 case Intrinsic::x86_sse2_ucomilt_sd:
5078 Opc = X86ISD::UCOMI;
5081 case Intrinsic::x86_sse_ucomile_ss:
5082 case Intrinsic::x86_sse2_ucomile_sd:
5083 Opc = X86ISD::UCOMI;
5086 case Intrinsic::x86_sse_ucomigt_ss:
5087 case Intrinsic::x86_sse2_ucomigt_sd:
5088 Opc = X86ISD::UCOMI;
5091 case Intrinsic::x86_sse_ucomige_ss:
5092 case Intrinsic::x86_sse2_ucomige_sd:
5093 Opc = X86ISD::UCOMI;
5096 case Intrinsic::x86_sse_ucomineq_ss:
5097 case Intrinsic::x86_sse2_ucomineq_sd:
5098 Opc = X86ISD::UCOMI;
5104 SDOperand LHS = Op.getOperand(1);
5105 SDOperand RHS = Op.getOperand(2);
5106 translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
5108 SDOperand Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
5109 SDOperand SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
5110 DAG.getConstant(X86CC, MVT::i8), Cond);
5111 return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
5116 SDOperand X86TargetLowering::LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
5117 // Depths > 0 not supported yet!
5118 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5121 // Just load the return address
5122 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5123 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
5126 SDOperand X86TargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG) {
5127 // Depths > 0 not supported yet!
5128 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5131 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5132 return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI,
5133 DAG.getIntPtrConstant(4));
5136 SDOperand X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDOperand Op,
5137 SelectionDAG &DAG) {
5138 // Is not yet supported on x86-64
5139 if (Subtarget->is64Bit())
5142 return DAG.getIntPtrConstant(8);
5145 SDOperand X86TargetLowering::LowerEH_RETURN(SDOperand Op, SelectionDAG &DAG)
5147 assert(!Subtarget->is64Bit() &&
5148 "Lowering of eh_return builtin is not supported yet on x86-64");
5150 MachineFunction &MF = DAG.getMachineFunction();
5151 SDOperand Chain = Op.getOperand(0);
5152 SDOperand Offset = Op.getOperand(1);
5153 SDOperand Handler = Op.getOperand(2);
5155 SDOperand Frame = DAG.getRegister(RegInfo->getFrameRegister(MF),
5158 SDOperand StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
5159 DAG.getIntPtrConstant(-4UL));
5160 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
5161 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
5162 Chain = DAG.getCopyToReg(Chain, X86::ECX, StoreAddr);
5163 MF.getRegInfo().addLiveOut(X86::ECX);
5165 return DAG.getNode(X86ISD::EH_RETURN, MVT::Other,
5166 Chain, DAG.getRegister(X86::ECX, getPointerTy()));
5169 SDOperand X86TargetLowering::LowerTRAMPOLINE(SDOperand Op,
5170 SelectionDAG &DAG) {
5171 SDOperand Root = Op.getOperand(0);
5172 SDOperand Trmp = Op.getOperand(1); // trampoline
5173 SDOperand FPtr = Op.getOperand(2); // nested function
5174 SDOperand Nest = Op.getOperand(3); // 'nest' parameter value
5176 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5178 const X86InstrInfo *TII =
5179 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5181 if (Subtarget->is64Bit()) {
5182 SDOperand OutChains[6];
5184 // Large code-model.
5186 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
5187 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
5189 const unsigned char N86R10 =
5190 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(X86::R10);
5191 const unsigned char N86R11 =
5192 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(X86::R11);
5194 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
5196 // Load the pointer to the nested function into R11.
5197 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
5198 SDOperand Addr = Trmp;
5199 OutChains[0] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5202 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(2, MVT::i64));
5203 OutChains[1] = DAG.getStore(Root, FPtr, Addr, TrmpAddr, 2, false, 2);
5205 // Load the 'nest' parameter value into R10.
5206 // R10 is specified in X86CallingConv.td
5207 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
5208 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(10, MVT::i64));
5209 OutChains[2] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5212 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(12, MVT::i64));
5213 OutChains[3] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 12, false, 2);
5215 // Jump to the nested function.
5216 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
5217 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(20, MVT::i64));
5218 OutChains[4] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5221 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
5222 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(22, MVT::i64));
5223 OutChains[5] = DAG.getStore(Root, DAG.getConstant(ModRM, MVT::i8), Addr,
5227 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 6) };
5228 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5230 const Function *Func =
5231 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5232 unsigned CC = Func->getCallingConv();
5237 assert(0 && "Unsupported calling convention");
5238 case CallingConv::C:
5239 case CallingConv::X86_StdCall: {
5240 // Pass 'nest' parameter in ECX.
5241 // Must be kept in sync with X86CallingConv.td
5244 // Check that ECX wasn't needed by an 'inreg' parameter.
5245 const FunctionType *FTy = Func->getFunctionType();
5246 const PAListPtr &Attrs = Func->getParamAttrs();
5248 if (!Attrs.isEmpty() && !Func->isVarArg()) {
5249 unsigned InRegCount = 0;
5252 for (FunctionType::param_iterator I = FTy->param_begin(),
5253 E = FTy->param_end(); I != E; ++I, ++Idx)
5254 if (Attrs.paramHasAttr(Idx, ParamAttr::InReg))
5255 // FIXME: should only count parameters that are lowered to integers.
5256 InRegCount += (getTargetData()->getTypeSizeInBits(*I) + 31) / 32;
5258 if (InRegCount > 2) {
5259 cerr << "Nest register in use - reduce number of inreg parameters!\n";
5265 case CallingConv::X86_FastCall:
5266 // Pass 'nest' parameter in EAX.
5267 // Must be kept in sync with X86CallingConv.td
5272 SDOperand OutChains[4];
5273 SDOperand Addr, Disp;
5275 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5276 Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5278 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
5279 const unsigned char N86Reg =
5280 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(NestReg);
5281 OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
5284 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
5285 OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 1, false, 1);
5287 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
5288 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
5289 OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
5290 TrmpAddr, 5, false, 1);
5292 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
5293 OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpAddr, 6, false, 1);
5296 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
5297 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5301 SDOperand X86TargetLowering::LowerFLT_ROUNDS_(SDOperand Op, SelectionDAG &DAG) {
5303 The rounding mode is in bits 11:10 of FPSR, and has the following
5310 FLT_ROUNDS, on the other hand, expects the following:
5317 To perform the conversion, we do:
5318 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
5321 MachineFunction &MF = DAG.getMachineFunction();
5322 const TargetMachine &TM = MF.getTarget();
5323 const TargetFrameInfo &TFI = *TM.getFrameInfo();
5324 unsigned StackAlignment = TFI.getStackAlignment();
5325 MVT::ValueType VT = Op.getValueType();
5327 // Save FP Control Word to stack slot
5328 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
5329 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5331 SDOperand Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
5332 DAG.getEntryNode(), StackSlot);
5334 // Load FP Control Word from stack slot
5335 SDOperand CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
5337 // Transform as necessary
5339 DAG.getNode(ISD::SRL, MVT::i16,
5340 DAG.getNode(ISD::AND, MVT::i16,
5341 CWD, DAG.getConstant(0x800, MVT::i16)),
5342 DAG.getConstant(11, MVT::i8));
5344 DAG.getNode(ISD::SRL, MVT::i16,
5345 DAG.getNode(ISD::AND, MVT::i16,
5346 CWD, DAG.getConstant(0x400, MVT::i16)),
5347 DAG.getConstant(9, MVT::i8));
5350 DAG.getNode(ISD::AND, MVT::i16,
5351 DAG.getNode(ISD::ADD, MVT::i16,
5352 DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
5353 DAG.getConstant(1, MVT::i16)),
5354 DAG.getConstant(3, MVT::i16));
5357 return DAG.getNode((MVT::getSizeInBits(VT) < 16 ?
5358 ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
5361 SDOperand X86TargetLowering::LowerCTLZ(SDOperand Op, SelectionDAG &DAG) {
5362 MVT::ValueType VT = Op.getValueType();
5363 MVT::ValueType OpVT = VT;
5364 unsigned NumBits = MVT::getSizeInBits(VT);
5366 Op = Op.getOperand(0);
5367 if (VT == MVT::i8) {
5368 // Zero extend to i32 since there is not an i8 bsr.
5370 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5373 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
5374 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5375 Op = DAG.getNode(X86ISD::BSR, VTs, Op);
5377 // If src is zero (i.e. bsr sets ZF), returns NumBits.
5378 SmallVector<SDOperand, 4> Ops;
5380 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
5381 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5382 Ops.push_back(Op.getValue(1));
5383 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5385 // Finally xor with NumBits-1.
5386 Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
5389 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5393 SDOperand X86TargetLowering::LowerCTTZ(SDOperand Op, SelectionDAG &DAG) {
5394 MVT::ValueType VT = Op.getValueType();
5395 MVT::ValueType OpVT = VT;
5396 unsigned NumBits = MVT::getSizeInBits(VT);
5398 Op = Op.getOperand(0);
5399 if (VT == MVT::i8) {
5401 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5404 // Issue a bsf (scan bits forward) which also sets EFLAGS.
5405 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5406 Op = DAG.getNode(X86ISD::BSF, VTs, Op);
5408 // If src is zero (i.e. bsf sets ZF), returns NumBits.
5409 SmallVector<SDOperand, 4> Ops;
5411 Ops.push_back(DAG.getConstant(NumBits, OpVT));
5412 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5413 Ops.push_back(Op.getValue(1));
5414 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5417 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5421 SDOperand X86TargetLowering::LowerLCS(SDOperand Op, SelectionDAG &DAG) {
5422 MVT::ValueType T = cast<AtomicSDNode>(Op.Val)->getVT();
5426 case MVT::i8: Reg = X86::AL; size = 1; break;
5427 case MVT::i16: Reg = X86::AX; size = 2; break;
5428 case MVT::i32: Reg = X86::EAX; size = 4; break;
5430 if (Subtarget->is64Bit()) {
5431 Reg = X86::RAX; size = 8;
5432 } else //Should go away when LowerType stuff lands
5433 return SDOperand(ExpandATOMIC_LCS(Op.Val, DAG), 0);
5436 SDOperand cpIn = DAG.getCopyToReg(Op.getOperand(0), Reg,
5437 Op.getOperand(3), SDOperand());
5438 SDOperand Ops[] = { cpIn.getValue(0),
5441 DAG.getTargetConstant(size, MVT::i8),
5443 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5444 SDOperand Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, Tys, Ops, 5);
5446 DAG.getCopyFromReg(Result.getValue(0), Reg, T, Result.getValue(1));
5450 SDNode* X86TargetLowering::ExpandATOMIC_LCS(SDNode* Op, SelectionDAG &DAG) {
5451 MVT::ValueType T = cast<AtomicSDNode>(Op)->getVT();
5452 assert (T == MVT::i64 && "Only know how to expand i64 CAS");
5453 SDOperand cpInL, cpInH;
5454 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5455 DAG.getConstant(0, MVT::i32));
5456 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5457 DAG.getConstant(1, MVT::i32));
5458 cpInL = DAG.getCopyToReg(Op->getOperand(0), X86::EAX,
5459 cpInL, SDOperand());
5460 cpInH = DAG.getCopyToReg(cpInL.getValue(0), X86::EDX,
5461 cpInH, cpInL.getValue(1));
5462 SDOperand swapInL, swapInH;
5463 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5464 DAG.getConstant(0, MVT::i32));
5465 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5466 DAG.getConstant(1, MVT::i32));
5467 swapInL = DAG.getCopyToReg(cpInH.getValue(0), X86::EBX,
5468 swapInL, cpInH.getValue(1));
5469 swapInH = DAG.getCopyToReg(swapInL.getValue(0), X86::ECX,
5470 swapInH, swapInL.getValue(1));
5471 SDOperand Ops[] = { swapInH.getValue(0),
5473 swapInH.getValue(1)};
5474 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5475 SDOperand Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, Tys, Ops, 3);
5476 SDOperand cpOutL = DAG.getCopyFromReg(Result.getValue(0), X86::EAX, MVT::i32,
5477 Result.getValue(1));
5478 SDOperand cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), X86::EDX, MVT::i32,
5479 cpOutL.getValue(2));
5480 SDOperand OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
5481 SDOperand ResultVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2);
5482 Tys = DAG.getVTList(MVT::i64, MVT::Other);
5483 return DAG.getNode(ISD::MERGE_VALUES, Tys, ResultVal, cpOutH.getValue(1)).Val;
5486 /// LowerOperation - Provide custom lowering hooks for some operations.
5488 SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
5489 switch (Op.getOpcode()) {
5490 default: assert(0 && "Should not custom lower this!");
5491 case ISD::ATOMIC_LCS: return LowerLCS(Op,DAG);
5492 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5493 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5494 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5495 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5496 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5497 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5498 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5499 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5500 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
5501 case ISD::SHL_PARTS:
5502 case ISD::SRA_PARTS:
5503 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
5504 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
5505 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
5506 case ISD::FABS: return LowerFABS(Op, DAG);
5507 case ISD::FNEG: return LowerFNEG(Op, DAG);
5508 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5509 case ISD::SETCC: return LowerSETCC(Op, DAG);
5510 case ISD::SELECT: return LowerSELECT(Op, DAG);
5511 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
5512 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5513 case ISD::CALL: return LowerCALL(Op, DAG);
5514 case ISD::RET: return LowerRET(Op, DAG);
5515 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
5516 case ISD::VASTART: return LowerVASTART(Op, DAG);
5517 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
5518 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5519 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5520 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5521 case ISD::FRAME_TO_ARGS_OFFSET:
5522 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
5523 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
5524 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
5525 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
5526 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5527 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
5528 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
5530 // FIXME: REMOVE THIS WHEN LegalizeDAGTypes lands.
5531 case ISD::READCYCLECOUNTER:
5532 return SDOperand(ExpandREADCYCLECOUNTER(Op.Val, DAG), 0);
5536 /// ExpandOperation - Provide custom lowering hooks for expanding operations.
5537 SDNode *X86TargetLowering::ExpandOperationResult(SDNode *N, SelectionDAG &DAG) {
5538 switch (N->getOpcode()) {
5539 default: assert(0 && "Should not custom lower this!");
5540 case ISD::FP_TO_SINT: return ExpandFP_TO_SINT(N, DAG);
5541 case ISD::READCYCLECOUNTER: return ExpandREADCYCLECOUNTER(N, DAG);
5542 case ISD::ATOMIC_LCS: return ExpandATOMIC_LCS(N, DAG);
5546 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
5548 default: return NULL;
5549 case X86ISD::BSF: return "X86ISD::BSF";
5550 case X86ISD::BSR: return "X86ISD::BSR";
5551 case X86ISD::SHLD: return "X86ISD::SHLD";
5552 case X86ISD::SHRD: return "X86ISD::SHRD";
5553 case X86ISD::FAND: return "X86ISD::FAND";
5554 case X86ISD::FOR: return "X86ISD::FOR";
5555 case X86ISD::FXOR: return "X86ISD::FXOR";
5556 case X86ISD::FSRL: return "X86ISD::FSRL";
5557 case X86ISD::FILD: return "X86ISD::FILD";
5558 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
5559 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
5560 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
5561 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
5562 case X86ISD::FLD: return "X86ISD::FLD";
5563 case X86ISD::FST: return "X86ISD::FST";
5564 case X86ISD::CALL: return "X86ISD::CALL";
5565 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
5566 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
5567 case X86ISD::CMP: return "X86ISD::CMP";
5568 case X86ISD::COMI: return "X86ISD::COMI";
5569 case X86ISD::UCOMI: return "X86ISD::UCOMI";
5570 case X86ISD::SETCC: return "X86ISD::SETCC";
5571 case X86ISD::CMOV: return "X86ISD::CMOV";
5572 case X86ISD::BRCOND: return "X86ISD::BRCOND";
5573 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
5574 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
5575 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
5576 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
5577 case X86ISD::Wrapper: return "X86ISD::Wrapper";
5578 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
5579 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
5580 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
5581 case X86ISD::PINSRB: return "X86ISD::PINSRB";
5582 case X86ISD::PINSRW: return "X86ISD::PINSRW";
5583 case X86ISD::FMAX: return "X86ISD::FMAX";
5584 case X86ISD::FMIN: return "X86ISD::FMIN";
5585 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
5586 case X86ISD::FRCP: return "X86ISD::FRCP";
5587 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
5588 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
5589 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
5590 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
5591 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
5592 case X86ISD::LCMPXCHG_DAG: return "x86ISD::LCMPXCHG_DAG";
5593 case X86ISD::LCMPXCHG8_DAG: return "x86ISD::LCMPXCHG8_DAG";
5597 // isLegalAddressingMode - Return true if the addressing mode represented
5598 // by AM is legal for this target, for a load/store of the specified type.
5599 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
5600 const Type *Ty) const {
5601 // X86 supports extremely general addressing modes.
5603 // X86 allows a sign-extended 32-bit immediate field as a displacement.
5604 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
5608 // We can only fold this if we don't need an extra load.
5609 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
5612 // X86-64 only supports addr of globals in small code model.
5613 if (Subtarget->is64Bit()) {
5614 if (getTargetMachine().getCodeModel() != CodeModel::Small)
5616 // If lower 4G is not available, then we must use rip-relative addressing.
5617 if (AM.BaseOffs || AM.Scale > 1)
5628 // These scales always work.
5633 // These scales are formed with basereg+scalereg. Only accept if there is
5638 default: // Other stuff never works.
5646 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
5647 if (!Ty1->isInteger() || !Ty2->isInteger())
5649 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5650 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5651 if (NumBits1 <= NumBits2)
5653 return Subtarget->is64Bit() || NumBits1 < 64;
5656 bool X86TargetLowering::isTruncateFree(MVT::ValueType VT1,
5657 MVT::ValueType VT2) const {
5658 if (!MVT::isInteger(VT1) || !MVT::isInteger(VT2))
5660 unsigned NumBits1 = MVT::getSizeInBits(VT1);
5661 unsigned NumBits2 = MVT::getSizeInBits(VT2);
5662 if (NumBits1 <= NumBits2)
5664 return Subtarget->is64Bit() || NumBits1 < 64;
5667 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5668 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5669 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5670 /// are assumed to be legal.
5672 X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
5673 // Only do shuffles on 128-bit vector types for now.
5674 if (MVT::getSizeInBits(VT) == 64) return false;
5675 return (Mask.Val->getNumOperands() <= 4 ||
5676 isIdentityMask(Mask.Val) ||
5677 isIdentityMask(Mask.Val, true) ||
5678 isSplatMask(Mask.Val) ||
5679 isPSHUFHW_PSHUFLWMask(Mask.Val) ||
5680 X86::isUNPCKLMask(Mask.Val) ||
5681 X86::isUNPCKHMask(Mask.Val) ||
5682 X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
5683 X86::isUNPCKH_v_undef_Mask(Mask.Val));
5687 X86TargetLowering::isVectorClearMaskLegal(const std::vector<SDOperand> &BVOps,
5689 SelectionDAG &DAG) const {
5690 unsigned NumElts = BVOps.size();
5691 // Only do shuffles on 128-bit vector types for now.
5692 if (MVT::getSizeInBits(EVT) * NumElts == 64) return false;
5693 if (NumElts == 2) return true;
5695 return (isMOVLMask(&BVOps[0], 4) ||
5696 isCommutedMOVL(&BVOps[0], 4, true) ||
5697 isSHUFPMask(&BVOps[0], 4) ||
5698 isCommutedSHUFP(&BVOps[0], 4));
5703 //===----------------------------------------------------------------------===//
5704 // X86 Scheduler Hooks
5705 //===----------------------------------------------------------------------===//
5708 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
5709 MachineBasicBlock *BB) {
5710 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5711 switch (MI->getOpcode()) {
5712 default: assert(false && "Unexpected instr type to insert");
5713 case X86::CMOV_FR32:
5714 case X86::CMOV_FR64:
5715 case X86::CMOV_V4F32:
5716 case X86::CMOV_V2F64:
5717 case X86::CMOV_V2I64: {
5718 // To "insert" a SELECT_CC instruction, we actually have to insert the
5719 // diamond control-flow pattern. The incoming instruction knows the
5720 // destination vreg to set, the condition code register to branch on, the
5721 // true/false values to select between, and a branch opcode to use.
5722 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5723 ilist<MachineBasicBlock>::iterator It = BB;
5729 // cmpTY ccX, r1, r2
5731 // fallthrough --> copy0MBB
5732 MachineBasicBlock *thisMBB = BB;
5733 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
5734 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
5736 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
5737 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
5738 MachineFunction *F = BB->getParent();
5739 F->getBasicBlockList().insert(It, copy0MBB);
5740 F->getBasicBlockList().insert(It, sinkMBB);
5741 // Update machine-CFG edges by first adding all successors of the current
5742 // block to the new block which will contain the Phi node for the select.
5743 for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
5744 e = BB->succ_end(); i != e; ++i)
5745 sinkMBB->addSuccessor(*i);
5746 // Next, remove all successors of the current block, and add the true
5747 // and fallthrough blocks as its successors.
5748 while(!BB->succ_empty())
5749 BB->removeSuccessor(BB->succ_begin());
5750 BB->addSuccessor(copy0MBB);
5751 BB->addSuccessor(sinkMBB);
5754 // %FalseValue = ...
5755 // # fallthrough to sinkMBB
5758 // Update machine-CFG edges
5759 BB->addSuccessor(sinkMBB);
5762 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
5765 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
5766 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
5767 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
5769 delete MI; // The pseudo instruction is gone now.
5773 case X86::FP32_TO_INT16_IN_MEM:
5774 case X86::FP32_TO_INT32_IN_MEM:
5775 case X86::FP32_TO_INT64_IN_MEM:
5776 case X86::FP64_TO_INT16_IN_MEM:
5777 case X86::FP64_TO_INT32_IN_MEM:
5778 case X86::FP64_TO_INT64_IN_MEM:
5779 case X86::FP80_TO_INT16_IN_MEM:
5780 case X86::FP80_TO_INT32_IN_MEM:
5781 case X86::FP80_TO_INT64_IN_MEM: {
5782 // Change the floating point control register to use "round towards zero"
5783 // mode when truncating to an integer value.
5784 MachineFunction *F = BB->getParent();
5785 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
5786 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
5788 // Load the old value of the high byte of the control word...
5790 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
5791 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
5793 // Set the high part to be round to zero...
5794 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
5797 // Reload the modified control word now...
5798 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5800 // Restore the memory image of control word to original value
5801 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
5804 // Get the X86 opcode to use.
5806 switch (MI->getOpcode()) {
5807 default: assert(0 && "illegal opcode!");
5808 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
5809 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
5810 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
5811 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
5812 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
5813 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
5814 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
5815 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
5816 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
5820 MachineOperand &Op = MI->getOperand(0);
5821 if (Op.isRegister()) {
5822 AM.BaseType = X86AddressMode::RegBase;
5823 AM.Base.Reg = Op.getReg();
5825 AM.BaseType = X86AddressMode::FrameIndexBase;
5826 AM.Base.FrameIndex = Op.getIndex();
5828 Op = MI->getOperand(1);
5829 if (Op.isImmediate())
5830 AM.Scale = Op.getImm();
5831 Op = MI->getOperand(2);
5832 if (Op.isImmediate())
5833 AM.IndexReg = Op.getImm();
5834 Op = MI->getOperand(3);
5835 if (Op.isGlobalAddress()) {
5836 AM.GV = Op.getGlobal();
5838 AM.Disp = Op.getImm();
5840 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
5841 .addReg(MI->getOperand(4).getReg());
5843 // Reload the original control word now.
5844 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5846 delete MI; // The pseudo instruction is gone now.
5852 //===----------------------------------------------------------------------===//
5853 // X86 Optimization Hooks
5854 //===----------------------------------------------------------------------===//
5856 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
5860 const SelectionDAG &DAG,
5861 unsigned Depth) const {
5862 unsigned Opc = Op.getOpcode();
5863 assert((Opc >= ISD::BUILTIN_OP_END ||
5864 Opc == ISD::INTRINSIC_WO_CHAIN ||
5865 Opc == ISD::INTRINSIC_W_CHAIN ||
5866 Opc == ISD::INTRINSIC_VOID) &&
5867 "Should use MaskedValueIsZero if you don't know whether Op"
5868 " is a target node!");
5870 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
5874 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
5875 Mask.getBitWidth() - 1);
5880 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5881 /// element of the result of the vector shuffle.
5882 static SDOperand getShuffleScalarElt(SDNode *N, unsigned i, SelectionDAG &DAG) {
5883 MVT::ValueType VT = N->getValueType(0);
5884 SDOperand PermMask = N->getOperand(2);
5885 unsigned NumElems = PermMask.getNumOperands();
5886 SDOperand V = (i < NumElems) ? N->getOperand(0) : N->getOperand(1);
5888 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5890 ? V.getOperand(0) : DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5891 } else if (V.getOpcode() == ISD::VECTOR_SHUFFLE) {
5892 SDOperand Idx = PermMask.getOperand(i);
5893 if (Idx.getOpcode() == ISD::UNDEF)
5894 return DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5895 return getShuffleScalarElt(V.Val,cast<ConstantSDNode>(Idx)->getValue(),DAG);
5900 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
5901 /// node is a GlobalAddress + an offset.
5902 static bool isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) {
5903 unsigned Opc = N->getOpcode();
5904 if (Opc == X86ISD::Wrapper) {
5905 if (dyn_cast<GlobalAddressSDNode>(N->getOperand(0))) {
5906 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
5909 } else if (Opc == ISD::ADD) {
5910 SDOperand N1 = N->getOperand(0);
5911 SDOperand N2 = N->getOperand(1);
5912 if (isGAPlusOffset(N1.Val, GA, Offset)) {
5913 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
5915 Offset += V->getSignExtended();
5918 } else if (isGAPlusOffset(N2.Val, GA, Offset)) {
5919 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
5921 Offset += V->getSignExtended();
5929 /// isConsecutiveLoad - Returns true if N is loading from an address of Base
5931 static bool isConsecutiveLoad(SDNode *N, SDNode *Base, int Dist, int Size,
5932 MachineFrameInfo *MFI) {
5933 if (N->getOperand(0).Val != Base->getOperand(0).Val)
5936 SDOperand Loc = N->getOperand(1);
5937 SDOperand BaseLoc = Base->getOperand(1);
5938 if (Loc.getOpcode() == ISD::FrameIndex) {
5939 if (BaseLoc.getOpcode() != ISD::FrameIndex)
5941 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
5942 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
5943 int FS = MFI->getObjectSize(FI);
5944 int BFS = MFI->getObjectSize(BFI);
5945 if (FS != BFS || FS != Size) return false;
5946 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Size);
5948 GlobalValue *GV1 = NULL;
5949 GlobalValue *GV2 = NULL;
5950 int64_t Offset1 = 0;
5951 int64_t Offset2 = 0;
5952 bool isGA1 = isGAPlusOffset(Loc.Val, GV1, Offset1);
5953 bool isGA2 = isGAPlusOffset(BaseLoc.Val, GV2, Offset2);
5954 if (isGA1 && isGA2 && GV1 == GV2)
5955 return Offset1 == (Offset2 + Dist*Size);
5961 static bool isBaseAlignment16(SDNode *Base, MachineFrameInfo *MFI,
5962 const X86Subtarget *Subtarget) {
5965 if (isGAPlusOffset(Base, GV, Offset))
5966 return (GV->getAlignment() >= 16 && (Offset % 16) == 0);
5967 // DAG combine handles the stack object case.
5972 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
5973 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
5974 /// if the load addresses are consecutive, non-overlapping, and in the right
5976 static SDOperand PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
5977 const X86Subtarget *Subtarget) {
5978 MachineFunction &MF = DAG.getMachineFunction();
5979 MachineFrameInfo *MFI = MF.getFrameInfo();
5980 MVT::ValueType VT = N->getValueType(0);
5981 MVT::ValueType EVT = MVT::getVectorElementType(VT);
5982 SDOperand PermMask = N->getOperand(2);
5983 int NumElems = (int)PermMask.getNumOperands();
5984 SDNode *Base = NULL;
5985 for (int i = 0; i < NumElems; ++i) {
5986 SDOperand Idx = PermMask.getOperand(i);
5987 if (Idx.getOpcode() == ISD::UNDEF) {
5988 if (!Base) return SDOperand();
5991 getShuffleScalarElt(N, cast<ConstantSDNode>(Idx)->getValue(), DAG);
5992 if (!Arg.Val || !ISD::isNON_EXTLoad(Arg.Val))
5996 else if (!isConsecutiveLoad(Arg.Val, Base,
5997 i, MVT::getSizeInBits(EVT)/8,MFI))
6002 bool isAlign16 = isBaseAlignment16(Base->getOperand(1).Val, MFI, Subtarget);
6003 LoadSDNode *LD = cast<LoadSDNode>(Base);
6005 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6006 LD->getSrcValueOffset(), LD->isVolatile());
6008 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
6009 LD->getSrcValueOffset(), LD->isVolatile(),
6010 LD->getAlignment());
6014 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
6015 static SDOperand PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
6016 const X86Subtarget *Subtarget) {
6017 SDOperand Cond = N->getOperand(0);
6019 // If we have SSE[12] support, try to form min/max nodes.
6020 if (Subtarget->hasSSE2() &&
6021 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
6022 if (Cond.getOpcode() == ISD::SETCC) {
6023 // Get the LHS/RHS of the select.
6024 SDOperand LHS = N->getOperand(1);
6025 SDOperand RHS = N->getOperand(2);
6026 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
6028 unsigned Opcode = 0;
6029 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
6032 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
6035 if (!UnsafeFPMath) break;
6037 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
6039 Opcode = X86ISD::FMIN;
6042 case ISD::SETOGT: // (X > Y) ? X : Y -> max
6045 if (!UnsafeFPMath) break;
6047 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
6049 Opcode = X86ISD::FMAX;
6052 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
6055 case ISD::SETOGT: // (X > Y) ? Y : X -> min
6058 if (!UnsafeFPMath) break;
6060 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
6062 Opcode = X86ISD::FMIN;
6065 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
6068 if (!UnsafeFPMath) break;
6070 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
6072 Opcode = X86ISD::FMAX;
6078 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
6086 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
6087 static SDOperand PerformSTORECombine(StoreSDNode *St, SelectionDAG &DAG,
6088 const X86Subtarget *Subtarget) {
6089 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
6090 // the FP state in cases where an emms may be missing.
6091 // A preferable solution to the general problem is to figure out the right
6092 // places to insert EMMS. This qualifies as a quick hack.
6093 if (MVT::isVector(St->getValue().getValueType()) &&
6094 MVT::getSizeInBits(St->getValue().getValueType()) == 64 &&
6095 isa<LoadSDNode>(St->getValue()) &&
6096 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
6097 St->getChain().hasOneUse() && !St->isVolatile()) {
6098 SDNode* LdVal = St->getValue().Val;
6100 int TokenFactorIndex = -1;
6101 SmallVector<SDOperand, 8> Ops;
6102 SDNode* ChainVal = St->getChain().Val;
6103 // Must be a store of a load. We currently handle two cases: the load
6104 // is a direct child, and it's under an intervening TokenFactor. It is
6105 // possible to dig deeper under nested TokenFactors.
6106 if (ChainVal == LdVal)
6107 Ld = cast<LoadSDNode>(St->getChain());
6108 else if (St->getValue().hasOneUse() &&
6109 ChainVal->getOpcode() == ISD::TokenFactor) {
6110 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
6111 if (ChainVal->getOperand(i).Val == LdVal) {
6112 TokenFactorIndex = i;
6113 Ld = cast<LoadSDNode>(St->getValue());
6115 Ops.push_back(ChainVal->getOperand(i));
6119 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
6120 if (Subtarget->is64Bit()) {
6121 SDOperand NewLd = DAG.getLoad(MVT::i64, Ld->getChain(),
6122 Ld->getBasePtr(), Ld->getSrcValue(),
6123 Ld->getSrcValueOffset(), Ld->isVolatile(),
6124 Ld->getAlignment());
6125 SDOperand NewChain = NewLd.getValue(1);
6126 if (TokenFactorIndex != -1) {
6127 Ops.push_back(NewChain);
6128 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
6131 return DAG.getStore(NewChain, NewLd, St->getBasePtr(),
6132 St->getSrcValue(), St->getSrcValueOffset(),
6133 St->isVolatile(), St->getAlignment());
6136 // Otherwise, lower to two 32-bit copies.
6137 SDOperand LoAddr = Ld->getBasePtr();
6138 SDOperand HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6139 DAG.getConstant(MVT::i32, 4));
6141 SDOperand LoLd = DAG.getLoad(MVT::i32, Ld->getChain(), LoAddr,
6142 Ld->getSrcValue(), Ld->getSrcValueOffset(),
6143 Ld->isVolatile(), Ld->getAlignment());
6144 SDOperand HiLd = DAG.getLoad(MVT::i32, Ld->getChain(), HiAddr,
6145 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
6147 MinAlign(Ld->getAlignment(), 4));
6149 SDOperand NewChain = LoLd.getValue(1);
6150 if (TokenFactorIndex != -1) {
6151 Ops.push_back(LoLd);
6152 Ops.push_back(HiLd);
6153 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
6157 LoAddr = St->getBasePtr();
6158 HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6159 DAG.getConstant(MVT::i32, 4));
6161 SDOperand LoSt = DAG.getStore(NewChain, LoLd, LoAddr,
6162 St->getSrcValue(), St->getSrcValueOffset(),
6163 St->isVolatile(), St->getAlignment());
6164 SDOperand HiSt = DAG.getStore(NewChain, HiLd, HiAddr,
6165 St->getSrcValue(), St->getSrcValueOffset()+4,
6167 MinAlign(St->getAlignment(), 4));
6168 return DAG.getNode(ISD::TokenFactor, MVT::Other, LoSt, HiSt);
6174 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
6175 /// X86ISD::FXOR nodes.
6176 static SDOperand PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
6177 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
6178 // F[X]OR(0.0, x) -> x
6179 // F[X]OR(x, 0.0) -> x
6180 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6181 if (C->getValueAPF().isPosZero())
6182 return N->getOperand(1);
6183 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6184 if (C->getValueAPF().isPosZero())
6185 return N->getOperand(0);
6189 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
6190 static SDOperand PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
6191 // FAND(0.0, x) -> 0.0
6192 // FAND(x, 0.0) -> 0.0
6193 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6194 if (C->getValueAPF().isPosZero())
6195 return N->getOperand(0);
6196 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6197 if (C->getValueAPF().isPosZero())
6198 return N->getOperand(1);
6203 SDOperand X86TargetLowering::PerformDAGCombine(SDNode *N,
6204 DAGCombinerInfo &DCI) const {
6205 SelectionDAG &DAG = DCI.DAG;
6206 switch (N->getOpcode()) {
6208 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, Subtarget);
6209 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
6211 return PerformSTORECombine(cast<StoreSDNode>(N), DAG, Subtarget);
6213 case X86ISD::FOR: return PerformFORCombine(N, DAG);
6214 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
6220 //===----------------------------------------------------------------------===//
6221 // X86 Inline Assembly Support
6222 //===----------------------------------------------------------------------===//
6224 /// getConstraintType - Given a constraint letter, return the type of
6225 /// constraint it is for this target.
6226 X86TargetLowering::ConstraintType
6227 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
6228 if (Constraint.size() == 1) {
6229 switch (Constraint[0]) {
6240 return C_RegisterClass;
6245 return TargetLowering::getConstraintType(Constraint);
6248 /// LowerXConstraint - try to replace an X constraint, which matches anything,
6249 /// with another that has more specific requirements based on the type of the
6250 /// corresponding operand.
6251 void X86TargetLowering::lowerXConstraint(MVT::ValueType ConstraintVT,
6252 std::string& s) const {
6253 if (MVT::isFloatingPoint(ConstraintVT)) {
6254 if (Subtarget->hasSSE2())
6256 else if (Subtarget->hasSSE1())
6261 return TargetLowering::lowerXConstraint(ConstraintVT, s);
6264 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6265 /// vector. If it is invalid, don't add anything to Ops.
6266 void X86TargetLowering::LowerAsmOperandForConstraint(SDOperand Op,
6268 std::vector<SDOperand>&Ops,
6269 SelectionDAG &DAG) {
6270 SDOperand Result(0, 0);
6272 switch (Constraint) {
6275 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6276 if (C->getValue() <= 31) {
6277 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6283 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6284 if (C->getValue() <= 255) {
6285 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6291 // Literal immediates are always ok.
6292 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
6293 Result = DAG.getTargetConstant(CST->getValue(), Op.getValueType());
6297 // If we are in non-pic codegen mode, we allow the address of a global (with
6298 // an optional displacement) to be used with 'i'.
6299 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
6302 // Match either (GA) or (GA+C)
6304 Offset = GA->getOffset();
6305 } else if (Op.getOpcode() == ISD::ADD) {
6306 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6307 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6309 Offset = GA->getOffset()+C->getValue();
6311 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6312 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6314 Offset = GA->getOffset()+C->getValue();
6321 // If addressing this global requires a load (e.g. in PIC mode), we can't
6323 if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
6327 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
6333 // Otherwise, not valid for this mode.
6339 Ops.push_back(Result);
6342 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6345 std::vector<unsigned> X86TargetLowering::
6346 getRegClassForInlineAsmConstraint(const std::string &Constraint,
6347 MVT::ValueType VT) const {
6348 if (Constraint.size() == 1) {
6349 // FIXME: not handling fp-stack yet!
6350 switch (Constraint[0]) { // GCC X86 Constraint Letters
6351 default: break; // Unknown constraint letter
6352 case 'A': // EAX/EDX
6353 if (VT == MVT::i32 || VT == MVT::i64)
6354 return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
6356 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
6359 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
6360 else if (VT == MVT::i16)
6361 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
6362 else if (VT == MVT::i8)
6363 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
6364 else if (VT == MVT::i64)
6365 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
6370 return std::vector<unsigned>();
6373 std::pair<unsigned, const TargetRegisterClass*>
6374 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
6375 MVT::ValueType VT) const {
6376 // First, see if this is a constraint that directly corresponds to an LLVM
6378 if (Constraint.size() == 1) {
6379 // GCC Constraint Letters
6380 switch (Constraint[0]) {
6382 case 'r': // GENERAL_REGS
6383 case 'R': // LEGACY_REGS
6384 case 'l': // INDEX_REGS
6385 if (VT == MVT::i64 && Subtarget->is64Bit())
6386 return std::make_pair(0U, X86::GR64RegisterClass);
6388 return std::make_pair(0U, X86::GR32RegisterClass);
6389 else if (VT == MVT::i16)
6390 return std::make_pair(0U, X86::GR16RegisterClass);
6391 else if (VT == MVT::i8)
6392 return std::make_pair(0U, X86::GR8RegisterClass);
6394 case 'f': // FP Stack registers.
6395 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
6396 // value to the correct fpstack register class.
6397 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
6398 return std::make_pair(0U, X86::RFP32RegisterClass);
6399 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
6400 return std::make_pair(0U, X86::RFP64RegisterClass);
6401 return std::make_pair(0U, X86::RFP80RegisterClass);
6402 case 'y': // MMX_REGS if MMX allowed.
6403 if (!Subtarget->hasMMX()) break;
6404 return std::make_pair(0U, X86::VR64RegisterClass);
6406 case 'Y': // SSE_REGS if SSE2 allowed
6407 if (!Subtarget->hasSSE2()) break;
6409 case 'x': // SSE_REGS if SSE1 allowed
6410 if (!Subtarget->hasSSE1()) break;
6414 // Scalar SSE types.
6417 return std::make_pair(0U, X86::FR32RegisterClass);
6420 return std::make_pair(0U, X86::FR64RegisterClass);
6428 return std::make_pair(0U, X86::VR128RegisterClass);
6434 // Use the default implementation in TargetLowering to convert the register
6435 // constraint into a member of a register class.
6436 std::pair<unsigned, const TargetRegisterClass*> Res;
6437 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
6439 // Not found as a standard register?
6440 if (Res.second == 0) {
6441 // GCC calls "st(0)" just plain "st".
6442 if (StringsEqualNoCase("{st}", Constraint)) {
6443 Res.first = X86::ST0;
6444 Res.second = X86::RFP80RegisterClass;
6450 // Otherwise, check to see if this is a register class of the wrong value
6451 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
6452 // turn into {ax},{dx}.
6453 if (Res.second->hasType(VT))
6454 return Res; // Correct type already, nothing to do.
6456 // All of the single-register GCC register classes map their values onto
6457 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
6458 // really want an 8-bit or 32-bit register, map to the appropriate register
6459 // class and return the appropriate register.
6460 if (Res.second != X86::GR16RegisterClass)
6463 if (VT == MVT::i8) {
6464 unsigned DestReg = 0;
6465 switch (Res.first) {
6467 case X86::AX: DestReg = X86::AL; break;
6468 case X86::DX: DestReg = X86::DL; break;
6469 case X86::CX: DestReg = X86::CL; break;
6470 case X86::BX: DestReg = X86::BL; break;
6473 Res.first = DestReg;
6474 Res.second = Res.second = X86::GR8RegisterClass;
6476 } else if (VT == MVT::i32) {
6477 unsigned DestReg = 0;
6478 switch (Res.first) {
6480 case X86::AX: DestReg = X86::EAX; break;
6481 case X86::DX: DestReg = X86::EDX; break;
6482 case X86::CX: DestReg = X86::ECX; break;
6483 case X86::BX: DestReg = X86::EBX; break;
6484 case X86::SI: DestReg = X86::ESI; break;
6485 case X86::DI: DestReg = X86::EDI; break;
6486 case X86::BP: DestReg = X86::EBP; break;
6487 case X86::SP: DestReg = X86::ESP; break;
6490 Res.first = DestReg;
6491 Res.second = Res.second = X86::GR32RegisterClass;
6493 } else if (VT == MVT::i64) {
6494 unsigned DestReg = 0;
6495 switch (Res.first) {
6497 case X86::AX: DestReg = X86::RAX; break;
6498 case X86::DX: DestReg = X86::RDX; break;
6499 case X86::CX: DestReg = X86::RCX; break;
6500 case X86::BX: DestReg = X86::RBX; break;
6501 case X86::SI: DestReg = X86::RSI; break;
6502 case X86::DI: DestReg = X86::RDI; break;
6503 case X86::BP: DestReg = X86::RBP; break;
6504 case X86::SP: DestReg = X86::RSP; break;
6507 Res.first = DestReg;
6508 Res.second = Res.second = X86::GR64RegisterClass;