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 // Forward declarations.
45 static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG);
47 X86TargetLowering::X86TargetLowering(TargetMachine &TM)
48 : TargetLowering(TM) {
49 Subtarget = &TM.getSubtarget<X86Subtarget>();
50 X86ScalarSSEf64 = Subtarget->hasSSE2();
51 X86ScalarSSEf32 = Subtarget->hasSSE1();
52 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
56 RegInfo = TM.getRegisterInfo();
58 // Set up the TargetLowering object.
60 // X86 is weird, it always uses i8 for shift amounts and setcc results.
61 setShiftAmountType(MVT::i8);
62 setSetCCResultContents(ZeroOrOneSetCCResult);
63 setSchedulingPreference(SchedulingForRegPressure);
64 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
65 setStackPointerRegisterToSaveRestore(X86StackPtr);
67 if (Subtarget->isTargetDarwin()) {
68 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
69 setUseUnderscoreSetJmp(false);
70 setUseUnderscoreLongJmp(false);
71 } else if (Subtarget->isTargetMingw()) {
72 // MS runtime is weird: it exports _setjmp, but longjmp!
73 setUseUnderscoreSetJmp(true);
74 setUseUnderscoreLongJmp(false);
76 setUseUnderscoreSetJmp(true);
77 setUseUnderscoreLongJmp(true);
80 // Set up the register classes.
81 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
82 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
83 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
84 if (Subtarget->is64Bit())
85 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
87 setLoadXAction(ISD::SEXTLOAD, MVT::i1, Promote);
89 // We don't accept any truncstore of integer registers.
90 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
91 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
92 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
93 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
94 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
95 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
97 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
99 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
100 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
101 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
103 if (Subtarget->is64Bit()) {
104 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
105 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
108 // If SSE i64 SINT_TO_FP is not available, expand i32 UINT_TO_FP.
109 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Expand);
111 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
114 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
116 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
117 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
118 // SSE has no i16 to fp conversion, only i32
119 if (X86ScalarSSEf32) {
120 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
121 // f32 and f64 cases are Legal, f80 case is not
122 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
124 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
125 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
128 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
129 // are Legal, f80 is custom lowered.
130 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
131 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
133 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
135 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
136 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
138 if (X86ScalarSSEf32) {
139 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
140 // f32 and f64 cases are Legal, f80 case is not
141 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
143 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
144 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
147 // Handle FP_TO_UINT by promoting the destination to a larger signed
149 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
150 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
151 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
153 if (Subtarget->is64Bit()) {
154 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
155 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
157 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
158 // Expand FP_TO_UINT into a select.
159 // FIXME: We would like to use a Custom expander here eventually to do
160 // the optimal thing for SSE vs. the default expansion in the legalizer.
161 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
163 // With SSE3 we can use fisttpll to convert to a signed i64.
164 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
167 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
168 if (!X86ScalarSSEf64) {
169 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
170 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
173 // Scalar integer divide and remainder are lowered to use operations that
174 // produce two results, to match the available instructions. This exposes
175 // the two-result form to trivial CSE, which is able to combine x/y and x%y
176 // into a single instruction.
178 // Scalar integer multiply-high is also lowered to use two-result
179 // operations, to match the available instructions. However, plain multiply
180 // (low) operations are left as Legal, as there are single-result
181 // instructions for this in x86. Using the two-result multiply instructions
182 // when both high and low results are needed must be arranged by dagcombine.
183 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
184 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
185 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
186 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
187 setOperationAction(ISD::SREM , MVT::i8 , Expand);
188 setOperationAction(ISD::UREM , MVT::i8 , Expand);
189 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
190 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
191 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
192 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
193 setOperationAction(ISD::SREM , MVT::i16 , Expand);
194 setOperationAction(ISD::UREM , MVT::i16 , Expand);
195 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
196 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
197 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
198 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
199 setOperationAction(ISD::SREM , MVT::i32 , Expand);
200 setOperationAction(ISD::UREM , MVT::i32 , Expand);
201 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
202 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
203 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
204 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
205 setOperationAction(ISD::SREM , MVT::i64 , Expand);
206 setOperationAction(ISD::UREM , MVT::i64 , Expand);
208 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
209 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
210 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
211 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
212 if (Subtarget->is64Bit())
213 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
214 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
215 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
216 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
217 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
218 setOperationAction(ISD::FREM , MVT::f32 , Expand);
219 setOperationAction(ISD::FREM , MVT::f64 , Expand);
220 setOperationAction(ISD::FREM , MVT::f80 , Expand);
221 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
223 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
224 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
225 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
226 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
227 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
228 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
229 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
230 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
231 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
232 if (Subtarget->is64Bit()) {
233 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
234 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
235 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
238 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
239 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
241 // These should be promoted to a larger select which is supported.
242 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
243 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
244 // X86 wants to expand cmov itself.
245 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
246 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
247 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
248 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
249 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
250 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
251 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
252 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
253 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
254 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
255 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
256 if (Subtarget->is64Bit()) {
257 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
258 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
260 // X86 ret instruction may pop stack.
261 setOperationAction(ISD::RET , MVT::Other, Custom);
262 if (!Subtarget->is64Bit())
263 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
266 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
267 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
268 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
269 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
270 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
271 if (Subtarget->is64Bit()) {
272 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
273 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
274 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
275 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
277 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
278 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
279 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
280 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
281 if (Subtarget->is64Bit()) {
282 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
283 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
284 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
287 if (Subtarget->hasSSE1())
288 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
290 if (!Subtarget->hasSSE2())
291 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
293 setOperationAction(ISD::ATOMIC_LCS , MVT::i8, Custom);
294 setOperationAction(ISD::ATOMIC_LCS , MVT::i16, Custom);
295 setOperationAction(ISD::ATOMIC_LCS , MVT::i32, Custom);
296 setOperationAction(ISD::ATOMIC_LCS , MVT::i64, Custom);
298 // Use the default ISD::LOCATION, ISD::DECLARE expansion.
299 setOperationAction(ISD::LOCATION, MVT::Other, Expand);
300 // FIXME - use subtarget debug flags
301 if (!Subtarget->isTargetDarwin() &&
302 !Subtarget->isTargetELF() &&
303 !Subtarget->isTargetCygMing())
304 setOperationAction(ISD::LABEL, MVT::Other, Expand);
306 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
307 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
308 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
309 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
310 if (Subtarget->is64Bit()) {
312 setExceptionPointerRegister(X86::RAX);
313 setExceptionSelectorRegister(X86::RDX);
315 setExceptionPointerRegister(X86::EAX);
316 setExceptionSelectorRegister(X86::EDX);
318 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
320 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
322 setOperationAction(ISD::TRAP, MVT::Other, Legal);
324 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
325 setOperationAction(ISD::VASTART , MVT::Other, Custom);
326 setOperationAction(ISD::VAARG , MVT::Other, Expand);
327 setOperationAction(ISD::VAEND , MVT::Other, Expand);
328 if (Subtarget->is64Bit())
329 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
331 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
333 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
334 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
335 if (Subtarget->is64Bit())
336 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
337 if (Subtarget->isTargetCygMing())
338 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
340 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
342 if (X86ScalarSSEf64) {
343 // f32 and f64 use SSE.
344 // Set up the FP register classes.
345 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
346 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
348 // Use ANDPD to simulate FABS.
349 setOperationAction(ISD::FABS , MVT::f64, Custom);
350 setOperationAction(ISD::FABS , MVT::f32, Custom);
352 // Use XORP to simulate FNEG.
353 setOperationAction(ISD::FNEG , MVT::f64, Custom);
354 setOperationAction(ISD::FNEG , MVT::f32, Custom);
356 // Use ANDPD and ORPD to simulate FCOPYSIGN.
357 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
358 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
360 // We don't support sin/cos/fmod
361 setOperationAction(ISD::FSIN , MVT::f64, Expand);
362 setOperationAction(ISD::FCOS , MVT::f64, Expand);
363 setOperationAction(ISD::FSIN , MVT::f32, Expand);
364 setOperationAction(ISD::FCOS , MVT::f32, Expand);
366 // Expand FP immediates into loads from the stack, except for the special
368 addLegalFPImmediate(APFloat(+0.0)); // xorpd
369 addLegalFPImmediate(APFloat(+0.0f)); // xorps
371 // Floating truncations from f80 and extensions to f80 go through memory.
372 // If optimizing, we lie about this though and handle it in
373 // InstructionSelectPreprocess so that dagcombine2 can hack on these.
375 setConvertAction(MVT::f32, MVT::f80, Expand);
376 setConvertAction(MVT::f64, MVT::f80, Expand);
377 setConvertAction(MVT::f80, MVT::f32, Expand);
378 setConvertAction(MVT::f80, MVT::f64, Expand);
380 } else if (X86ScalarSSEf32) {
381 // Use SSE for f32, x87 for f64.
382 // Set up the FP register classes.
383 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
384 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
386 // Use ANDPS to simulate FABS.
387 setOperationAction(ISD::FABS , MVT::f32, Custom);
389 // Use XORP to simulate FNEG.
390 setOperationAction(ISD::FNEG , MVT::f32, Custom);
392 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
394 // Use ANDPS and ORPS to simulate FCOPYSIGN.
395 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
396 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
398 // We don't support sin/cos/fmod
399 setOperationAction(ISD::FSIN , MVT::f32, Expand);
400 setOperationAction(ISD::FCOS , MVT::f32, Expand);
402 // Special cases we handle for FP constants.
403 addLegalFPImmediate(APFloat(+0.0f)); // xorps
404 addLegalFPImmediate(APFloat(+0.0)); // FLD0
405 addLegalFPImmediate(APFloat(+1.0)); // FLD1
406 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
407 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
409 // SSE <-> X87 conversions go through memory. If optimizing, we lie about
410 // this though and handle it in InstructionSelectPreprocess so that
411 // dagcombine2 can hack on these.
413 setConvertAction(MVT::f32, MVT::f64, Expand);
414 setConvertAction(MVT::f32, MVT::f80, Expand);
415 setConvertAction(MVT::f80, MVT::f32, Expand);
416 setConvertAction(MVT::f64, MVT::f32, Expand);
417 // And x87->x87 truncations also.
418 setConvertAction(MVT::f80, MVT::f64, Expand);
422 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
423 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
426 // f32 and f64 in x87.
427 // Set up the FP register classes.
428 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
429 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
431 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
432 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
433 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
434 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
436 // Floating truncations go through memory. If optimizing, we lie about
437 // this though and handle it in InstructionSelectPreprocess so that
438 // dagcombine2 can hack on these.
440 setConvertAction(MVT::f80, MVT::f32, Expand);
441 setConvertAction(MVT::f64, MVT::f32, Expand);
442 setConvertAction(MVT::f80, MVT::f64, Expand);
446 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
447 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
449 addLegalFPImmediate(APFloat(+0.0)); // FLD0
450 addLegalFPImmediate(APFloat(+1.0)); // FLD1
451 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
452 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
453 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
454 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
455 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
456 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
459 // Long double always uses X87.
460 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
461 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
462 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
464 APFloat TmpFlt(+0.0);
465 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
466 addLegalFPImmediate(TmpFlt); // FLD0
468 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
469 APFloat TmpFlt2(+1.0);
470 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
471 addLegalFPImmediate(TmpFlt2); // FLD1
472 TmpFlt2.changeSign();
473 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
477 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
478 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
481 // Always use a library call for pow.
482 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
483 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
484 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
486 // First set operation action for all vector types to expand. Then we
487 // will selectively turn on ones that can be effectively codegen'd.
488 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
489 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
490 setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
491 setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
492 setOperationAction(ISD::FADD, (MVT::ValueType)VT, Expand);
493 setOperationAction(ISD::FNEG, (MVT::ValueType)VT, Expand);
494 setOperationAction(ISD::FSUB, (MVT::ValueType)VT, Expand);
495 setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
496 setOperationAction(ISD::FMUL, (MVT::ValueType)VT, Expand);
497 setOperationAction(ISD::SDIV, (MVT::ValueType)VT, Expand);
498 setOperationAction(ISD::UDIV, (MVT::ValueType)VT, Expand);
499 setOperationAction(ISD::FDIV, (MVT::ValueType)VT, Expand);
500 setOperationAction(ISD::SREM, (MVT::ValueType)VT, Expand);
501 setOperationAction(ISD::UREM, (MVT::ValueType)VT, Expand);
502 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
503 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Expand);
504 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
505 setOperationAction(ISD::INSERT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
506 setOperationAction(ISD::FABS, (MVT::ValueType)VT, Expand);
507 setOperationAction(ISD::FSIN, (MVT::ValueType)VT, Expand);
508 setOperationAction(ISD::FCOS, (MVT::ValueType)VT, Expand);
509 setOperationAction(ISD::FREM, (MVT::ValueType)VT, Expand);
510 setOperationAction(ISD::FPOWI, (MVT::ValueType)VT, Expand);
511 setOperationAction(ISD::FSQRT, (MVT::ValueType)VT, Expand);
512 setOperationAction(ISD::FCOPYSIGN, (MVT::ValueType)VT, Expand);
513 setOperationAction(ISD::SMUL_LOHI, (MVT::ValueType)VT, Expand);
514 setOperationAction(ISD::UMUL_LOHI, (MVT::ValueType)VT, Expand);
515 setOperationAction(ISD::SDIVREM, (MVT::ValueType)VT, Expand);
516 setOperationAction(ISD::UDIVREM, (MVT::ValueType)VT, Expand);
517 setOperationAction(ISD::FPOW, (MVT::ValueType)VT, Expand);
518 setOperationAction(ISD::CTPOP, (MVT::ValueType)VT, Expand);
519 setOperationAction(ISD::CTTZ, (MVT::ValueType)VT, Expand);
520 setOperationAction(ISD::CTLZ, (MVT::ValueType)VT, Expand);
521 setOperationAction(ISD::SHL, (MVT::ValueType)VT, Expand);
522 setOperationAction(ISD::SRA, (MVT::ValueType)VT, Expand);
523 setOperationAction(ISD::SRL, (MVT::ValueType)VT, Expand);
524 setOperationAction(ISD::ROTL, (MVT::ValueType)VT, Expand);
525 setOperationAction(ISD::ROTR, (MVT::ValueType)VT, Expand);
526 setOperationAction(ISD::BSWAP, (MVT::ValueType)VT, Expand);
529 if (Subtarget->hasMMX()) {
530 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
531 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
532 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
533 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
535 // FIXME: add MMX packed arithmetics
537 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
538 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
539 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
540 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
542 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
543 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
544 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
545 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
547 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
548 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
550 setOperationAction(ISD::AND, MVT::v8i8, Promote);
551 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
552 setOperationAction(ISD::AND, MVT::v4i16, Promote);
553 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
554 setOperationAction(ISD::AND, MVT::v2i32, Promote);
555 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
556 setOperationAction(ISD::AND, MVT::v1i64, Legal);
558 setOperationAction(ISD::OR, MVT::v8i8, Promote);
559 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
560 setOperationAction(ISD::OR, MVT::v4i16, Promote);
561 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
562 setOperationAction(ISD::OR, MVT::v2i32, Promote);
563 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
564 setOperationAction(ISD::OR, MVT::v1i64, Legal);
566 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
567 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
568 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
569 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
570 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
571 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
572 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
574 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
575 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
576 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
577 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
578 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
579 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
580 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
582 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
583 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
584 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
585 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
587 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
588 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
589 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
590 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
592 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
593 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
594 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
597 if (Subtarget->hasSSE1()) {
598 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
600 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
601 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
602 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
603 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
604 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
605 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
606 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
607 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
608 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
609 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
610 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
613 if (Subtarget->hasSSE2()) {
614 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
615 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
616 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
617 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
618 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
620 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
621 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
622 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
623 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
624 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
625 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
626 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
627 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
628 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
629 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
630 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
631 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
632 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
633 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
634 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
636 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
637 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
638 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
639 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
640 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
642 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
643 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
644 // Do not attempt to custom lower non-power-of-2 vectors
645 if (!isPowerOf2_32(MVT::getVectorNumElements(VT)))
647 setOperationAction(ISD::BUILD_VECTOR, (MVT::ValueType)VT, Custom);
648 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Custom);
649 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Custom);
651 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
652 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
653 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
654 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
655 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
656 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
657 if (Subtarget->is64Bit()) {
658 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
659 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
662 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
663 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
664 setOperationAction(ISD::AND, (MVT::ValueType)VT, Promote);
665 AddPromotedToType (ISD::AND, (MVT::ValueType)VT, MVT::v2i64);
666 setOperationAction(ISD::OR, (MVT::ValueType)VT, Promote);
667 AddPromotedToType (ISD::OR, (MVT::ValueType)VT, MVT::v2i64);
668 setOperationAction(ISD::XOR, (MVT::ValueType)VT, Promote);
669 AddPromotedToType (ISD::XOR, (MVT::ValueType)VT, MVT::v2i64);
670 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Promote);
671 AddPromotedToType (ISD::LOAD, (MVT::ValueType)VT, MVT::v2i64);
672 setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
673 AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v2i64);
676 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
678 // Custom lower v2i64 and v2f64 selects.
679 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
680 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
681 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
682 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
685 if (Subtarget->hasSSE41()) {
686 // FIXME: Do we need to handle scalar-to-vector here?
687 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
689 // i8 and i16 vectors are custom , because the source register and source
690 // source memory operand types are not the same width. f32 vectors are
691 // custom since the immediate controlling the insert encodes additional
693 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
694 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
695 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Legal);
696 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
698 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
699 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
700 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
701 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
703 if (Subtarget->is64Bit()) {
704 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
705 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
709 // We want to custom lower some of our intrinsics.
710 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
712 // We have target-specific dag combine patterns for the following nodes:
713 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
714 setTargetDAGCombine(ISD::SELECT);
715 setTargetDAGCombine(ISD::STORE);
717 computeRegisterProperties();
719 // FIXME: These should be based on subtarget info. Plus, the values should
720 // be smaller when we are in optimizing for size mode.
721 maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
722 maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
723 maxStoresPerMemmove = 16; // For %llvm.memmove -> sequence of stores
724 allowUnalignedMemoryAccesses = true; // x86 supports it!
725 setPrefLoopAlignment(16);
730 X86TargetLowering::getSetCCResultType(const SDOperand &) const {
735 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
736 /// the desired ByVal argument alignment.
737 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
740 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
741 if (VTy->getBitWidth() == 128)
743 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
744 unsigned EltAlign = 0;
745 getMaxByValAlign(ATy->getElementType(), EltAlign);
746 if (EltAlign > MaxAlign)
748 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
749 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
750 unsigned EltAlign = 0;
751 getMaxByValAlign(STy->getElementType(i), EltAlign);
752 if (EltAlign > MaxAlign)
761 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
762 /// function arguments in the caller parameter area. For X86, aggregates
763 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
764 /// are at 4-byte boundaries.
765 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
766 if (Subtarget->is64Bit())
767 return getTargetData()->getABITypeAlignment(Ty);
769 if (Subtarget->hasSSE1())
770 getMaxByValAlign(Ty, Align);
774 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
776 SDOperand X86TargetLowering::getPICJumpTableRelocBase(SDOperand Table,
777 SelectionDAG &DAG) const {
778 if (usesGlobalOffsetTable())
779 return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
780 if (!Subtarget->isPICStyleRIPRel())
781 return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
785 //===----------------------------------------------------------------------===//
786 // Return Value Calling Convention Implementation
787 //===----------------------------------------------------------------------===//
789 #include "X86GenCallingConv.inc"
791 /// LowerRET - Lower an ISD::RET node.
792 SDOperand X86TargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG) {
793 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
795 SmallVector<CCValAssign, 16> RVLocs;
796 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
797 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
798 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
799 CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
801 // If this is the first return lowered for this function, add the regs to the
802 // liveout set for the function.
803 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
804 for (unsigned i = 0; i != RVLocs.size(); ++i)
805 if (RVLocs[i].isRegLoc())
806 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
808 SDOperand Chain = Op.getOperand(0);
810 // Handle tail call return.
811 Chain = GetPossiblePreceedingTailCall(Chain, X86ISD::TAILCALL);
812 if (Chain.getOpcode() == X86ISD::TAILCALL) {
813 SDOperand TailCall = Chain;
814 SDOperand TargetAddress = TailCall.getOperand(1);
815 SDOperand StackAdjustment = TailCall.getOperand(2);
816 assert(((TargetAddress.getOpcode() == ISD::Register &&
817 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::ECX ||
818 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
819 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
820 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
821 "Expecting an global address, external symbol, or register");
822 assert(StackAdjustment.getOpcode() == ISD::Constant &&
823 "Expecting a const value");
825 SmallVector<SDOperand,8> Operands;
826 Operands.push_back(Chain.getOperand(0));
827 Operands.push_back(TargetAddress);
828 Operands.push_back(StackAdjustment);
829 // Copy registers used by the call. Last operand is a flag so it is not
831 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
832 Operands.push_back(Chain.getOperand(i));
834 return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0],
841 SmallVector<SDOperand, 6> RetOps;
842 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
843 // Operand #1 = Bytes To Pop
844 RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
846 // Copy the result values into the output registers.
847 for (unsigned i = 0; i != RVLocs.size(); ++i) {
848 CCValAssign &VA = RVLocs[i];
849 assert(VA.isRegLoc() && "Can only return in registers!");
850 SDOperand ValToCopy = Op.getOperand(i*2+1);
852 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
853 // the RET instruction and handled by the FP Stackifier.
854 if (RVLocs[i].getLocReg() == X86::ST0 ||
855 RVLocs[i].getLocReg() == X86::ST1) {
856 // If this is a copy from an xmm register to ST(0), use an FPExtend to
857 // change the value to the FP stack register class.
858 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT()))
859 ValToCopy = DAG.getNode(ISD::FP_EXTEND, MVT::f80, ValToCopy);
860 RetOps.push_back(ValToCopy);
861 // Don't emit a copytoreg.
865 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), ValToCopy, Flag);
866 Flag = Chain.getValue(1);
869 // The x86-64 ABI for returning structs by value requires that we copy
870 // the sret argument into %rax for the return. We saved the argument into
871 // a virtual register in the entry block, so now we copy the value out
873 if (Subtarget->is64Bit() &&
874 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
875 MachineFunction &MF = DAG.getMachineFunction();
876 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
877 unsigned Reg = FuncInfo->getSRetReturnReg();
879 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
880 FuncInfo->setSRetReturnReg(Reg);
882 SDOperand Val = DAG.getCopyFromReg(Chain, Reg, getPointerTy());
884 Chain = DAG.getCopyToReg(Chain, X86::RAX, Val, Flag);
885 Flag = Chain.getValue(1);
888 RetOps[0] = Chain; // Update chain.
890 // Add the flag if we have it.
892 RetOps.push_back(Flag);
894 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, &RetOps[0], RetOps.size());
898 /// LowerCallResult - Lower the result values of an ISD::CALL into the
899 /// appropriate copies out of appropriate physical registers. This assumes that
900 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
901 /// being lowered. The returns a SDNode with the same number of values as the
903 SDNode *X86TargetLowering::
904 LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall,
905 unsigned CallingConv, SelectionDAG &DAG) {
907 // Assign locations to each value returned by this call.
908 SmallVector<CCValAssign, 16> RVLocs;
909 bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
910 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
911 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
913 SmallVector<SDOperand, 8> ResultVals;
915 // Copy all of the result registers out of their specified physreg.
916 for (unsigned i = 0; i != RVLocs.size(); ++i) {
917 MVT::ValueType CopyVT = RVLocs[i].getValVT();
919 // If this is a call to a function that returns an fp value on the floating
920 // point stack, but where we prefer to use the value in xmm registers, copy
921 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
922 if (RVLocs[i].getLocReg() == X86::ST0 &&
923 isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
927 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
928 CopyVT, InFlag).getValue(1);
929 SDOperand Val = Chain.getValue(0);
930 InFlag = Chain.getValue(2);
932 if (CopyVT != RVLocs[i].getValVT()) {
933 // Round the F80 the right size, which also moves to the appropriate xmm
935 Val = DAG.getNode(ISD::FP_ROUND, RVLocs[i].getValVT(), Val,
936 // This truncation won't change the value.
937 DAG.getIntPtrConstant(1));
940 ResultVals.push_back(Val);
943 // Merge everything together with a MERGE_VALUES node.
944 ResultVals.push_back(Chain);
945 return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
946 &ResultVals[0], ResultVals.size()).Val;
950 //===----------------------------------------------------------------------===//
951 // C & StdCall & Fast Calling Convention implementation
952 //===----------------------------------------------------------------------===//
953 // StdCall calling convention seems to be standard for many Windows' API
954 // routines and around. It differs from C calling convention just a little:
955 // callee should clean up the stack, not caller. Symbols should be also
956 // decorated in some fancy way :) It doesn't support any vector arguments.
957 // For info on fast calling convention see Fast Calling Convention (tail call)
958 // implementation LowerX86_32FastCCCallTo.
960 /// AddLiveIn - This helper function adds the specified physical register to the
961 /// MachineFunction as a live in value. It also creates a corresponding virtual
963 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
964 const TargetRegisterClass *RC) {
965 assert(RC->contains(PReg) && "Not the correct regclass!");
966 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
967 MF.getRegInfo().addLiveIn(PReg, VReg);
971 /// CallIsStructReturn - Determines whether a CALL node uses struct return
973 static bool CallIsStructReturn(SDOperand Op) {
974 unsigned NumOps = (Op.getNumOperands() - 5) / 2;
978 return cast<ARG_FLAGSSDNode>(Op.getOperand(6))->getArgFlags().isSRet();
981 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
982 /// return semantics.
983 static bool ArgsAreStructReturn(SDOperand Op) {
984 unsigned NumArgs = Op.Val->getNumValues() - 1;
988 return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
991 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
992 /// the callee to pop its own arguments. Callee pop is necessary to support tail
994 bool X86TargetLowering::IsCalleePop(SDOperand Op) {
995 bool IsVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
999 switch (cast<ConstantSDNode>(Op.getOperand(1))->getValue()) {
1002 case CallingConv::X86_StdCall:
1003 return !Subtarget->is64Bit();
1004 case CallingConv::X86_FastCall:
1005 return !Subtarget->is64Bit();
1006 case CallingConv::Fast:
1007 return PerformTailCallOpt;
1011 /// CCAssignFnForNode - Selects the correct CCAssignFn for a CALL or
1012 /// FORMAL_ARGUMENTS node.
1013 CCAssignFn *X86TargetLowering::CCAssignFnForNode(SDOperand Op) const {
1014 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1016 if (Subtarget->is64Bit()) {
1017 if (Subtarget->isTargetWin64())
1018 return CC_X86_Win64_C;
1020 if (CC == CallingConv::Fast && PerformTailCallOpt)
1021 return CC_X86_64_TailCall;
1027 if (CC == CallingConv::X86_FastCall)
1028 return CC_X86_32_FastCall;
1029 else if (CC == CallingConv::Fast && PerformTailCallOpt)
1030 return CC_X86_32_TailCall;
1035 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1036 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1038 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDOperand Op) {
1039 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1040 if (CC == CallingConv::X86_FastCall)
1042 else if (CC == CallingConv::X86_StdCall)
1048 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1049 /// in a register before calling.
1050 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1051 return !IsTailCall && !Is64Bit &&
1052 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1053 Subtarget->isPICStyleGOT();
1056 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1057 /// address to be loaded in a register.
1059 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1060 return !Is64Bit && IsTailCall &&
1061 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1062 Subtarget->isPICStyleGOT();
1065 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1066 /// by "Src" to address "Dst" with size and alignment information specified by
1067 /// the specific parameter attribute. The copy will be passed as a byval
1068 /// function parameter.
1070 CreateCopyOfByValArgument(SDOperand Src, SDOperand Dst, SDOperand Chain,
1071 ISD::ArgFlagsTy Flags, SelectionDAG &DAG) {
1072 SDOperand SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1073 return DAG.getMemcpy(Chain, Dst, Src, SizeNode, Flags.getByValAlign(),
1074 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1077 SDOperand X86TargetLowering::LowerMemArgument(SDOperand Op, SelectionDAG &DAG,
1078 const CCValAssign &VA,
1079 MachineFrameInfo *MFI,
1081 SDOperand Root, unsigned i) {
1082 // Create the nodes corresponding to a load from this parameter slot.
1083 ISD::ArgFlagsTy Flags =
1084 cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1085 bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1086 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1088 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1089 // changed with more analysis.
1090 // In case of tail call optimization mark all arguments mutable. Since they
1091 // could be overwritten by lowering of arguments in case of a tail call.
1092 int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
1093 VA.getLocMemOffset(), isImmutable);
1094 SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
1095 if (Flags.isByVal())
1097 return DAG.getLoad(VA.getValVT(), Root, FIN,
1098 PseudoSourceValue::getFixedStack(), FI);
1102 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
1103 MachineFunction &MF = DAG.getMachineFunction();
1104 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1106 const Function* Fn = MF.getFunction();
1107 if (Fn->hasExternalLinkage() &&
1108 Subtarget->isTargetCygMing() &&
1109 Fn->getName() == "main")
1110 FuncInfo->setForceFramePointer(true);
1112 // Decorate the function name.
1113 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1115 MachineFrameInfo *MFI = MF.getFrameInfo();
1116 SDOperand Root = Op.getOperand(0);
1117 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1118 unsigned CC = MF.getFunction()->getCallingConv();
1119 bool Is64Bit = Subtarget->is64Bit();
1120 bool IsWin64 = Subtarget->isTargetWin64();
1122 assert(!(isVarArg && CC == CallingConv::Fast) &&
1123 "Var args not supported with calling convention fastcc");
1125 // Assign locations to all of the incoming arguments.
1126 SmallVector<CCValAssign, 16> ArgLocs;
1127 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1128 CCInfo.AnalyzeFormalArguments(Op.Val, CCAssignFnForNode(Op));
1130 SmallVector<SDOperand, 8> ArgValues;
1131 unsigned LastVal = ~0U;
1132 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1133 CCValAssign &VA = ArgLocs[i];
1134 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1136 assert(VA.getValNo() != LastVal &&
1137 "Don't support value assigned to multiple locs yet");
1138 LastVal = VA.getValNo();
1140 if (VA.isRegLoc()) {
1141 MVT::ValueType RegVT = VA.getLocVT();
1142 TargetRegisterClass *RC;
1143 if (RegVT == MVT::i32)
1144 RC = X86::GR32RegisterClass;
1145 else if (Is64Bit && RegVT == MVT::i64)
1146 RC = X86::GR64RegisterClass;
1147 else if (RegVT == MVT::f32)
1148 RC = X86::FR32RegisterClass;
1149 else if (RegVT == MVT::f64)
1150 RC = X86::FR64RegisterClass;
1151 else if (MVT::isVector(RegVT) && MVT::getSizeInBits(RegVT) == 128)
1152 RC = X86::VR128RegisterClass;
1153 else if (MVT::isVector(RegVT)) {
1154 assert(MVT::getSizeInBits(RegVT) == 64);
1156 RC = X86::VR64RegisterClass; // MMX values are passed in MMXs.
1158 // Darwin calling convention passes MMX values in either GPRs or
1159 // XMMs in x86-64. Other targets pass them in memory.
1160 if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1161 RC = X86::VR128RegisterClass; // MMX values are passed in XMMs.
1164 RC = X86::GR64RegisterClass; // v1i64 values are passed in GPRs.
1169 assert(0 && "Unknown argument type!");
1172 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1173 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1175 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1176 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1178 if (VA.getLocInfo() == CCValAssign::SExt)
1179 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1180 DAG.getValueType(VA.getValVT()));
1181 else if (VA.getLocInfo() == CCValAssign::ZExt)
1182 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1183 DAG.getValueType(VA.getValVT()));
1185 if (VA.getLocInfo() != CCValAssign::Full)
1186 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1188 // Handle MMX values passed in GPRs.
1189 if (Is64Bit && RegVT != VA.getLocVT()) {
1190 if (MVT::getSizeInBits(RegVT) == 64 && RC == X86::GR64RegisterClass)
1191 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1192 else if (RC == X86::VR128RegisterClass) {
1193 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i64, ArgValue,
1194 DAG.getConstant(0, MVT::i64));
1195 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1199 ArgValues.push_back(ArgValue);
1201 assert(VA.isMemLoc());
1202 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1206 // The x86-64 ABI for returning structs by value requires that we copy
1207 // the sret argument into %rax for the return. Save the argument into
1208 // a virtual register so that we can access it from the return points.
1209 if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1210 MachineFunction &MF = DAG.getMachineFunction();
1211 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1212 unsigned Reg = FuncInfo->getSRetReturnReg();
1214 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1215 FuncInfo->setSRetReturnReg(Reg);
1217 SDOperand Copy = DAG.getCopyToReg(DAG.getEntryNode(), Reg, ArgValues[0]);
1218 Root = DAG.getNode(ISD::TokenFactor, MVT::Other, Copy, Root);
1221 unsigned StackSize = CCInfo.getNextStackOffset();
1222 // align stack specially for tail calls
1223 if (CC == CallingConv::Fast)
1224 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1226 // If the function takes variable number of arguments, make a frame index for
1227 // the start of the first vararg value... for expansion of llvm.va_start.
1229 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1230 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1233 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1235 // FIXME: We should really autogenerate these arrays
1236 static const unsigned GPR64ArgRegsWin64[] = {
1237 X86::RCX, X86::RDX, X86::R8, X86::R9
1239 static const unsigned XMMArgRegsWin64[] = {
1240 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1242 static const unsigned GPR64ArgRegs64Bit[] = {
1243 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1245 static const unsigned XMMArgRegs64Bit[] = {
1246 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1247 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1249 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1252 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1253 GPR64ArgRegs = GPR64ArgRegsWin64;
1254 XMMArgRegs = XMMArgRegsWin64;
1256 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1257 GPR64ArgRegs = GPR64ArgRegs64Bit;
1258 XMMArgRegs = XMMArgRegs64Bit;
1260 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1262 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1265 // For X86-64, if there are vararg parameters that are passed via
1266 // registers, then we must store them to their spots on the stack so they
1267 // may be loaded by deferencing the result of va_next.
1268 VarArgsGPOffset = NumIntRegs * 8;
1269 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1270 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1271 TotalNumXMMRegs * 16, 16);
1273 // Store the integer parameter registers.
1274 SmallVector<SDOperand, 8> MemOps;
1275 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1276 SDOperand FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1277 DAG.getIntPtrConstant(VarArgsGPOffset));
1278 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1279 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1280 X86::GR64RegisterClass);
1281 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1283 DAG.getStore(Val.getValue(1), Val, FIN,
1284 PseudoSourceValue::getFixedStack(),
1286 MemOps.push_back(Store);
1287 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1288 DAG.getIntPtrConstant(8));
1291 // Now store the XMM (fp + vector) parameter registers.
1292 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1293 DAG.getIntPtrConstant(VarArgsFPOffset));
1294 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1295 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1296 X86::VR128RegisterClass);
1297 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1299 DAG.getStore(Val.getValue(1), Val, FIN,
1300 PseudoSourceValue::getFixedStack(),
1302 MemOps.push_back(Store);
1303 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1304 DAG.getIntPtrConstant(16));
1306 if (!MemOps.empty())
1307 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1308 &MemOps[0], MemOps.size());
1312 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1313 // arguments and the arguments after the retaddr has been pushed are
1315 if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1316 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1317 (StackSize & 7) == 0)
1320 ArgValues.push_back(Root);
1322 // Some CCs need callee pop.
1323 if (IsCalleePop(Op)) {
1324 BytesToPopOnReturn = StackSize; // Callee pops everything.
1325 BytesCallerReserves = 0;
1327 BytesToPopOnReturn = 0; // Callee pops nothing.
1328 // If this is an sret function, the return should pop the hidden pointer.
1329 if (!Is64Bit && ArgsAreStructReturn(Op))
1330 BytesToPopOnReturn = 4;
1331 BytesCallerReserves = StackSize;
1335 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1336 if (CC == CallingConv::X86_FastCall)
1337 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1340 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1342 // Return the new list of results.
1343 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1344 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1348 X86TargetLowering::LowerMemOpCallTo(SDOperand Op, SelectionDAG &DAG,
1349 const SDOperand &StackPtr,
1350 const CCValAssign &VA,
1353 unsigned LocMemOffset = VA.getLocMemOffset();
1354 SDOperand PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1355 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1356 ISD::ArgFlagsTy Flags =
1357 cast<ARG_FLAGSSDNode>(Op.getOperand(6+2*VA.getValNo()))->getArgFlags();
1358 if (Flags.isByVal()) {
1359 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG);
1361 return DAG.getStore(Chain, Arg, PtrOff,
1362 PseudoSourceValue::getStack(), LocMemOffset);
1365 /// EmitTailCallLoadRetAddr - Emit a load of return adress if tail call
1366 /// optimization is performed and it is required.
1368 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1369 SDOperand &OutRetAddr,
1374 if (!IsTailCall || FPDiff==0) return Chain;
1376 // Adjust the Return address stack slot.
1377 MVT::ValueType VT = getPointerTy();
1378 OutRetAddr = getReturnAddressFrameIndex(DAG);
1379 // Load the "old" Return address.
1380 OutRetAddr = DAG.getLoad(VT, Chain,OutRetAddr, NULL, 0);
1381 return SDOperand(OutRetAddr.Val, 1);
1384 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1385 /// optimization is performed and it is required (FPDiff!=0).
1387 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1388 SDOperand Chain, SDOperand RetAddrFrIdx,
1389 bool Is64Bit, int FPDiff) {
1390 // Store the return address to the appropriate stack slot.
1391 if (!FPDiff) return Chain;
1392 // Calculate the new stack slot for the return address.
1393 int SlotSize = Is64Bit ? 8 : 4;
1394 int NewReturnAddrFI =
1395 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1396 MVT::ValueType VT = Is64Bit ? MVT::i64 : MVT::i32;
1397 SDOperand NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1398 Chain = DAG.getStore(Chain, RetAddrFrIdx, NewRetAddrFrIdx,
1399 PseudoSourceValue::getFixedStack(), NewReturnAddrFI);
1403 SDOperand X86TargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
1404 MachineFunction &MF = DAG.getMachineFunction();
1405 SDOperand Chain = Op.getOperand(0);
1406 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1407 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1408 bool IsTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0
1409 && CC == CallingConv::Fast && PerformTailCallOpt;
1410 SDOperand Callee = Op.getOperand(4);
1411 bool Is64Bit = Subtarget->is64Bit();
1412 bool IsStructRet = CallIsStructReturn(Op);
1414 assert(!(isVarArg && CC == CallingConv::Fast) &&
1415 "Var args not supported with calling convention fastcc");
1417 // Analyze operands of the call, assigning locations to each operand.
1418 SmallVector<CCValAssign, 16> ArgLocs;
1419 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1420 CCInfo.AnalyzeCallOperands(Op.Val, CCAssignFnForNode(Op));
1422 // Get a count of how many bytes are to be pushed on the stack.
1423 unsigned NumBytes = CCInfo.getNextStackOffset();
1424 if (CC == CallingConv::Fast)
1425 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1427 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1428 // arguments and the arguments after the retaddr has been pushed are aligned.
1429 if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1430 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1431 (NumBytes & 7) == 0)
1436 // Lower arguments at fp - stackoffset + fpdiff.
1437 unsigned NumBytesCallerPushed =
1438 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1439 FPDiff = NumBytesCallerPushed - NumBytes;
1441 // Set the delta of movement of the returnaddr stackslot.
1442 // But only set if delta is greater than previous delta.
1443 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1444 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1447 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes));
1449 SDOperand RetAddrFrIdx;
1450 // Load return adress for tail calls.
1451 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1454 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1455 SmallVector<SDOperand, 8> MemOpChains;
1458 // Walk the register/memloc assignments, inserting copies/loads. In the case
1459 // of tail call optimization arguments are handle later.
1460 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1461 CCValAssign &VA = ArgLocs[i];
1462 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1463 bool isByVal = cast<ARG_FLAGSSDNode>(Op.getOperand(6+2*VA.getValNo()))->
1464 getArgFlags().isByVal();
1466 // Promote the value if needed.
1467 switch (VA.getLocInfo()) {
1468 default: assert(0 && "Unknown loc info!");
1469 case CCValAssign::Full: break;
1470 case CCValAssign::SExt:
1471 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1473 case CCValAssign::ZExt:
1474 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1476 case CCValAssign::AExt:
1477 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1481 if (VA.isRegLoc()) {
1483 MVT::ValueType RegVT = VA.getLocVT();
1484 if (MVT::isVector(RegVT) && MVT::getSizeInBits(RegVT) == 64)
1485 switch (VA.getLocReg()) {
1488 case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1490 // Special case: passing MMX values in GPR registers.
1491 Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1494 case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1495 case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1496 // Special case: passing MMX values in XMM registers.
1497 Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1498 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Arg);
1499 Arg = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
1500 DAG.getNode(ISD::UNDEF, MVT::v2i64), Arg,
1501 getMOVLMask(2, DAG));
1506 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1508 if (!IsTailCall || (IsTailCall && isByVal)) {
1509 assert(VA.isMemLoc());
1510 if (StackPtr.Val == 0)
1511 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1513 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1519 if (!MemOpChains.empty())
1520 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1521 &MemOpChains[0], MemOpChains.size());
1523 // Build a sequence of copy-to-reg nodes chained together with token chain
1524 // and flag operands which copy the outgoing args into registers.
1526 // Tail call byval lowering might overwrite argument registers so in case of
1527 // tail call optimization the copies to registers are lowered later.
1529 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1530 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1532 InFlag = Chain.getValue(1);
1535 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1537 if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1538 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1539 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1541 InFlag = Chain.getValue(1);
1543 // If we are tail calling and generating PIC/GOT style code load the address
1544 // of the callee into ecx. The value in ecx is used as target of the tail
1545 // jump. This is done to circumvent the ebx/callee-saved problem for tail
1546 // calls on PIC/GOT architectures. Normally we would just put the address of
1547 // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1548 // restored (since ebx is callee saved) before jumping to the target@PLT.
1549 if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1550 // Note: The actual moving to ecx is done further down.
1551 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1552 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1553 !G->getGlobal()->hasProtectedVisibility())
1554 Callee = LowerGlobalAddress(Callee, DAG);
1555 else if (isa<ExternalSymbolSDNode>(Callee))
1556 Callee = LowerExternalSymbol(Callee,DAG);
1559 if (Is64Bit && isVarArg) {
1560 // From AMD64 ABI document:
1561 // For calls that may call functions that use varargs or stdargs
1562 // (prototype-less calls or calls to functions containing ellipsis (...) in
1563 // the declaration) %al is used as hidden argument to specify the number
1564 // of SSE registers used. The contents of %al do not need to match exactly
1565 // the number of registers, but must be an ubound on the number of SSE
1566 // registers used and is in the range 0 - 8 inclusive.
1568 // FIXME: Verify this on Win64
1569 // Count the number of XMM registers allocated.
1570 static const unsigned XMMArgRegs[] = {
1571 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1572 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1574 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1576 Chain = DAG.getCopyToReg(Chain, X86::AL,
1577 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1578 InFlag = Chain.getValue(1);
1582 // For tail calls lower the arguments to the 'real' stack slot.
1584 SmallVector<SDOperand, 8> MemOpChains2;
1587 // Do not flag preceeding copytoreg stuff together with the following stuff.
1588 InFlag = SDOperand();
1589 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1590 CCValAssign &VA = ArgLocs[i];
1591 if (!VA.isRegLoc()) {
1592 assert(VA.isMemLoc());
1593 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1594 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1595 ISD::ArgFlagsTy Flags =
1596 cast<ARG_FLAGSSDNode>(FlagsOp)->getArgFlags();
1597 // Create frame index.
1598 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1599 uint32_t OpSize = (MVT::getSizeInBits(VA.getLocVT())+7)/8;
1600 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1601 FIN = DAG.getFrameIndex(FI, getPointerTy());
1603 if (Flags.isByVal()) {
1604 // Copy relative to framepointer.
1605 SDOperand Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1606 if (StackPtr.Val == 0)
1607 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1608 Source = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, Source);
1610 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1613 // Store relative to framepointer.
1614 MemOpChains2.push_back(
1615 DAG.getStore(Chain, Arg, FIN,
1616 PseudoSourceValue::getFixedStack(), FI));
1621 if (!MemOpChains2.empty())
1622 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1623 &MemOpChains2[0], MemOpChains2.size());
1625 // Copy arguments to their registers.
1626 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1627 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1629 InFlag = Chain.getValue(1);
1631 InFlag =SDOperand();
1633 // Store the return address to the appropriate stack slot.
1634 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1638 // If the callee is a GlobalAddress node (quite common, every direct call is)
1639 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1640 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1641 // We should use extra load for direct calls to dllimported functions in
1643 if ((IsTailCall || !Is64Bit ||
1644 getTargetMachine().getCodeModel() != CodeModel::Large)
1645 && !Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1646 getTargetMachine(), true))
1647 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1648 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1649 if (IsTailCall || !Is64Bit ||
1650 getTargetMachine().getCodeModel() != CodeModel::Large)
1651 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1652 } else if (IsTailCall) {
1653 unsigned Opc = Is64Bit ? X86::R9 : X86::ECX;
1655 Chain = DAG.getCopyToReg(Chain,
1656 DAG.getRegister(Opc, getPointerTy()),
1658 Callee = DAG.getRegister(Opc, getPointerTy());
1659 // Add register as live out.
1660 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1663 // Returns a chain & a flag for retval copy to use.
1664 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1665 SmallVector<SDOperand, 8> Ops;
1668 Ops.push_back(Chain);
1669 Ops.push_back(DAG.getIntPtrConstant(NumBytes));
1670 Ops.push_back(DAG.getIntPtrConstant(0));
1672 Ops.push_back(InFlag);
1673 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1674 InFlag = Chain.getValue(1);
1676 // Returns a chain & a flag for retval copy to use.
1677 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1681 Ops.push_back(Chain);
1682 Ops.push_back(Callee);
1685 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1687 // Add argument registers to the end of the list so that they are known live
1689 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1690 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1691 RegsToPass[i].second.getValueType()));
1693 // Add an implicit use GOT pointer in EBX.
1694 if (!IsTailCall && !Is64Bit &&
1695 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1696 Subtarget->isPICStyleGOT())
1697 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1699 // Add an implicit use of AL for x86 vararg functions.
1700 if (Is64Bit && isVarArg)
1701 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1704 Ops.push_back(InFlag);
1707 assert(InFlag.Val &&
1708 "Flag must be set. Depend on flag being set in LowerRET");
1709 Chain = DAG.getNode(X86ISD::TAILCALL,
1710 Op.Val->getVTList(), &Ops[0], Ops.size());
1712 return SDOperand(Chain.Val, Op.ResNo);
1715 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1716 InFlag = Chain.getValue(1);
1718 // Create the CALLSEQ_END node.
1719 unsigned NumBytesForCalleeToPush;
1720 if (IsCalleePop(Op))
1721 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1722 else if (!Is64Bit && IsStructRet)
1723 // If this is is a call to a struct-return function, the callee
1724 // pops the hidden struct pointer, so we have to push it back.
1725 // This is common for Darwin/X86, Linux & Mingw32 targets.
1726 NumBytesForCalleeToPush = 4;
1728 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1730 // Returns a flag for retval copy to use.
1731 Chain = DAG.getCALLSEQ_END(Chain,
1732 DAG.getIntPtrConstant(NumBytes),
1733 DAG.getIntPtrConstant(NumBytesForCalleeToPush),
1735 InFlag = Chain.getValue(1);
1737 // Handle result values, copying them out of physregs into vregs that we
1739 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1743 //===----------------------------------------------------------------------===//
1744 // Fast Calling Convention (tail call) implementation
1745 //===----------------------------------------------------------------------===//
1747 // Like std call, callee cleans arguments, convention except that ECX is
1748 // reserved for storing the tail called function address. Only 2 registers are
1749 // free for argument passing (inreg). Tail call optimization is performed
1751 // * tailcallopt is enabled
1752 // * caller/callee are fastcc
1753 // On X86_64 architecture with GOT-style position independent code only local
1754 // (within module) calls are supported at the moment.
1755 // To keep the stack aligned according to platform abi the function
1756 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1757 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1758 // If a tail called function callee has more arguments than the caller the
1759 // caller needs to make sure that there is room to move the RETADDR to. This is
1760 // achieved by reserving an area the size of the argument delta right after the
1761 // original REtADDR, but before the saved framepointer or the spilled registers
1762 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1774 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1775 /// for a 16 byte align requirement.
1776 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1777 SelectionDAG& DAG) {
1778 if (PerformTailCallOpt) {
1779 MachineFunction &MF = DAG.getMachineFunction();
1780 const TargetMachine &TM = MF.getTarget();
1781 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1782 unsigned StackAlignment = TFI.getStackAlignment();
1783 uint64_t AlignMask = StackAlignment - 1;
1784 int64_t Offset = StackSize;
1785 unsigned SlotSize = Subtarget->is64Bit() ? 8 : 4;
1786 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1787 // Number smaller than 12 so just add the difference.
1788 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1790 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1791 Offset = ((~AlignMask) & Offset) + StackAlignment +
1792 (StackAlignment-SlotSize);
1799 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1800 /// following the call is a return. A function is eligible if caller/callee
1801 /// calling conventions match, currently only fastcc supports tail calls, and
1802 /// the function CALL is immediatly followed by a RET.
1803 bool X86TargetLowering::IsEligibleForTailCallOptimization(SDOperand Call,
1805 SelectionDAG& DAG) const {
1806 if (!PerformTailCallOpt)
1809 if (CheckTailCallReturnConstraints(Call, Ret)) {
1810 MachineFunction &MF = DAG.getMachineFunction();
1811 unsigned CallerCC = MF.getFunction()->getCallingConv();
1812 unsigned CalleeCC = cast<ConstantSDNode>(Call.getOperand(1))->getValue();
1813 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1814 SDOperand Callee = Call.getOperand(4);
1815 // On x86/32Bit PIC/GOT tail calls are supported.
1816 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1817 !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1820 // Can only do local tail calls (in same module, hidden or protected) on
1821 // x86_64 PIC/GOT at the moment.
1822 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1823 return G->getGlobal()->hasHiddenVisibility()
1824 || G->getGlobal()->hasProtectedVisibility();
1831 //===----------------------------------------------------------------------===//
1832 // Other Lowering Hooks
1833 //===----------------------------------------------------------------------===//
1836 SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1837 MachineFunction &MF = DAG.getMachineFunction();
1838 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1839 int ReturnAddrIndex = FuncInfo->getRAIndex();
1841 if (ReturnAddrIndex == 0) {
1842 // Set up a frame object for the return address.
1843 if (Subtarget->is64Bit())
1844 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
1846 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
1848 FuncInfo->setRAIndex(ReturnAddrIndex);
1851 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1856 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1857 /// specific condition code. It returns a false if it cannot do a direct
1858 /// translation. X86CC is the translated CondCode. LHS/RHS are modified as
1860 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1861 unsigned &X86CC, SDOperand &LHS, SDOperand &RHS,
1862 SelectionDAG &DAG) {
1863 X86CC = X86::COND_INVALID;
1865 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1866 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
1867 // X > -1 -> X == 0, jump !sign.
1868 RHS = DAG.getConstant(0, RHS.getValueType());
1869 X86CC = X86::COND_NS;
1871 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
1872 // X < 0 -> X == 0, jump on sign.
1873 X86CC = X86::COND_S;
1875 } else if (SetCCOpcode == ISD::SETLT && RHSC->getValue() == 1) {
1877 RHS = DAG.getConstant(0, RHS.getValueType());
1878 X86CC = X86::COND_LE;
1883 switch (SetCCOpcode) {
1885 case ISD::SETEQ: X86CC = X86::COND_E; break;
1886 case ISD::SETGT: X86CC = X86::COND_G; break;
1887 case ISD::SETGE: X86CC = X86::COND_GE; break;
1888 case ISD::SETLT: X86CC = X86::COND_L; break;
1889 case ISD::SETLE: X86CC = X86::COND_LE; break;
1890 case ISD::SETNE: X86CC = X86::COND_NE; break;
1891 case ISD::SETULT: X86CC = X86::COND_B; break;
1892 case ISD::SETUGT: X86CC = X86::COND_A; break;
1893 case ISD::SETULE: X86CC = X86::COND_BE; break;
1894 case ISD::SETUGE: X86CC = X86::COND_AE; break;
1897 // On a floating point condition, the flags are set as follows:
1899 // 0 | 0 | 0 | X > Y
1900 // 0 | 0 | 1 | X < Y
1901 // 1 | 0 | 0 | X == Y
1902 // 1 | 1 | 1 | unordered
1904 switch (SetCCOpcode) {
1907 case ISD::SETEQ: X86CC = X86::COND_E; break;
1908 case ISD::SETOLT: Flip = true; // Fallthrough
1910 case ISD::SETGT: X86CC = X86::COND_A; break;
1911 case ISD::SETOLE: Flip = true; // Fallthrough
1913 case ISD::SETGE: X86CC = X86::COND_AE; break;
1914 case ISD::SETUGT: Flip = true; // Fallthrough
1916 case ISD::SETLT: X86CC = X86::COND_B; break;
1917 case ISD::SETUGE: Flip = true; // Fallthrough
1919 case ISD::SETLE: X86CC = X86::COND_BE; break;
1921 case ISD::SETNE: X86CC = X86::COND_NE; break;
1922 case ISD::SETUO: X86CC = X86::COND_P; break;
1923 case ISD::SETO: X86CC = X86::COND_NP; break;
1926 std::swap(LHS, RHS);
1929 return X86CC != X86::COND_INVALID;
1932 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
1933 /// code. Current x86 isa includes the following FP cmov instructions:
1934 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
1935 static bool hasFPCMov(unsigned X86CC) {
1951 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
1952 /// true if Op is undef or if its value falls within the specified range (L, H].
1953 static bool isUndefOrInRange(SDOperand Op, unsigned Low, unsigned Hi) {
1954 if (Op.getOpcode() == ISD::UNDEF)
1957 unsigned Val = cast<ConstantSDNode>(Op)->getValue();
1958 return (Val >= Low && Val < Hi);
1961 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
1962 /// true if Op is undef or if its value equal to the specified value.
1963 static bool isUndefOrEqual(SDOperand Op, unsigned Val) {
1964 if (Op.getOpcode() == ISD::UNDEF)
1966 return cast<ConstantSDNode>(Op)->getValue() == Val;
1969 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
1970 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
1971 bool X86::isPSHUFDMask(SDNode *N) {
1972 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1974 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
1977 // Check if the value doesn't reference the second vector.
1978 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1979 SDOperand Arg = N->getOperand(i);
1980 if (Arg.getOpcode() == ISD::UNDEF) continue;
1981 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1982 if (cast<ConstantSDNode>(Arg)->getValue() >= e)
1989 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
1990 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
1991 bool X86::isPSHUFHWMask(SDNode *N) {
1992 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1994 if (N->getNumOperands() != 8)
1997 // Lower quadword copied in order.
1998 for (unsigned i = 0; i != 4; ++i) {
1999 SDOperand Arg = N->getOperand(i);
2000 if (Arg.getOpcode() == ISD::UNDEF) continue;
2001 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2002 if (cast<ConstantSDNode>(Arg)->getValue() != i)
2006 // Upper quadword shuffled.
2007 for (unsigned i = 4; i != 8; ++i) {
2008 SDOperand Arg = N->getOperand(i);
2009 if (Arg.getOpcode() == ISD::UNDEF) continue;
2010 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2011 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2012 if (Val < 4 || Val > 7)
2019 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2020 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2021 bool X86::isPSHUFLWMask(SDNode *N) {
2022 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2024 if (N->getNumOperands() != 8)
2027 // Upper quadword copied in order.
2028 for (unsigned i = 4; i != 8; ++i)
2029 if (!isUndefOrEqual(N->getOperand(i), i))
2032 // Lower quadword shuffled.
2033 for (unsigned i = 0; i != 4; ++i)
2034 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2040 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2041 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2042 static bool isSHUFPMask(SDOperandPtr Elems, unsigned NumElems) {
2043 if (NumElems != 2 && NumElems != 4) return false;
2045 unsigned Half = NumElems / 2;
2046 for (unsigned i = 0; i < Half; ++i)
2047 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2049 for (unsigned i = Half; i < NumElems; ++i)
2050 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2056 bool X86::isSHUFPMask(SDNode *N) {
2057 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2058 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2061 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2062 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2063 /// half elements to come from vector 1 (which would equal the dest.) and
2064 /// the upper half to come from vector 2.
2065 static bool isCommutedSHUFP(SDOperandPtr Ops, unsigned NumOps) {
2066 if (NumOps != 2 && NumOps != 4) return false;
2068 unsigned Half = NumOps / 2;
2069 for (unsigned i = 0; i < Half; ++i)
2070 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2072 for (unsigned i = Half; i < NumOps; ++i)
2073 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2078 static bool isCommutedSHUFP(SDNode *N) {
2079 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2080 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2083 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2084 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2085 bool X86::isMOVHLPSMask(SDNode *N) {
2086 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2088 if (N->getNumOperands() != 4)
2091 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2092 return isUndefOrEqual(N->getOperand(0), 6) &&
2093 isUndefOrEqual(N->getOperand(1), 7) &&
2094 isUndefOrEqual(N->getOperand(2), 2) &&
2095 isUndefOrEqual(N->getOperand(3), 3);
2098 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2099 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2101 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2102 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2104 if (N->getNumOperands() != 4)
2107 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2108 return isUndefOrEqual(N->getOperand(0), 2) &&
2109 isUndefOrEqual(N->getOperand(1), 3) &&
2110 isUndefOrEqual(N->getOperand(2), 2) &&
2111 isUndefOrEqual(N->getOperand(3), 3);
2114 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2115 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2116 bool X86::isMOVLPMask(SDNode *N) {
2117 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2119 unsigned NumElems = N->getNumOperands();
2120 if (NumElems != 2 && NumElems != 4)
2123 for (unsigned i = 0; i < NumElems/2; ++i)
2124 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2127 for (unsigned i = NumElems/2; i < NumElems; ++i)
2128 if (!isUndefOrEqual(N->getOperand(i), i))
2134 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2135 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2137 bool X86::isMOVHPMask(SDNode *N) {
2138 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2140 unsigned NumElems = N->getNumOperands();
2141 if (NumElems != 2 && NumElems != 4)
2144 for (unsigned i = 0; i < NumElems/2; ++i)
2145 if (!isUndefOrEqual(N->getOperand(i), i))
2148 for (unsigned i = 0; i < NumElems/2; ++i) {
2149 SDOperand Arg = N->getOperand(i + NumElems/2);
2150 if (!isUndefOrEqual(Arg, i + NumElems))
2157 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2158 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2159 bool static isUNPCKLMask(SDOperandPtr Elts, unsigned NumElts,
2160 bool V2IsSplat = false) {
2161 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2164 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2165 SDOperand BitI = Elts[i];
2166 SDOperand BitI1 = Elts[i+1];
2167 if (!isUndefOrEqual(BitI, j))
2170 if (isUndefOrEqual(BitI1, NumElts))
2173 if (!isUndefOrEqual(BitI1, j + NumElts))
2181 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2182 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2183 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2186 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2187 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2188 bool static isUNPCKHMask(SDOperandPtr Elts, unsigned NumElts,
2189 bool V2IsSplat = false) {
2190 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2193 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2194 SDOperand BitI = Elts[i];
2195 SDOperand BitI1 = Elts[i+1];
2196 if (!isUndefOrEqual(BitI, j + NumElts/2))
2199 if (isUndefOrEqual(BitI1, NumElts))
2202 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2210 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2211 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2212 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2215 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2216 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2218 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2219 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2221 unsigned NumElems = N->getNumOperands();
2222 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2225 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2226 SDOperand BitI = N->getOperand(i);
2227 SDOperand BitI1 = N->getOperand(i+1);
2229 if (!isUndefOrEqual(BitI, j))
2231 if (!isUndefOrEqual(BitI1, j))
2238 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2239 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2241 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2242 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2244 unsigned NumElems = N->getNumOperands();
2245 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2248 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2249 SDOperand BitI = N->getOperand(i);
2250 SDOperand BitI1 = N->getOperand(i + 1);
2252 if (!isUndefOrEqual(BitI, j))
2254 if (!isUndefOrEqual(BitI1, j))
2261 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2262 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2263 /// MOVSD, and MOVD, i.e. setting the lowest element.
2264 static bool isMOVLMask(SDOperandPtr Elts, unsigned NumElts) {
2265 if (NumElts != 2 && NumElts != 4)
2268 if (!isUndefOrEqual(Elts[0], NumElts))
2271 for (unsigned i = 1; i < NumElts; ++i) {
2272 if (!isUndefOrEqual(Elts[i], i))
2279 bool X86::isMOVLMask(SDNode *N) {
2280 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2281 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2284 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2285 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2286 /// element of vector 2 and the other elements to come from vector 1 in order.
2287 static bool isCommutedMOVL(SDOperandPtr Ops, unsigned NumOps,
2288 bool V2IsSplat = false,
2289 bool V2IsUndef = false) {
2290 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2293 if (!isUndefOrEqual(Ops[0], 0))
2296 for (unsigned i = 1; i < NumOps; ++i) {
2297 SDOperand Arg = Ops[i];
2298 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2299 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2300 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2307 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2308 bool V2IsUndef = false) {
2309 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2310 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2311 V2IsSplat, V2IsUndef);
2314 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2315 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2316 bool X86::isMOVSHDUPMask(SDNode *N) {
2317 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2319 if (N->getNumOperands() != 4)
2322 // Expect 1, 1, 3, 3
2323 for (unsigned i = 0; i < 2; ++i) {
2324 SDOperand Arg = N->getOperand(i);
2325 if (Arg.getOpcode() == ISD::UNDEF) continue;
2326 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2327 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2328 if (Val != 1) return false;
2332 for (unsigned i = 2; i < 4; ++i) {
2333 SDOperand Arg = N->getOperand(i);
2334 if (Arg.getOpcode() == ISD::UNDEF) continue;
2335 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2336 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2337 if (Val != 3) return false;
2341 // Don't use movshdup if it can be done with a shufps.
2345 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2346 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2347 bool X86::isMOVSLDUPMask(SDNode *N) {
2348 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2350 if (N->getNumOperands() != 4)
2353 // Expect 0, 0, 2, 2
2354 for (unsigned i = 0; i < 2; ++i) {
2355 SDOperand Arg = N->getOperand(i);
2356 if (Arg.getOpcode() == ISD::UNDEF) continue;
2357 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2358 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2359 if (Val != 0) return false;
2363 for (unsigned i = 2; i < 4; ++i) {
2364 SDOperand Arg = N->getOperand(i);
2365 if (Arg.getOpcode() == ISD::UNDEF) continue;
2366 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2367 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2368 if (Val != 2) return false;
2372 // Don't use movshdup if it can be done with a shufps.
2376 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2377 /// specifies a identity operation on the LHS or RHS.
2378 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2379 unsigned NumElems = N->getNumOperands();
2380 for (unsigned i = 0; i < NumElems; ++i)
2381 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2386 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2387 /// a splat of a single element.
2388 static bool isSplatMask(SDNode *N) {
2389 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2391 // This is a splat operation if each element of the permute is the same, and
2392 // if the value doesn't reference the second vector.
2393 unsigned NumElems = N->getNumOperands();
2394 SDOperand ElementBase;
2396 for (; i != NumElems; ++i) {
2397 SDOperand Elt = N->getOperand(i);
2398 if (isa<ConstantSDNode>(Elt)) {
2404 if (!ElementBase.Val)
2407 for (; i != NumElems; ++i) {
2408 SDOperand Arg = N->getOperand(i);
2409 if (Arg.getOpcode() == ISD::UNDEF) continue;
2410 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2411 if (Arg != ElementBase) return false;
2414 // Make sure it is a splat of the first vector operand.
2415 return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
2418 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2419 /// a splat of a single element and it's a 2 or 4 element mask.
2420 bool X86::isSplatMask(SDNode *N) {
2421 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2423 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2424 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2426 return ::isSplatMask(N);
2429 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2430 /// specifies a splat of zero element.
2431 bool X86::isSplatLoMask(SDNode *N) {
2432 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2434 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2435 if (!isUndefOrEqual(N->getOperand(i), 0))
2440 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2441 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2443 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2444 unsigned NumOperands = N->getNumOperands();
2445 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2447 for (unsigned i = 0; i < NumOperands; ++i) {
2449 SDOperand Arg = N->getOperand(NumOperands-i-1);
2450 if (Arg.getOpcode() != ISD::UNDEF)
2451 Val = cast<ConstantSDNode>(Arg)->getValue();
2452 if (Val >= NumOperands) Val -= NumOperands;
2454 if (i != NumOperands - 1)
2461 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2462 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2464 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2466 // 8 nodes, but we only care about the last 4.
2467 for (unsigned i = 7; i >= 4; --i) {
2469 SDOperand Arg = N->getOperand(i);
2470 if (Arg.getOpcode() != ISD::UNDEF)
2471 Val = cast<ConstantSDNode>(Arg)->getValue();
2480 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2481 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2483 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2485 // 8 nodes, but we only care about the first 4.
2486 for (int i = 3; i >= 0; --i) {
2488 SDOperand Arg = N->getOperand(i);
2489 if (Arg.getOpcode() != ISD::UNDEF)
2490 Val = cast<ConstantSDNode>(Arg)->getValue();
2499 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2500 /// specifies a 8 element shuffle that can be broken into a pair of
2501 /// PSHUFHW and PSHUFLW.
2502 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2503 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2505 if (N->getNumOperands() != 8)
2508 // Lower quadword shuffled.
2509 for (unsigned i = 0; i != 4; ++i) {
2510 SDOperand Arg = N->getOperand(i);
2511 if (Arg.getOpcode() == ISD::UNDEF) continue;
2512 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2513 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2518 // Upper quadword shuffled.
2519 for (unsigned i = 4; i != 8; ++i) {
2520 SDOperand Arg = N->getOperand(i);
2521 if (Arg.getOpcode() == ISD::UNDEF) continue;
2522 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2523 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2524 if (Val < 4 || Val > 7)
2531 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2532 /// values in ther permute mask.
2533 static SDOperand CommuteVectorShuffle(SDOperand Op, SDOperand &V1,
2534 SDOperand &V2, SDOperand &Mask,
2535 SelectionDAG &DAG) {
2536 MVT::ValueType VT = Op.getValueType();
2537 MVT::ValueType MaskVT = Mask.getValueType();
2538 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2539 unsigned NumElems = Mask.getNumOperands();
2540 SmallVector<SDOperand, 8> MaskVec;
2542 for (unsigned i = 0; i != NumElems; ++i) {
2543 SDOperand Arg = Mask.getOperand(i);
2544 if (Arg.getOpcode() == ISD::UNDEF) {
2545 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2548 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2549 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2551 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2553 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2557 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2558 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2561 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2562 /// the two vector operands have swapped position.
2564 SDOperand CommuteVectorShuffleMask(SDOperand Mask, SelectionDAG &DAG) {
2565 MVT::ValueType MaskVT = Mask.getValueType();
2566 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2567 unsigned NumElems = Mask.getNumOperands();
2568 SmallVector<SDOperand, 8> MaskVec;
2569 for (unsigned i = 0; i != NumElems; ++i) {
2570 SDOperand Arg = Mask.getOperand(i);
2571 if (Arg.getOpcode() == ISD::UNDEF) {
2572 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2575 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2576 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2578 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2580 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2582 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2586 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2587 /// match movhlps. The lower half elements should come from upper half of
2588 /// V1 (and in order), and the upper half elements should come from the upper
2589 /// half of V2 (and in order).
2590 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2591 unsigned NumElems = Mask->getNumOperands();
2594 for (unsigned i = 0, e = 2; i != e; ++i)
2595 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2597 for (unsigned i = 2; i != 4; ++i)
2598 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2603 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2604 /// is promoted to a vector.
2605 static inline bool isScalarLoadToVector(SDNode *N) {
2606 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2607 N = N->getOperand(0).Val;
2608 return ISD::isNON_EXTLoad(N);
2613 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2614 /// match movlp{s|d}. The lower half elements should come from lower half of
2615 /// V1 (and in order), and the upper half elements should come from the upper
2616 /// half of V2 (and in order). And since V1 will become the source of the
2617 /// MOVLP, it must be either a vector load or a scalar load to vector.
2618 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2619 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2621 // Is V2 is a vector load, don't do this transformation. We will try to use
2622 // load folding shufps op.
2623 if (ISD::isNON_EXTLoad(V2))
2626 unsigned NumElems = Mask->getNumOperands();
2627 if (NumElems != 2 && NumElems != 4)
2629 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2630 if (!isUndefOrEqual(Mask->getOperand(i), i))
2632 for (unsigned i = NumElems/2; i != NumElems; ++i)
2633 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2638 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2640 static bool isSplatVector(SDNode *N) {
2641 if (N->getOpcode() != ISD::BUILD_VECTOR)
2644 SDOperand SplatValue = N->getOperand(0);
2645 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2646 if (N->getOperand(i) != SplatValue)
2651 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2653 static bool isUndefShuffle(SDNode *N) {
2654 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2657 SDOperand V1 = N->getOperand(0);
2658 SDOperand V2 = N->getOperand(1);
2659 SDOperand Mask = N->getOperand(2);
2660 unsigned NumElems = Mask.getNumOperands();
2661 for (unsigned i = 0; i != NumElems; ++i) {
2662 SDOperand Arg = Mask.getOperand(i);
2663 if (Arg.getOpcode() != ISD::UNDEF) {
2664 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2665 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2667 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2674 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2676 static inline bool isZeroNode(SDOperand Elt) {
2677 return ((isa<ConstantSDNode>(Elt) &&
2678 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2679 (isa<ConstantFPSDNode>(Elt) &&
2680 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2683 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2684 /// to an zero vector.
2685 static bool isZeroShuffle(SDNode *N) {
2686 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2689 SDOperand V1 = N->getOperand(0);
2690 SDOperand V2 = N->getOperand(1);
2691 SDOperand Mask = N->getOperand(2);
2692 unsigned NumElems = Mask.getNumOperands();
2693 for (unsigned i = 0; i != NumElems; ++i) {
2694 SDOperand Arg = Mask.getOperand(i);
2695 if (Arg.getOpcode() == ISD::UNDEF)
2698 unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
2699 if (Idx < NumElems) {
2700 unsigned Opc = V1.Val->getOpcode();
2701 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.Val))
2703 if (Opc != ISD::BUILD_VECTOR ||
2704 !isZeroNode(V1.Val->getOperand(Idx)))
2706 } else if (Idx >= NumElems) {
2707 unsigned Opc = V2.Val->getOpcode();
2708 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.Val))
2710 if (Opc != ISD::BUILD_VECTOR ||
2711 !isZeroNode(V2.Val->getOperand(Idx - NumElems)))
2718 /// getZeroVector - Returns a vector of specified type with all zero elements.
2720 static SDOperand getZeroVector(MVT::ValueType VT, SelectionDAG &DAG) {
2721 assert(MVT::isVector(VT) && "Expected a vector type");
2723 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2724 // type. This ensures they get CSE'd.
2725 SDOperand Cst = DAG.getTargetConstant(0, MVT::i32);
2727 if (MVT::getSizeInBits(VT) == 64) // MMX
2728 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2730 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2731 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2734 /// getOnesVector - Returns a vector of specified type with all bits set.
2736 static SDOperand getOnesVector(MVT::ValueType VT, SelectionDAG &DAG) {
2737 assert(MVT::isVector(VT) && "Expected a vector type");
2739 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2740 // type. This ensures they get CSE'd.
2741 SDOperand Cst = DAG.getTargetConstant(~0U, MVT::i32);
2743 if (MVT::getSizeInBits(VT) == 64) // MMX
2744 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2746 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2747 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2751 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2752 /// that point to V2 points to its first element.
2753 static SDOperand NormalizeMask(SDOperand Mask, SelectionDAG &DAG) {
2754 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2756 bool Changed = false;
2757 SmallVector<SDOperand, 8> MaskVec;
2758 unsigned NumElems = Mask.getNumOperands();
2759 for (unsigned i = 0; i != NumElems; ++i) {
2760 SDOperand Arg = Mask.getOperand(i);
2761 if (Arg.getOpcode() != ISD::UNDEF) {
2762 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2763 if (Val > NumElems) {
2764 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2768 MaskVec.push_back(Arg);
2772 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2773 &MaskVec[0], MaskVec.size());
2777 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2778 /// operation of specified width.
2779 static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2780 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2781 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2783 SmallVector<SDOperand, 8> MaskVec;
2784 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2785 for (unsigned i = 1; i != NumElems; ++i)
2786 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2787 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2790 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2791 /// of specified width.
2792 static SDOperand getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2793 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2794 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2795 SmallVector<SDOperand, 8> MaskVec;
2796 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2797 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2798 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2800 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2803 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2804 /// of specified width.
2805 static SDOperand getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2806 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2807 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2808 unsigned Half = NumElems/2;
2809 SmallVector<SDOperand, 8> MaskVec;
2810 for (unsigned i = 0; i != Half; ++i) {
2811 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
2812 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2814 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2817 /// getSwapEltZeroMask - Returns a vector_shuffle mask for a shuffle that swaps
2818 /// element #0 of a vector with the specified index, leaving the rest of the
2819 /// elements in place.
2820 static SDOperand getSwapEltZeroMask(unsigned NumElems, unsigned DestElt,
2821 SelectionDAG &DAG) {
2822 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2823 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2824 SmallVector<SDOperand, 8> MaskVec;
2825 // Element #0 of the result gets the elt we are replacing.
2826 MaskVec.push_back(DAG.getConstant(DestElt, BaseVT));
2827 for (unsigned i = 1; i != NumElems; ++i)
2828 MaskVec.push_back(DAG.getConstant(i == DestElt ? 0 : i, BaseVT));
2829 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2832 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
2833 static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG, bool HasSSE2) {
2834 MVT::ValueType PVT = HasSSE2 ? MVT::v4i32 : MVT::v4f32;
2835 MVT::ValueType VT = Op.getValueType();
2838 SDOperand V1 = Op.getOperand(0);
2839 SDOperand Mask = Op.getOperand(2);
2840 unsigned NumElems = Mask.getNumOperands();
2841 // Special handling of v4f32 -> v4i32.
2842 if (VT != MVT::v4f32) {
2843 Mask = getUnpacklMask(NumElems, DAG);
2844 while (NumElems > 4) {
2845 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2848 Mask = getZeroVector(MVT::v4i32, DAG);
2851 V1 = DAG.getNode(ISD::BIT_CONVERT, PVT, V1);
2852 SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, PVT, V1,
2853 DAG.getNode(ISD::UNDEF, PVT), Mask);
2854 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2857 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2858 /// vector of zero or undef vector. This produces a shuffle where the low
2859 /// element of V2 is swizzled into the zero/undef vector, landing at element
2860 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
2861 static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, unsigned Idx,
2862 bool isZero, SelectionDAG &DAG) {
2863 MVT::ValueType VT = V2.getValueType();
2864 SDOperand V1 = isZero ? getZeroVector(VT, DAG) : DAG.getNode(ISD::UNDEF, VT);
2865 unsigned NumElems = MVT::getVectorNumElements(V2.getValueType());
2866 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2867 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
2868 SmallVector<SDOperand, 16> MaskVec;
2869 for (unsigned i = 0; i != NumElems; ++i)
2870 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
2871 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
2873 MaskVec.push_back(DAG.getConstant(i, EVT));
2874 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2875 &MaskVec[0], MaskVec.size());
2876 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2879 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2881 static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
2882 unsigned NumNonZero, unsigned NumZero,
2883 SelectionDAG &DAG, TargetLowering &TLI) {
2889 for (unsigned i = 0; i < 16; ++i) {
2890 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
2891 if (ThisIsNonZero && First) {
2893 V = getZeroVector(MVT::v8i16, DAG);
2895 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2900 SDOperand ThisElt(0, 0), LastElt(0, 0);
2901 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
2902 if (LastIsNonZero) {
2903 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
2905 if (ThisIsNonZero) {
2906 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
2907 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
2908 ThisElt, DAG.getConstant(8, MVT::i8));
2910 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
2915 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
2916 DAG.getIntPtrConstant(i/2));
2920 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
2923 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
2925 static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
2926 unsigned NumNonZero, unsigned NumZero,
2927 SelectionDAG &DAG, TargetLowering &TLI) {
2933 for (unsigned i = 0; i < 8; ++i) {
2934 bool isNonZero = (NonZeros & (1 << i)) != 0;
2938 V = getZeroVector(MVT::v8i16, DAG);
2940 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2943 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
2944 DAG.getIntPtrConstant(i));
2952 X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
2953 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
2954 if (ISD::isBuildVectorAllZeros(Op.Val) || ISD::isBuildVectorAllOnes(Op.Val)) {
2955 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
2956 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
2957 // eliminated on x86-32 hosts.
2958 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
2961 if (ISD::isBuildVectorAllOnes(Op.Val))
2962 return getOnesVector(Op.getValueType(), DAG);
2963 return getZeroVector(Op.getValueType(), DAG);
2966 MVT::ValueType VT = Op.getValueType();
2967 MVT::ValueType EVT = MVT::getVectorElementType(VT);
2968 unsigned EVTBits = MVT::getSizeInBits(EVT);
2970 unsigned NumElems = Op.getNumOperands();
2971 unsigned NumZero = 0;
2972 unsigned NumNonZero = 0;
2973 unsigned NonZeros = 0;
2974 bool IsAllConstants = true;
2975 SmallSet<SDOperand, 8> Values;
2976 for (unsigned i = 0; i < NumElems; ++i) {
2977 SDOperand Elt = Op.getOperand(i);
2978 if (Elt.getOpcode() == ISD::UNDEF)
2981 if (Elt.getOpcode() != ISD::Constant &&
2982 Elt.getOpcode() != ISD::ConstantFP)
2983 IsAllConstants = false;
2984 if (isZeroNode(Elt))
2987 NonZeros |= (1 << i);
2992 if (NumNonZero == 0) {
2993 // All undef vector. Return an UNDEF. All zero vectors were handled above.
2994 return DAG.getNode(ISD::UNDEF, VT);
2997 // Special case for single non-zero, non-undef, element.
2998 if (NumNonZero == 1 && NumElems <= 4) {
2999 unsigned Idx = CountTrailingZeros_32(NonZeros);
3000 SDOperand Item = Op.getOperand(Idx);
3002 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3003 // the value are obviously zero, truncate the value to i32 and do the
3004 // insertion that way. Only do this if the value is non-constant or if the
3005 // value is a constant being inserted into element 0. It is cheaper to do
3006 // a constant pool load than it is to do a movd + shuffle.
3007 if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3008 (!IsAllConstants || Idx == 0)) {
3009 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3010 // Handle MMX and SSE both.
3011 MVT::ValueType VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3012 MVT::ValueType VecElts = VT == MVT::v2i64 ? 4 : 2;
3014 // Truncate the value (which may itself be a constant) to i32, and
3015 // convert it to a vector with movd (S2V+shuffle to zero extend).
3016 Item = DAG.getNode(ISD::TRUNCATE, MVT::i32, Item);
3017 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VecVT, Item);
3018 Item = getShuffleVectorZeroOrUndef(Item, 0, true, DAG);
3020 // Now we have our 32-bit value zero extended in the low element of
3021 // a vector. If Idx != 0, swizzle it into place.
3024 Item, DAG.getNode(ISD::UNDEF, Item.getValueType()),
3025 getSwapEltZeroMask(VecElts, Idx, DAG)
3027 Item = DAG.getNode(ISD::VECTOR_SHUFFLE, VecVT, Ops, 3);
3029 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Item);
3033 // If we have a constant or non-constant insertion into the low element of
3034 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3035 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3036 // depending on what the source datatype is. Because we can only get here
3037 // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3039 // Don't do this for i64 values on x86-32.
3040 (EVT != MVT::i64 || Subtarget->is64Bit())) {
3041 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3042 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3043 return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, DAG);
3046 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3049 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3050 // is a non-constant being inserted into an element other than the low one,
3051 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3052 // movd/movss) to move this into the low element, then shuffle it into
3054 if (EVTBits == 32) {
3055 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3057 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3058 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, DAG);
3059 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3060 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3061 SmallVector<SDOperand, 8> MaskVec;
3062 for (unsigned i = 0; i < NumElems; i++)
3063 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3064 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3065 &MaskVec[0], MaskVec.size());
3066 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3067 DAG.getNode(ISD::UNDEF, VT), Mask);
3071 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3072 if (Values.size() == 1)
3075 // A vector full of immediates; various special cases are already
3076 // handled, so this is best done with a single constant-pool load.
3080 // Let legalizer expand 2-wide build_vectors.
3084 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3085 if (EVTBits == 8 && NumElems == 16) {
3086 SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3088 if (V.Val) return V;
3091 if (EVTBits == 16 && NumElems == 8) {
3092 SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3094 if (V.Val) return V;
3097 // If element VT is == 32 bits, turn it into a number of shuffles.
3098 SmallVector<SDOperand, 8> V;
3100 if (NumElems == 4 && NumZero > 0) {
3101 for (unsigned i = 0; i < 4; ++i) {
3102 bool isZero = !(NonZeros & (1 << i));
3104 V[i] = getZeroVector(VT, DAG);
3106 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3109 for (unsigned i = 0; i < 2; ++i) {
3110 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3113 V[i] = V[i*2]; // Must be a zero vector.
3116 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3117 getMOVLMask(NumElems, DAG));
3120 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3121 getMOVLMask(NumElems, DAG));
3124 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3125 getUnpacklMask(NumElems, DAG));
3130 // Take advantage of the fact GR32 to VR128 scalar_to_vector (i.e. movd)
3131 // clears the upper bits.
3132 // FIXME: we can do the same for v4f32 case when we know both parts of
3133 // the lower half come from scalar_to_vector (loadf32). We should do
3134 // that in post legalizer dag combiner with target specific hooks.
3135 if (MVT::isInteger(EVT) && (NonZeros & (0x3 << 2)) == 0)
3137 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3138 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
3139 SmallVector<SDOperand, 8> MaskVec;
3140 bool Reverse = (NonZeros & 0x3) == 2;
3141 for (unsigned i = 0; i < 2; ++i)
3143 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3145 MaskVec.push_back(DAG.getConstant(i, EVT));
3146 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3147 for (unsigned i = 0; i < 2; ++i)
3149 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3151 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3152 SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3153 &MaskVec[0], MaskVec.size());
3154 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3157 if (Values.size() > 2) {
3158 // Expand into a number of unpckl*.
3160 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3161 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3162 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3163 SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
3164 for (unsigned i = 0; i < NumElems; ++i)
3165 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3167 while (NumElems != 0) {
3168 for (unsigned i = 0; i < NumElems; ++i)
3169 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3180 SDOperand LowerVECTOR_SHUFFLEv8i16(SDOperand V1, SDOperand V2,
3181 SDOperand PermMask, SelectionDAG &DAG,
3182 TargetLowering &TLI) {
3184 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(8);
3185 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3186 MVT::ValueType PtrVT = TLI.getPointerTy();
3187 SmallVector<SDOperand, 8> MaskElts(PermMask.Val->op_begin(),
3188 PermMask.Val->op_end());
3190 // First record which half of which vector the low elements come from.
3191 SmallVector<unsigned, 4> LowQuad(4);
3192 for (unsigned i = 0; i < 4; ++i) {
3193 SDOperand Elt = MaskElts[i];
3194 if (Elt.getOpcode() == ISD::UNDEF)
3196 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3197 int QuadIdx = EltIdx / 4;
3200 int BestLowQuad = -1;
3201 unsigned MaxQuad = 1;
3202 for (unsigned i = 0; i < 4; ++i) {
3203 if (LowQuad[i] > MaxQuad) {
3205 MaxQuad = LowQuad[i];
3209 // Record which half of which vector the high elements come from.
3210 SmallVector<unsigned, 4> HighQuad(4);
3211 for (unsigned i = 4; i < 8; ++i) {
3212 SDOperand Elt = MaskElts[i];
3213 if (Elt.getOpcode() == ISD::UNDEF)
3215 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3216 int QuadIdx = EltIdx / 4;
3217 ++HighQuad[QuadIdx];
3219 int BestHighQuad = -1;
3221 for (unsigned i = 0; i < 4; ++i) {
3222 if (HighQuad[i] > MaxQuad) {
3224 MaxQuad = HighQuad[i];
3228 // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3229 if (BestLowQuad != -1 || BestHighQuad != -1) {
3230 // First sort the 4 chunks in order using shufpd.
3231 SmallVector<SDOperand, 8> MaskVec;
3232 if (BestLowQuad != -1)
3233 MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3235 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3236 if (BestHighQuad != -1)
3237 MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3239 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3240 SDOperand Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3241 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3242 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3243 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3244 NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3246 // Now sort high and low parts separately.
3247 BitVector InOrder(8);
3248 if (BestLowQuad != -1) {
3249 // Sort lower half in order using PSHUFLW.
3251 bool AnyOutOrder = false;
3252 for (unsigned i = 0; i != 4; ++i) {
3253 SDOperand Elt = MaskElts[i];
3254 if (Elt.getOpcode() == ISD::UNDEF) {
3255 MaskVec.push_back(Elt);
3258 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3261 MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3262 // If this element is in the right place after this shuffle, then
3264 if ((int)(EltIdx / 4) == BestLowQuad)
3269 for (unsigned i = 4; i != 8; ++i)
3270 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3271 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3272 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3276 if (BestHighQuad != -1) {
3277 // Sort high half in order using PSHUFHW if possible.
3279 for (unsigned i = 0; i != 4; ++i)
3280 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3281 bool AnyOutOrder = false;
3282 for (unsigned i = 4; i != 8; ++i) {
3283 SDOperand Elt = MaskElts[i];
3284 if (Elt.getOpcode() == ISD::UNDEF) {
3285 MaskVec.push_back(Elt);
3288 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3291 MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3292 // If this element is in the right place after this shuffle, then
3294 if ((int)(EltIdx / 4) == BestHighQuad)
3299 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3300 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3304 // The other elements are put in the right place using pextrw and pinsrw.
3305 for (unsigned i = 0; i != 8; ++i) {
3308 SDOperand Elt = MaskElts[i];
3309 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3312 SDOperand ExtOp = (EltIdx < 8)
3313 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3314 DAG.getConstant(EltIdx, PtrVT))
3315 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3316 DAG.getConstant(EltIdx - 8, PtrVT));
3317 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3318 DAG.getConstant(i, PtrVT));
3323 // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use
3324 ///as few as possible.
3325 // First, let's find out how many elements are already in the right order.
3326 unsigned V1InOrder = 0;
3327 unsigned V1FromV1 = 0;
3328 unsigned V2InOrder = 0;
3329 unsigned V2FromV2 = 0;
3330 SmallVector<SDOperand, 8> V1Elts;
3331 SmallVector<SDOperand, 8> V2Elts;
3332 for (unsigned i = 0; i < 8; ++i) {
3333 SDOperand Elt = MaskElts[i];
3334 if (Elt.getOpcode() == ISD::UNDEF) {
3335 V1Elts.push_back(Elt);
3336 V2Elts.push_back(Elt);
3341 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3343 V1Elts.push_back(Elt);
3344 V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3346 } else if (EltIdx == i+8) {
3347 V1Elts.push_back(Elt);
3348 V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3350 } else if (EltIdx < 8) {
3351 V1Elts.push_back(Elt);
3354 V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3359 if (V2InOrder > V1InOrder) {
3360 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3362 std::swap(V1Elts, V2Elts);
3363 std::swap(V1FromV1, V2FromV2);
3366 if ((V1FromV1 + V1InOrder) != 8) {
3367 // Some elements are from V2.
3369 // If there are elements that are from V1 but out of place,
3370 // then first sort them in place
3371 SmallVector<SDOperand, 8> MaskVec;
3372 for (unsigned i = 0; i < 8; ++i) {
3373 SDOperand Elt = V1Elts[i];
3374 if (Elt.getOpcode() == ISD::UNDEF) {
3375 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3378 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3380 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3382 MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3384 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3385 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3389 for (unsigned i = 0; i < 8; ++i) {
3390 SDOperand Elt = V1Elts[i];
3391 if (Elt.getOpcode() == ISD::UNDEF)
3393 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3396 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3397 DAG.getConstant(EltIdx - 8, PtrVT));
3398 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3399 DAG.getConstant(i, PtrVT));
3403 // All elements are from V1.
3405 for (unsigned i = 0; i < 8; ++i) {
3406 SDOperand Elt = V1Elts[i];
3407 if (Elt.getOpcode() == ISD::UNDEF)
3409 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3410 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3411 DAG.getConstant(EltIdx, PtrVT));
3412 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3413 DAG.getConstant(i, PtrVT));
3419 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3420 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3421 /// done when every pair / quad of shuffle mask elements point to elements in
3422 /// the right sequence. e.g.
3423 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3425 SDOperand RewriteAsNarrowerShuffle(SDOperand V1, SDOperand V2,
3427 SDOperand PermMask, SelectionDAG &DAG,
3428 TargetLowering &TLI) {
3429 unsigned NumElems = PermMask.getNumOperands();
3430 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3431 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3432 MVT::ValueType NewVT = MaskVT;
3434 case MVT::v4f32: NewVT = MVT::v2f64; break;
3435 case MVT::v4i32: NewVT = MVT::v2i64; break;
3436 case MVT::v8i16: NewVT = MVT::v4i32; break;
3437 case MVT::v16i8: NewVT = MVT::v4i32; break;
3438 default: assert(false && "Unexpected!");
3441 if (NewWidth == 2) {
3442 if (MVT::isInteger(VT))
3447 unsigned Scale = NumElems / NewWidth;
3448 SmallVector<SDOperand, 8> MaskVec;
3449 for (unsigned i = 0; i < NumElems; i += Scale) {
3450 unsigned StartIdx = ~0U;
3451 for (unsigned j = 0; j < Scale; ++j) {
3452 SDOperand Elt = PermMask.getOperand(i+j);
3453 if (Elt.getOpcode() == ISD::UNDEF)
3455 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3456 if (StartIdx == ~0U)
3457 StartIdx = EltIdx - (EltIdx % Scale);
3458 if (EltIdx != StartIdx + j)
3461 if (StartIdx == ~0U)
3462 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
3464 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MVT::i32));
3467 V1 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V1);
3468 V2 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V2);
3469 return DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, V1, V2,
3470 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3471 &MaskVec[0], MaskVec.size()));
3475 X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
3476 SDOperand V1 = Op.getOperand(0);
3477 SDOperand V2 = Op.getOperand(1);
3478 SDOperand PermMask = Op.getOperand(2);
3479 MVT::ValueType VT = Op.getValueType();
3480 unsigned NumElems = PermMask.getNumOperands();
3481 bool isMMX = MVT::getSizeInBits(VT) == 64;
3482 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3483 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3484 bool V1IsSplat = false;
3485 bool V2IsSplat = false;
3487 if (isUndefShuffle(Op.Val))
3488 return DAG.getNode(ISD::UNDEF, VT);
3490 if (isZeroShuffle(Op.Val))
3491 return getZeroVector(VT, DAG);
3493 if (isIdentityMask(PermMask.Val))
3495 else if (isIdentityMask(PermMask.Val, true))
3498 if (isSplatMask(PermMask.Val)) {
3499 if (isMMX || NumElems < 4) return Op;
3500 // Promote it to a v4{if}32 splat.
3501 return PromoteSplat(Op, DAG, Subtarget->hasSSE2());
3504 // If the shuffle can be profitably rewritten as a narrower shuffle, then
3506 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3507 SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3509 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3510 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3511 // FIXME: Figure out a cleaner way to do this.
3512 // Try to make use of movq to zero out the top part.
3513 if (ISD::isBuildVectorAllZeros(V2.Val)) {
3514 SDOperand NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3516 SDOperand NewV1 = NewOp.getOperand(0);
3517 SDOperand NewV2 = NewOp.getOperand(1);
3518 SDOperand NewMask = NewOp.getOperand(2);
3519 if (isCommutedMOVL(NewMask.Val, true, false)) {
3520 NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
3521 NewOp = DAG.getNode(ISD::VECTOR_SHUFFLE, NewOp.getValueType(),
3522 NewV1, NewV2, getMOVLMask(2, DAG));
3523 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3526 } else if (ISD::isBuildVectorAllZeros(V1.Val)) {
3527 SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3528 if (NewOp.Val && X86::isMOVLMask(NewOp.getOperand(2).Val))
3529 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3533 if (X86::isMOVLMask(PermMask.Val))
3534 return (V1IsUndef) ? V2 : Op;
3536 if (X86::isMOVSHDUPMask(PermMask.Val) ||
3537 X86::isMOVSLDUPMask(PermMask.Val) ||
3538 X86::isMOVHLPSMask(PermMask.Val) ||
3539 X86::isMOVHPMask(PermMask.Val) ||
3540 X86::isMOVLPMask(PermMask.Val))
3543 if (ShouldXformToMOVHLPS(PermMask.Val) ||
3544 ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
3545 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3547 bool Commuted = false;
3548 // FIXME: This should also accept a bitcast of a splat? Be careful, not
3549 // 1,1,1,1 -> v8i16 though.
3550 V1IsSplat = isSplatVector(V1.Val);
3551 V2IsSplat = isSplatVector(V2.Val);
3553 // Canonicalize the splat or undef, if present, to be on the RHS.
3554 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3555 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3556 std::swap(V1IsSplat, V2IsSplat);
3557 std::swap(V1IsUndef, V2IsUndef);
3561 // FIXME: Figure out a cleaner way to do this.
3562 if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
3563 if (V2IsUndef) return V1;
3564 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3566 // V2 is a splat, so the mask may be malformed. That is, it may point
3567 // to any V2 element. The instruction selectior won't like this. Get
3568 // a corrected mask and commute to form a proper MOVS{S|D}.
3569 SDOperand NewMask = getMOVLMask(NumElems, DAG);
3570 if (NewMask.Val != PermMask.Val)
3571 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3576 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3577 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3578 X86::isUNPCKLMask(PermMask.Val) ||
3579 X86::isUNPCKHMask(PermMask.Val))
3583 // Normalize mask so all entries that point to V2 points to its first
3584 // element then try to match unpck{h|l} again. If match, return a
3585 // new vector_shuffle with the corrected mask.
3586 SDOperand NewMask = NormalizeMask(PermMask, DAG);
3587 if (NewMask.Val != PermMask.Val) {
3588 if (X86::isUNPCKLMask(PermMask.Val, true)) {
3589 SDOperand NewMask = getUnpacklMask(NumElems, DAG);
3590 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3591 } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
3592 SDOperand NewMask = getUnpackhMask(NumElems, DAG);
3593 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3598 // Normalize the node to match x86 shuffle ops if needed
3599 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
3600 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3603 // Commute is back and try unpck* again.
3604 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3605 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3606 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3607 X86::isUNPCKLMask(PermMask.Val) ||
3608 X86::isUNPCKHMask(PermMask.Val))
3612 // Try PSHUF* first, then SHUFP*.
3613 // MMX doesn't have PSHUFD but it does have PSHUFW. While it's theoretically
3614 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
3615 if (isMMX && NumElems == 4 && X86::isPSHUFDMask(PermMask.Val)) {
3616 if (V2.getOpcode() != ISD::UNDEF)
3617 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3618 DAG.getNode(ISD::UNDEF, VT), PermMask);
3623 if (Subtarget->hasSSE2() &&
3624 (X86::isPSHUFDMask(PermMask.Val) ||
3625 X86::isPSHUFHWMask(PermMask.Val) ||
3626 X86::isPSHUFLWMask(PermMask.Val))) {
3627 MVT::ValueType RVT = VT;
3628 if (VT == MVT::v4f32) {
3630 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT,
3631 DAG.getNode(ISD::BIT_CONVERT, RVT, V1),
3632 DAG.getNode(ISD::UNDEF, RVT), PermMask);
3633 } else if (V2.getOpcode() != ISD::UNDEF)
3634 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT, V1,
3635 DAG.getNode(ISD::UNDEF, RVT), PermMask);
3637 Op = DAG.getNode(ISD::BIT_CONVERT, VT, Op);
3641 // Binary or unary shufps.
3642 if (X86::isSHUFPMask(PermMask.Val) ||
3643 (V2.getOpcode() == ISD::UNDEF && X86::isPSHUFDMask(PermMask.Val)))
3647 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
3648 if (VT == MVT::v8i16) {
3649 SDOperand NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
3654 // Handle all 4 wide cases with a number of shuffles.
3655 if (NumElems == 4 && !isMMX) {
3656 // Don't do this for MMX.
3657 MVT::ValueType MaskVT = PermMask.getValueType();
3658 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3659 SmallVector<std::pair<int, int>, 8> Locs;
3660 Locs.reserve(NumElems);
3661 SmallVector<SDOperand, 8> Mask1(NumElems,
3662 DAG.getNode(ISD::UNDEF, MaskEVT));
3663 SmallVector<SDOperand, 8> Mask2(NumElems,
3664 DAG.getNode(ISD::UNDEF, MaskEVT));
3667 // If no more than two elements come from either vector. This can be
3668 // implemented with two shuffles. First shuffle gather the elements.
3669 // The second shuffle, which takes the first shuffle as both of its
3670 // vector operands, put the elements into the right order.
3671 for (unsigned i = 0; i != NumElems; ++i) {
3672 SDOperand Elt = PermMask.getOperand(i);
3673 if (Elt.getOpcode() == ISD::UNDEF) {
3674 Locs[i] = std::make_pair(-1, -1);
3676 unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3677 if (Val < NumElems) {
3678 Locs[i] = std::make_pair(0, NumLo);
3682 Locs[i] = std::make_pair(1, NumHi);
3683 if (2+NumHi < NumElems)
3684 Mask1[2+NumHi] = Elt;
3689 if (NumLo <= 2 && NumHi <= 2) {
3690 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3691 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3692 &Mask1[0], Mask1.size()));
3693 for (unsigned i = 0; i != NumElems; ++i) {
3694 if (Locs[i].first == -1)
3697 unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
3698 Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
3699 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3703 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3704 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3705 &Mask2[0], Mask2.size()));
3708 // Break it into (shuffle shuffle_hi, shuffle_lo).
3710 SmallVector<SDOperand,8> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3711 SmallVector<SDOperand,8> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3712 SmallVector<SDOperand,8> *MaskPtr = &LoMask;
3713 unsigned MaskIdx = 0;
3715 unsigned HiIdx = NumElems/2;
3716 for (unsigned i = 0; i != NumElems; ++i) {
3717 if (i == NumElems/2) {
3723 SDOperand Elt = PermMask.getOperand(i);
3724 if (Elt.getOpcode() == ISD::UNDEF) {
3725 Locs[i] = std::make_pair(-1, -1);
3726 } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
3727 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3728 (*MaskPtr)[LoIdx] = Elt;
3731 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3732 (*MaskPtr)[HiIdx] = Elt;
3737 SDOperand LoShuffle =
3738 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3739 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3740 &LoMask[0], LoMask.size()));
3741 SDOperand HiShuffle =
3742 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3743 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3744 &HiMask[0], HiMask.size()));
3745 SmallVector<SDOperand, 8> MaskOps;
3746 for (unsigned i = 0; i != NumElems; ++i) {
3747 if (Locs[i].first == -1) {
3748 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3750 unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
3751 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3754 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3755 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3756 &MaskOps[0], MaskOps.size()));
3763 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDOperand Op,
3764 SelectionDAG &DAG) {
3765 MVT::ValueType VT = Op.getValueType();
3766 if (MVT::getSizeInBits(VT) == 8) {
3767 SDOperand Extract = DAG.getNode(X86ISD::PEXTRB, MVT::i32,
3768 Op.getOperand(0), Op.getOperand(1));
3769 SDOperand Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
3770 DAG.getValueType(VT));
3771 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3772 } else if (MVT::getSizeInBits(VT) == 16) {
3773 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, MVT::i32,
3774 Op.getOperand(0), Op.getOperand(1));
3775 SDOperand Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
3776 DAG.getValueType(VT));
3777 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3778 } else if (VT == MVT::f32) {
3779 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
3780 // the result back to FR32 register. It's only worth matching if the
3781 // result has a single use which is a store or a bitcast to i32.
3782 if (!Op.hasOneUse())
3784 SDNode *User = Op.Val->use_begin()->getUser();
3785 if (User->getOpcode() != ISD::STORE &&
3786 (User->getOpcode() != ISD::BIT_CONVERT ||
3787 User->getValueType(0) != MVT::i32))
3789 SDOperand Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
3790 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Op.getOperand(0)),
3792 return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, Extract);
3799 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3800 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3803 if (Subtarget->hasSSE41()) {
3804 SDOperand Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
3809 MVT::ValueType VT = Op.getValueType();
3810 // TODO: handle v16i8.
3811 if (MVT::getSizeInBits(VT) == 16) {
3812 SDOperand Vec = Op.getOperand(0);
3813 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3815 return DAG.getNode(ISD::TRUNCATE, MVT::i16,
3816 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
3817 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
3819 // Transform it so it match pextrw which produces a 32-bit result.
3820 MVT::ValueType EVT = (MVT::ValueType)(VT+1);
3821 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
3822 Op.getOperand(0), Op.getOperand(1));
3823 SDOperand Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
3824 DAG.getValueType(VT));
3825 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3826 } else if (MVT::getSizeInBits(VT) == 32) {
3827 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3830 // SHUFPS the element to the lowest double word, then movss.
3831 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3832 SmallVector<SDOperand, 8> IdxVec;
3834 push_back(DAG.getConstant(Idx, MVT::getVectorElementType(MaskVT)));
3836 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3838 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3840 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3841 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3842 &IdxVec[0], IdxVec.size());
3843 SDOperand Vec = Op.getOperand(0);
3844 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3845 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3846 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3847 DAG.getIntPtrConstant(0));
3848 } else if (MVT::getSizeInBits(VT) == 64) {
3849 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
3850 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
3851 // to match extract_elt for f64.
3852 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3856 // UNPCKHPD the element to the lowest double word, then movsd.
3857 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
3858 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
3859 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3860 SmallVector<SDOperand, 8> IdxVec;
3861 IdxVec.push_back(DAG.getConstant(1, MVT::getVectorElementType(MaskVT)));
3863 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3864 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3865 &IdxVec[0], IdxVec.size());
3866 SDOperand Vec = Op.getOperand(0);
3867 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3868 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3869 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3870 DAG.getIntPtrConstant(0));
3877 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDOperand Op, SelectionDAG &DAG){
3878 MVT::ValueType VT = Op.getValueType();
3879 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3881 SDOperand N0 = Op.getOperand(0);
3882 SDOperand N1 = Op.getOperand(1);
3883 SDOperand N2 = Op.getOperand(2);
3885 if ((MVT::getSizeInBits(EVT) == 8) || (MVT::getSizeInBits(EVT) == 16)) {
3886 unsigned Opc = (MVT::getSizeInBits(EVT) == 8) ? X86ISD::PINSRB
3888 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
3890 if (N1.getValueType() != MVT::i32)
3891 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3892 if (N2.getValueType() != MVT::i32)
3893 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
3894 return DAG.getNode(Opc, VT, N0, N1, N2);
3895 } else if (EVT == MVT::f32) {
3896 // Bits [7:6] of the constant are the source select. This will always be
3897 // zero here. The DAG Combiner may combine an extract_elt index into these
3898 // bits. For example (insert (extract, 3), 2) could be matched by putting
3899 // the '3' into bits [7:6] of X86ISD::INSERTPS.
3900 // Bits [5:4] of the constant are the destination select. This is the
3901 // value of the incoming immediate.
3902 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
3903 // combine either bitwise AND or insert of float 0.0 to set these bits.
3904 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue() << 4);
3905 return DAG.getNode(X86ISD::INSERTPS, VT, N0, N1, N2);
3911 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3912 MVT::ValueType VT = Op.getValueType();
3913 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3915 if (Subtarget->hasSSE41())
3916 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
3921 SDOperand N0 = Op.getOperand(0);
3922 SDOperand N1 = Op.getOperand(1);
3923 SDOperand N2 = Op.getOperand(2);
3925 if (MVT::getSizeInBits(EVT) == 16) {
3926 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
3927 // as its second argument.
3928 if (N1.getValueType() != MVT::i32)
3929 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3930 if (N2.getValueType() != MVT::i32)
3931 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
3932 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
3938 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3939 SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
3940 MVT::ValueType VT = MVT::v2i32;
3941 switch (Op.getValueType()) {
3948 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(),
3949 DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, AnyExt));
3952 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3953 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
3954 // one of the above mentioned nodes. It has to be wrapped because otherwise
3955 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3956 // be used to form addressing mode. These wrapped nodes will be selected
3959 X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
3960 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3961 SDOperand Result = DAG.getTargetConstantPool(CP->getConstVal(),
3963 CP->getAlignment());
3964 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3965 // With PIC, the address is actually $g + Offset.
3966 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3967 !Subtarget->isPICStyleRIPRel()) {
3968 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3969 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3977 X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
3978 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3979 SDOperand Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
3980 // If it's a debug information descriptor, don't mess with it.
3981 if (DAG.isVerifiedDebugInfoDesc(Op))
3983 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3984 // With PIC, the address is actually $g + Offset.
3985 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3986 !Subtarget->isPICStyleRIPRel()) {
3987 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3988 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3992 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
3993 // load the value at address GV, not the value of GV itself. This means that
3994 // the GlobalAddress must be in the base or index register of the address, not
3995 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
3996 // The same applies for external symbols during PIC codegen
3997 if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
3998 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
3999 PseudoSourceValue::getGOT(), 0);
4004 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
4006 LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4007 const MVT::ValueType PtrVT) {
4009 SDOperand Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
4010 DAG.getNode(X86ISD::GlobalBaseReg,
4012 InFlag = Chain.getValue(1);
4014 // emit leal symbol@TLSGD(,%ebx,1), %eax
4015 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4016 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4017 GA->getValueType(0),
4019 SDOperand Ops[] = { Chain, TGA, InFlag };
4020 SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
4021 InFlag = Result.getValue(2);
4022 Chain = Result.getValue(1);
4024 // call ___tls_get_addr. This function receives its argument in
4025 // the register EAX.
4026 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
4027 InFlag = Chain.getValue(1);
4029 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4030 SDOperand Ops1[] = { Chain,
4031 DAG.getTargetExternalSymbol("___tls_get_addr",
4033 DAG.getRegister(X86::EAX, PtrVT),
4034 DAG.getRegister(X86::EBX, PtrVT),
4036 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
4037 InFlag = Chain.getValue(1);
4039 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
4042 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4043 // "local exec" model.
4045 LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4046 const MVT::ValueType PtrVT) {
4047 // Get the Thread Pointer
4048 SDOperand ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4049 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4051 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4052 GA->getValueType(0),
4054 SDOperand Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4056 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4057 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
4058 PseudoSourceValue::getGOT(), 0);
4060 // The address of the thread local variable is the add of the thread
4061 // pointer with the offset of the variable.
4062 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4066 X86TargetLowering::LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
4067 // TODO: implement the "local dynamic" model
4068 // TODO: implement the "initial exec"model for pic executables
4069 assert(!Subtarget->is64Bit() && Subtarget->isTargetELF() &&
4070 "TLS not implemented for non-ELF and 64-bit targets");
4071 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4072 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4073 // otherwise use the "Local Exec"TLS Model
4074 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4075 return LowerToTLSGeneralDynamicModel(GA, DAG, getPointerTy());
4077 return LowerToTLSExecModel(GA, DAG, getPointerTy());
4081 X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
4082 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4083 SDOperand Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
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()),
4096 SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
4097 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4098 SDOperand Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4099 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4100 // With PIC, the address is actually $g + Offset.
4101 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4102 !Subtarget->isPICStyleRIPRel()) {
4103 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4104 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4111 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4112 /// take a 2 x i32 value to shift plus a shift amount.
4113 SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
4114 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4115 MVT::ValueType VT = Op.getValueType();
4116 unsigned VTBits = MVT::getSizeInBits(VT);
4117 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4118 SDOperand ShOpLo = Op.getOperand(0);
4119 SDOperand ShOpHi = Op.getOperand(1);
4120 SDOperand ShAmt = Op.getOperand(2);
4121 SDOperand Tmp1 = isSRA ?
4122 DAG.getNode(ISD::SRA, VT, ShOpHi, DAG.getConstant(VTBits - 1, MVT::i8)) :
4123 DAG.getConstant(0, VT);
4125 SDOperand Tmp2, Tmp3;
4126 if (Op.getOpcode() == ISD::SHL_PARTS) {
4127 Tmp2 = DAG.getNode(X86ISD::SHLD, VT, ShOpHi, ShOpLo, ShAmt);
4128 Tmp3 = DAG.getNode(ISD::SHL, VT, ShOpLo, ShAmt);
4130 Tmp2 = DAG.getNode(X86ISD::SHRD, VT, ShOpLo, ShOpHi, ShAmt);
4131 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, VT, ShOpHi, ShAmt);
4134 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
4135 SDOperand AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4136 DAG.getConstant(VTBits, MVT::i8));
4137 SDOperand Cond = DAG.getNode(X86ISD::CMP, VT,
4138 AndNode, DAG.getConstant(0, MVT::i8));
4141 SDOperand CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4142 VTs = DAG.getNodeValueTypes(VT, MVT::Flag);
4143 SmallVector<SDOperand, 4> Ops;
4144 if (Op.getOpcode() == ISD::SHL_PARTS) {
4145 Ops.push_back(Tmp2);
4146 Ops.push_back(Tmp3);
4148 Ops.push_back(Cond);
4149 Hi = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4152 Ops.push_back(Tmp3);
4153 Ops.push_back(Tmp1);
4155 Ops.push_back(Cond);
4156 Lo = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4158 Ops.push_back(Tmp2);
4159 Ops.push_back(Tmp3);
4161 Ops.push_back(Cond);
4162 Lo = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4165 Ops.push_back(Tmp3);
4166 Ops.push_back(Tmp1);
4168 Ops.push_back(Cond);
4169 Hi = DAG.getNode(X86ISD::CMOV, VT, &Ops[0], Ops.size());
4172 VTs = DAG.getNodeValueTypes(VT, VT);
4176 return DAG.getNode(ISD::MERGE_VALUES, VTs, 2, &Ops[0], Ops.size());
4179 SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
4180 MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
4181 assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
4182 "Unknown SINT_TO_FP to lower!");
4184 // These are really Legal; caller falls through into that case.
4185 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4187 if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 &&
4188 Subtarget->is64Bit())
4191 unsigned Size = MVT::getSizeInBits(SrcVT)/8;
4192 MachineFunction &MF = DAG.getMachineFunction();
4193 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4194 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4195 SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4197 PseudoSourceValue::getFixedStack(),
4202 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4204 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4206 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4207 SmallVector<SDOperand, 8> Ops;
4208 Ops.push_back(Chain);
4209 Ops.push_back(StackSlot);
4210 Ops.push_back(DAG.getValueType(SrcVT));
4211 SDOperand Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD,
4212 Tys, &Ops[0], Ops.size());
4215 Chain = Result.getValue(1);
4216 SDOperand InFlag = Result.getValue(2);
4218 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4219 // shouldn't be necessary except that RFP cannot be live across
4220 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4221 MachineFunction &MF = DAG.getMachineFunction();
4222 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4223 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4224 Tys = DAG.getVTList(MVT::Other);
4225 SmallVector<SDOperand, 8> Ops;
4226 Ops.push_back(Chain);
4227 Ops.push_back(Result);
4228 Ops.push_back(StackSlot);
4229 Ops.push_back(DAG.getValueType(Op.getValueType()));
4230 Ops.push_back(InFlag);
4231 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4232 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
4233 PseudoSourceValue::getFixedStack(), SSFI);
4239 std::pair<SDOperand,SDOperand> X86TargetLowering::
4240 FP_TO_SINTHelper(SDOperand Op, SelectionDAG &DAG) {
4241 assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
4242 "Unknown FP_TO_SINT to lower!");
4244 // These are really Legal.
4245 if (Op.getValueType() == MVT::i32 &&
4246 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4247 return std::make_pair(SDOperand(), SDOperand());
4248 if (Subtarget->is64Bit() &&
4249 Op.getValueType() == MVT::i64 &&
4250 Op.getOperand(0).getValueType() != MVT::f80)
4251 return std::make_pair(SDOperand(), SDOperand());
4253 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4255 MachineFunction &MF = DAG.getMachineFunction();
4256 unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
4257 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4258 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4260 switch (Op.getValueType()) {
4261 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4262 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4263 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4264 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4267 SDOperand Chain = DAG.getEntryNode();
4268 SDOperand Value = Op.getOperand(0);
4269 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4270 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4271 Chain = DAG.getStore(Chain, Value, StackSlot,
4272 PseudoSourceValue::getFixedStack(), SSFI);
4273 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4275 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4277 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4278 Chain = Value.getValue(1);
4279 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4280 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4283 // Build the FP_TO_INT*_IN_MEM
4284 SDOperand Ops[] = { Chain, Value, StackSlot };
4285 SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4287 return std::make_pair(FIST, StackSlot);
4290 SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
4291 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(Op, DAG);
4292 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4293 if (FIST.Val == 0) return SDOperand();
4296 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4299 SDNode *X86TargetLowering::ExpandFP_TO_SINT(SDNode *N, SelectionDAG &DAG) {
4300 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(SDOperand(N, 0), DAG);
4301 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4302 if (FIST.Val == 0) return 0;
4304 // Return an i64 load from the stack slot.
4305 SDOperand Res = DAG.getLoad(MVT::i64, FIST, StackSlot, NULL, 0);
4307 // Use a MERGE_VALUES node to drop the chain result value.
4308 return DAG.getNode(ISD::MERGE_VALUES, MVT::i64, Res).Val;
4311 SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
4312 MVT::ValueType VT = Op.getValueType();
4313 MVT::ValueType EltVT = VT;
4314 if (MVT::isVector(VT))
4315 EltVT = MVT::getVectorElementType(VT);
4316 std::vector<Constant*> CV;
4317 if (EltVT == MVT::f64) {
4318 Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
4322 Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
4328 Constant *C = ConstantVector::get(CV);
4329 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4330 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4331 PseudoSourceValue::getConstantPool(), 0,
4333 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4336 SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
4337 MVT::ValueType VT = Op.getValueType();
4338 MVT::ValueType EltVT = VT;
4339 unsigned EltNum = 1;
4340 if (MVT::isVector(VT)) {
4341 EltVT = MVT::getVectorElementType(VT);
4342 EltNum = MVT::getVectorNumElements(VT);
4344 std::vector<Constant*> CV;
4345 if (EltVT == MVT::f64) {
4346 Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
4350 Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
4356 Constant *C = ConstantVector::get(CV);
4357 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4358 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4359 PseudoSourceValue::getConstantPool(), 0,
4361 if (MVT::isVector(VT)) {
4362 return DAG.getNode(ISD::BIT_CONVERT, VT,
4363 DAG.getNode(ISD::XOR, MVT::v2i64,
4364 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4365 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4367 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4371 SDOperand X86TargetLowering::LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
4372 SDOperand Op0 = Op.getOperand(0);
4373 SDOperand Op1 = Op.getOperand(1);
4374 MVT::ValueType VT = Op.getValueType();
4375 MVT::ValueType SrcVT = Op1.getValueType();
4377 // If second operand is smaller, extend it first.
4378 if (MVT::getSizeInBits(SrcVT) < MVT::getSizeInBits(VT)) {
4379 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4382 // And if it is bigger, shrink it first.
4383 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4384 Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1, DAG.getIntPtrConstant(1));
4388 // At this point the operands and the result should have the same
4389 // type, and that won't be f80 since that is not custom lowered.
4391 // First get the sign bit of second operand.
4392 std::vector<Constant*> CV;
4393 if (SrcVT == MVT::f64) {
4394 CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
4395 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4397 CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
4398 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4399 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4400 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4402 Constant *C = ConstantVector::get(CV);
4403 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4404 SDOperand Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx,
4405 PseudoSourceValue::getConstantPool(), 0,
4407 SDOperand SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4409 // Shift sign bit right or left if the two operands have different types.
4410 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4411 // Op0 is MVT::f32, Op1 is MVT::f64.
4412 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4413 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4414 DAG.getConstant(32, MVT::i32));
4415 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4416 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4417 DAG.getIntPtrConstant(0));
4420 // Clear first operand sign bit.
4422 if (VT == MVT::f64) {
4423 CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
4424 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4426 CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
4427 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4428 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4429 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4431 C = ConstantVector::get(CV);
4432 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4433 SDOperand Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4434 PseudoSourceValue::getConstantPool(), 0,
4436 SDOperand Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4438 // Or the value with the sign bit.
4439 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4442 SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG) {
4443 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
4445 SDOperand Op0 = Op.getOperand(0);
4446 SDOperand Op1 = Op.getOperand(1);
4447 SDOperand CC = Op.getOperand(2);
4448 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4449 bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
4452 if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
4454 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4455 return DAG.getNode(X86ISD::SETCC, MVT::i8,
4456 DAG.getConstant(X86CC, MVT::i8), Cond);
4459 assert(isFP && "Illegal integer SetCC!");
4461 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4462 switch (SetCCOpcode) {
4463 default: assert(false && "Illegal floating point SetCC!");
4464 case ISD::SETOEQ: { // !PF & ZF
4465 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4466 DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
4467 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4468 DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4469 return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4471 case ISD::SETUNE: { // PF | !ZF
4472 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4473 DAG.getConstant(X86::COND_P, MVT::i8), Cond);
4474 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4475 DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4476 return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4482 SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
4483 bool addTest = true;
4484 SDOperand Cond = Op.getOperand(0);
4487 if (Cond.getOpcode() == ISD::SETCC)
4488 Cond = LowerSETCC(Cond, DAG);
4490 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4491 // setting operand in place of the X86ISD::SETCC.
4492 if (Cond.getOpcode() == X86ISD::SETCC) {
4493 CC = Cond.getOperand(0);
4495 SDOperand Cmp = Cond.getOperand(1);
4496 unsigned Opc = Cmp.getOpcode();
4497 MVT::ValueType VT = Op.getValueType();
4499 bool IllegalFPCMov = false;
4500 if (MVT::isFloatingPoint(VT) && !MVT::isVector(VT) &&
4501 !isScalarFPTypeInSSEReg(VT)) // FPStack?
4502 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4504 if ((Opc == X86ISD::CMP ||
4505 Opc == X86ISD::COMI ||
4506 Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
4513 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4514 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4517 const MVT::ValueType *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4519 SmallVector<SDOperand, 4> Ops;
4520 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4521 // condition is true.
4522 Ops.push_back(Op.getOperand(2));
4523 Ops.push_back(Op.getOperand(1));
4525 Ops.push_back(Cond);
4526 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
4529 SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
4530 bool addTest = true;
4531 SDOperand Chain = Op.getOperand(0);
4532 SDOperand Cond = Op.getOperand(1);
4533 SDOperand Dest = Op.getOperand(2);
4536 if (Cond.getOpcode() == ISD::SETCC)
4537 Cond = LowerSETCC(Cond, DAG);
4539 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4540 // setting operand in place of the X86ISD::SETCC.
4541 if (Cond.getOpcode() == X86ISD::SETCC) {
4542 CC = Cond.getOperand(0);
4544 SDOperand Cmp = Cond.getOperand(1);
4545 unsigned Opc = Cmp.getOpcode();
4546 if (Opc == X86ISD::CMP ||
4547 Opc == X86ISD::COMI ||
4548 Opc == X86ISD::UCOMI) {
4555 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4556 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4558 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
4559 Chain, Op.getOperand(2), CC, Cond);
4563 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
4564 // Calls to _alloca is needed to probe the stack when allocating more than 4k
4565 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
4566 // that the guard pages used by the OS virtual memory manager are allocated in
4567 // correct sequence.
4569 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDOperand Op,
4570 SelectionDAG &DAG) {
4571 assert(Subtarget->isTargetCygMing() &&
4572 "This should be used only on Cygwin/Mingw targets");
4575 SDOperand Chain = Op.getOperand(0);
4576 SDOperand Size = Op.getOperand(1);
4577 // FIXME: Ensure alignment here
4581 MVT::ValueType IntPtr = getPointerTy();
4582 MVT::ValueType SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
4584 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
4585 Flag = Chain.getValue(1);
4587 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4588 SDOperand Ops[] = { Chain,
4589 DAG.getTargetExternalSymbol("_alloca", IntPtr),
4590 DAG.getRegister(X86::EAX, IntPtr),
4592 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 4);
4593 Flag = Chain.getValue(1);
4595 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
4597 std::vector<MVT::ValueType> Tys;
4598 Tys.push_back(SPTy);
4599 Tys.push_back(MVT::Other);
4600 SDOperand Ops1[2] = { Chain.getValue(0), Chain };
4601 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops1, 2);
4605 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG,
4607 SDOperand Dst, SDOperand Src,
4608 SDOperand Size, unsigned Align,
4609 const Value *DstSV, uint64_t DstSVOff) {
4610 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
4612 /// If not DWORD aligned or size is more than the threshold, call the library.
4613 /// The libc version is likely to be faster for these cases. It can use the
4614 /// address value and run time information about the CPU.
4615 if ((Align & 3) == 0 ||
4617 ConstantSize->getValue() > getSubtarget()->getMaxInlineSizeThreshold()) {
4618 SDOperand InFlag(0, 0);
4620 // Check to see if there is a specialized entry-point for memory zeroing.
4621 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
4622 if (const char *bzeroEntry =
4623 V && V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
4624 MVT::ValueType IntPtr = getPointerTy();
4625 const Type *IntPtrTy = getTargetData()->getIntPtrType();
4626 TargetLowering::ArgListTy Args;
4627 TargetLowering::ArgListEntry Entry;
4629 Entry.Ty = IntPtrTy;
4630 Args.push_back(Entry);
4632 Args.push_back(Entry);
4633 std::pair<SDOperand,SDOperand> CallResult =
4634 LowerCallTo(Chain, Type::VoidTy, false, false, false, CallingConv::C,
4635 false, DAG.getExternalSymbol(bzeroEntry, IntPtr),
4637 return CallResult.second;
4640 // Otherwise have the target-independent code call memset.
4644 uint64_t SizeVal = ConstantSize->getValue();
4645 SDOperand InFlag(0, 0);
4648 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
4649 unsigned BytesLeft = 0;
4650 bool TwoRepStos = false;
4653 uint64_t Val = ValC->getValue() & 255;
4655 // If the value is a constant, then we can potentially use larger sets.
4656 switch (Align & 3) {
4657 case 2: // WORD aligned
4660 Val = (Val << 8) | Val;
4662 case 0: // DWORD aligned
4665 Val = (Val << 8) | Val;
4666 Val = (Val << 16) | Val;
4667 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
4670 Val = (Val << 32) | Val;
4673 default: // Byte aligned
4676 Count = DAG.getIntPtrConstant(SizeVal);
4680 if (AVT > MVT::i8) {
4681 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4682 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
4683 BytesLeft = SizeVal % UBytes;
4686 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
4688 InFlag = Chain.getValue(1);
4691 Count = DAG.getIntPtrConstant(SizeVal);
4692 Chain = DAG.getCopyToReg(Chain, X86::AL, Src, InFlag);
4693 InFlag = Chain.getValue(1);
4696 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4698 InFlag = Chain.getValue(1);
4699 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4701 InFlag = Chain.getValue(1);
4703 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4704 SmallVector<SDOperand, 8> Ops;
4705 Ops.push_back(Chain);
4706 Ops.push_back(DAG.getValueType(AVT));
4707 Ops.push_back(InFlag);
4708 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4711 InFlag = Chain.getValue(1);
4713 MVT::ValueType CVT = Count.getValueType();
4714 SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
4715 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
4716 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
4718 InFlag = Chain.getValue(1);
4719 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4721 Ops.push_back(Chain);
4722 Ops.push_back(DAG.getValueType(MVT::i8));
4723 Ops.push_back(InFlag);
4724 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4725 } else if (BytesLeft) {
4726 // Handle the last 1 - 7 bytes.
4727 unsigned Offset = SizeVal - BytesLeft;
4728 MVT::ValueType AddrVT = Dst.getValueType();
4729 MVT::ValueType SizeVT = Size.getValueType();
4731 Chain = DAG.getMemset(Chain,
4732 DAG.getNode(ISD::ADD, AddrVT, Dst,
4733 DAG.getConstant(Offset, AddrVT)),
4735 DAG.getConstant(BytesLeft, SizeVT),
4736 Align, DstSV, DstSVOff + Offset);
4739 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
4744 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG,
4746 SDOperand Dst, SDOperand Src,
4747 SDOperand Size, unsigned Align,
4749 const Value *DstSV, uint64_t DstSVOff,
4750 const Value *SrcSV, uint64_t SrcSVOff){
4752 // This requires the copy size to be a constant, preferrably
4753 // within a subtarget-specific limit.
4754 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
4757 uint64_t SizeVal = ConstantSize->getValue();
4758 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
4762 unsigned BytesLeft = 0;
4763 if (Align >= 8 && Subtarget->is64Bit())
4765 else if (Align >= 4)
4767 else if (Align >= 2)
4772 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4773 unsigned CountVal = SizeVal / UBytes;
4774 SDOperand Count = DAG.getIntPtrConstant(CountVal);
4775 BytesLeft = SizeVal % UBytes;
4777 SDOperand InFlag(0, 0);
4778 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4780 InFlag = Chain.getValue(1);
4781 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4783 InFlag = Chain.getValue(1);
4784 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
4786 InFlag = Chain.getValue(1);
4788 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4789 SmallVector<SDOperand, 8> Ops;
4790 Ops.push_back(Chain);
4791 Ops.push_back(DAG.getValueType(AVT));
4792 Ops.push_back(InFlag);
4793 SDOperand RepMovs = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
4795 SmallVector<SDOperand, 4> Results;
4796 Results.push_back(RepMovs);
4798 // Handle the last 1 - 7 bytes.
4799 unsigned Offset = SizeVal - BytesLeft;
4800 MVT::ValueType DstVT = Dst.getValueType();
4801 MVT::ValueType SrcVT = Src.getValueType();
4802 MVT::ValueType SizeVT = Size.getValueType();
4803 Results.push_back(DAG.getMemcpy(Chain,
4804 DAG.getNode(ISD::ADD, DstVT, Dst,
4805 DAG.getConstant(Offset, DstVT)),
4806 DAG.getNode(ISD::ADD, SrcVT, Src,
4807 DAG.getConstant(Offset, SrcVT)),
4808 DAG.getConstant(BytesLeft, SizeVT),
4809 Align, AlwaysInline,
4810 DstSV, DstSVOff + Offset,
4811 SrcSV, SrcSVOff + Offset));
4814 return DAG.getNode(ISD::TokenFactor, MVT::Other, &Results[0], Results.size());
4817 /// Expand the result of: i64,outchain = READCYCLECOUNTER inchain
4818 SDNode *X86TargetLowering::ExpandREADCYCLECOUNTER(SDNode *N, SelectionDAG &DAG){
4819 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4820 SDOperand TheChain = N->getOperand(0);
4821 SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
4822 if (Subtarget->is64Bit()) {
4823 SDOperand rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
4824 SDOperand rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX,
4825 MVT::i64, rax.getValue(2));
4826 SDOperand Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
4827 DAG.getConstant(32, MVT::i8));
4829 DAG.getNode(ISD::OR, MVT::i64, rax, Tmp), rdx.getValue(1)
4832 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4833 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4836 SDOperand eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
4837 SDOperand edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX,
4838 MVT::i32, eax.getValue(2));
4839 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
4840 SDOperand Ops[] = { eax, edx };
4841 Ops[0] = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2);
4843 // Use a MERGE_VALUES to return the value and chain.
4844 Ops[1] = edx.getValue(1);
4845 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4846 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4849 SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
4850 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4852 if (!Subtarget->is64Bit()) {
4853 // vastart just stores the address of the VarArgsFrameIndex slot into the
4854 // memory location argument.
4855 SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4856 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV, 0);
4860 // gp_offset (0 - 6 * 8)
4861 // fp_offset (48 - 48 + 8 * 16)
4862 // overflow_arg_area (point to parameters coming in memory).
4864 SmallVector<SDOperand, 8> MemOps;
4865 SDOperand FIN = Op.getOperand(1);
4867 SDOperand Store = DAG.getStore(Op.getOperand(0),
4868 DAG.getConstant(VarArgsGPOffset, MVT::i32),
4870 MemOps.push_back(Store);
4873 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
4874 Store = DAG.getStore(Op.getOperand(0),
4875 DAG.getConstant(VarArgsFPOffset, MVT::i32),
4877 MemOps.push_back(Store);
4879 // Store ptr to overflow_arg_area
4880 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
4881 SDOperand OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4882 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV, 0);
4883 MemOps.push_back(Store);
4885 // Store ptr to reg_save_area.
4886 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
4887 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
4888 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV, 0);
4889 MemOps.push_back(Store);
4890 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
4893 SDOperand X86TargetLowering::LowerVACOPY(SDOperand Op, SelectionDAG &DAG) {
4894 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
4895 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
4896 SDOperand Chain = Op.getOperand(0);
4897 SDOperand DstPtr = Op.getOperand(1);
4898 SDOperand SrcPtr = Op.getOperand(2);
4899 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4900 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4902 return DAG.getMemcpy(Chain, DstPtr, SrcPtr,
4903 DAG.getIntPtrConstant(24), 8, false,
4904 DstSV, 0, SrcSV, 0);
4908 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
4909 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
4911 default: return SDOperand(); // Don't custom lower most intrinsics.
4912 // Comparison intrinsics.
4913 case Intrinsic::x86_sse_comieq_ss:
4914 case Intrinsic::x86_sse_comilt_ss:
4915 case Intrinsic::x86_sse_comile_ss:
4916 case Intrinsic::x86_sse_comigt_ss:
4917 case Intrinsic::x86_sse_comige_ss:
4918 case Intrinsic::x86_sse_comineq_ss:
4919 case Intrinsic::x86_sse_ucomieq_ss:
4920 case Intrinsic::x86_sse_ucomilt_ss:
4921 case Intrinsic::x86_sse_ucomile_ss:
4922 case Intrinsic::x86_sse_ucomigt_ss:
4923 case Intrinsic::x86_sse_ucomige_ss:
4924 case Intrinsic::x86_sse_ucomineq_ss:
4925 case Intrinsic::x86_sse2_comieq_sd:
4926 case Intrinsic::x86_sse2_comilt_sd:
4927 case Intrinsic::x86_sse2_comile_sd:
4928 case Intrinsic::x86_sse2_comigt_sd:
4929 case Intrinsic::x86_sse2_comige_sd:
4930 case Intrinsic::x86_sse2_comineq_sd:
4931 case Intrinsic::x86_sse2_ucomieq_sd:
4932 case Intrinsic::x86_sse2_ucomilt_sd:
4933 case Intrinsic::x86_sse2_ucomile_sd:
4934 case Intrinsic::x86_sse2_ucomigt_sd:
4935 case Intrinsic::x86_sse2_ucomige_sd:
4936 case Intrinsic::x86_sse2_ucomineq_sd: {
4938 ISD::CondCode CC = ISD::SETCC_INVALID;
4941 case Intrinsic::x86_sse_comieq_ss:
4942 case Intrinsic::x86_sse2_comieq_sd:
4946 case Intrinsic::x86_sse_comilt_ss:
4947 case Intrinsic::x86_sse2_comilt_sd:
4951 case Intrinsic::x86_sse_comile_ss:
4952 case Intrinsic::x86_sse2_comile_sd:
4956 case Intrinsic::x86_sse_comigt_ss:
4957 case Intrinsic::x86_sse2_comigt_sd:
4961 case Intrinsic::x86_sse_comige_ss:
4962 case Intrinsic::x86_sse2_comige_sd:
4966 case Intrinsic::x86_sse_comineq_ss:
4967 case Intrinsic::x86_sse2_comineq_sd:
4971 case Intrinsic::x86_sse_ucomieq_ss:
4972 case Intrinsic::x86_sse2_ucomieq_sd:
4973 Opc = X86ISD::UCOMI;
4976 case Intrinsic::x86_sse_ucomilt_ss:
4977 case Intrinsic::x86_sse2_ucomilt_sd:
4978 Opc = X86ISD::UCOMI;
4981 case Intrinsic::x86_sse_ucomile_ss:
4982 case Intrinsic::x86_sse2_ucomile_sd:
4983 Opc = X86ISD::UCOMI;
4986 case Intrinsic::x86_sse_ucomigt_ss:
4987 case Intrinsic::x86_sse2_ucomigt_sd:
4988 Opc = X86ISD::UCOMI;
4991 case Intrinsic::x86_sse_ucomige_ss:
4992 case Intrinsic::x86_sse2_ucomige_sd:
4993 Opc = X86ISD::UCOMI;
4996 case Intrinsic::x86_sse_ucomineq_ss:
4997 case Intrinsic::x86_sse2_ucomineq_sd:
4998 Opc = X86ISD::UCOMI;
5004 SDOperand LHS = Op.getOperand(1);
5005 SDOperand RHS = Op.getOperand(2);
5006 translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
5008 SDOperand Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
5009 SDOperand SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
5010 DAG.getConstant(X86CC, MVT::i8), Cond);
5011 return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
5014 // Fix vector shift instructions where the last operand is a non-immediate
5016 case Intrinsic::x86_sse2_pslli_w:
5017 case Intrinsic::x86_sse2_pslli_d:
5018 case Intrinsic::x86_sse2_pslli_q:
5019 case Intrinsic::x86_sse2_psrli_w:
5020 case Intrinsic::x86_sse2_psrli_d:
5021 case Intrinsic::x86_sse2_psrli_q:
5022 case Intrinsic::x86_sse2_psrai_w:
5023 case Intrinsic::x86_sse2_psrai_d:
5024 case Intrinsic::x86_mmx_pslli_w:
5025 case Intrinsic::x86_mmx_pslli_d:
5026 case Intrinsic::x86_mmx_pslli_q:
5027 case Intrinsic::x86_mmx_psrli_w:
5028 case Intrinsic::x86_mmx_psrli_d:
5029 case Intrinsic::x86_mmx_psrli_q:
5030 case Intrinsic::x86_mmx_psrai_w:
5031 case Intrinsic::x86_mmx_psrai_d: {
5032 SDOperand ShAmt = Op.getOperand(2);
5033 if (isa<ConstantSDNode>(ShAmt))
5036 unsigned NewIntNo = 0;
5037 MVT::ValueType ShAmtVT = MVT::v4i32;
5039 case Intrinsic::x86_sse2_pslli_w:
5040 NewIntNo = Intrinsic::x86_sse2_psll_w;
5042 case Intrinsic::x86_sse2_pslli_d:
5043 NewIntNo = Intrinsic::x86_sse2_psll_d;
5045 case Intrinsic::x86_sse2_pslli_q:
5046 NewIntNo = Intrinsic::x86_sse2_psll_q;
5048 case Intrinsic::x86_sse2_psrli_w:
5049 NewIntNo = Intrinsic::x86_sse2_psrl_w;
5051 case Intrinsic::x86_sse2_psrli_d:
5052 NewIntNo = Intrinsic::x86_sse2_psrl_d;
5054 case Intrinsic::x86_sse2_psrli_q:
5055 NewIntNo = Intrinsic::x86_sse2_psrl_q;
5057 case Intrinsic::x86_sse2_psrai_w:
5058 NewIntNo = Intrinsic::x86_sse2_psra_w;
5060 case Intrinsic::x86_sse2_psrai_d:
5061 NewIntNo = Intrinsic::x86_sse2_psra_d;
5064 ShAmtVT = MVT::v2i32;
5066 case Intrinsic::x86_mmx_pslli_w:
5067 NewIntNo = Intrinsic::x86_mmx_psll_w;
5069 case Intrinsic::x86_mmx_pslli_d:
5070 NewIntNo = Intrinsic::x86_mmx_psll_d;
5072 case Intrinsic::x86_mmx_pslli_q:
5073 NewIntNo = Intrinsic::x86_mmx_psll_q;
5075 case Intrinsic::x86_mmx_psrli_w:
5076 NewIntNo = Intrinsic::x86_mmx_psrl_w;
5078 case Intrinsic::x86_mmx_psrli_d:
5079 NewIntNo = Intrinsic::x86_mmx_psrl_d;
5081 case Intrinsic::x86_mmx_psrli_q:
5082 NewIntNo = Intrinsic::x86_mmx_psrl_q;
5084 case Intrinsic::x86_mmx_psrai_w:
5085 NewIntNo = Intrinsic::x86_mmx_psra_w;
5087 case Intrinsic::x86_mmx_psrai_d:
5088 NewIntNo = Intrinsic::x86_mmx_psra_d;
5090 default: abort(); // Can't reach here.
5095 MVT::ValueType VT = Op.getValueType();
5096 ShAmt = DAG.getNode(ISD::BIT_CONVERT, VT,
5097 DAG.getNode(ISD::SCALAR_TO_VECTOR, ShAmtVT, ShAmt));
5098 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
5099 DAG.getConstant(NewIntNo, MVT::i32),
5100 Op.getOperand(1), ShAmt);
5105 SDOperand X86TargetLowering::LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
5106 // Depths > 0 not supported yet!
5107 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5110 // Just load the return address
5111 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5112 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
5115 SDOperand X86TargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG) {
5116 // Depths > 0 not supported yet!
5117 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5120 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5121 return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI,
5122 DAG.getIntPtrConstant(4));
5125 SDOperand X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDOperand Op,
5126 SelectionDAG &DAG) {
5127 // Is not yet supported on x86-64
5128 if (Subtarget->is64Bit())
5131 return DAG.getIntPtrConstant(8);
5134 SDOperand X86TargetLowering::LowerEH_RETURN(SDOperand Op, SelectionDAG &DAG)
5136 assert(!Subtarget->is64Bit() &&
5137 "Lowering of eh_return builtin is not supported yet on x86-64");
5139 MachineFunction &MF = DAG.getMachineFunction();
5140 SDOperand Chain = Op.getOperand(0);
5141 SDOperand Offset = Op.getOperand(1);
5142 SDOperand Handler = Op.getOperand(2);
5144 SDOperand Frame = DAG.getRegister(RegInfo->getFrameRegister(MF),
5147 SDOperand StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
5148 DAG.getIntPtrConstant(-4UL));
5149 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
5150 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
5151 Chain = DAG.getCopyToReg(Chain, X86::ECX, StoreAddr);
5152 MF.getRegInfo().addLiveOut(X86::ECX);
5154 return DAG.getNode(X86ISD::EH_RETURN, MVT::Other,
5155 Chain, DAG.getRegister(X86::ECX, getPointerTy()));
5158 SDOperand X86TargetLowering::LowerTRAMPOLINE(SDOperand Op,
5159 SelectionDAG &DAG) {
5160 SDOperand Root = Op.getOperand(0);
5161 SDOperand Trmp = Op.getOperand(1); // trampoline
5162 SDOperand FPtr = Op.getOperand(2); // nested function
5163 SDOperand Nest = Op.getOperand(3); // 'nest' parameter value
5165 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5167 const X86InstrInfo *TII =
5168 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5170 if (Subtarget->is64Bit()) {
5171 SDOperand OutChains[6];
5173 // Large code-model.
5175 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
5176 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
5178 const unsigned char N86R10 =
5179 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(X86::R10);
5180 const unsigned char N86R11 =
5181 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(X86::R11);
5183 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
5185 // Load the pointer to the nested function into R11.
5186 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
5187 SDOperand Addr = Trmp;
5188 OutChains[0] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5191 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(2, MVT::i64));
5192 OutChains[1] = DAG.getStore(Root, FPtr, Addr, TrmpAddr, 2, false, 2);
5194 // Load the 'nest' parameter value into R10.
5195 // R10 is specified in X86CallingConv.td
5196 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
5197 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(10, MVT::i64));
5198 OutChains[2] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5201 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(12, MVT::i64));
5202 OutChains[3] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 12, false, 2);
5204 // Jump to the nested function.
5205 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
5206 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(20, MVT::i64));
5207 OutChains[4] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5210 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
5211 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(22, MVT::i64));
5212 OutChains[5] = DAG.getStore(Root, DAG.getConstant(ModRM, MVT::i8), Addr,
5216 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 6) };
5217 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5219 const Function *Func =
5220 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5221 unsigned CC = Func->getCallingConv();
5226 assert(0 && "Unsupported calling convention");
5227 case CallingConv::C:
5228 case CallingConv::X86_StdCall: {
5229 // Pass 'nest' parameter in ECX.
5230 // Must be kept in sync with X86CallingConv.td
5233 // Check that ECX wasn't needed by an 'inreg' parameter.
5234 const FunctionType *FTy = Func->getFunctionType();
5235 const PAListPtr &Attrs = Func->getParamAttrs();
5237 if (!Attrs.isEmpty() && !Func->isVarArg()) {
5238 unsigned InRegCount = 0;
5241 for (FunctionType::param_iterator I = FTy->param_begin(),
5242 E = FTy->param_end(); I != E; ++I, ++Idx)
5243 if (Attrs.paramHasAttr(Idx, ParamAttr::InReg))
5244 // FIXME: should only count parameters that are lowered to integers.
5245 InRegCount += (getTargetData()->getTypeSizeInBits(*I) + 31) / 32;
5247 if (InRegCount > 2) {
5248 cerr << "Nest register in use - reduce number of inreg parameters!\n";
5254 case CallingConv::X86_FastCall:
5255 // Pass 'nest' parameter in EAX.
5256 // Must be kept in sync with X86CallingConv.td
5261 SDOperand OutChains[4];
5262 SDOperand Addr, Disp;
5264 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5265 Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5267 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
5268 const unsigned char N86Reg =
5269 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(NestReg);
5270 OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
5273 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
5274 OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 1, false, 1);
5276 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
5277 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
5278 OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
5279 TrmpAddr, 5, false, 1);
5281 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
5282 OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpAddr, 6, false, 1);
5285 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
5286 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5290 SDOperand X86TargetLowering::LowerFLT_ROUNDS_(SDOperand Op, SelectionDAG &DAG) {
5292 The rounding mode is in bits 11:10 of FPSR, and has the following
5299 FLT_ROUNDS, on the other hand, expects the following:
5306 To perform the conversion, we do:
5307 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
5310 MachineFunction &MF = DAG.getMachineFunction();
5311 const TargetMachine &TM = MF.getTarget();
5312 const TargetFrameInfo &TFI = *TM.getFrameInfo();
5313 unsigned StackAlignment = TFI.getStackAlignment();
5314 MVT::ValueType VT = Op.getValueType();
5316 // Save FP Control Word to stack slot
5317 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
5318 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5320 SDOperand Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
5321 DAG.getEntryNode(), StackSlot);
5323 // Load FP Control Word from stack slot
5324 SDOperand CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
5326 // Transform as necessary
5328 DAG.getNode(ISD::SRL, MVT::i16,
5329 DAG.getNode(ISD::AND, MVT::i16,
5330 CWD, DAG.getConstant(0x800, MVT::i16)),
5331 DAG.getConstant(11, MVT::i8));
5333 DAG.getNode(ISD::SRL, MVT::i16,
5334 DAG.getNode(ISD::AND, MVT::i16,
5335 CWD, DAG.getConstant(0x400, MVT::i16)),
5336 DAG.getConstant(9, MVT::i8));
5339 DAG.getNode(ISD::AND, MVT::i16,
5340 DAG.getNode(ISD::ADD, MVT::i16,
5341 DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
5342 DAG.getConstant(1, MVT::i16)),
5343 DAG.getConstant(3, MVT::i16));
5346 return DAG.getNode((MVT::getSizeInBits(VT) < 16 ?
5347 ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
5350 SDOperand X86TargetLowering::LowerCTLZ(SDOperand Op, SelectionDAG &DAG) {
5351 MVT::ValueType VT = Op.getValueType();
5352 MVT::ValueType OpVT = VT;
5353 unsigned NumBits = MVT::getSizeInBits(VT);
5355 Op = Op.getOperand(0);
5356 if (VT == MVT::i8) {
5357 // Zero extend to i32 since there is not an i8 bsr.
5359 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5362 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
5363 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5364 Op = DAG.getNode(X86ISD::BSR, VTs, Op);
5366 // If src is zero (i.e. bsr sets ZF), returns NumBits.
5367 SmallVector<SDOperand, 4> Ops;
5369 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
5370 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5371 Ops.push_back(Op.getValue(1));
5372 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5374 // Finally xor with NumBits-1.
5375 Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
5378 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5382 SDOperand X86TargetLowering::LowerCTTZ(SDOperand Op, SelectionDAG &DAG) {
5383 MVT::ValueType VT = Op.getValueType();
5384 MVT::ValueType OpVT = VT;
5385 unsigned NumBits = MVT::getSizeInBits(VT);
5387 Op = Op.getOperand(0);
5388 if (VT == MVT::i8) {
5390 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5393 // Issue a bsf (scan bits forward) which also sets EFLAGS.
5394 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5395 Op = DAG.getNode(X86ISD::BSF, VTs, Op);
5397 // If src is zero (i.e. bsf sets ZF), returns NumBits.
5398 SmallVector<SDOperand, 4> Ops;
5400 Ops.push_back(DAG.getConstant(NumBits, OpVT));
5401 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5402 Ops.push_back(Op.getValue(1));
5403 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5406 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5410 SDOperand X86TargetLowering::LowerLCS(SDOperand Op, SelectionDAG &DAG) {
5411 MVT::ValueType T = cast<AtomicSDNode>(Op.Val)->getVT();
5415 case MVT::i8: Reg = X86::AL; size = 1; break;
5416 case MVT::i16: Reg = X86::AX; size = 2; break;
5417 case MVT::i32: Reg = X86::EAX; size = 4; break;
5419 if (Subtarget->is64Bit()) {
5420 Reg = X86::RAX; size = 8;
5421 } else //Should go away when LowerType stuff lands
5422 return SDOperand(ExpandATOMIC_LCS(Op.Val, DAG), 0);
5425 SDOperand cpIn = DAG.getCopyToReg(Op.getOperand(0), Reg,
5426 Op.getOperand(3), SDOperand());
5427 SDOperand Ops[] = { cpIn.getValue(0),
5430 DAG.getTargetConstant(size, MVT::i8),
5432 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5433 SDOperand Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, Tys, Ops, 5);
5435 DAG.getCopyFromReg(Result.getValue(0), Reg, T, Result.getValue(1));
5439 SDNode* X86TargetLowering::ExpandATOMIC_LCS(SDNode* Op, SelectionDAG &DAG) {
5440 MVT::ValueType T = cast<AtomicSDNode>(Op)->getVT();
5441 assert (T == MVT::i64 && "Only know how to expand i64 CAS");
5442 SDOperand cpInL, cpInH;
5443 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5444 DAG.getConstant(0, MVT::i32));
5445 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
5446 DAG.getConstant(1, MVT::i32));
5447 cpInL = DAG.getCopyToReg(Op->getOperand(0), X86::EAX,
5448 cpInL, SDOperand());
5449 cpInH = DAG.getCopyToReg(cpInL.getValue(0), X86::EDX,
5450 cpInH, cpInL.getValue(1));
5451 SDOperand swapInL, swapInH;
5452 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5453 DAG.getConstant(0, MVT::i32));
5454 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
5455 DAG.getConstant(1, MVT::i32));
5456 swapInL = DAG.getCopyToReg(cpInH.getValue(0), X86::EBX,
5457 swapInL, cpInH.getValue(1));
5458 swapInH = DAG.getCopyToReg(swapInL.getValue(0), X86::ECX,
5459 swapInH, swapInL.getValue(1));
5460 SDOperand Ops[] = { swapInH.getValue(0),
5462 swapInH.getValue(1)};
5463 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5464 SDOperand Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, Tys, Ops, 3);
5465 SDOperand cpOutL = DAG.getCopyFromReg(Result.getValue(0), X86::EAX, MVT::i32,
5466 Result.getValue(1));
5467 SDOperand cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), X86::EDX, MVT::i32,
5468 cpOutL.getValue(2));
5469 SDOperand OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
5470 SDOperand ResultVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2);
5471 Tys = DAG.getVTList(MVT::i64, MVT::Other);
5472 return DAG.getNode(ISD::MERGE_VALUES, Tys, ResultVal, cpOutH.getValue(1)).Val;
5475 /// LowerOperation - Provide custom lowering hooks for some operations.
5477 SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
5478 switch (Op.getOpcode()) {
5479 default: assert(0 && "Should not custom lower this!");
5480 case ISD::ATOMIC_LCS: return LowerLCS(Op,DAG);
5481 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5482 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5483 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5484 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5485 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5486 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5487 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5488 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5489 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
5490 case ISD::SHL_PARTS:
5491 case ISD::SRA_PARTS:
5492 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
5493 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
5494 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
5495 case ISD::FABS: return LowerFABS(Op, DAG);
5496 case ISD::FNEG: return LowerFNEG(Op, DAG);
5497 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5498 case ISD::SETCC: return LowerSETCC(Op, DAG);
5499 case ISD::SELECT: return LowerSELECT(Op, DAG);
5500 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
5501 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5502 case ISD::CALL: return LowerCALL(Op, DAG);
5503 case ISD::RET: return LowerRET(Op, DAG);
5504 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
5505 case ISD::VASTART: return LowerVASTART(Op, DAG);
5506 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
5507 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5508 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5509 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5510 case ISD::FRAME_TO_ARGS_OFFSET:
5511 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
5512 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
5513 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
5514 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
5515 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5516 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
5517 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
5519 // FIXME: REMOVE THIS WHEN LegalizeDAGTypes lands.
5520 case ISD::READCYCLECOUNTER:
5521 return SDOperand(ExpandREADCYCLECOUNTER(Op.Val, DAG), 0);
5525 /// ExpandOperation - Provide custom lowering hooks for expanding operations.
5526 SDNode *X86TargetLowering::ExpandOperationResult(SDNode *N, SelectionDAG &DAG) {
5527 switch (N->getOpcode()) {
5528 default: assert(0 && "Should not custom lower this!");
5529 case ISD::FP_TO_SINT: return ExpandFP_TO_SINT(N, DAG);
5530 case ISD::READCYCLECOUNTER: return ExpandREADCYCLECOUNTER(N, DAG);
5531 case ISD::ATOMIC_LCS: return ExpandATOMIC_LCS(N, DAG);
5535 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
5537 default: return NULL;
5538 case X86ISD::BSF: return "X86ISD::BSF";
5539 case X86ISD::BSR: return "X86ISD::BSR";
5540 case X86ISD::SHLD: return "X86ISD::SHLD";
5541 case X86ISD::SHRD: return "X86ISD::SHRD";
5542 case X86ISD::FAND: return "X86ISD::FAND";
5543 case X86ISD::FOR: return "X86ISD::FOR";
5544 case X86ISD::FXOR: return "X86ISD::FXOR";
5545 case X86ISD::FSRL: return "X86ISD::FSRL";
5546 case X86ISD::FILD: return "X86ISD::FILD";
5547 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
5548 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
5549 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
5550 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
5551 case X86ISD::FLD: return "X86ISD::FLD";
5552 case X86ISD::FST: return "X86ISD::FST";
5553 case X86ISD::CALL: return "X86ISD::CALL";
5554 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
5555 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
5556 case X86ISD::CMP: return "X86ISD::CMP";
5557 case X86ISD::COMI: return "X86ISD::COMI";
5558 case X86ISD::UCOMI: return "X86ISD::UCOMI";
5559 case X86ISD::SETCC: return "X86ISD::SETCC";
5560 case X86ISD::CMOV: return "X86ISD::CMOV";
5561 case X86ISD::BRCOND: return "X86ISD::BRCOND";
5562 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
5563 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
5564 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
5565 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
5566 case X86ISD::Wrapper: return "X86ISD::Wrapper";
5567 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
5568 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
5569 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
5570 case X86ISD::PINSRB: return "X86ISD::PINSRB";
5571 case X86ISD::PINSRW: return "X86ISD::PINSRW";
5572 case X86ISD::FMAX: return "X86ISD::FMAX";
5573 case X86ISD::FMIN: return "X86ISD::FMIN";
5574 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
5575 case X86ISD::FRCP: return "X86ISD::FRCP";
5576 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
5577 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
5578 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
5579 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
5580 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
5581 case X86ISD::LCMPXCHG_DAG: return "x86ISD::LCMPXCHG_DAG";
5582 case X86ISD::LCMPXCHG8_DAG: return "x86ISD::LCMPXCHG8_DAG";
5586 // isLegalAddressingMode - Return true if the addressing mode represented
5587 // by AM is legal for this target, for a load/store of the specified type.
5588 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
5589 const Type *Ty) const {
5590 // X86 supports extremely general addressing modes.
5592 // X86 allows a sign-extended 32-bit immediate field as a displacement.
5593 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
5597 // We can only fold this if we don't need an extra load.
5598 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
5601 // X86-64 only supports addr of globals in small code model.
5602 if (Subtarget->is64Bit()) {
5603 if (getTargetMachine().getCodeModel() != CodeModel::Small)
5605 // If lower 4G is not available, then we must use rip-relative addressing.
5606 if (AM.BaseOffs || AM.Scale > 1)
5617 // These scales always work.
5622 // These scales are formed with basereg+scalereg. Only accept if there is
5627 default: // Other stuff never works.
5635 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
5636 if (!Ty1->isInteger() || !Ty2->isInteger())
5638 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5639 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5640 if (NumBits1 <= NumBits2)
5642 return Subtarget->is64Bit() || NumBits1 < 64;
5645 bool X86TargetLowering::isTruncateFree(MVT::ValueType VT1,
5646 MVT::ValueType VT2) const {
5647 if (!MVT::isInteger(VT1) || !MVT::isInteger(VT2))
5649 unsigned NumBits1 = MVT::getSizeInBits(VT1);
5650 unsigned NumBits2 = MVT::getSizeInBits(VT2);
5651 if (NumBits1 <= NumBits2)
5653 return Subtarget->is64Bit() || NumBits1 < 64;
5656 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5657 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5658 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5659 /// are assumed to be legal.
5661 X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
5662 // Only do shuffles on 128-bit vector types for now.
5663 if (MVT::getSizeInBits(VT) == 64) return false;
5664 return (Mask.Val->getNumOperands() <= 4 ||
5665 isIdentityMask(Mask.Val) ||
5666 isIdentityMask(Mask.Val, true) ||
5667 isSplatMask(Mask.Val) ||
5668 isPSHUFHW_PSHUFLWMask(Mask.Val) ||
5669 X86::isUNPCKLMask(Mask.Val) ||
5670 X86::isUNPCKHMask(Mask.Val) ||
5671 X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
5672 X86::isUNPCKH_v_undef_Mask(Mask.Val));
5676 X86TargetLowering::isVectorClearMaskLegal(const std::vector<SDOperand> &BVOps,
5678 SelectionDAG &DAG) const {
5679 unsigned NumElts = BVOps.size();
5680 // Only do shuffles on 128-bit vector types for now.
5681 if (MVT::getSizeInBits(EVT) * NumElts == 64) return false;
5682 if (NumElts == 2) return true;
5684 return (isMOVLMask(&BVOps[0], 4) ||
5685 isCommutedMOVL(&BVOps[0], 4, true) ||
5686 isSHUFPMask(&BVOps[0], 4) ||
5687 isCommutedSHUFP(&BVOps[0], 4));
5692 //===----------------------------------------------------------------------===//
5693 // X86 Scheduler Hooks
5694 //===----------------------------------------------------------------------===//
5697 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
5698 MachineBasicBlock *BB) {
5699 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5700 switch (MI->getOpcode()) {
5701 default: assert(false && "Unexpected instr type to insert");
5702 case X86::CMOV_FR32:
5703 case X86::CMOV_FR64:
5704 case X86::CMOV_V4F32:
5705 case X86::CMOV_V2F64:
5706 case X86::CMOV_V2I64: {
5707 // To "insert" a SELECT_CC instruction, we actually have to insert the
5708 // diamond control-flow pattern. The incoming instruction knows the
5709 // destination vreg to set, the condition code register to branch on, the
5710 // true/false values to select between, and a branch opcode to use.
5711 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5712 ilist<MachineBasicBlock>::iterator It = BB;
5718 // cmpTY ccX, r1, r2
5720 // fallthrough --> copy0MBB
5721 MachineBasicBlock *thisMBB = BB;
5722 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
5723 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
5725 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
5726 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
5727 MachineFunction *F = BB->getParent();
5728 F->getBasicBlockList().insert(It, copy0MBB);
5729 F->getBasicBlockList().insert(It, sinkMBB);
5730 // Update machine-CFG edges by first adding all successors of the current
5731 // block to the new block which will contain the Phi node for the select.
5732 for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
5733 e = BB->succ_end(); i != e; ++i)
5734 sinkMBB->addSuccessor(*i);
5735 // Next, remove all successors of the current block, and add the true
5736 // and fallthrough blocks as its successors.
5737 while(!BB->succ_empty())
5738 BB->removeSuccessor(BB->succ_begin());
5739 BB->addSuccessor(copy0MBB);
5740 BB->addSuccessor(sinkMBB);
5743 // %FalseValue = ...
5744 // # fallthrough to sinkMBB
5747 // Update machine-CFG edges
5748 BB->addSuccessor(sinkMBB);
5751 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
5754 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
5755 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
5756 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
5758 delete MI; // The pseudo instruction is gone now.
5762 case X86::FP32_TO_INT16_IN_MEM:
5763 case X86::FP32_TO_INT32_IN_MEM:
5764 case X86::FP32_TO_INT64_IN_MEM:
5765 case X86::FP64_TO_INT16_IN_MEM:
5766 case X86::FP64_TO_INT32_IN_MEM:
5767 case X86::FP64_TO_INT64_IN_MEM:
5768 case X86::FP80_TO_INT16_IN_MEM:
5769 case X86::FP80_TO_INT32_IN_MEM:
5770 case X86::FP80_TO_INT64_IN_MEM: {
5771 // Change the floating point control register to use "round towards zero"
5772 // mode when truncating to an integer value.
5773 MachineFunction *F = BB->getParent();
5774 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
5775 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
5777 // Load the old value of the high byte of the control word...
5779 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
5780 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
5782 // Set the high part to be round to zero...
5783 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
5786 // Reload the modified control word now...
5787 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5789 // Restore the memory image of control word to original value
5790 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
5793 // Get the X86 opcode to use.
5795 switch (MI->getOpcode()) {
5796 default: assert(0 && "illegal opcode!");
5797 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
5798 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
5799 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
5800 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
5801 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
5802 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
5803 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
5804 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
5805 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
5809 MachineOperand &Op = MI->getOperand(0);
5810 if (Op.isRegister()) {
5811 AM.BaseType = X86AddressMode::RegBase;
5812 AM.Base.Reg = Op.getReg();
5814 AM.BaseType = X86AddressMode::FrameIndexBase;
5815 AM.Base.FrameIndex = Op.getIndex();
5817 Op = MI->getOperand(1);
5818 if (Op.isImmediate())
5819 AM.Scale = Op.getImm();
5820 Op = MI->getOperand(2);
5821 if (Op.isImmediate())
5822 AM.IndexReg = Op.getImm();
5823 Op = MI->getOperand(3);
5824 if (Op.isGlobalAddress()) {
5825 AM.GV = Op.getGlobal();
5827 AM.Disp = Op.getImm();
5829 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
5830 .addReg(MI->getOperand(4).getReg());
5832 // Reload the original control word now.
5833 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5835 delete MI; // The pseudo instruction is gone now.
5841 //===----------------------------------------------------------------------===//
5842 // X86 Optimization Hooks
5843 //===----------------------------------------------------------------------===//
5845 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
5849 const SelectionDAG &DAG,
5850 unsigned Depth) const {
5851 unsigned Opc = Op.getOpcode();
5852 assert((Opc >= ISD::BUILTIN_OP_END ||
5853 Opc == ISD::INTRINSIC_WO_CHAIN ||
5854 Opc == ISD::INTRINSIC_W_CHAIN ||
5855 Opc == ISD::INTRINSIC_VOID) &&
5856 "Should use MaskedValueIsZero if you don't know whether Op"
5857 " is a target node!");
5859 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
5863 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
5864 Mask.getBitWidth() - 1);
5869 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5870 /// element of the result of the vector shuffle.
5871 static SDOperand getShuffleScalarElt(SDNode *N, unsigned i, SelectionDAG &DAG) {
5872 MVT::ValueType VT = N->getValueType(0);
5873 SDOperand PermMask = N->getOperand(2);
5874 unsigned NumElems = PermMask.getNumOperands();
5875 SDOperand V = (i < NumElems) ? N->getOperand(0) : N->getOperand(1);
5877 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5879 ? V.getOperand(0) : DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5880 } else if (V.getOpcode() == ISD::VECTOR_SHUFFLE) {
5881 SDOperand Idx = PermMask.getOperand(i);
5882 if (Idx.getOpcode() == ISD::UNDEF)
5883 return DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5884 return getShuffleScalarElt(V.Val,cast<ConstantSDNode>(Idx)->getValue(),DAG);
5889 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
5890 /// node is a GlobalAddress + an offset.
5891 static bool isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) {
5892 unsigned Opc = N->getOpcode();
5893 if (Opc == X86ISD::Wrapper) {
5894 if (dyn_cast<GlobalAddressSDNode>(N->getOperand(0))) {
5895 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
5898 } else if (Opc == ISD::ADD) {
5899 SDOperand N1 = N->getOperand(0);
5900 SDOperand N2 = N->getOperand(1);
5901 if (isGAPlusOffset(N1.Val, GA, Offset)) {
5902 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
5904 Offset += V->getSignExtended();
5907 } else if (isGAPlusOffset(N2.Val, GA, Offset)) {
5908 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
5910 Offset += V->getSignExtended();
5918 /// isConsecutiveLoad - Returns true if N is loading from an address of Base
5920 static bool isConsecutiveLoad(SDNode *N, SDNode *Base, int Dist, int Size,
5921 MachineFrameInfo *MFI) {
5922 if (N->getOperand(0).Val != Base->getOperand(0).Val)
5925 SDOperand Loc = N->getOperand(1);
5926 SDOperand BaseLoc = Base->getOperand(1);
5927 if (Loc.getOpcode() == ISD::FrameIndex) {
5928 if (BaseLoc.getOpcode() != ISD::FrameIndex)
5930 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
5931 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
5932 int FS = MFI->getObjectSize(FI);
5933 int BFS = MFI->getObjectSize(BFI);
5934 if (FS != BFS || FS != Size) return false;
5935 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Size);
5937 GlobalValue *GV1 = NULL;
5938 GlobalValue *GV2 = NULL;
5939 int64_t Offset1 = 0;
5940 int64_t Offset2 = 0;
5941 bool isGA1 = isGAPlusOffset(Loc.Val, GV1, Offset1);
5942 bool isGA2 = isGAPlusOffset(BaseLoc.Val, GV2, Offset2);
5943 if (isGA1 && isGA2 && GV1 == GV2)
5944 return Offset1 == (Offset2 + Dist*Size);
5950 static bool isBaseAlignment16(SDNode *Base, MachineFrameInfo *MFI,
5951 const X86Subtarget *Subtarget) {
5954 if (isGAPlusOffset(Base, GV, Offset))
5955 return (GV->getAlignment() >= 16 && (Offset % 16) == 0);
5956 // DAG combine handles the stack object case.
5961 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
5962 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
5963 /// if the load addresses are consecutive, non-overlapping, and in the right
5965 static SDOperand PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
5966 const X86Subtarget *Subtarget) {
5967 MachineFunction &MF = DAG.getMachineFunction();
5968 MachineFrameInfo *MFI = MF.getFrameInfo();
5969 MVT::ValueType VT = N->getValueType(0);
5970 MVT::ValueType EVT = MVT::getVectorElementType(VT);
5971 SDOperand PermMask = N->getOperand(2);
5972 int NumElems = (int)PermMask.getNumOperands();
5973 SDNode *Base = NULL;
5974 for (int i = 0; i < NumElems; ++i) {
5975 SDOperand Idx = PermMask.getOperand(i);
5976 if (Idx.getOpcode() == ISD::UNDEF) {
5977 if (!Base) return SDOperand();
5980 getShuffleScalarElt(N, cast<ConstantSDNode>(Idx)->getValue(), DAG);
5981 if (!Arg.Val || !ISD::isNON_EXTLoad(Arg.Val))
5985 else if (!isConsecutiveLoad(Arg.Val, Base,
5986 i, MVT::getSizeInBits(EVT)/8,MFI))
5991 bool isAlign16 = isBaseAlignment16(Base->getOperand(1).Val, MFI, Subtarget);
5992 LoadSDNode *LD = cast<LoadSDNode>(Base);
5994 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
5995 LD->getSrcValueOffset(), LD->isVolatile());
5997 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
5998 LD->getSrcValueOffset(), LD->isVolatile(),
5999 LD->getAlignment());
6003 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
6004 static SDOperand PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
6005 const X86Subtarget *Subtarget) {
6006 SDOperand Cond = N->getOperand(0);
6008 // If we have SSE[12] support, try to form min/max nodes.
6009 if (Subtarget->hasSSE2() &&
6010 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
6011 if (Cond.getOpcode() == ISD::SETCC) {
6012 // Get the LHS/RHS of the select.
6013 SDOperand LHS = N->getOperand(1);
6014 SDOperand RHS = N->getOperand(2);
6015 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
6017 unsigned Opcode = 0;
6018 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
6021 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
6024 if (!UnsafeFPMath) break;
6026 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
6028 Opcode = X86ISD::FMIN;
6031 case ISD::SETOGT: // (X > Y) ? X : Y -> max
6034 if (!UnsafeFPMath) break;
6036 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
6038 Opcode = X86ISD::FMAX;
6041 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
6044 case ISD::SETOGT: // (X > Y) ? Y : X -> min
6047 if (!UnsafeFPMath) break;
6049 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
6051 Opcode = X86ISD::FMIN;
6054 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
6057 if (!UnsafeFPMath) break;
6059 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
6061 Opcode = X86ISD::FMAX;
6067 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
6075 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
6076 static SDOperand PerformSTORECombine(StoreSDNode *St, SelectionDAG &DAG,
6077 const X86Subtarget *Subtarget) {
6078 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
6079 // the FP state in cases where an emms may be missing.
6080 // A preferable solution to the general problem is to figure out the right
6081 // places to insert EMMS. This qualifies as a quick hack.
6082 if (MVT::isVector(St->getValue().getValueType()) &&
6083 MVT::getSizeInBits(St->getValue().getValueType()) == 64 &&
6084 isa<LoadSDNode>(St->getValue()) &&
6085 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
6086 St->getChain().hasOneUse() && !St->isVolatile()) {
6087 SDNode* LdVal = St->getValue().Val;
6089 int TokenFactorIndex = -1;
6090 SmallVector<SDOperand, 8> Ops;
6091 SDNode* ChainVal = St->getChain().Val;
6092 // Must be a store of a load. We currently handle two cases: the load
6093 // is a direct child, and it's under an intervening TokenFactor. It is
6094 // possible to dig deeper under nested TokenFactors.
6095 if (ChainVal == LdVal)
6096 Ld = cast<LoadSDNode>(St->getChain());
6097 else if (St->getValue().hasOneUse() &&
6098 ChainVal->getOpcode() == ISD::TokenFactor) {
6099 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
6100 if (ChainVal->getOperand(i).Val == LdVal) {
6101 TokenFactorIndex = i;
6102 Ld = cast<LoadSDNode>(St->getValue());
6104 Ops.push_back(ChainVal->getOperand(i));
6108 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
6109 if (Subtarget->is64Bit()) {
6110 SDOperand NewLd = DAG.getLoad(MVT::i64, Ld->getChain(),
6111 Ld->getBasePtr(), Ld->getSrcValue(),
6112 Ld->getSrcValueOffset(), Ld->isVolatile(),
6113 Ld->getAlignment());
6114 SDOperand NewChain = NewLd.getValue(1);
6115 if (TokenFactorIndex != -1) {
6116 Ops.push_back(NewChain);
6117 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
6120 return DAG.getStore(NewChain, NewLd, St->getBasePtr(),
6121 St->getSrcValue(), St->getSrcValueOffset(),
6122 St->isVolatile(), St->getAlignment());
6125 // Otherwise, lower to two 32-bit copies.
6126 SDOperand LoAddr = Ld->getBasePtr();
6127 SDOperand HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6128 DAG.getConstant(MVT::i32, 4));
6130 SDOperand LoLd = DAG.getLoad(MVT::i32, Ld->getChain(), LoAddr,
6131 Ld->getSrcValue(), Ld->getSrcValueOffset(),
6132 Ld->isVolatile(), Ld->getAlignment());
6133 SDOperand HiLd = DAG.getLoad(MVT::i32, Ld->getChain(), HiAddr,
6134 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
6136 MinAlign(Ld->getAlignment(), 4));
6138 SDOperand NewChain = LoLd.getValue(1);
6139 if (TokenFactorIndex != -1) {
6140 Ops.push_back(LoLd);
6141 Ops.push_back(HiLd);
6142 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
6146 LoAddr = St->getBasePtr();
6147 HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6148 DAG.getConstant(MVT::i32, 4));
6150 SDOperand LoSt = DAG.getStore(NewChain, LoLd, LoAddr,
6151 St->getSrcValue(), St->getSrcValueOffset(),
6152 St->isVolatile(), St->getAlignment());
6153 SDOperand HiSt = DAG.getStore(NewChain, HiLd, HiAddr,
6154 St->getSrcValue(), St->getSrcValueOffset()+4,
6156 MinAlign(St->getAlignment(), 4));
6157 return DAG.getNode(ISD::TokenFactor, MVT::Other, LoSt, HiSt);
6163 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
6164 /// X86ISD::FXOR nodes.
6165 static SDOperand PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
6166 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
6167 // F[X]OR(0.0, x) -> x
6168 // F[X]OR(x, 0.0) -> x
6169 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6170 if (C->getValueAPF().isPosZero())
6171 return N->getOperand(1);
6172 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6173 if (C->getValueAPF().isPosZero())
6174 return N->getOperand(0);
6178 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
6179 static SDOperand PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
6180 // FAND(0.0, x) -> 0.0
6181 // FAND(x, 0.0) -> 0.0
6182 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6183 if (C->getValueAPF().isPosZero())
6184 return N->getOperand(0);
6185 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6186 if (C->getValueAPF().isPosZero())
6187 return N->getOperand(1);
6192 SDOperand X86TargetLowering::PerformDAGCombine(SDNode *N,
6193 DAGCombinerInfo &DCI) const {
6194 SelectionDAG &DAG = DCI.DAG;
6195 switch (N->getOpcode()) {
6197 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, Subtarget);
6198 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
6200 return PerformSTORECombine(cast<StoreSDNode>(N), DAG, Subtarget);
6202 case X86ISD::FOR: return PerformFORCombine(N, DAG);
6203 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
6209 //===----------------------------------------------------------------------===//
6210 // X86 Inline Assembly Support
6211 //===----------------------------------------------------------------------===//
6213 /// getConstraintType - Given a constraint letter, return the type of
6214 /// constraint it is for this target.
6215 X86TargetLowering::ConstraintType
6216 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
6217 if (Constraint.size() == 1) {
6218 switch (Constraint[0]) {
6229 return C_RegisterClass;
6234 return TargetLowering::getConstraintType(Constraint);
6237 /// LowerXConstraint - try to replace an X constraint, which matches anything,
6238 /// with another that has more specific requirements based on the type of the
6239 /// corresponding operand.
6240 const char *X86TargetLowering::
6241 LowerXConstraint(MVT::ValueType ConstraintVT) const {
6242 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
6243 // 'f' like normal targets.
6244 if (MVT::isFloatingPoint(ConstraintVT)) {
6245 if (Subtarget->hasSSE2())
6247 if (Subtarget->hasSSE1())
6251 return TargetLowering::LowerXConstraint(ConstraintVT);
6254 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6255 /// vector. If it is invalid, don't add anything to Ops.
6256 void X86TargetLowering::LowerAsmOperandForConstraint(SDOperand Op,
6258 std::vector<SDOperand>&Ops,
6259 SelectionDAG &DAG) const {
6260 SDOperand Result(0, 0);
6262 switch (Constraint) {
6265 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6266 if (C->getValue() <= 31) {
6267 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6273 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6274 if (C->getValue() <= 255) {
6275 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6281 // Literal immediates are always ok.
6282 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
6283 Result = DAG.getTargetConstant(CST->getValue(), Op.getValueType());
6287 // If we are in non-pic codegen mode, we allow the address of a global (with
6288 // an optional displacement) to be used with 'i'.
6289 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
6292 // Match either (GA) or (GA+C)
6294 Offset = GA->getOffset();
6295 } else if (Op.getOpcode() == ISD::ADD) {
6296 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6297 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6299 Offset = GA->getOffset()+C->getValue();
6301 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6302 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6304 Offset = GA->getOffset()+C->getValue();
6311 // If addressing this global requires a load (e.g. in PIC mode), we can't
6313 if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
6317 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
6323 // Otherwise, not valid for this mode.
6329 Ops.push_back(Result);
6332 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6335 std::vector<unsigned> X86TargetLowering::
6336 getRegClassForInlineAsmConstraint(const std::string &Constraint,
6337 MVT::ValueType VT) const {
6338 if (Constraint.size() == 1) {
6339 // FIXME: not handling fp-stack yet!
6340 switch (Constraint[0]) { // GCC X86 Constraint Letters
6341 default: break; // Unknown constraint letter
6342 case 'A': // EAX/EDX
6343 if (VT == MVT::i32 || VT == MVT::i64)
6344 return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
6346 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
6349 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
6350 else if (VT == MVT::i16)
6351 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
6352 else if (VT == MVT::i8)
6353 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
6354 else if (VT == MVT::i64)
6355 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
6360 return std::vector<unsigned>();
6363 std::pair<unsigned, const TargetRegisterClass*>
6364 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
6365 MVT::ValueType VT) const {
6366 // First, see if this is a constraint that directly corresponds to an LLVM
6368 if (Constraint.size() == 1) {
6369 // GCC Constraint Letters
6370 switch (Constraint[0]) {
6372 case 'r': // GENERAL_REGS
6373 case 'R': // LEGACY_REGS
6374 case 'l': // INDEX_REGS
6375 if (VT == MVT::i64 && Subtarget->is64Bit())
6376 return std::make_pair(0U, X86::GR64RegisterClass);
6378 return std::make_pair(0U, X86::GR32RegisterClass);
6379 else if (VT == MVT::i16)
6380 return std::make_pair(0U, X86::GR16RegisterClass);
6381 else if (VT == MVT::i8)
6382 return std::make_pair(0U, X86::GR8RegisterClass);
6384 case 'f': // FP Stack registers.
6385 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
6386 // value to the correct fpstack register class.
6387 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
6388 return std::make_pair(0U, X86::RFP32RegisterClass);
6389 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
6390 return std::make_pair(0U, X86::RFP64RegisterClass);
6391 return std::make_pair(0U, X86::RFP80RegisterClass);
6392 case 'y': // MMX_REGS if MMX allowed.
6393 if (!Subtarget->hasMMX()) break;
6394 return std::make_pair(0U, X86::VR64RegisterClass);
6396 case 'Y': // SSE_REGS if SSE2 allowed
6397 if (!Subtarget->hasSSE2()) break;
6399 case 'x': // SSE_REGS if SSE1 allowed
6400 if (!Subtarget->hasSSE1()) break;
6404 // Scalar SSE types.
6407 return std::make_pair(0U, X86::FR32RegisterClass);
6410 return std::make_pair(0U, X86::FR64RegisterClass);
6418 return std::make_pair(0U, X86::VR128RegisterClass);
6424 // Use the default implementation in TargetLowering to convert the register
6425 // constraint into a member of a register class.
6426 std::pair<unsigned, const TargetRegisterClass*> Res;
6427 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
6429 // Not found as a standard register?
6430 if (Res.second == 0) {
6431 // GCC calls "st(0)" just plain "st".
6432 if (StringsEqualNoCase("{st}", Constraint)) {
6433 Res.first = X86::ST0;
6434 Res.second = X86::RFP80RegisterClass;
6440 // Otherwise, check to see if this is a register class of the wrong value
6441 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
6442 // turn into {ax},{dx}.
6443 if (Res.second->hasType(VT))
6444 return Res; // Correct type already, nothing to do.
6446 // All of the single-register GCC register classes map their values onto
6447 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
6448 // really want an 8-bit or 32-bit register, map to the appropriate register
6449 // class and return the appropriate register.
6450 if (Res.second != X86::GR16RegisterClass)
6453 if (VT == MVT::i8) {
6454 unsigned DestReg = 0;
6455 switch (Res.first) {
6457 case X86::AX: DestReg = X86::AL; break;
6458 case X86::DX: DestReg = X86::DL; break;
6459 case X86::CX: DestReg = X86::CL; break;
6460 case X86::BX: DestReg = X86::BL; break;
6463 Res.first = DestReg;
6464 Res.second = Res.second = X86::GR8RegisterClass;
6466 } else if (VT == MVT::i32) {
6467 unsigned DestReg = 0;
6468 switch (Res.first) {
6470 case X86::AX: DestReg = X86::EAX; break;
6471 case X86::DX: DestReg = X86::EDX; break;
6472 case X86::CX: DestReg = X86::ECX; break;
6473 case X86::BX: DestReg = X86::EBX; break;
6474 case X86::SI: DestReg = X86::ESI; break;
6475 case X86::DI: DestReg = X86::EDI; break;
6476 case X86::BP: DestReg = X86::EBP; break;
6477 case X86::SP: DestReg = X86::ESP; break;
6480 Res.first = DestReg;
6481 Res.second = Res.second = X86::GR32RegisterClass;
6483 } else if (VT == MVT::i64) {
6484 unsigned DestReg = 0;
6485 switch (Res.first) {
6487 case X86::AX: DestReg = X86::RAX; break;
6488 case X86::DX: DestReg = X86::RDX; break;
6489 case X86::CX: DestReg = X86::RCX; break;
6490 case X86::BX: DestReg = X86::RBX; break;
6491 case X86::SI: DestReg = X86::RSI; break;
6492 case X86::DI: DestReg = X86::RDI; break;
6493 case X86::BP: DestReg = X86::RBP; break;
6494 case X86::SP: DestReg = X86::RSP; break;
6497 Res.first = DestReg;
6498 Res.second = Res.second = X86::GR64RegisterClass;