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"
42 #include "llvm/ParamAttrsList.h"
45 X86TargetLowering::X86TargetLowering(TargetMachine &TM)
46 : TargetLowering(TM) {
47 Subtarget = &TM.getSubtarget<X86Subtarget>();
48 X86ScalarSSEf64 = Subtarget->hasSSE2();
49 X86ScalarSSEf32 = Subtarget->hasSSE1();
50 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
54 RegInfo = TM.getRegisterInfo();
56 // Set up the TargetLowering object.
58 // X86 is weird, it always uses i8 for shift amounts and setcc results.
59 setShiftAmountType(MVT::i8);
60 setSetCCResultType(MVT::i8);
61 setSetCCResultContents(ZeroOrOneSetCCResult);
62 setSchedulingPreference(SchedulingForRegPressure);
63 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
64 setStackPointerRegisterToSaveRestore(X86StackPtr);
66 if (Subtarget->isTargetDarwin()) {
67 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
68 setUseUnderscoreSetJmp(false);
69 setUseUnderscoreLongJmp(false);
70 } else if (Subtarget->isTargetMingw()) {
71 // MS runtime is weird: it exports _setjmp, but longjmp!
72 setUseUnderscoreSetJmp(true);
73 setUseUnderscoreLongJmp(false);
75 setUseUnderscoreSetJmp(true);
76 setUseUnderscoreLongJmp(true);
79 // Set up the register classes.
80 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
81 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
82 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
83 if (Subtarget->is64Bit())
84 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
86 setLoadXAction(ISD::SEXTLOAD, MVT::i1, Promote);
88 // We don't accept any truncstore of integer registers.
89 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
90 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
91 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
92 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
93 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
94 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
96 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
98 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
99 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
100 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
102 if (Subtarget->is64Bit()) {
103 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
104 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
107 // If SSE i64 SINT_TO_FP is not available, expand i32 UINT_TO_FP.
108 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Expand);
110 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
113 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
115 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
116 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
117 // SSE has no i16 to fp conversion, only i32
118 if (X86ScalarSSEf32) {
119 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
120 // f32 and f64 cases are Legal, f80 case is not
121 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
123 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
124 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
127 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
128 // are Legal, f80 is custom lowered.
129 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
130 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
132 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
134 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
135 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
137 if (X86ScalarSSEf32) {
138 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
139 // f32 and f64 cases are Legal, f80 case is not
140 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
142 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
143 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
146 // Handle FP_TO_UINT by promoting the destination to a larger signed
148 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
149 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
150 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
152 if (Subtarget->is64Bit()) {
153 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
154 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
156 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
157 // Expand FP_TO_UINT into a select.
158 // FIXME: We would like to use a Custom expander here eventually to do
159 // the optimal thing for SSE vs. the default expansion in the legalizer.
160 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
162 // With SSE3 we can use fisttpll to convert to a signed i64.
163 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
166 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
167 if (!X86ScalarSSEf64) {
168 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
169 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
172 // Scalar integer divide and remainder are lowered to use operations that
173 // produce two results, to match the available instructions. This exposes
174 // the two-result form to trivial CSE, which is able to combine x/y and x%y
175 // into a single instruction.
177 // Scalar integer multiply-high is also lowered to use two-result
178 // operations, to match the available instructions. However, plain multiply
179 // (low) operations are left as Legal, as there are single-result
180 // instructions for this in x86. Using the two-result multiply instructions
181 // when both high and low results are needed must be arranged by dagcombine.
182 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
183 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
184 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
185 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
186 setOperationAction(ISD::SREM , MVT::i8 , Expand);
187 setOperationAction(ISD::UREM , MVT::i8 , Expand);
188 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
189 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
190 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
191 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
192 setOperationAction(ISD::SREM , MVT::i16 , Expand);
193 setOperationAction(ISD::UREM , MVT::i16 , Expand);
194 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
195 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
196 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
197 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
198 setOperationAction(ISD::SREM , MVT::i32 , Expand);
199 setOperationAction(ISD::UREM , MVT::i32 , Expand);
200 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
201 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
202 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
203 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
204 setOperationAction(ISD::SREM , MVT::i64 , Expand);
205 setOperationAction(ISD::UREM , MVT::i64 , Expand);
207 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
208 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
209 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
210 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
211 setOperationAction(ISD::MEMMOVE , 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::f64 , Expand);
219 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
221 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
222 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
223 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
224 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
225 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
226 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
227 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
228 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
229 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
230 if (Subtarget->is64Bit()) {
231 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
232 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
233 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
236 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
237 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
239 // These should be promoted to a larger select which is supported.
240 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
241 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
242 // X86 wants to expand cmov itself.
243 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
244 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
245 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
246 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
247 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
248 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
249 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
250 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
251 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
252 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
253 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
254 if (Subtarget->is64Bit()) {
255 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
256 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
258 // X86 ret instruction may pop stack.
259 setOperationAction(ISD::RET , MVT::Other, Custom);
260 if (!Subtarget->is64Bit())
261 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
264 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
265 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
266 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
267 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
268 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
269 if (Subtarget->is64Bit()) {
270 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
271 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
272 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
273 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
275 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
276 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
277 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
278 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
279 // X86 wants to expand memset / memcpy itself.
280 setOperationAction(ISD::MEMSET , MVT::Other, Custom);
281 setOperationAction(ISD::MEMCPY , MVT::Other, Custom);
283 if (!Subtarget->hasSSE2())
284 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
287 // Use the default ISD::LOCATION, ISD::DECLARE expansion.
288 setOperationAction(ISD::LOCATION, MVT::Other, Expand);
289 // FIXME - use subtarget debug flags
290 if (!Subtarget->isTargetDarwin() &&
291 !Subtarget->isTargetELF() &&
292 !Subtarget->isTargetCygMing())
293 setOperationAction(ISD::LABEL, MVT::Other, Expand);
295 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
296 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
297 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
298 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
299 if (Subtarget->is64Bit()) {
301 setExceptionPointerRegister(X86::RAX);
302 setExceptionSelectorRegister(X86::RDX);
304 setExceptionPointerRegister(X86::EAX);
305 setExceptionSelectorRegister(X86::EDX);
307 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
309 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
311 setOperationAction(ISD::TRAP, MVT::Other, Legal);
313 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
314 setOperationAction(ISD::VASTART , MVT::Other, Custom);
315 setOperationAction(ISD::VAARG , MVT::Other, Expand);
316 setOperationAction(ISD::VAEND , MVT::Other, Expand);
317 if (Subtarget->is64Bit())
318 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
320 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
322 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
323 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
324 if (Subtarget->is64Bit())
325 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
326 if (Subtarget->isTargetCygMing())
327 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
329 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
331 if (X86ScalarSSEf64) {
332 // f32 and f64 use SSE.
333 // Set up the FP register classes.
334 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
335 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
337 // Use ANDPD to simulate FABS.
338 setOperationAction(ISD::FABS , MVT::f64, Custom);
339 setOperationAction(ISD::FABS , MVT::f32, Custom);
341 // Use XORP to simulate FNEG.
342 setOperationAction(ISD::FNEG , MVT::f64, Custom);
343 setOperationAction(ISD::FNEG , MVT::f32, Custom);
345 // Use ANDPD and ORPD to simulate FCOPYSIGN.
346 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
347 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
349 // We don't support sin/cos/fmod
350 setOperationAction(ISD::FSIN , MVT::f64, Expand);
351 setOperationAction(ISD::FCOS , MVT::f64, Expand);
352 setOperationAction(ISD::FREM , MVT::f64, Expand);
353 setOperationAction(ISD::FSIN , MVT::f32, Expand);
354 setOperationAction(ISD::FCOS , MVT::f32, Expand);
355 setOperationAction(ISD::FREM , MVT::f32, Expand);
357 // Expand FP immediates into loads from the stack, except for the special
359 addLegalFPImmediate(APFloat(+0.0)); // xorpd
360 addLegalFPImmediate(APFloat(+0.0f)); // xorps
362 // Floating truncations from f80 and extensions to f80 go through memory.
363 // If optimizing, we lie about this though and handle it in
364 // InstructionSelectPreprocess so that dagcombine2 can hack on these.
366 setConvertAction(MVT::f32, MVT::f80, Expand);
367 setConvertAction(MVT::f64, MVT::f80, Expand);
368 setConvertAction(MVT::f80, MVT::f32, Expand);
369 setConvertAction(MVT::f80, MVT::f64, Expand);
371 } else if (X86ScalarSSEf32) {
372 // Use SSE for f32, x87 for f64.
373 // Set up the FP register classes.
374 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
375 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
377 // Use ANDPS to simulate FABS.
378 setOperationAction(ISD::FABS , MVT::f32, Custom);
380 // Use XORP to simulate FNEG.
381 setOperationAction(ISD::FNEG , MVT::f32, Custom);
383 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
385 // Use ANDPS and ORPS to simulate FCOPYSIGN.
386 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
387 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
389 // We don't support sin/cos/fmod
390 setOperationAction(ISD::FSIN , MVT::f32, Expand);
391 setOperationAction(ISD::FCOS , MVT::f32, Expand);
392 setOperationAction(ISD::FREM , MVT::f32, Expand);
394 // Special cases we handle for FP constants.
395 addLegalFPImmediate(APFloat(+0.0f)); // xorps
396 addLegalFPImmediate(APFloat(+0.0)); // FLD0
397 addLegalFPImmediate(APFloat(+1.0)); // FLD1
398 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
399 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
401 // SSE <-> X87 conversions go through memory. If optimizing, we lie about
402 // this though and handle it in InstructionSelectPreprocess so that
403 // dagcombine2 can hack on these.
405 setConvertAction(MVT::f32, MVT::f64, Expand);
406 setConvertAction(MVT::f32, MVT::f80, Expand);
407 setConvertAction(MVT::f80, MVT::f32, Expand);
408 setConvertAction(MVT::f64, MVT::f32, Expand);
409 // And x87->x87 truncations also.
410 setConvertAction(MVT::f80, MVT::f64, Expand);
414 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
415 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
418 // f32 and f64 in x87.
419 // Set up the FP register classes.
420 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
421 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
423 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
424 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
425 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
426 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
428 // Floating truncations go through memory. If optimizing, we lie about
429 // this though and handle it in InstructionSelectPreprocess so that
430 // dagcombine2 can hack on these.
432 setConvertAction(MVT::f80, MVT::f32, Expand);
433 setConvertAction(MVT::f64, MVT::f32, Expand);
434 setConvertAction(MVT::f80, MVT::f64, Expand);
438 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
439 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
441 addLegalFPImmediate(APFloat(+0.0)); // FLD0
442 addLegalFPImmediate(APFloat(+1.0)); // FLD1
443 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
444 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
445 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
446 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
447 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
448 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
451 // Long double always uses X87.
452 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
453 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
454 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
456 APFloat TmpFlt(+0.0);
457 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
458 addLegalFPImmediate(TmpFlt); // FLD0
460 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
461 APFloat TmpFlt2(+1.0);
462 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
463 addLegalFPImmediate(TmpFlt2); // FLD1
464 TmpFlt2.changeSign();
465 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
469 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
470 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
473 // Always use a library call for pow.
474 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
475 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
476 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
478 // First set operation action for all vector types to expand. Then we
479 // will selectively turn on ones that can be effectively codegen'd.
480 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
481 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
482 setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
483 setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
484 setOperationAction(ISD::FADD, (MVT::ValueType)VT, Expand);
485 setOperationAction(ISD::FNEG, (MVT::ValueType)VT, Expand);
486 setOperationAction(ISD::FSUB, (MVT::ValueType)VT, Expand);
487 setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
488 setOperationAction(ISD::FMUL, (MVT::ValueType)VT, Expand);
489 setOperationAction(ISD::SDIV, (MVT::ValueType)VT, Expand);
490 setOperationAction(ISD::UDIV, (MVT::ValueType)VT, Expand);
491 setOperationAction(ISD::FDIV, (MVT::ValueType)VT, Expand);
492 setOperationAction(ISD::SREM, (MVT::ValueType)VT, Expand);
493 setOperationAction(ISD::UREM, (MVT::ValueType)VT, Expand);
494 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
495 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Expand);
496 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
497 setOperationAction(ISD::INSERT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
498 setOperationAction(ISD::FABS, (MVT::ValueType)VT, Expand);
499 setOperationAction(ISD::FSIN, (MVT::ValueType)VT, Expand);
500 setOperationAction(ISD::FCOS, (MVT::ValueType)VT, Expand);
501 setOperationAction(ISD::FREM, (MVT::ValueType)VT, Expand);
502 setOperationAction(ISD::FPOWI, (MVT::ValueType)VT, Expand);
503 setOperationAction(ISD::FSQRT, (MVT::ValueType)VT, Expand);
504 setOperationAction(ISD::FCOPYSIGN, (MVT::ValueType)VT, Expand);
505 setOperationAction(ISD::SMUL_LOHI, (MVT::ValueType)VT, Expand);
506 setOperationAction(ISD::UMUL_LOHI, (MVT::ValueType)VT, Expand);
507 setOperationAction(ISD::SDIVREM, (MVT::ValueType)VT, Expand);
508 setOperationAction(ISD::UDIVREM, (MVT::ValueType)VT, Expand);
509 setOperationAction(ISD::FPOW, (MVT::ValueType)VT, Expand);
510 setOperationAction(ISD::CTPOP, (MVT::ValueType)VT, Expand);
511 setOperationAction(ISD::CTTZ, (MVT::ValueType)VT, Expand);
512 setOperationAction(ISD::CTLZ, (MVT::ValueType)VT, Expand);
513 setOperationAction(ISD::SHL, (MVT::ValueType)VT, Expand);
514 setOperationAction(ISD::SRA, (MVT::ValueType)VT, Expand);
515 setOperationAction(ISD::SRL, (MVT::ValueType)VT, Expand);
516 setOperationAction(ISD::ROTL, (MVT::ValueType)VT, Expand);
517 setOperationAction(ISD::ROTR, (MVT::ValueType)VT, Expand);
518 setOperationAction(ISD::BSWAP, (MVT::ValueType)VT, Expand);
521 if (Subtarget->hasMMX()) {
522 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
523 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
524 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
525 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
527 // FIXME: add MMX packed arithmetics
529 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
530 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
531 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
532 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
534 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
535 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
536 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
537 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
539 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
540 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
542 setOperationAction(ISD::AND, MVT::v8i8, Promote);
543 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
544 setOperationAction(ISD::AND, MVT::v4i16, Promote);
545 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
546 setOperationAction(ISD::AND, MVT::v2i32, Promote);
547 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
548 setOperationAction(ISD::AND, MVT::v1i64, Legal);
550 setOperationAction(ISD::OR, MVT::v8i8, Promote);
551 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
552 setOperationAction(ISD::OR, MVT::v4i16, Promote);
553 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
554 setOperationAction(ISD::OR, MVT::v2i32, Promote);
555 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
556 setOperationAction(ISD::OR, MVT::v1i64, Legal);
558 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
559 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
560 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
561 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
562 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
563 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
564 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
566 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
567 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
568 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
569 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
570 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
571 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
572 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
574 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
575 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
576 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
577 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
579 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
580 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
581 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
582 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
584 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
585 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
586 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
589 if (Subtarget->hasSSE1()) {
590 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
592 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
593 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
594 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
595 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
596 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
597 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
598 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
599 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
600 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
601 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
602 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
605 if (Subtarget->hasSSE2()) {
606 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
607 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
608 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
609 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
610 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
612 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
613 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
614 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
615 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
616 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
617 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
618 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
619 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
620 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
621 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
622 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
623 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
624 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
625 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
626 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
628 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
629 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
630 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
631 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
632 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
634 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
635 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
636 // Do not attempt to custom lower non-power-of-2 vectors
637 if (!isPowerOf2_32(MVT::getVectorNumElements(VT)))
639 setOperationAction(ISD::BUILD_VECTOR, (MVT::ValueType)VT, Custom);
640 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Custom);
641 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Custom);
643 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
644 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
645 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
646 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
647 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
648 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
649 if (Subtarget->is64Bit()) {
650 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
651 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
654 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
655 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
656 setOperationAction(ISD::AND, (MVT::ValueType)VT, Promote);
657 AddPromotedToType (ISD::AND, (MVT::ValueType)VT, MVT::v2i64);
658 setOperationAction(ISD::OR, (MVT::ValueType)VT, Promote);
659 AddPromotedToType (ISD::OR, (MVT::ValueType)VT, MVT::v2i64);
660 setOperationAction(ISD::XOR, (MVT::ValueType)VT, Promote);
661 AddPromotedToType (ISD::XOR, (MVT::ValueType)VT, MVT::v2i64);
662 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Promote);
663 AddPromotedToType (ISD::LOAD, (MVT::ValueType)VT, MVT::v2i64);
664 setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
665 AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v2i64);
668 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
670 // Custom lower v2i64 and v2f64 selects.
671 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
672 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
673 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
674 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
677 if (Subtarget->hasSSE41()) {
678 // FIXME: Do we need to handle scalar-to-vector here?
679 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
681 // i8 and i16 vectors are custom , because the source register and source
682 // source memory operand types are not the same width. f32 vectors are
683 // custom since the immediate controlling the insert encodes additional
685 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
686 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
687 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Legal);
688 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
690 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
691 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
692 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
693 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
695 if (Subtarget->is64Bit()) {
696 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
697 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
701 // We want to custom lower some of our intrinsics.
702 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
704 // We have target-specific dag combine patterns for the following nodes:
705 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
706 setTargetDAGCombine(ISD::SELECT);
707 setTargetDAGCombine(ISD::STORE);
709 computeRegisterProperties();
711 // FIXME: These should be based on subtarget info. Plus, the values should
712 // be smaller when we are in optimizing for size mode.
713 maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
714 maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
715 maxStoresPerMemmove = 16; // For %llvm.memmove -> sequence of stores
716 allowUnalignedMemoryAccesses = true; // x86 supports it!
719 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
720 /// the desired ByVal argument alignment.
721 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
724 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
725 if (VTy->getBitWidth() == 128)
727 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
728 unsigned EltAlign = 0;
729 getMaxByValAlign(ATy->getElementType(), EltAlign);
730 if (EltAlign > MaxAlign)
732 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
733 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
734 unsigned EltAlign = 0;
735 getMaxByValAlign(STy->getElementType(i), EltAlign);
736 if (EltAlign > MaxAlign)
745 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
746 /// function arguments in the caller parameter area. For X86, aggregates
747 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
748 /// are at 4-byte boundaries.
749 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
750 if (Subtarget->is64Bit())
751 return getTargetData()->getABITypeAlignment(Ty);
753 if (Subtarget->hasSSE1())
754 getMaxByValAlign(Ty, Align);
758 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
760 SDOperand X86TargetLowering::getPICJumpTableRelocBase(SDOperand Table,
761 SelectionDAG &DAG) const {
762 if (usesGlobalOffsetTable())
763 return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
764 if (!Subtarget->isPICStyleRIPRel())
765 return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
769 //===----------------------------------------------------------------------===//
770 // Return Value Calling Convention Implementation
771 //===----------------------------------------------------------------------===//
773 #include "X86GenCallingConv.inc"
775 /// GetPossiblePreceedingTailCall - Get preceeding X86ISD::TAILCALL node if it
776 /// exists skip possible ISD:TokenFactor.
777 static SDOperand GetPossiblePreceedingTailCall(SDOperand Chain) {
778 if (Chain.getOpcode() == X86ISD::TAILCALL) {
780 } else if (Chain.getOpcode() == ISD::TokenFactor) {
781 if (Chain.getNumOperands() &&
782 Chain.getOperand(0).getOpcode() == X86ISD::TAILCALL)
783 return Chain.getOperand(0);
788 /// LowerRET - Lower an ISD::RET node.
789 SDOperand X86TargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG) {
790 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
792 SmallVector<CCValAssign, 16> RVLocs;
793 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
794 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
795 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
796 CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
798 // If this is the first return lowered for this function, add the regs to the
799 // liveout set for the function.
800 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
801 for (unsigned i = 0; i != RVLocs.size(); ++i)
802 if (RVLocs[i].isRegLoc())
803 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
805 SDOperand Chain = Op.getOperand(0);
807 // Handle tail call return.
808 Chain = GetPossiblePreceedingTailCall(Chain);
809 if (Chain.getOpcode() == X86ISD::TAILCALL) {
810 SDOperand TailCall = Chain;
811 SDOperand TargetAddress = TailCall.getOperand(1);
812 SDOperand StackAdjustment = TailCall.getOperand(2);
813 assert(((TargetAddress.getOpcode() == ISD::Register &&
814 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::ECX ||
815 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
816 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
817 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
818 "Expecting an global address, external symbol, or register");
819 assert(StackAdjustment.getOpcode() == ISD::Constant &&
820 "Expecting a const value");
822 SmallVector<SDOperand,8> Operands;
823 Operands.push_back(Chain.getOperand(0));
824 Operands.push_back(TargetAddress);
825 Operands.push_back(StackAdjustment);
826 // Copy registers used by the call. Last operand is a flag so it is not
828 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
829 Operands.push_back(Chain.getOperand(i));
831 return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0],
838 // Copy the result values into the output registers.
839 if (RVLocs.size() != 1 || !RVLocs[0].isRegLoc() ||
840 RVLocs[0].getLocReg() != X86::ST0) {
841 for (unsigned i = 0; i != RVLocs.size(); ++i) {
842 CCValAssign &VA = RVLocs[i];
843 assert(VA.isRegLoc() && "Can only return in registers!");
844 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1),
846 Flag = Chain.getValue(1);
849 // We need to handle a destination of ST0 specially, because it isn't really
851 SDOperand Value = Op.getOperand(1);
853 // an XMM register onto the fp-stack. Do this with an FP_EXTEND to f80.
854 // This will get legalized into a load/store if it can't get optimized away.
855 if (isScalarFPTypeInSSEReg(RVLocs[0].getValVT()))
856 Value = DAG.getNode(ISD::FP_EXTEND, MVT::f80, Value);
858 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
859 SDOperand Ops[] = { Chain, Value };
860 Chain = DAG.getNode(X86ISD::FP_SET_RESULT, Tys, Ops, 2);
861 Flag = Chain.getValue(1);
864 SDOperand BytesToPop = DAG.getConstant(getBytesToPopOnReturn(), MVT::i16);
866 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop, Flag);
868 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop);
872 /// LowerCallResult - Lower the result values of an ISD::CALL into the
873 /// appropriate copies out of appropriate physical registers. This assumes that
874 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
875 /// being lowered. The returns a SDNode with the same number of values as the
877 SDNode *X86TargetLowering::
878 LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall,
879 unsigned CallingConv, SelectionDAG &DAG) {
881 // Assign locations to each value returned by this call.
882 SmallVector<CCValAssign, 16> RVLocs;
883 bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
884 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
885 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
887 SmallVector<SDOperand, 8> ResultVals;
889 // Copy all of the result registers out of their specified physreg.
890 if (RVLocs.size() != 1 || RVLocs[0].getLocReg() != X86::ST0) {
891 for (unsigned i = 0; i != RVLocs.size(); ++i) {
892 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
893 RVLocs[i].getValVT(), InFlag).getValue(1);
894 InFlag = Chain.getValue(2);
895 ResultVals.push_back(Chain.getValue(0));
898 // Copies from the FP stack are special, as ST0 isn't a valid register
899 // before the fp stackifier runs.
901 // Copy ST0 into an RFP register with FP_GET_RESULT. If this will end up
902 // in an SSE register, copy it out as F80 and do a truncate, otherwise use
903 // the specified value type.
904 MVT::ValueType GetResultTy = RVLocs[0].getValVT();
905 if (isScalarFPTypeInSSEReg(GetResultTy))
906 GetResultTy = MVT::f80;
907 SDVTList Tys = DAG.getVTList(GetResultTy, MVT::Other, MVT::Flag);
909 SDOperand GROps[] = { Chain, InFlag };
910 SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, GROps, 2);
911 Chain = RetVal.getValue(1);
912 InFlag = RetVal.getValue(2);
914 // If we want the result in an SSE register, use an FP_TRUNCATE to get it
916 if (GetResultTy != RVLocs[0].getValVT())
917 RetVal = DAG.getNode(ISD::FP_ROUND, RVLocs[0].getValVT(), RetVal,
918 // This truncation won't change the value.
919 DAG.getIntPtrConstant(1));
921 ResultVals.push_back(RetVal);
924 // Merge everything together with a MERGE_VALUES node.
925 ResultVals.push_back(Chain);
926 return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
927 &ResultVals[0], ResultVals.size()).Val;
930 /// LowerCallResultToTwo64BitRegs - Lower the result values of an x86-64
931 /// ISD::CALL where the results are known to be in two 64-bit registers,
932 /// e.g. XMM0 and XMM1. This simplify store the two values back to the
933 /// fixed stack slot allocated for StructRet.
934 SDNode *X86TargetLowering::
935 LowerCallResultToTwo64BitRegs(SDOperand Chain, SDOperand InFlag,
936 SDNode *TheCall, unsigned Reg1, unsigned Reg2,
937 MVT::ValueType VT, SelectionDAG &DAG) {
938 SDOperand RetVal1 = DAG.getCopyFromReg(Chain, Reg1, VT, InFlag);
939 Chain = RetVal1.getValue(1);
940 InFlag = RetVal1.getValue(2);
941 SDOperand RetVal2 = DAG.getCopyFromReg(Chain, Reg2, VT, InFlag);
942 Chain = RetVal2.getValue(1);
943 InFlag = RetVal2.getValue(2);
944 SDOperand FIN = TheCall->getOperand(5);
945 Chain = DAG.getStore(Chain, RetVal1, FIN, NULL, 0);
946 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
947 Chain = DAG.getStore(Chain, RetVal2, FIN, NULL, 0);
951 /// LowerCallResultToTwoX87Regs - Lower the result values of an x86-64 ISD::CALL
952 /// where the results are known to be in ST0 and ST1.
953 SDNode *X86TargetLowering::
954 LowerCallResultToTwoX87Regs(SDOperand Chain, SDOperand InFlag,
955 SDNode *TheCall, SelectionDAG &DAG) {
956 SmallVector<SDOperand, 8> ResultVals;
957 const MVT::ValueType VTs[] = { MVT::f80, MVT::f80, MVT::Other, MVT::Flag };
958 SDVTList Tys = DAG.getVTList(VTs, 4);
959 SDOperand Ops[] = { Chain, InFlag };
960 SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT2, Tys, Ops, 2);
961 Chain = RetVal.getValue(2);
962 SDOperand FIN = TheCall->getOperand(5);
963 Chain = DAG.getStore(Chain, RetVal.getValue(1), FIN, NULL, 0);
964 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(16));
965 Chain = DAG.getStore(Chain, RetVal, FIN, NULL, 0);
969 //===----------------------------------------------------------------------===//
970 // C & StdCall & Fast Calling Convention implementation
971 //===----------------------------------------------------------------------===//
972 // StdCall calling convention seems to be standard for many Windows' API
973 // routines and around. It differs from C calling convention just a little:
974 // callee should clean up the stack, not caller. Symbols should be also
975 // decorated in some fancy way :) It doesn't support any vector arguments.
976 // For info on fast calling convention see Fast Calling Convention (tail call)
977 // implementation LowerX86_32FastCCCallTo.
979 /// AddLiveIn - This helper function adds the specified physical register to the
980 /// MachineFunction as a live in value. It also creates a corresponding virtual
982 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
983 const TargetRegisterClass *RC) {
984 assert(RC->contains(PReg) && "Not the correct regclass!");
985 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
986 MF.getRegInfo().addLiveIn(PReg, VReg);
990 // Determines whether a CALL node uses struct return semantics.
991 static bool CallIsStructReturn(SDOperand Op) {
992 unsigned NumOps = (Op.getNumOperands() - 5) / 2;
996 ConstantSDNode *Flags = cast<ConstantSDNode>(Op.getOperand(6));
997 return Flags->getValue() & ISD::ParamFlags::StructReturn;
1000 // Determines whether a FORMAL_ARGUMENTS node uses struct return semantics.
1001 static bool ArgsAreStructReturn(SDOperand Op) {
1002 unsigned NumArgs = Op.Val->getNumValues() - 1;
1006 ConstantSDNode *Flags = cast<ConstantSDNode>(Op.getOperand(3));
1007 return Flags->getValue() & ISD::ParamFlags::StructReturn;
1010 // Determines whether a CALL or FORMAL_ARGUMENTS node requires the callee to pop
1011 // its own arguments. Callee pop is necessary to support tail calls.
1012 bool X86TargetLowering::IsCalleePop(SDOperand Op) {
1013 bool IsVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1017 switch (cast<ConstantSDNode>(Op.getOperand(1))->getValue()) {
1020 case CallingConv::X86_StdCall:
1021 return !Subtarget->is64Bit();
1022 case CallingConv::X86_FastCall:
1023 return !Subtarget->is64Bit();
1024 case CallingConv::Fast:
1025 return PerformTailCallOpt;
1029 // Selects the correct CCAssignFn for a CALL or FORMAL_ARGUMENTS node.
1030 CCAssignFn *X86TargetLowering::CCAssignFnForNode(SDOperand Op) const {
1031 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1033 if (Subtarget->is64Bit()) {
1034 if (CC == CallingConv::Fast && PerformTailCallOpt)
1035 return CC_X86_64_TailCall;
1040 if (CC == CallingConv::X86_FastCall)
1041 return CC_X86_32_FastCall;
1042 else if (CC == CallingConv::Fast && PerformTailCallOpt)
1043 return CC_X86_32_TailCall;
1048 // Selects the appropriate decoration to apply to a MachineFunction containing a
1049 // given FORMAL_ARGUMENTS node.
1051 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDOperand Op) {
1052 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1053 if (CC == CallingConv::X86_FastCall)
1055 else if (CC == CallingConv::X86_StdCall)
1060 // IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could possibly
1061 // be overwritten when lowering the outgoing arguments in a tail call. Currently
1062 // the implementation of this call is very conservative and assumes all
1063 // arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with virtual
1064 // registers would be overwritten by direct lowering.
1065 static bool IsPossiblyOverwrittenArgumentOfTailCall(SDOperand Op,
1066 MachineFrameInfo * MFI) {
1067 RegisterSDNode * OpReg = NULL;
1068 FrameIndexSDNode * FrameIdxNode = NULL;
1070 if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
1071 (Op.getOpcode()== ISD::CopyFromReg &&
1072 (OpReg = dyn_cast<RegisterSDNode>(Op.getOperand(1))) &&
1073 (OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister)) ||
1074 (Op.getOpcode() == ISD::LOAD &&
1075 (FrameIdxNode = dyn_cast<FrameIndexSDNode>(Op.getOperand(1))) &&
1076 (MFI->isFixedObjectIndex((FrameIdx = FrameIdxNode->getIndex()))) &&
1077 (MFI->getObjectOffset(FrameIdx) >= 0)))
1082 // CopyTailCallClobberedArgumentsToVRegs - Create virtual registers for all
1083 // arguments to force loading and guarantee that arguments sourcing from
1084 // incomming parameters are not overwriting each other.
1086 CopyTailCallClobberedArgumentsToVRegs(SDOperand Chain,
1087 SmallVector<std::pair<unsigned, SDOperand>, 8> &TailCallClobberedVRegs,
1089 MachineFunction &MF,
1090 const TargetLowering * TL) {
1093 for (unsigned i = 0, e = TailCallClobberedVRegs.size(); i != e; i++) {
1094 SDOperand Arg = TailCallClobberedVRegs[i].second;
1095 unsigned Idx = TailCallClobberedVRegs[i].first;
1098 createVirtualRegister(TL->getRegClassFor(Arg.getValueType()));
1099 Chain = DAG.getCopyToReg(Chain, VReg, Arg, InFlag);
1100 InFlag = Chain.getValue(1);
1101 Arg = DAG.getCopyFromReg(Chain, VReg, Arg.getValueType(), InFlag);
1102 TailCallClobberedVRegs[i] = std::make_pair(Idx, Arg);
1103 Chain = Arg.getValue(1);
1104 InFlag = Arg.getValue(2);
1109 // CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1110 // by "Src" to address "Dst" with size and alignment information specified by
1111 // the specific parameter attribute. The copy will be passed as a byval function
1114 CreateCopyOfByValArgument(SDOperand Src, SDOperand Dst, SDOperand Chain,
1115 unsigned Flags, SelectionDAG &DAG) {
1116 unsigned Align = 1 <<
1117 ((Flags & ISD::ParamFlags::ByValAlign) >> ISD::ParamFlags::ByValAlignOffs);
1118 unsigned Size = (Flags & ISD::ParamFlags::ByValSize) >>
1119 ISD::ParamFlags::ByValSizeOffs;
1120 SDOperand AlignNode = DAG.getConstant(Align, MVT::i32);
1121 SDOperand SizeNode = DAG.getConstant(Size, MVT::i32);
1122 SDOperand AlwaysInline = DAG.getConstant(1, MVT::i32);
1123 return DAG.getMemcpy(Chain, Dst, Src, SizeNode, AlignNode, AlwaysInline);
1126 SDOperand X86TargetLowering::LowerMemArgument(SDOperand Op, SelectionDAG &DAG,
1127 const CCValAssign &VA,
1128 MachineFrameInfo *MFI,
1130 SDOperand Root, unsigned i) {
1131 // Create the nodes corresponding to a load from this parameter slot.
1132 unsigned Flags = cast<ConstantSDNode>(Op.getOperand(3 + i))->getValue();
1133 bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1134 bool isByVal = Flags & ISD::ParamFlags::ByVal;
1135 bool isImmutable = !AlwaysUseMutable && !isByVal;
1137 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1138 // changed with more analysis.
1139 // In case of tail call optimization mark all arguments mutable. Since they
1140 // could be overwritten by lowering of arguments in case of a tail call.
1141 int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
1142 VA.getLocMemOffset(), isImmutable);
1143 SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
1146 return DAG.getLoad(VA.getValVT(), Root, FIN,
1147 PseudoSourceValue::getFixedStack(), FI);
1151 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
1152 MachineFunction &MF = DAG.getMachineFunction();
1153 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1155 const Function* Fn = MF.getFunction();
1156 if (Fn->hasExternalLinkage() &&
1157 Subtarget->isTargetCygMing() &&
1158 Fn->getName() == "main")
1159 FuncInfo->setForceFramePointer(true);
1161 // Decorate the function name.
1162 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1164 MachineFrameInfo *MFI = MF.getFrameInfo();
1165 SDOperand Root = Op.getOperand(0);
1166 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1167 unsigned CC = MF.getFunction()->getCallingConv();
1168 bool Is64Bit = Subtarget->is64Bit();
1170 assert(!(isVarArg && CC == CallingConv::Fast) &&
1171 "Var args not supported with calling convention fastcc");
1173 // Assign locations to all of the incoming arguments.
1174 SmallVector<CCValAssign, 16> ArgLocs;
1175 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1176 CCInfo.AnalyzeFormalArguments(Op.Val, CCAssignFnForNode(Op));
1178 SmallVector<SDOperand, 8> ArgValues;
1179 unsigned LastVal = ~0U;
1180 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1181 CCValAssign &VA = ArgLocs[i];
1182 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1184 assert(VA.getValNo() != LastVal &&
1185 "Don't support value assigned to multiple locs yet");
1186 LastVal = VA.getValNo();
1188 if (VA.isRegLoc()) {
1189 MVT::ValueType RegVT = VA.getLocVT();
1190 TargetRegisterClass *RC;
1191 if (RegVT == MVT::i32)
1192 RC = X86::GR32RegisterClass;
1193 else if (Is64Bit && RegVT == MVT::i64)
1194 RC = X86::GR64RegisterClass;
1195 else if (RegVT == MVT::f32)
1196 RC = X86::FR32RegisterClass;
1197 else if (RegVT == MVT::f64)
1198 RC = X86::FR64RegisterClass;
1200 assert(MVT::isVector(RegVT));
1201 if (Is64Bit && MVT::getSizeInBits(RegVT) == 64) {
1202 RC = X86::GR64RegisterClass; // MMX values are passed in GPRs.
1205 RC = X86::VR128RegisterClass;
1208 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1209 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1211 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1212 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1214 if (VA.getLocInfo() == CCValAssign::SExt)
1215 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1216 DAG.getValueType(VA.getValVT()));
1217 else if (VA.getLocInfo() == CCValAssign::ZExt)
1218 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1219 DAG.getValueType(VA.getValVT()));
1221 if (VA.getLocInfo() != CCValAssign::Full)
1222 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1224 // Handle MMX values passed in GPRs.
1225 if (Is64Bit && RegVT != VA.getLocVT() && RC == X86::GR64RegisterClass &&
1226 MVT::getSizeInBits(RegVT) == 64)
1227 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1229 ArgValues.push_back(ArgValue);
1231 assert(VA.isMemLoc());
1232 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1236 unsigned StackSize = CCInfo.getNextStackOffset();
1237 // align stack specially for tail calls
1238 if (CC == CallingConv::Fast)
1239 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1241 // If the function takes variable number of arguments, make a frame index for
1242 // the start of the first vararg value... for expansion of llvm.va_start.
1244 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1245 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1248 static const unsigned GPR64ArgRegs[] = {
1249 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1251 static const unsigned XMMArgRegs[] = {
1252 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1253 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1256 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 6);
1257 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1259 // For X86-64, if there are vararg parameters that are passed via
1260 // registers, then we must store them to their spots on the stack so they
1261 // may be loaded by deferencing the result of va_next.
1262 VarArgsGPOffset = NumIntRegs * 8;
1263 VarArgsFPOffset = 6 * 8 + NumXMMRegs * 16;
1264 RegSaveFrameIndex = MFI->CreateStackObject(6 * 8 + 8 * 16, 16);
1266 // Store the integer parameter registers.
1267 SmallVector<SDOperand, 8> MemOps;
1268 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1269 SDOperand FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1270 DAG.getIntPtrConstant(VarArgsGPOffset));
1271 for (; NumIntRegs != 6; ++NumIntRegs) {
1272 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1273 X86::GR64RegisterClass);
1274 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1276 DAG.getStore(Val.getValue(1), Val, FIN,
1277 PseudoSourceValue::getFixedStack(),
1279 MemOps.push_back(Store);
1280 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1281 DAG.getIntPtrConstant(8));
1284 // Now store the XMM (fp + vector) parameter registers.
1285 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1286 DAG.getIntPtrConstant(VarArgsFPOffset));
1287 for (; NumXMMRegs != 8; ++NumXMMRegs) {
1288 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1289 X86::VR128RegisterClass);
1290 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1292 DAG.getStore(Val.getValue(1), Val, FIN,
1293 PseudoSourceValue::getFixedStack(),
1295 MemOps.push_back(Store);
1296 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1297 DAG.getIntPtrConstant(16));
1299 if (!MemOps.empty())
1300 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1301 &MemOps[0], MemOps.size());
1305 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1306 // arguments and the arguments after the retaddr has been pushed are
1308 if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1309 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1310 (StackSize & 7) == 0)
1313 ArgValues.push_back(Root);
1315 // Some CCs need callee pop.
1316 if (IsCalleePop(Op)) {
1317 BytesToPopOnReturn = StackSize; // Callee pops everything.
1318 BytesCallerReserves = 0;
1320 BytesToPopOnReturn = 0; // Callee pops nothing.
1321 // If this is an sret function, the return should pop the hidden pointer.
1322 if (!Is64Bit && ArgsAreStructReturn(Op))
1323 BytesToPopOnReturn = 4;
1324 BytesCallerReserves = StackSize;
1328 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1329 if (CC == CallingConv::X86_FastCall)
1330 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1333 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1335 // Return the new list of results.
1336 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1337 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1341 X86TargetLowering::LowerMemOpCallTo(SDOperand Op, SelectionDAG &DAG,
1342 const SDOperand &StackPtr,
1343 const CCValAssign &VA,
1346 unsigned LocMemOffset = VA.getLocMemOffset();
1347 SDOperand PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1348 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1349 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1350 unsigned Flags = cast<ConstantSDNode>(FlagsOp)->getValue();
1351 if (Flags & ISD::ParamFlags::ByVal) {
1352 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG);
1354 return DAG.getStore(Chain, Arg, PtrOff,
1355 PseudoSourceValue::getStack(), LocMemOffset);
1358 /// ClassifyX86_64SRetCallReturn - Classify how to implement a x86-64
1359 /// struct return call to the specified function. X86-64 ABI specifies
1360 /// some SRet calls are actually returned in registers. Since current
1361 /// LLVM cannot represent multi-value calls, they are represent as
1362 /// calls where the results are passed in a hidden struct provided by
1363 /// the caller. This function examines the type of the struct to
1364 /// determine the correct way to implement the call.
1366 X86TargetLowering::ClassifyX86_64SRetCallReturn(const Function *Fn) {
1367 // FIXME: Disabled for now.
1368 return X86::InMemory;
1370 const PointerType *PTy = cast<PointerType>(Fn->arg_begin()->getType());
1371 const Type *RTy = PTy->getElementType();
1372 unsigned Size = getTargetData()->getABITypeSize(RTy);
1373 if (Size != 16 && Size != 32)
1374 return X86::InMemory;
1377 const StructType *STy = dyn_cast<StructType>(RTy);
1378 if (!STy) return X86::InMemory;
1379 if (STy->getNumElements() == 2 &&
1380 STy->getElementType(0) == Type::X86_FP80Ty &&
1381 STy->getElementType(1) == Type::X86_FP80Ty)
1386 for (Type::subtype_iterator I = RTy->subtype_begin(), E = RTy->subtype_end();
1388 const Type *STy = I->get();
1389 if (!STy->isFPOrFPVector()) {
1397 return X86::InGPR64;
1400 void X86TargetLowering::X86_64AnalyzeSRetCallOperands(SDNode *TheCall,
1403 unsigned NumOps = (TheCall->getNumOperands() - 5) / 2;
1404 for (unsigned i = 1; i != NumOps; ++i) {
1405 MVT::ValueType ArgVT = TheCall->getOperand(5+2*i).getValueType();
1406 SDOperand FlagOp = TheCall->getOperand(5+2*i+1);
1407 unsigned ArgFlags =cast<ConstantSDNode>(FlagOp)->getValue();
1408 if (Fn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo)) {
1409 cerr << "Call operand #" << i << " has unhandled type "
1410 << MVT::getValueTypeString(ArgVT) << "\n";
1416 SDOperand X86TargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
1417 MachineFunction &MF = DAG.getMachineFunction();
1418 MachineFrameInfo * MFI = MF.getFrameInfo();
1419 SDOperand Chain = Op.getOperand(0);
1420 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1421 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1422 bool IsTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0
1423 && CC == CallingConv::Fast && PerformTailCallOpt;
1424 SDOperand Callee = Op.getOperand(4);
1425 bool Is64Bit = Subtarget->is64Bit();
1426 bool IsStructRet = CallIsStructReturn(Op);
1428 assert(!(isVarArg && CC == CallingConv::Fast) &&
1429 "Var args not supported with calling convention fastcc");
1431 // Analyze operands of the call, assigning locations to each operand.
1432 SmallVector<CCValAssign, 16> ArgLocs;
1433 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1434 CCAssignFn *CCFn = CCAssignFnForNode(Op);
1436 X86::X86_64SRet SRetMethod = X86::InMemory;
1437 if (Is64Bit && IsStructRet)
1438 // FIXME: We can't figure out type of the sret structure for indirect
1439 // calls. We need to copy more information from CallSite to the ISD::CALL
1441 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1443 ClassifyX86_64SRetCallReturn(dyn_cast<Function>(G->getGlobal()));
1445 // UGLY HACK! For x86-64, some 128-bit aggregates are returns in a pair of
1446 // registers. Unfortunately, llvm does not support i128 yet so we pretend it's
1448 if (SRetMethod != X86::InMemory)
1449 X86_64AnalyzeSRetCallOperands(Op.Val, CCFn, CCInfo);
1451 CCInfo.AnalyzeCallOperands(Op.Val, CCFn);
1453 // Get a count of how many bytes are to be pushed on the stack.
1454 unsigned NumBytes = CCInfo.getNextStackOffset();
1455 if (CC == CallingConv::Fast)
1456 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1458 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1459 // arguments and the arguments after the retaddr has been pushed are aligned.
1460 if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1461 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1462 (NumBytes & 7) == 0)
1467 // Lower arguments at fp - stackoffset + fpdiff.
1468 unsigned NumBytesCallerPushed =
1469 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1470 FPDiff = NumBytesCallerPushed - NumBytes;
1472 // Set the delta of movement of the returnaddr stackslot.
1473 // But only set if delta is greater than previous delta.
1474 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1475 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1478 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes));
1480 SDOperand RetAddrFrIdx;
1482 // Adjust the Return address stack slot.
1484 MVT::ValueType VT = Is64Bit ? MVT::i64 : MVT::i32;
1485 RetAddrFrIdx = getReturnAddressFrameIndex(DAG);
1486 // Load the "old" Return address.
1488 DAG.getLoad(VT, Chain,RetAddrFrIdx, NULL, 0);
1489 Chain = SDOperand(RetAddrFrIdx.Val, 1);
1493 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1494 SmallVector<std::pair<unsigned, SDOperand>, 8> TailCallClobberedVRegs;
1495 SmallVector<SDOperand, 8> MemOpChains;
1499 // Walk the register/memloc assignments, inserting copies/loads. For tail
1500 // calls, remember all arguments for later special lowering.
1501 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1502 CCValAssign &VA = ArgLocs[i];
1503 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1505 // Promote the value if needed.
1506 switch (VA.getLocInfo()) {
1507 default: assert(0 && "Unknown loc info!");
1508 case CCValAssign::Full: break;
1509 case CCValAssign::SExt:
1510 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1512 case CCValAssign::ZExt:
1513 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1515 case CCValAssign::AExt:
1516 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1520 if (VA.isRegLoc()) {
1521 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1524 assert(VA.isMemLoc());
1525 if (StackPtr.Val == 0)
1526 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1528 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1530 } else if (IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)) {
1531 TailCallClobberedVRegs.push_back(std::make_pair(i,Arg));
1536 if (!MemOpChains.empty())
1537 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1538 &MemOpChains[0], MemOpChains.size());
1540 // Build a sequence of copy-to-reg nodes chained together with token chain
1541 // and flag operands which copy the outgoing args into registers.
1543 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1544 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1546 InFlag = Chain.getValue(1);
1549 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1551 // If we are tail calling and generating PIC/GOT style code load the address
1552 // of the callee into ecx. The value in ecx is used as target of the tail
1553 // jump. This is done to circumvent the ebx/callee-saved problem for tail
1554 // calls on PIC/GOT architectures. Normally we would just put the address of
1555 // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1556 // restored (since ebx is callee saved) before jumping to the target@PLT.
1557 if (!IsTailCall && !Is64Bit &&
1558 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1559 Subtarget->isPICStyleGOT()) {
1560 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1561 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1563 InFlag = Chain.getValue(1);
1564 } else if (!Is64Bit && IsTailCall &&
1565 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1566 Subtarget->isPICStyleGOT() ) {
1567 // Note: The actual moving to ecx is done further down.
1568 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1569 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1570 !G->getGlobal()->hasProtectedVisibility())
1571 Callee = LowerGlobalAddress(Callee, DAG);
1572 else if (isa<ExternalSymbolSDNode>(Callee))
1573 Callee = LowerExternalSymbol(Callee,DAG);
1576 if (Is64Bit && isVarArg) {
1577 // From AMD64 ABI document:
1578 // For calls that may call functions that use varargs or stdargs
1579 // (prototype-less calls or calls to functions containing ellipsis (...) in
1580 // the declaration) %al is used as hidden argument to specify the number
1581 // of SSE registers used. The contents of %al do not need to match exactly
1582 // the number of registers, but must be an ubound on the number of SSE
1583 // registers used and is in the range 0 - 8 inclusive.
1585 // Count the number of XMM registers allocated.
1586 static const unsigned XMMArgRegs[] = {
1587 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1588 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1590 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1592 Chain = DAG.getCopyToReg(Chain, X86::AL,
1593 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1594 InFlag = Chain.getValue(1);
1598 // For tail calls lower the arguments to the 'real' stack slot.
1600 SmallVector<SDOperand, 8> MemOpChains2;
1603 // Do not flag preceeding copytoreg stuff together with the following stuff.
1604 InFlag = SDOperand();
1606 Chain = CopyTailCallClobberedArgumentsToVRegs(Chain, TailCallClobberedVRegs,
1609 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1610 CCValAssign &VA = ArgLocs[i];
1611 if (!VA.isRegLoc()) {
1612 assert(VA.isMemLoc());
1613 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1614 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1615 unsigned Flags = cast<ConstantSDNode>(FlagsOp)->getValue();
1616 // Create frame index.
1617 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1618 uint32_t OpSize = (MVT::getSizeInBits(VA.getLocVT())+7)/8;
1619 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1620 FIN = DAG.getFrameIndex(FI, MVT::i32);
1622 // Find virtual register for this argument.
1624 for (unsigned idx=0, e= TailCallClobberedVRegs.size(); idx < e; idx++)
1625 if (TailCallClobberedVRegs[idx].first==i) {
1626 Arg = TailCallClobberedVRegs[idx].second;
1630 assert(IsPossiblyOverwrittenArgumentOfTailCall(Arg, MFI)==false ||
1631 (Found==true && "No corresponding Argument was found"));
1633 if (Flags & ISD::ParamFlags::ByVal) {
1634 // Copy relative to framepointer.
1635 MemOpChains2.push_back(CreateCopyOfByValArgument(Arg, FIN, Chain,
1638 // Store relative to framepointer.
1639 MemOpChains2.push_back(
1640 DAG.getStore(Chain, Arg, FIN,
1641 PseudoSourceValue::getFixedStack(), FI));
1646 if (!MemOpChains2.empty())
1647 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1648 &MemOpChains2[0], MemOpChains2.size());
1650 // Store the return address to the appropriate stack slot.
1652 // Calculate the new stack slot for the return address.
1653 int SlotSize = Is64Bit ? 8 : 4;
1654 int NewReturnAddrFI =
1655 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1656 MVT::ValueType VT = Is64Bit ? MVT::i64 : MVT::i32;
1657 SDOperand NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1658 Chain = DAG.getStore(Chain, RetAddrFrIdx, NewRetAddrFrIdx,
1659 PseudoSourceValue::getFixedStack(), NewReturnAddrFI);
1663 // If the callee is a GlobalAddress node (quite common, every direct call is)
1664 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1665 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1666 // We should use extra load for direct calls to dllimported functions in
1668 if ((IsTailCall || !Is64Bit ||
1669 getTargetMachine().getCodeModel() != CodeModel::Large)
1670 && !Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1671 getTargetMachine(), true))
1672 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1673 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1674 if (IsTailCall || !Is64Bit ||
1675 getTargetMachine().getCodeModel() != CodeModel::Large)
1676 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1677 } else if (IsTailCall) {
1678 unsigned Opc = Is64Bit ? X86::R9 : X86::ECX;
1680 Chain = DAG.getCopyToReg(Chain,
1681 DAG.getRegister(Opc, getPointerTy()),
1683 Callee = DAG.getRegister(Opc, getPointerTy());
1684 // Add register as live out.
1685 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1688 // Returns a chain & a flag for retval copy to use.
1689 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1690 SmallVector<SDOperand, 8> Ops;
1693 Ops.push_back(Chain);
1694 Ops.push_back(DAG.getIntPtrConstant(NumBytes));
1695 Ops.push_back(DAG.getIntPtrConstant(0));
1697 Ops.push_back(InFlag);
1698 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1699 InFlag = Chain.getValue(1);
1701 // Returns a chain & a flag for retval copy to use.
1702 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1706 Ops.push_back(Chain);
1707 Ops.push_back(Callee);
1710 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1712 // Add an implicit use GOT pointer in EBX.
1713 if (!IsTailCall && !Is64Bit &&
1714 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1715 Subtarget->isPICStyleGOT())
1716 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1718 // Add argument registers to the end of the list so that they are known live
1720 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1721 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1722 RegsToPass[i].second.getValueType()));
1725 Ops.push_back(InFlag);
1728 assert(InFlag.Val &&
1729 "Flag must be set. Depend on flag being set in LowerRET");
1730 Chain = DAG.getNode(X86ISD::TAILCALL,
1731 Op.Val->getVTList(), &Ops[0], Ops.size());
1733 return SDOperand(Chain.Val, Op.ResNo);
1736 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1737 InFlag = Chain.getValue(1);
1739 // Create the CALLSEQ_END node.
1740 unsigned NumBytesForCalleeToPush;
1741 if (IsCalleePop(Op))
1742 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1743 else if (!Is64Bit && IsStructRet)
1744 // If this is is a call to a struct-return function, the callee
1745 // pops the hidden struct pointer, so we have to push it back.
1746 // This is common for Darwin/X86, Linux & Mingw32 targets.
1747 NumBytesForCalleeToPush = 4;
1749 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1751 // Returns a flag for retval copy to use.
1752 Chain = DAG.getCALLSEQ_END(Chain,
1753 DAG.getIntPtrConstant(NumBytes),
1754 DAG.getIntPtrConstant(NumBytesForCalleeToPush),
1756 InFlag = Chain.getValue(1);
1758 // Handle result values, copying them out of physregs into vregs that we
1760 switch (SRetMethod) {
1762 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1764 return SDOperand(LowerCallResultToTwo64BitRegs(Chain, InFlag, Op.Val,
1766 MVT::i64, DAG), Op.ResNo);
1768 return SDOperand(LowerCallResultToTwo64BitRegs(Chain, InFlag, Op.Val,
1769 X86::XMM0, X86::XMM1,
1770 MVT::f64, DAG), Op.ResNo);
1772 return SDOperand(LowerCallResultToTwoX87Regs(Chain, InFlag, Op.Val, DAG),
1778 //===----------------------------------------------------------------------===//
1779 // Fast Calling Convention (tail call) implementation
1780 //===----------------------------------------------------------------------===//
1782 // Like std call, callee cleans arguments, convention except that ECX is
1783 // reserved for storing the tail called function address. Only 2 registers are
1784 // free for argument passing (inreg). Tail call optimization is performed
1786 // * tailcallopt is enabled
1787 // * caller/callee are fastcc
1788 // On X86_64 architecture with GOT-style position independent code only local
1789 // (within module) calls are supported at the moment.
1790 // To keep the stack aligned according to platform abi the function
1791 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1792 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1793 // If a tail called function callee has more arguments than the caller the
1794 // caller needs to make sure that there is room to move the RETADDR to. This is
1795 // achieved by reserving an area the size of the argument delta right after the
1796 // original REtADDR, but before the saved framepointer or the spilled registers
1797 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1809 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1810 /// for a 16 byte align requirement.
1811 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1812 SelectionDAG& DAG) {
1813 if (PerformTailCallOpt) {
1814 MachineFunction &MF = DAG.getMachineFunction();
1815 const TargetMachine &TM = MF.getTarget();
1816 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1817 unsigned StackAlignment = TFI.getStackAlignment();
1818 uint64_t AlignMask = StackAlignment - 1;
1819 int64_t Offset = StackSize;
1820 unsigned SlotSize = Subtarget->is64Bit() ? 8 : 4;
1821 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1822 // Number smaller than 12 so just add the difference.
1823 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1825 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1826 Offset = ((~AlignMask) & Offset) + StackAlignment +
1827 (StackAlignment-SlotSize);
1834 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1835 /// following the call is a return. A function is eligible if caller/callee
1836 /// calling conventions match, currently only fastcc supports tail calls, and
1837 /// the function CALL is immediatly followed by a RET.
1838 bool X86TargetLowering::IsEligibleForTailCallOptimization(SDOperand Call,
1840 SelectionDAG& DAG) const {
1841 if (!PerformTailCallOpt)
1844 // Check whether CALL node immediatly preceeds the RET node and whether the
1845 // return uses the result of the node or is a void return.
1846 unsigned NumOps = Ret.getNumOperands();
1848 (Ret.getOperand(0) == SDOperand(Call.Val,1) ||
1849 Ret.getOperand(0) == SDOperand(Call.Val,0))) ||
1851 Ret.getOperand(0) == SDOperand(Call.Val,Call.Val->getNumValues()-1) &&
1852 Ret.getOperand(1) == SDOperand(Call.Val,0))) {
1853 MachineFunction &MF = DAG.getMachineFunction();
1854 unsigned CallerCC = MF.getFunction()->getCallingConv();
1855 unsigned CalleeCC = cast<ConstantSDNode>(Call.getOperand(1))->getValue();
1856 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1857 SDOperand Callee = Call.getOperand(4);
1858 // On x86/32Bit PIC/GOT tail calls are supported.
1859 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1860 !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1863 // Can only do local tail calls (in same module, hidden or protected) on
1864 // x86_64 PIC/GOT at the moment.
1865 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1866 return G->getGlobal()->hasHiddenVisibility()
1867 || G->getGlobal()->hasProtectedVisibility();
1874 //===----------------------------------------------------------------------===//
1875 // Other Lowering Hooks
1876 //===----------------------------------------------------------------------===//
1879 SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1880 MachineFunction &MF = DAG.getMachineFunction();
1881 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1882 int ReturnAddrIndex = FuncInfo->getRAIndex();
1884 if (ReturnAddrIndex == 0) {
1885 // Set up a frame object for the return address.
1886 if (Subtarget->is64Bit())
1887 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
1889 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
1891 FuncInfo->setRAIndex(ReturnAddrIndex);
1894 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1899 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1900 /// specific condition code. It returns a false if it cannot do a direct
1901 /// translation. X86CC is the translated CondCode. LHS/RHS are modified as
1903 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1904 unsigned &X86CC, SDOperand &LHS, SDOperand &RHS,
1905 SelectionDAG &DAG) {
1906 X86CC = X86::COND_INVALID;
1908 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1909 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
1910 // X > -1 -> X == 0, jump !sign.
1911 RHS = DAG.getConstant(0, RHS.getValueType());
1912 X86CC = X86::COND_NS;
1914 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
1915 // X < 0 -> X == 0, jump on sign.
1916 X86CC = X86::COND_S;
1918 } else if (SetCCOpcode == ISD::SETLT && RHSC->getValue() == 1) {
1920 RHS = DAG.getConstant(0, RHS.getValueType());
1921 X86CC = X86::COND_LE;
1926 switch (SetCCOpcode) {
1928 case ISD::SETEQ: X86CC = X86::COND_E; break;
1929 case ISD::SETGT: X86CC = X86::COND_G; break;
1930 case ISD::SETGE: X86CC = X86::COND_GE; break;
1931 case ISD::SETLT: X86CC = X86::COND_L; break;
1932 case ISD::SETLE: X86CC = X86::COND_LE; break;
1933 case ISD::SETNE: X86CC = X86::COND_NE; break;
1934 case ISD::SETULT: X86CC = X86::COND_B; break;
1935 case ISD::SETUGT: X86CC = X86::COND_A; break;
1936 case ISD::SETULE: X86CC = X86::COND_BE; break;
1937 case ISD::SETUGE: X86CC = X86::COND_AE; break;
1940 // On a floating point condition, the flags are set as follows:
1942 // 0 | 0 | 0 | X > Y
1943 // 0 | 0 | 1 | X < Y
1944 // 1 | 0 | 0 | X == Y
1945 // 1 | 1 | 1 | unordered
1947 switch (SetCCOpcode) {
1950 case ISD::SETEQ: X86CC = X86::COND_E; break;
1951 case ISD::SETOLT: Flip = true; // Fallthrough
1953 case ISD::SETGT: X86CC = X86::COND_A; break;
1954 case ISD::SETOLE: Flip = true; // Fallthrough
1956 case ISD::SETGE: X86CC = X86::COND_AE; break;
1957 case ISD::SETUGT: Flip = true; // Fallthrough
1959 case ISD::SETLT: X86CC = X86::COND_B; break;
1960 case ISD::SETUGE: Flip = true; // Fallthrough
1962 case ISD::SETLE: X86CC = X86::COND_BE; break;
1964 case ISD::SETNE: X86CC = X86::COND_NE; break;
1965 case ISD::SETUO: X86CC = X86::COND_P; break;
1966 case ISD::SETO: X86CC = X86::COND_NP; break;
1969 std::swap(LHS, RHS);
1972 return X86CC != X86::COND_INVALID;
1975 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
1976 /// code. Current x86 isa includes the following FP cmov instructions:
1977 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
1978 static bool hasFPCMov(unsigned X86CC) {
1994 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
1995 /// true if Op is undef or if its value falls within the specified range (L, H].
1996 static bool isUndefOrInRange(SDOperand Op, unsigned Low, unsigned Hi) {
1997 if (Op.getOpcode() == ISD::UNDEF)
2000 unsigned Val = cast<ConstantSDNode>(Op)->getValue();
2001 return (Val >= Low && Val < Hi);
2004 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
2005 /// true if Op is undef or if its value equal to the specified value.
2006 static bool isUndefOrEqual(SDOperand Op, unsigned Val) {
2007 if (Op.getOpcode() == ISD::UNDEF)
2009 return cast<ConstantSDNode>(Op)->getValue() == Val;
2012 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2013 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
2014 bool X86::isPSHUFDMask(SDNode *N) {
2015 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2017 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
2020 // Check if the value doesn't reference the second vector.
2021 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2022 SDOperand Arg = N->getOperand(i);
2023 if (Arg.getOpcode() == ISD::UNDEF) continue;
2024 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2025 if (cast<ConstantSDNode>(Arg)->getValue() >= e)
2032 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2033 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2034 bool X86::isPSHUFHWMask(SDNode *N) {
2035 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2037 if (N->getNumOperands() != 8)
2040 // Lower quadword copied in order.
2041 for (unsigned i = 0; i != 4; ++i) {
2042 SDOperand Arg = N->getOperand(i);
2043 if (Arg.getOpcode() == ISD::UNDEF) continue;
2044 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2045 if (cast<ConstantSDNode>(Arg)->getValue() != i)
2049 // Upper quadword shuffled.
2050 for (unsigned i = 4; i != 8; ++i) {
2051 SDOperand Arg = N->getOperand(i);
2052 if (Arg.getOpcode() == ISD::UNDEF) continue;
2053 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2054 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2055 if (Val < 4 || Val > 7)
2062 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2063 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2064 bool X86::isPSHUFLWMask(SDNode *N) {
2065 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2067 if (N->getNumOperands() != 8)
2070 // Upper quadword copied in order.
2071 for (unsigned i = 4; i != 8; ++i)
2072 if (!isUndefOrEqual(N->getOperand(i), i))
2075 // Lower quadword shuffled.
2076 for (unsigned i = 0; i != 4; ++i)
2077 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2083 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2084 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2085 static bool isSHUFPMask(const SDOperand *Elems, unsigned NumElems) {
2086 if (NumElems != 2 && NumElems != 4) return false;
2088 unsigned Half = NumElems / 2;
2089 for (unsigned i = 0; i < Half; ++i)
2090 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2092 for (unsigned i = Half; i < NumElems; ++i)
2093 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2099 bool X86::isSHUFPMask(SDNode *N) {
2100 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2101 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2104 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2105 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2106 /// half elements to come from vector 1 (which would equal the dest.) and
2107 /// the upper half to come from vector 2.
2108 static bool isCommutedSHUFP(const SDOperand *Ops, unsigned NumOps) {
2109 if (NumOps != 2 && NumOps != 4) return false;
2111 unsigned Half = NumOps / 2;
2112 for (unsigned i = 0; i < Half; ++i)
2113 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2115 for (unsigned i = Half; i < NumOps; ++i)
2116 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2121 static bool isCommutedSHUFP(SDNode *N) {
2122 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2123 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2126 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2127 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2128 bool X86::isMOVHLPSMask(SDNode *N) {
2129 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2131 if (N->getNumOperands() != 4)
2134 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2135 return isUndefOrEqual(N->getOperand(0), 6) &&
2136 isUndefOrEqual(N->getOperand(1), 7) &&
2137 isUndefOrEqual(N->getOperand(2), 2) &&
2138 isUndefOrEqual(N->getOperand(3), 3);
2141 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2142 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2144 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2145 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2147 if (N->getNumOperands() != 4)
2150 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2151 return isUndefOrEqual(N->getOperand(0), 2) &&
2152 isUndefOrEqual(N->getOperand(1), 3) &&
2153 isUndefOrEqual(N->getOperand(2), 2) &&
2154 isUndefOrEqual(N->getOperand(3), 3);
2157 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2158 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2159 bool X86::isMOVLPMask(SDNode *N) {
2160 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2162 unsigned NumElems = N->getNumOperands();
2163 if (NumElems != 2 && NumElems != 4)
2166 for (unsigned i = 0; i < NumElems/2; ++i)
2167 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2170 for (unsigned i = NumElems/2; i < NumElems; ++i)
2171 if (!isUndefOrEqual(N->getOperand(i), i))
2177 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2178 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2180 bool X86::isMOVHPMask(SDNode *N) {
2181 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2183 unsigned NumElems = N->getNumOperands();
2184 if (NumElems != 2 && NumElems != 4)
2187 for (unsigned i = 0; i < NumElems/2; ++i)
2188 if (!isUndefOrEqual(N->getOperand(i), i))
2191 for (unsigned i = 0; i < NumElems/2; ++i) {
2192 SDOperand Arg = N->getOperand(i + NumElems/2);
2193 if (!isUndefOrEqual(Arg, i + NumElems))
2200 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2201 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2202 bool static isUNPCKLMask(const SDOperand *Elts, unsigned NumElts,
2203 bool V2IsSplat = false) {
2204 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2207 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2208 SDOperand BitI = Elts[i];
2209 SDOperand BitI1 = Elts[i+1];
2210 if (!isUndefOrEqual(BitI, j))
2213 if (isUndefOrEqual(BitI1, NumElts))
2216 if (!isUndefOrEqual(BitI1, j + NumElts))
2224 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2225 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2226 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2229 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2230 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2231 bool static isUNPCKHMask(const SDOperand *Elts, unsigned NumElts,
2232 bool V2IsSplat = false) {
2233 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2236 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2237 SDOperand BitI = Elts[i];
2238 SDOperand BitI1 = Elts[i+1];
2239 if (!isUndefOrEqual(BitI, j + NumElts/2))
2242 if (isUndefOrEqual(BitI1, NumElts))
2245 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2253 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2254 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2255 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2258 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2259 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2261 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2262 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2264 unsigned NumElems = N->getNumOperands();
2265 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2268 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2269 SDOperand BitI = N->getOperand(i);
2270 SDOperand BitI1 = N->getOperand(i+1);
2272 if (!isUndefOrEqual(BitI, j))
2274 if (!isUndefOrEqual(BitI1, j))
2281 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2282 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2284 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2285 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2287 unsigned NumElems = N->getNumOperands();
2288 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2291 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2292 SDOperand BitI = N->getOperand(i);
2293 SDOperand BitI1 = N->getOperand(i + 1);
2295 if (!isUndefOrEqual(BitI, j))
2297 if (!isUndefOrEqual(BitI1, j))
2304 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2305 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2306 /// MOVSD, and MOVD, i.e. setting the lowest element.
2307 static bool isMOVLMask(const SDOperand *Elts, unsigned NumElts) {
2308 if (NumElts != 2 && NumElts != 4)
2311 if (!isUndefOrEqual(Elts[0], NumElts))
2314 for (unsigned i = 1; i < NumElts; ++i) {
2315 if (!isUndefOrEqual(Elts[i], i))
2322 bool X86::isMOVLMask(SDNode *N) {
2323 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2324 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2327 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2328 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2329 /// element of vector 2 and the other elements to come from vector 1 in order.
2330 static bool isCommutedMOVL(const SDOperand *Ops, unsigned NumOps,
2331 bool V2IsSplat = false,
2332 bool V2IsUndef = false) {
2333 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2336 if (!isUndefOrEqual(Ops[0], 0))
2339 for (unsigned i = 1; i < NumOps; ++i) {
2340 SDOperand Arg = Ops[i];
2341 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2342 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2343 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2350 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2351 bool V2IsUndef = false) {
2352 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2353 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2354 V2IsSplat, V2IsUndef);
2357 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2358 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2359 bool X86::isMOVSHDUPMask(SDNode *N) {
2360 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2362 if (N->getNumOperands() != 4)
2365 // Expect 1, 1, 3, 3
2366 for (unsigned i = 0; i < 2; ++i) {
2367 SDOperand Arg = N->getOperand(i);
2368 if (Arg.getOpcode() == ISD::UNDEF) continue;
2369 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2370 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2371 if (Val != 1) return false;
2375 for (unsigned i = 2; i < 4; ++i) {
2376 SDOperand Arg = N->getOperand(i);
2377 if (Arg.getOpcode() == ISD::UNDEF) continue;
2378 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2379 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2380 if (Val != 3) return false;
2384 // Don't use movshdup if it can be done with a shufps.
2388 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2389 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2390 bool X86::isMOVSLDUPMask(SDNode *N) {
2391 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2393 if (N->getNumOperands() != 4)
2396 // Expect 0, 0, 2, 2
2397 for (unsigned i = 0; i < 2; ++i) {
2398 SDOperand Arg = N->getOperand(i);
2399 if (Arg.getOpcode() == ISD::UNDEF) continue;
2400 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2401 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2402 if (Val != 0) return false;
2406 for (unsigned i = 2; i < 4; ++i) {
2407 SDOperand Arg = N->getOperand(i);
2408 if (Arg.getOpcode() == ISD::UNDEF) continue;
2409 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2410 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2411 if (Val != 2) return false;
2415 // Don't use movshdup if it can be done with a shufps.
2419 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2420 /// specifies a identity operation on the LHS or RHS.
2421 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2422 unsigned NumElems = N->getNumOperands();
2423 for (unsigned i = 0; i < NumElems; ++i)
2424 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2429 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2430 /// a splat of a single element.
2431 static bool isSplatMask(SDNode *N) {
2432 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2434 // This is a splat operation if each element of the permute is the same, and
2435 // if the value doesn't reference the second vector.
2436 unsigned NumElems = N->getNumOperands();
2437 SDOperand ElementBase;
2439 for (; i != NumElems; ++i) {
2440 SDOperand Elt = N->getOperand(i);
2441 if (isa<ConstantSDNode>(Elt)) {
2447 if (!ElementBase.Val)
2450 for (; i != NumElems; ++i) {
2451 SDOperand Arg = N->getOperand(i);
2452 if (Arg.getOpcode() == ISD::UNDEF) continue;
2453 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2454 if (Arg != ElementBase) return false;
2457 // Make sure it is a splat of the first vector operand.
2458 return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
2461 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2462 /// a splat of a single element and it's a 2 or 4 element mask.
2463 bool X86::isSplatMask(SDNode *N) {
2464 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2466 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2467 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2469 return ::isSplatMask(N);
2472 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2473 /// specifies a splat of zero element.
2474 bool X86::isSplatLoMask(SDNode *N) {
2475 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2477 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2478 if (!isUndefOrEqual(N->getOperand(i), 0))
2483 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2484 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2486 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2487 unsigned NumOperands = N->getNumOperands();
2488 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2490 for (unsigned i = 0; i < NumOperands; ++i) {
2492 SDOperand Arg = N->getOperand(NumOperands-i-1);
2493 if (Arg.getOpcode() != ISD::UNDEF)
2494 Val = cast<ConstantSDNode>(Arg)->getValue();
2495 if (Val >= NumOperands) Val -= NumOperands;
2497 if (i != NumOperands - 1)
2504 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2505 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2507 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2509 // 8 nodes, but we only care about the last 4.
2510 for (unsigned i = 7; i >= 4; --i) {
2512 SDOperand Arg = N->getOperand(i);
2513 if (Arg.getOpcode() != ISD::UNDEF)
2514 Val = cast<ConstantSDNode>(Arg)->getValue();
2523 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2524 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2526 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2528 // 8 nodes, but we only care about the first 4.
2529 for (int i = 3; i >= 0; --i) {
2531 SDOperand Arg = N->getOperand(i);
2532 if (Arg.getOpcode() != ISD::UNDEF)
2533 Val = cast<ConstantSDNode>(Arg)->getValue();
2542 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2543 /// specifies a 8 element shuffle that can be broken into a pair of
2544 /// PSHUFHW and PSHUFLW.
2545 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2546 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2548 if (N->getNumOperands() != 8)
2551 // Lower quadword shuffled.
2552 for (unsigned i = 0; i != 4; ++i) {
2553 SDOperand Arg = N->getOperand(i);
2554 if (Arg.getOpcode() == ISD::UNDEF) continue;
2555 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2556 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2561 // Upper quadword shuffled.
2562 for (unsigned i = 4; i != 8; ++i) {
2563 SDOperand Arg = N->getOperand(i);
2564 if (Arg.getOpcode() == ISD::UNDEF) continue;
2565 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2566 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2567 if (Val < 4 || Val > 7)
2574 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2575 /// values in ther permute mask.
2576 static SDOperand CommuteVectorShuffle(SDOperand Op, SDOperand &V1,
2577 SDOperand &V2, SDOperand &Mask,
2578 SelectionDAG &DAG) {
2579 MVT::ValueType VT = Op.getValueType();
2580 MVT::ValueType MaskVT = Mask.getValueType();
2581 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2582 unsigned NumElems = Mask.getNumOperands();
2583 SmallVector<SDOperand, 8> MaskVec;
2585 for (unsigned i = 0; i != NumElems; ++i) {
2586 SDOperand Arg = Mask.getOperand(i);
2587 if (Arg.getOpcode() == ISD::UNDEF) {
2588 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2591 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2592 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2594 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2596 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2600 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2601 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2604 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2605 /// the two vector operands have swapped position.
2607 SDOperand CommuteVectorShuffleMask(SDOperand Mask, SelectionDAG &DAG) {
2608 MVT::ValueType MaskVT = Mask.getValueType();
2609 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2610 unsigned NumElems = Mask.getNumOperands();
2611 SmallVector<SDOperand, 8> MaskVec;
2612 for (unsigned i = 0; i != NumElems; ++i) {
2613 SDOperand Arg = Mask.getOperand(i);
2614 if (Arg.getOpcode() == ISD::UNDEF) {
2615 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2618 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2619 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2621 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2623 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2625 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2629 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2630 /// match movhlps. The lower half elements should come from upper half of
2631 /// V1 (and in order), and the upper half elements should come from the upper
2632 /// half of V2 (and in order).
2633 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2634 unsigned NumElems = Mask->getNumOperands();
2637 for (unsigned i = 0, e = 2; i != e; ++i)
2638 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2640 for (unsigned i = 2; i != 4; ++i)
2641 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2646 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2647 /// is promoted to a vector.
2648 static inline bool isScalarLoadToVector(SDNode *N) {
2649 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2650 N = N->getOperand(0).Val;
2651 return ISD::isNON_EXTLoad(N);
2656 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2657 /// match movlp{s|d}. The lower half elements should come from lower half of
2658 /// V1 (and in order), and the upper half elements should come from the upper
2659 /// half of V2 (and in order). And since V1 will become the source of the
2660 /// MOVLP, it must be either a vector load or a scalar load to vector.
2661 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2662 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2664 // Is V2 is a vector load, don't do this transformation. We will try to use
2665 // load folding shufps op.
2666 if (ISD::isNON_EXTLoad(V2))
2669 unsigned NumElems = Mask->getNumOperands();
2670 if (NumElems != 2 && NumElems != 4)
2672 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2673 if (!isUndefOrEqual(Mask->getOperand(i), i))
2675 for (unsigned i = NumElems/2; i != NumElems; ++i)
2676 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2681 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2683 static bool isSplatVector(SDNode *N) {
2684 if (N->getOpcode() != ISD::BUILD_VECTOR)
2687 SDOperand SplatValue = N->getOperand(0);
2688 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2689 if (N->getOperand(i) != SplatValue)
2694 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2696 static bool isUndefShuffle(SDNode *N) {
2697 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2700 SDOperand V1 = N->getOperand(0);
2701 SDOperand V2 = N->getOperand(1);
2702 SDOperand Mask = N->getOperand(2);
2703 unsigned NumElems = Mask.getNumOperands();
2704 for (unsigned i = 0; i != NumElems; ++i) {
2705 SDOperand Arg = Mask.getOperand(i);
2706 if (Arg.getOpcode() != ISD::UNDEF) {
2707 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2708 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2710 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2717 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2719 static inline bool isZeroNode(SDOperand Elt) {
2720 return ((isa<ConstantSDNode>(Elt) &&
2721 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2722 (isa<ConstantFPSDNode>(Elt) &&
2723 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2726 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2727 /// to an zero vector.
2728 static bool isZeroShuffle(SDNode *N) {
2729 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2732 SDOperand V1 = N->getOperand(0);
2733 SDOperand V2 = N->getOperand(1);
2734 SDOperand Mask = N->getOperand(2);
2735 unsigned NumElems = Mask.getNumOperands();
2736 for (unsigned i = 0; i != NumElems; ++i) {
2737 SDOperand Arg = Mask.getOperand(i);
2738 if (Arg.getOpcode() == ISD::UNDEF)
2741 unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
2742 if (Idx < NumElems) {
2743 unsigned Opc = V1.Val->getOpcode();
2744 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.Val))
2746 if (Opc != ISD::BUILD_VECTOR ||
2747 !isZeroNode(V1.Val->getOperand(Idx)))
2749 } else if (Idx >= NumElems) {
2750 unsigned Opc = V2.Val->getOpcode();
2751 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.Val))
2753 if (Opc != ISD::BUILD_VECTOR ||
2754 !isZeroNode(V2.Val->getOperand(Idx - NumElems)))
2761 /// getZeroVector - Returns a vector of specified type with all zero elements.
2763 static SDOperand getZeroVector(MVT::ValueType VT, SelectionDAG &DAG) {
2764 assert(MVT::isVector(VT) && "Expected a vector type");
2766 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2767 // type. This ensures they get CSE'd.
2768 SDOperand Cst = DAG.getTargetConstant(0, MVT::i32);
2770 if (MVT::getSizeInBits(VT) == 64) // MMX
2771 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2773 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2774 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2777 /// getOnesVector - Returns a vector of specified type with all bits set.
2779 static SDOperand getOnesVector(MVT::ValueType VT, SelectionDAG &DAG) {
2780 assert(MVT::isVector(VT) && "Expected a vector type");
2782 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2783 // type. This ensures they get CSE'd.
2784 SDOperand Cst = DAG.getTargetConstant(~0U, MVT::i32);
2786 if (MVT::getSizeInBits(VT) == 64) // MMX
2787 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2789 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2790 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2794 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2795 /// that point to V2 points to its first element.
2796 static SDOperand NormalizeMask(SDOperand Mask, SelectionDAG &DAG) {
2797 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2799 bool Changed = false;
2800 SmallVector<SDOperand, 8> MaskVec;
2801 unsigned NumElems = Mask.getNumOperands();
2802 for (unsigned i = 0; i != NumElems; ++i) {
2803 SDOperand Arg = Mask.getOperand(i);
2804 if (Arg.getOpcode() != ISD::UNDEF) {
2805 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2806 if (Val > NumElems) {
2807 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2811 MaskVec.push_back(Arg);
2815 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2816 &MaskVec[0], MaskVec.size());
2820 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2821 /// operation of specified width.
2822 static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2823 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2824 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2826 SmallVector<SDOperand, 8> MaskVec;
2827 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2828 for (unsigned i = 1; i != NumElems; ++i)
2829 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2830 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2833 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2834 /// of specified width.
2835 static SDOperand getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2836 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2837 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2838 SmallVector<SDOperand, 8> MaskVec;
2839 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2840 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2841 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2843 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2846 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2847 /// of specified width.
2848 static SDOperand getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2849 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2850 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2851 unsigned Half = NumElems/2;
2852 SmallVector<SDOperand, 8> MaskVec;
2853 for (unsigned i = 0; i != Half; ++i) {
2854 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
2855 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2857 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2860 /// PromoteSplat - Promote a splat of v8i16 or v16i8 to v4i32.
2862 static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG) {
2863 SDOperand V1 = Op.getOperand(0);
2864 SDOperand Mask = Op.getOperand(2);
2865 MVT::ValueType VT = Op.getValueType();
2866 unsigned NumElems = Mask.getNumOperands();
2867 Mask = getUnpacklMask(NumElems, DAG);
2868 while (NumElems != 4) {
2869 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2872 V1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, V1);
2874 Mask = getZeroVector(MVT::v4i32, DAG);
2875 SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32, V1,
2876 DAG.getNode(ISD::UNDEF, MVT::v4i32), Mask);
2877 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2880 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2881 /// vector of zero or undef vector. This produces a shuffle where the low
2882 /// element of V2 is swizzled into the zero/undef vector, landing at element
2883 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
2884 static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, MVT::ValueType VT,
2885 unsigned NumElems, unsigned Idx,
2886 bool isZero, SelectionDAG &DAG) {
2887 SDOperand V1 = isZero ? getZeroVector(VT, DAG) : DAG.getNode(ISD::UNDEF, VT);
2888 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2889 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
2890 SmallVector<SDOperand, 16> MaskVec;
2891 for (unsigned i = 0; i != NumElems; ++i)
2892 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
2893 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
2895 MaskVec.push_back(DAG.getConstant(i, EVT));
2896 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2897 &MaskVec[0], MaskVec.size());
2898 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2901 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2903 static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
2904 unsigned NumNonZero, unsigned NumZero,
2905 SelectionDAG &DAG, TargetLowering &TLI) {
2911 for (unsigned i = 0; i < 16; ++i) {
2912 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
2913 if (ThisIsNonZero && First) {
2915 V = getZeroVector(MVT::v8i16, DAG);
2917 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2922 SDOperand ThisElt(0, 0), LastElt(0, 0);
2923 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
2924 if (LastIsNonZero) {
2925 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
2927 if (ThisIsNonZero) {
2928 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
2929 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
2930 ThisElt, DAG.getConstant(8, MVT::i8));
2932 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
2937 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
2938 DAG.getIntPtrConstant(i/2));
2942 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
2945 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
2947 static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
2948 unsigned NumNonZero, unsigned NumZero,
2949 SelectionDAG &DAG, TargetLowering &TLI) {
2955 for (unsigned i = 0; i < 8; ++i) {
2956 bool isNonZero = (NonZeros & (1 << i)) != 0;
2960 V = getZeroVector(MVT::v8i16, DAG);
2962 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2965 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
2966 DAG.getIntPtrConstant(i));
2974 X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
2975 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
2976 if (ISD::isBuildVectorAllZeros(Op.Val) || ISD::isBuildVectorAllOnes(Op.Val)) {
2977 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
2978 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
2979 // eliminated on x86-32 hosts.
2980 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
2983 if (ISD::isBuildVectorAllOnes(Op.Val))
2984 return getOnesVector(Op.getValueType(), DAG);
2985 return getZeroVector(Op.getValueType(), DAG);
2988 MVT::ValueType VT = Op.getValueType();
2989 MVT::ValueType EVT = MVT::getVectorElementType(VT);
2990 unsigned EVTBits = MVT::getSizeInBits(EVT);
2992 unsigned NumElems = Op.getNumOperands();
2993 unsigned NumZero = 0;
2994 unsigned NumNonZero = 0;
2995 unsigned NonZeros = 0;
2996 bool HasNonImms = false;
2997 SmallSet<SDOperand, 8> Values;
2998 for (unsigned i = 0; i < NumElems; ++i) {
2999 SDOperand Elt = Op.getOperand(i);
3000 if (Elt.getOpcode() == ISD::UNDEF)
3003 if (Elt.getOpcode() != ISD::Constant &&
3004 Elt.getOpcode() != ISD::ConstantFP)
3006 if (isZeroNode(Elt))
3009 NonZeros |= (1 << i);
3014 if (NumNonZero == 0) {
3015 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3016 return DAG.getNode(ISD::UNDEF, VT);
3019 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3020 if (Values.size() == 1)
3023 // Special case for single non-zero element.
3024 if (NumNonZero == 1 && NumElems <= 4) {
3025 unsigned Idx = CountTrailingZeros_32(NonZeros);
3026 SDOperand Item = Op.getOperand(Idx);
3027 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3029 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3030 return getShuffleVectorZeroOrUndef(Item, VT, NumElems, Idx,
3032 else if (!HasNonImms) // Otherwise, it's better to do a constpool load.
3035 if (EVTBits == 32) {
3036 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3037 Item = getShuffleVectorZeroOrUndef(Item, VT, NumElems, 0, NumZero > 0,
3039 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3040 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3041 SmallVector<SDOperand, 8> MaskVec;
3042 for (unsigned i = 0; i < NumElems; i++)
3043 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3044 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3045 &MaskVec[0], MaskVec.size());
3046 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3047 DAG.getNode(ISD::UNDEF, VT), Mask);
3051 // A vector full of immediates; various special cases are already
3052 // handled, so this is best done with a single constant-pool load.
3056 // Let legalizer expand 2-wide build_vectors.
3060 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3061 if (EVTBits == 8 && NumElems == 16) {
3062 SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3064 if (V.Val) return V;
3067 if (EVTBits == 16 && NumElems == 8) {
3068 SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3070 if (V.Val) return V;
3073 // If element VT is == 32 bits, turn it into a number of shuffles.
3074 SmallVector<SDOperand, 8> V;
3076 if (NumElems == 4 && NumZero > 0) {
3077 for (unsigned i = 0; i < 4; ++i) {
3078 bool isZero = !(NonZeros & (1 << i));
3080 V[i] = getZeroVector(VT, DAG);
3082 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3085 for (unsigned i = 0; i < 2; ++i) {
3086 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3089 V[i] = V[i*2]; // Must be a zero vector.
3092 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3093 getMOVLMask(NumElems, DAG));
3096 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3097 getMOVLMask(NumElems, DAG));
3100 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3101 getUnpacklMask(NumElems, DAG));
3106 // Take advantage of the fact GR32 to VR128 scalar_to_vector (i.e. movd)
3107 // clears the upper bits.
3108 // FIXME: we can do the same for v4f32 case when we know both parts of
3109 // the lower half come from scalar_to_vector (loadf32). We should do
3110 // that in post legalizer dag combiner with target specific hooks.
3111 if (MVT::isInteger(EVT) && (NonZeros & (0x3 << 2)) == 0)
3113 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3114 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
3115 SmallVector<SDOperand, 8> MaskVec;
3116 bool Reverse = (NonZeros & 0x3) == 2;
3117 for (unsigned i = 0; i < 2; ++i)
3119 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3121 MaskVec.push_back(DAG.getConstant(i, EVT));
3122 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3123 for (unsigned i = 0; i < 2; ++i)
3125 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3127 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3128 SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3129 &MaskVec[0], MaskVec.size());
3130 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3133 if (Values.size() > 2) {
3134 // Expand into a number of unpckl*.
3136 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3137 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3138 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3139 SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
3140 for (unsigned i = 0; i < NumElems; ++i)
3141 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3143 while (NumElems != 0) {
3144 for (unsigned i = 0; i < NumElems; ++i)
3145 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3156 SDOperand LowerVECTOR_SHUFFLEv8i16(SDOperand V1, SDOperand V2,
3157 SDOperand PermMask, SelectionDAG &DAG,
3158 TargetLowering &TLI) {
3160 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(8);
3161 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3162 MVT::ValueType PtrVT = TLI.getPointerTy();
3163 SmallVector<SDOperand, 8> MaskElts(PermMask.Val->op_begin(),
3164 PermMask.Val->op_end());
3166 // First record which half of which vector the low elements come from.
3167 SmallVector<unsigned, 4> LowQuad(4);
3168 for (unsigned i = 0; i < 4; ++i) {
3169 SDOperand Elt = MaskElts[i];
3170 if (Elt.getOpcode() == ISD::UNDEF)
3172 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3173 int QuadIdx = EltIdx / 4;
3176 int BestLowQuad = -1;
3177 unsigned MaxQuad = 1;
3178 for (unsigned i = 0; i < 4; ++i) {
3179 if (LowQuad[i] > MaxQuad) {
3181 MaxQuad = LowQuad[i];
3185 // Record which half of which vector the high elements come from.
3186 SmallVector<unsigned, 4> HighQuad(4);
3187 for (unsigned i = 4; i < 8; ++i) {
3188 SDOperand Elt = MaskElts[i];
3189 if (Elt.getOpcode() == ISD::UNDEF)
3191 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3192 int QuadIdx = EltIdx / 4;
3193 ++HighQuad[QuadIdx];
3195 int BestHighQuad = -1;
3197 for (unsigned i = 0; i < 4; ++i) {
3198 if (HighQuad[i] > MaxQuad) {
3200 MaxQuad = HighQuad[i];
3204 // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3205 if (BestLowQuad != -1 || BestHighQuad != -1) {
3206 // First sort the 4 chunks in order using shufpd.
3207 SmallVector<SDOperand, 8> MaskVec;
3208 if (BestLowQuad != -1)
3209 MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3211 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3212 if (BestHighQuad != -1)
3213 MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3215 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3216 SDOperand Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3217 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3218 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3219 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3220 NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3222 // Now sort high and low parts separately.
3223 BitVector InOrder(8);
3224 if (BestLowQuad != -1) {
3225 // Sort lower half in order using PSHUFLW.
3227 bool AnyOutOrder = false;
3228 for (unsigned i = 0; i != 4; ++i) {
3229 SDOperand Elt = MaskElts[i];
3230 if (Elt.getOpcode() == ISD::UNDEF) {
3231 MaskVec.push_back(Elt);
3234 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3237 MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3238 // If this element is in the right place after this shuffle, then
3240 if ((int)(EltIdx / 4) == BestLowQuad)
3245 for (unsigned i = 4; i != 8; ++i)
3246 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3247 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3248 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3252 if (BestHighQuad != -1) {
3253 // Sort high half in order using PSHUFHW if possible.
3255 for (unsigned i = 0; i != 4; ++i)
3256 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3257 bool AnyOutOrder = false;
3258 for (unsigned i = 4; i != 8; ++i) {
3259 SDOperand Elt = MaskElts[i];
3260 if (Elt.getOpcode() == ISD::UNDEF) {
3261 MaskVec.push_back(Elt);
3264 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3267 MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3268 // If this element is in the right place after this shuffle, then
3270 if ((int)(EltIdx / 4) == BestHighQuad)
3275 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3276 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3280 // The other elements are put in the right place using pextrw and pinsrw.
3281 for (unsigned i = 0; i != 8; ++i) {
3284 SDOperand Elt = MaskElts[i];
3285 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3288 SDOperand ExtOp = (EltIdx < 8)
3289 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3290 DAG.getConstant(EltIdx, PtrVT))
3291 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3292 DAG.getConstant(EltIdx - 8, PtrVT));
3293 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3294 DAG.getConstant(i, PtrVT));
3299 // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use
3300 ///as few as possible.
3301 // First, let's find out how many elements are already in the right order.
3302 unsigned V1InOrder = 0;
3303 unsigned V1FromV1 = 0;
3304 unsigned V2InOrder = 0;
3305 unsigned V2FromV2 = 0;
3306 SmallVector<SDOperand, 8> V1Elts;
3307 SmallVector<SDOperand, 8> V2Elts;
3308 for (unsigned i = 0; i < 8; ++i) {
3309 SDOperand Elt = MaskElts[i];
3310 if (Elt.getOpcode() == ISD::UNDEF) {
3311 V1Elts.push_back(Elt);
3312 V2Elts.push_back(Elt);
3317 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3319 V1Elts.push_back(Elt);
3320 V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3322 } else if (EltIdx == i+8) {
3323 V1Elts.push_back(Elt);
3324 V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3326 } else if (EltIdx < 8) {
3327 V1Elts.push_back(Elt);
3330 V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3335 if (V2InOrder > V1InOrder) {
3336 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3338 std::swap(V1Elts, V2Elts);
3339 std::swap(V1FromV1, V2FromV2);
3342 if ((V1FromV1 + V1InOrder) != 8) {
3343 // Some elements are from V2.
3345 // If there are elements that are from V1 but out of place,
3346 // then first sort them in place
3347 SmallVector<SDOperand, 8> MaskVec;
3348 for (unsigned i = 0; i < 8; ++i) {
3349 SDOperand Elt = V1Elts[i];
3350 if (Elt.getOpcode() == ISD::UNDEF) {
3351 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3354 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3356 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3358 MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3360 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3361 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3365 for (unsigned i = 0; i < 8; ++i) {
3366 SDOperand Elt = V1Elts[i];
3367 if (Elt.getOpcode() == ISD::UNDEF)
3369 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3372 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3373 DAG.getConstant(EltIdx - 8, PtrVT));
3374 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3375 DAG.getConstant(i, PtrVT));
3379 // All elements are from V1.
3381 for (unsigned i = 0; i < 8; ++i) {
3382 SDOperand Elt = V1Elts[i];
3383 if (Elt.getOpcode() == ISD::UNDEF)
3385 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3386 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3387 DAG.getConstant(EltIdx, PtrVT));
3388 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3389 DAG.getConstant(i, PtrVT));
3395 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3396 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3397 /// done when every pair / quad of shuffle mask elements point to elements in
3398 /// the right sequence. e.g.
3399 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3401 SDOperand RewriteAsNarrowerShuffle(SDOperand V1, SDOperand V2,
3403 SDOperand PermMask, SelectionDAG &DAG,
3404 TargetLowering &TLI) {
3405 unsigned NumElems = PermMask.getNumOperands();
3406 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3407 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3408 MVT::ValueType NewVT = MaskVT;
3410 case MVT::v4f32: NewVT = MVT::v2f64; break;
3411 case MVT::v4i32: NewVT = MVT::v2i64; break;
3412 case MVT::v8i16: NewVT = MVT::v4i32; break;
3413 case MVT::v16i8: NewVT = MVT::v4i32; break;
3414 default: assert(false && "Unexpected!");
3417 if (NewWidth == 2) {
3418 if (MVT::isInteger(VT))
3423 unsigned Scale = NumElems / NewWidth;
3424 SmallVector<SDOperand, 8> MaskVec;
3425 for (unsigned i = 0; i < NumElems; i += Scale) {
3426 unsigned StartIdx = ~0U;
3427 for (unsigned j = 0; j < Scale; ++j) {
3428 SDOperand Elt = PermMask.getOperand(i+j);
3429 if (Elt.getOpcode() == ISD::UNDEF)
3431 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3432 if (StartIdx == ~0U)
3433 StartIdx = EltIdx - (EltIdx % Scale);
3434 if (EltIdx != StartIdx + j)
3437 if (StartIdx == ~0U)
3438 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
3440 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MVT::i32));
3443 V1 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V1);
3444 V2 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V2);
3445 return DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, V1, V2,
3446 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3447 &MaskVec[0], MaskVec.size()));
3451 X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
3452 SDOperand V1 = Op.getOperand(0);
3453 SDOperand V2 = Op.getOperand(1);
3454 SDOperand PermMask = Op.getOperand(2);
3455 MVT::ValueType VT = Op.getValueType();
3456 unsigned NumElems = PermMask.getNumOperands();
3457 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3458 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3459 bool V1IsSplat = false;
3460 bool V2IsSplat = false;
3462 if (isUndefShuffle(Op.Val))
3463 return DAG.getNode(ISD::UNDEF, VT);
3465 if (isZeroShuffle(Op.Val))
3466 return getZeroVector(VT, DAG);
3468 if (isIdentityMask(PermMask.Val))
3470 else if (isIdentityMask(PermMask.Val, true))
3473 if (isSplatMask(PermMask.Val)) {
3474 if (NumElems <= 4) return Op;
3475 // Promote it to a v4i32 splat.
3476 return PromoteSplat(Op, DAG);
3479 // If the shuffle can be profitably rewritten as a narrower shuffle, then
3481 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3482 SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3484 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3485 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3486 // FIXME: Figure out a cleaner way to do this.
3487 // Try to make use of movq to zero out the top part.
3488 if (ISD::isBuildVectorAllZeros(V2.Val)) {
3489 SDOperand NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3491 SDOperand NewV1 = NewOp.getOperand(0);
3492 SDOperand NewV2 = NewOp.getOperand(1);
3493 SDOperand NewMask = NewOp.getOperand(2);
3494 if (isCommutedMOVL(NewMask.Val, true, false)) {
3495 NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
3496 NewOp = DAG.getNode(ISD::VECTOR_SHUFFLE, NewOp.getValueType(),
3497 NewV1, NewV2, getMOVLMask(2, DAG));
3498 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3501 } else if (ISD::isBuildVectorAllZeros(V1.Val)) {
3502 SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3503 if (NewOp.Val && X86::isMOVLMask(NewOp.getOperand(2).Val))
3504 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3508 if (X86::isMOVLMask(PermMask.Val))
3509 return (V1IsUndef) ? V2 : Op;
3511 if (X86::isMOVSHDUPMask(PermMask.Val) ||
3512 X86::isMOVSLDUPMask(PermMask.Val) ||
3513 X86::isMOVHLPSMask(PermMask.Val) ||
3514 X86::isMOVHPMask(PermMask.Val) ||
3515 X86::isMOVLPMask(PermMask.Val))
3518 if (ShouldXformToMOVHLPS(PermMask.Val) ||
3519 ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
3520 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3522 bool Commuted = false;
3523 // FIXME: This should also accept a bitcast of a splat? Be careful, not
3524 // 1,1,1,1 -> v8i16 though.
3525 V1IsSplat = isSplatVector(V1.Val);
3526 V2IsSplat = isSplatVector(V2.Val);
3528 // Canonicalize the splat or undef, if present, to be on the RHS.
3529 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3530 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3531 std::swap(V1IsSplat, V2IsSplat);
3532 std::swap(V1IsUndef, V2IsUndef);
3536 // FIXME: Figure out a cleaner way to do this.
3537 if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
3538 if (V2IsUndef) return V1;
3539 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3541 // V2 is a splat, so the mask may be malformed. That is, it may point
3542 // to any V2 element. The instruction selectior won't like this. Get
3543 // a corrected mask and commute to form a proper MOVS{S|D}.
3544 SDOperand NewMask = getMOVLMask(NumElems, DAG);
3545 if (NewMask.Val != PermMask.Val)
3546 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3551 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3552 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3553 X86::isUNPCKLMask(PermMask.Val) ||
3554 X86::isUNPCKHMask(PermMask.Val))
3558 // Normalize mask so all entries that point to V2 points to its first
3559 // element then try to match unpck{h|l} again. If match, return a
3560 // new vector_shuffle with the corrected mask.
3561 SDOperand NewMask = NormalizeMask(PermMask, DAG);
3562 if (NewMask.Val != PermMask.Val) {
3563 if (X86::isUNPCKLMask(PermMask.Val, true)) {
3564 SDOperand NewMask = getUnpacklMask(NumElems, DAG);
3565 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3566 } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
3567 SDOperand NewMask = getUnpackhMask(NumElems, DAG);
3568 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3573 // Normalize the node to match x86 shuffle ops if needed
3574 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
3575 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3578 // Commute is back and try unpck* again.
3579 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3580 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3581 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3582 X86::isUNPCKLMask(PermMask.Val) ||
3583 X86::isUNPCKHMask(PermMask.Val))
3587 // If VT is integer, try PSHUF* first, then SHUFP*.
3588 if (MVT::isInteger(VT)) {
3589 // MMX doesn't have PSHUFD; it does have PSHUFW. While it's theoretically
3590 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
3591 if (((MVT::getSizeInBits(VT) != 64 || NumElems == 4) &&
3592 X86::isPSHUFDMask(PermMask.Val)) ||
3593 X86::isPSHUFHWMask(PermMask.Val) ||
3594 X86::isPSHUFLWMask(PermMask.Val)) {
3595 if (V2.getOpcode() != ISD::UNDEF)
3596 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3597 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3601 if (X86::isSHUFPMask(PermMask.Val) &&
3602 MVT::getSizeInBits(VT) != 64) // Don't do this for MMX.
3605 // Floating point cases in the other order.
3606 if (X86::isSHUFPMask(PermMask.Val))
3608 if (X86::isPSHUFDMask(PermMask.Val) ||
3609 X86::isPSHUFHWMask(PermMask.Val) ||
3610 X86::isPSHUFLWMask(PermMask.Val)) {
3611 if (V2.getOpcode() != ISD::UNDEF)
3612 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3613 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3618 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
3619 if (VT == MVT::v8i16) {
3620 SDOperand NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
3625 // Handle all 4 wide cases with a number of shuffles.
3626 if (NumElems == 4 && MVT::getSizeInBits(VT) != 64) {
3627 // Don't do this for MMX.
3628 MVT::ValueType MaskVT = PermMask.getValueType();
3629 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3630 SmallVector<std::pair<int, int>, 8> Locs;
3631 Locs.reserve(NumElems);
3632 SmallVector<SDOperand, 8> Mask1(NumElems,
3633 DAG.getNode(ISD::UNDEF, MaskEVT));
3634 SmallVector<SDOperand, 8> Mask2(NumElems,
3635 DAG.getNode(ISD::UNDEF, MaskEVT));
3638 // If no more than two elements come from either vector. This can be
3639 // implemented with two shuffles. First shuffle gather the elements.
3640 // The second shuffle, which takes the first shuffle as both of its
3641 // vector operands, put the elements into the right order.
3642 for (unsigned i = 0; i != NumElems; ++i) {
3643 SDOperand Elt = PermMask.getOperand(i);
3644 if (Elt.getOpcode() == ISD::UNDEF) {
3645 Locs[i] = std::make_pair(-1, -1);
3647 unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3648 if (Val < NumElems) {
3649 Locs[i] = std::make_pair(0, NumLo);
3653 Locs[i] = std::make_pair(1, NumHi);
3654 if (2+NumHi < NumElems)
3655 Mask1[2+NumHi] = Elt;
3660 if (NumLo <= 2 && NumHi <= 2) {
3661 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3662 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3663 &Mask1[0], Mask1.size()));
3664 for (unsigned i = 0; i != NumElems; ++i) {
3665 if (Locs[i].first == -1)
3668 unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
3669 Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
3670 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3674 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3675 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3676 &Mask2[0], Mask2.size()));
3679 // Break it into (shuffle shuffle_hi, shuffle_lo).
3681 SmallVector<SDOperand,8> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3682 SmallVector<SDOperand,8> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3683 SmallVector<SDOperand,8> *MaskPtr = &LoMask;
3684 unsigned MaskIdx = 0;
3686 unsigned HiIdx = NumElems/2;
3687 for (unsigned i = 0; i != NumElems; ++i) {
3688 if (i == NumElems/2) {
3694 SDOperand Elt = PermMask.getOperand(i);
3695 if (Elt.getOpcode() == ISD::UNDEF) {
3696 Locs[i] = std::make_pair(-1, -1);
3697 } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
3698 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3699 (*MaskPtr)[LoIdx] = Elt;
3702 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3703 (*MaskPtr)[HiIdx] = Elt;
3708 SDOperand LoShuffle =
3709 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3710 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3711 &LoMask[0], LoMask.size()));
3712 SDOperand HiShuffle =
3713 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3714 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3715 &HiMask[0], HiMask.size()));
3716 SmallVector<SDOperand, 8> MaskOps;
3717 for (unsigned i = 0; i != NumElems; ++i) {
3718 if (Locs[i].first == -1) {
3719 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3721 unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
3722 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3725 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3726 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3727 &MaskOps[0], MaskOps.size()));
3734 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDOperand Op,
3735 SelectionDAG &DAG) {
3736 MVT::ValueType VT = Op.getValueType();
3737 if (MVT::getSizeInBits(VT) == 8) {
3738 SDOperand Extract = DAG.getNode(X86ISD::PEXTRB, MVT::i32,
3739 Op.getOperand(0), Op.getOperand(1));
3740 SDOperand Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
3741 DAG.getValueType(VT));
3742 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3743 } else if (MVT::getSizeInBits(VT) == 16) {
3744 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, MVT::i32,
3745 Op.getOperand(0), Op.getOperand(1));
3746 SDOperand Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
3747 DAG.getValueType(VT));
3748 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3755 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3756 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3759 if (Subtarget->hasSSE41())
3760 return LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
3762 MVT::ValueType VT = Op.getValueType();
3763 // TODO: handle v16i8.
3764 if (MVT::getSizeInBits(VT) == 16) {
3765 SDOperand Vec = Op.getOperand(0);
3766 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3768 return DAG.getNode(ISD::TRUNCATE, MVT::i16,
3769 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
3770 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
3772 // Transform it so it match pextrw which produces a 32-bit result.
3773 MVT::ValueType EVT = (MVT::ValueType)(VT+1);
3774 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
3775 Op.getOperand(0), Op.getOperand(1));
3776 SDOperand Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
3777 DAG.getValueType(VT));
3778 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3779 } else if (MVT::getSizeInBits(VT) == 32) {
3780 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3783 // SHUFPS the element to the lowest double word, then movss.
3784 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3785 SmallVector<SDOperand, 8> IdxVec;
3787 push_back(DAG.getConstant(Idx, MVT::getVectorElementType(MaskVT)));
3789 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3791 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3793 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3794 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3795 &IdxVec[0], IdxVec.size());
3796 SDOperand Vec = Op.getOperand(0);
3797 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3798 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3799 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3800 DAG.getIntPtrConstant(0));
3801 } else if (MVT::getSizeInBits(VT) == 64) {
3802 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
3803 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
3804 // to match extract_elt for f64.
3805 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3809 // UNPCKHPD the element to the lowest double word, then movsd.
3810 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
3811 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
3812 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3813 SmallVector<SDOperand, 8> IdxVec;
3814 IdxVec.push_back(DAG.getConstant(1, MVT::getVectorElementType(MaskVT)));
3816 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3817 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3818 &IdxVec[0], IdxVec.size());
3819 SDOperand Vec = Op.getOperand(0);
3820 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3821 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3822 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3823 DAG.getIntPtrConstant(0));
3830 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDOperand Op, SelectionDAG &DAG){
3831 MVT::ValueType VT = Op.getValueType();
3832 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3834 SDOperand N0 = Op.getOperand(0);
3835 SDOperand N1 = Op.getOperand(1);
3836 SDOperand N2 = Op.getOperand(2);
3838 if ((MVT::getSizeInBits(EVT) == 8) || (MVT::getSizeInBits(EVT) == 16)) {
3839 unsigned Opc = (MVT::getSizeInBits(EVT) == 8) ? X86ISD::PINSRB
3841 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
3843 if (N1.getValueType() != MVT::i32)
3844 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3845 if (N2.getValueType() != MVT::i32)
3846 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
3847 return DAG.getNode(Opc, VT, N0, N1, N2);
3848 } else if (EVT == MVT::f32) {
3849 // Bits [7:6] of the constant are the source select. This will always be
3850 // zero here. The DAG Combiner may combine an extract_elt index into these
3851 // bits. For example (insert (extract, 3), 2) could be matched by putting
3852 // the '3' into bits [7:6] of X86ISD::INSERTPS.
3853 // Bits [5:4] of the constant are the destination select. This is the
3854 // value of the incoming immediate.
3855 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
3856 // combine either bitwise AND or insert of float 0.0 to set these bits.
3857 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue() << 4);
3858 return DAG.getNode(X86ISD::INSERTPS, VT, N0, N1, N2);
3864 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3865 MVT::ValueType VT = Op.getValueType();
3866 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3868 if (Subtarget->hasSSE41())
3869 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
3874 SDOperand N0 = Op.getOperand(0);
3875 SDOperand N1 = Op.getOperand(1);
3876 SDOperand N2 = Op.getOperand(2);
3878 if (MVT::getSizeInBits(EVT) == 16) {
3879 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
3880 // as its second argument.
3881 if (N1.getValueType() != MVT::i32)
3882 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3883 if (N2.getValueType() != MVT::i32)
3884 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
3885 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
3891 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3892 SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
3893 MVT::ValueType VT = MVT::v2i32;
3894 switch (Op.getValueType()) {
3901 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(),
3902 DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, AnyExt));
3905 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3906 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
3907 // one of the above mentioned nodes. It has to be wrapped because otherwise
3908 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3909 // be used to form addressing mode. These wrapped nodes will be selected
3912 X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
3913 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3914 SDOperand Result = DAG.getTargetConstantPool(CP->getConstVal(),
3916 CP->getAlignment());
3917 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3918 // With PIC, the address is actually $g + Offset.
3919 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3920 !Subtarget->isPICStyleRIPRel()) {
3921 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3922 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3930 X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
3931 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3932 SDOperand Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
3933 // If it's a debug information descriptor, don't mess with it.
3934 if (DAG.isVerifiedDebugInfoDesc(Op))
3936 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3937 // With PIC, the address is actually $g + Offset.
3938 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3939 !Subtarget->isPICStyleRIPRel()) {
3940 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3941 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3945 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
3946 // load the value at address GV, not the value of GV itself. This means that
3947 // the GlobalAddress must be in the base or index register of the address, not
3948 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
3949 // The same applies for external symbols during PIC codegen
3950 if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
3951 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
3952 PseudoSourceValue::getGOT(), 0);
3957 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
3959 LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
3960 const MVT::ValueType PtrVT) {
3962 SDOperand Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
3963 DAG.getNode(X86ISD::GlobalBaseReg,
3965 InFlag = Chain.getValue(1);
3967 // emit leal symbol@TLSGD(,%ebx,1), %eax
3968 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
3969 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
3970 GA->getValueType(0),
3972 SDOperand Ops[] = { Chain, TGA, InFlag };
3973 SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
3974 InFlag = Result.getValue(2);
3975 Chain = Result.getValue(1);
3977 // call ___tls_get_addr. This function receives its argument in
3978 // the register EAX.
3979 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
3980 InFlag = Chain.getValue(1);
3982 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
3983 SDOperand Ops1[] = { Chain,
3984 DAG.getTargetExternalSymbol("___tls_get_addr",
3986 DAG.getRegister(X86::EAX, PtrVT),
3987 DAG.getRegister(X86::EBX, PtrVT),
3989 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
3990 InFlag = Chain.getValue(1);
3992 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
3995 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
3996 // "local exec" model.
3998 LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
3999 const MVT::ValueType PtrVT) {
4000 // Get the Thread Pointer
4001 SDOperand ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4002 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4004 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4005 GA->getValueType(0),
4007 SDOperand Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4009 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4010 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
4011 PseudoSourceValue::getGOT(), 0);
4013 // The address of the thread local variable is the add of the thread
4014 // pointer with the offset of the variable.
4015 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4019 X86TargetLowering::LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
4020 // TODO: implement the "local dynamic" model
4021 // TODO: implement the "initial exec"model for pic executables
4022 assert(!Subtarget->is64Bit() && Subtarget->isTargetELF() &&
4023 "TLS not implemented for non-ELF and 64-bit targets");
4024 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4025 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4026 // otherwise use the "Local Exec"TLS Model
4027 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4028 return LowerToTLSGeneralDynamicModel(GA, DAG, getPointerTy());
4030 return LowerToTLSExecModel(GA, DAG, getPointerTy());
4034 X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
4035 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4036 SDOperand Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4037 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4038 // With PIC, the address is actually $g + Offset.
4039 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4040 !Subtarget->isPICStyleRIPRel()) {
4041 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4042 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4049 SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
4050 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4051 SDOperand Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4052 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4053 // With PIC, the address is actually $g + Offset.
4054 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4055 !Subtarget->isPICStyleRIPRel()) {
4056 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4057 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4064 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4065 /// take a 2 x i32 value to shift plus a shift amount.
4066 SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
4067 assert(Op.getNumOperands() == 3 && Op.getValueType() == MVT::i32 &&
4068 "Not an i64 shift!");
4069 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4070 SDOperand ShOpLo = Op.getOperand(0);
4071 SDOperand ShOpHi = Op.getOperand(1);
4072 SDOperand ShAmt = Op.getOperand(2);
4073 SDOperand Tmp1 = isSRA ?
4074 DAG.getNode(ISD::SRA, MVT::i32, ShOpHi, DAG.getConstant(31, MVT::i8)) :
4075 DAG.getConstant(0, MVT::i32);
4077 SDOperand Tmp2, Tmp3;
4078 if (Op.getOpcode() == ISD::SHL_PARTS) {
4079 Tmp2 = DAG.getNode(X86ISD::SHLD, MVT::i32, ShOpHi, ShOpLo, ShAmt);
4080 Tmp3 = DAG.getNode(ISD::SHL, MVT::i32, ShOpLo, ShAmt);
4082 Tmp2 = DAG.getNode(X86ISD::SHRD, MVT::i32, ShOpLo, ShOpHi, ShAmt);
4083 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, MVT::i32, ShOpHi, ShAmt);
4086 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
4087 SDOperand AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4088 DAG.getConstant(32, MVT::i8));
4089 SDOperand Cond = DAG.getNode(X86ISD::CMP, MVT::i32,
4090 AndNode, DAG.getConstant(0, MVT::i8));
4093 SDOperand CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4094 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::Flag);
4095 SmallVector<SDOperand, 4> Ops;
4096 if (Op.getOpcode() == ISD::SHL_PARTS) {
4097 Ops.push_back(Tmp2);
4098 Ops.push_back(Tmp3);
4100 Ops.push_back(Cond);
4101 Hi = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4104 Ops.push_back(Tmp3);
4105 Ops.push_back(Tmp1);
4107 Ops.push_back(Cond);
4108 Lo = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4110 Ops.push_back(Tmp2);
4111 Ops.push_back(Tmp3);
4113 Ops.push_back(Cond);
4114 Lo = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4117 Ops.push_back(Tmp3);
4118 Ops.push_back(Tmp1);
4120 Ops.push_back(Cond);
4121 Hi = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4124 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::i32);
4128 return DAG.getNode(ISD::MERGE_VALUES, VTs, 2, &Ops[0], Ops.size());
4131 SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
4132 assert(Op.getOperand(0).getValueType() <= MVT::i64 &&
4133 Op.getOperand(0).getValueType() >= MVT::i16 &&
4134 "Unknown SINT_TO_FP to lower!");
4137 MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
4138 unsigned Size = MVT::getSizeInBits(SrcVT)/8;
4139 MachineFunction &MF = DAG.getMachineFunction();
4140 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4141 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4142 SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4144 PseudoSourceValue::getFixedStack(),
4147 // These are really Legal; caller falls through into that case.
4148 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4150 if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 &&
4151 Subtarget->is64Bit())
4156 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4158 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4160 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4161 SmallVector<SDOperand, 8> Ops;
4162 Ops.push_back(Chain);
4163 Ops.push_back(StackSlot);
4164 Ops.push_back(DAG.getValueType(SrcVT));
4165 Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG :X86ISD::FILD,
4166 Tys, &Ops[0], Ops.size());
4169 Chain = Result.getValue(1);
4170 SDOperand InFlag = Result.getValue(2);
4172 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4173 // shouldn't be necessary except that RFP cannot be live across
4174 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4175 MachineFunction &MF = DAG.getMachineFunction();
4176 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4177 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4178 Tys = DAG.getVTList(MVT::Other);
4179 SmallVector<SDOperand, 8> Ops;
4180 Ops.push_back(Chain);
4181 Ops.push_back(Result);
4182 Ops.push_back(StackSlot);
4183 Ops.push_back(DAG.getValueType(Op.getValueType()));
4184 Ops.push_back(InFlag);
4185 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4186 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
4187 PseudoSourceValue::getFixedStack(), SSFI);
4193 std::pair<SDOperand,SDOperand> X86TargetLowering::
4194 FP_TO_SINTHelper(SDOperand Op, SelectionDAG &DAG) {
4195 assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
4196 "Unknown FP_TO_SINT to lower!");
4198 // These are really Legal.
4199 if (Op.getValueType() == MVT::i32 &&
4200 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4201 return std::make_pair(SDOperand(), SDOperand());
4202 if (Subtarget->is64Bit() &&
4203 Op.getValueType() == MVT::i64 &&
4204 Op.getOperand(0).getValueType() != MVT::f80)
4205 return std::make_pair(SDOperand(), SDOperand());
4207 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4209 MachineFunction &MF = DAG.getMachineFunction();
4210 unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
4211 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4212 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4214 switch (Op.getValueType()) {
4215 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4216 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4217 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4218 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4221 SDOperand Chain = DAG.getEntryNode();
4222 SDOperand Value = Op.getOperand(0);
4223 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4224 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4225 Chain = DAG.getStore(Chain, Value, StackSlot,
4226 PseudoSourceValue::getFixedStack(), SSFI);
4227 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4229 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4231 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4232 Chain = Value.getValue(1);
4233 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4234 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4237 // Build the FP_TO_INT*_IN_MEM
4238 SDOperand Ops[] = { Chain, Value, StackSlot };
4239 SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4241 return std::make_pair(FIST, StackSlot);
4244 SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
4245 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(Op, DAG);
4246 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4247 if (FIST.Val == 0) return SDOperand();
4250 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4253 SDNode *X86TargetLowering::ExpandFP_TO_SINT(SDNode *N, SelectionDAG &DAG) {
4254 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(SDOperand(N, 0), DAG);
4255 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4256 if (FIST.Val == 0) return 0;
4258 // Return an i64 load from the stack slot.
4259 SDOperand Res = DAG.getLoad(MVT::i64, FIST, StackSlot, NULL, 0);
4261 // Use a MERGE_VALUES node to drop the chain result value.
4262 return DAG.getNode(ISD::MERGE_VALUES, MVT::i64, Res).Val;
4265 SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
4266 MVT::ValueType VT = Op.getValueType();
4267 MVT::ValueType EltVT = VT;
4268 if (MVT::isVector(VT))
4269 EltVT = MVT::getVectorElementType(VT);
4270 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
4271 std::vector<Constant*> CV;
4272 if (EltVT == MVT::f64) {
4273 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, ~(1ULL << 63))));
4277 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, ~(1U << 31))));
4283 Constant *C = ConstantVector::get(CV);
4284 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4285 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4286 PseudoSourceValue::getConstantPool(), 0,
4288 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4291 SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
4292 MVT::ValueType VT = Op.getValueType();
4293 MVT::ValueType EltVT = VT;
4294 unsigned EltNum = 1;
4295 if (MVT::isVector(VT)) {
4296 EltVT = MVT::getVectorElementType(VT);
4297 EltNum = MVT::getVectorNumElements(VT);
4299 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
4300 std::vector<Constant*> CV;
4301 if (EltVT == MVT::f64) {
4302 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, 1ULL << 63)));
4306 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, 1U << 31)));
4312 Constant *C = ConstantVector::get(CV);
4313 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4314 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4315 PseudoSourceValue::getConstantPool(), 0,
4317 if (MVT::isVector(VT)) {
4318 return DAG.getNode(ISD::BIT_CONVERT, VT,
4319 DAG.getNode(ISD::XOR, MVT::v2i64,
4320 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4321 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4323 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4327 SDOperand X86TargetLowering::LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
4328 SDOperand Op0 = Op.getOperand(0);
4329 SDOperand Op1 = Op.getOperand(1);
4330 MVT::ValueType VT = Op.getValueType();
4331 MVT::ValueType SrcVT = Op1.getValueType();
4332 const Type *SrcTy = MVT::getTypeForValueType(SrcVT);
4334 // If second operand is smaller, extend it first.
4335 if (MVT::getSizeInBits(SrcVT) < MVT::getSizeInBits(VT)) {
4336 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4338 SrcTy = MVT::getTypeForValueType(SrcVT);
4340 // And if it is bigger, shrink it first.
4341 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4342 Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1, DAG.getIntPtrConstant(1));
4344 SrcTy = MVT::getTypeForValueType(SrcVT);
4347 // At this point the operands and the result should have the same
4348 // type, and that won't be f80 since that is not custom lowered.
4350 // First get the sign bit of second operand.
4351 std::vector<Constant*> CV;
4352 if (SrcVT == MVT::f64) {
4353 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 1ULL << 63))));
4354 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
4356 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 1U << 31))));
4357 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4358 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4359 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4361 Constant *C = ConstantVector::get(CV);
4362 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4363 SDOperand Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx,
4364 PseudoSourceValue::getConstantPool(), 0,
4366 SDOperand SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4368 // Shift sign bit right or left if the two operands have different types.
4369 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4370 // Op0 is MVT::f32, Op1 is MVT::f64.
4371 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4372 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4373 DAG.getConstant(32, MVT::i32));
4374 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4375 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4376 DAG.getIntPtrConstant(0));
4379 // Clear first operand sign bit.
4381 if (VT == MVT::f64) {
4382 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, ~(1ULL << 63)))));
4383 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
4385 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, ~(1U << 31)))));
4386 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4387 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4388 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4390 C = ConstantVector::get(CV);
4391 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4392 SDOperand Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4393 PseudoSourceValue::getConstantPool(), 0,
4395 SDOperand Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4397 // Or the value with the sign bit.
4398 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4401 SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG) {
4402 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
4404 SDOperand Op0 = Op.getOperand(0);
4405 SDOperand Op1 = Op.getOperand(1);
4406 SDOperand CC = Op.getOperand(2);
4407 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4408 bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
4411 if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
4413 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4414 return DAG.getNode(X86ISD::SETCC, MVT::i8,
4415 DAG.getConstant(X86CC, MVT::i8), Cond);
4418 assert(isFP && "Illegal integer SetCC!");
4420 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4421 switch (SetCCOpcode) {
4422 default: assert(false && "Illegal floating point SetCC!");
4423 case ISD::SETOEQ: { // !PF & ZF
4424 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4425 DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
4426 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4427 DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4428 return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4430 case ISD::SETUNE: { // PF | !ZF
4431 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4432 DAG.getConstant(X86::COND_P, MVT::i8), Cond);
4433 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4434 DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4435 return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4441 SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
4442 bool addTest = true;
4443 SDOperand Cond = Op.getOperand(0);
4446 if (Cond.getOpcode() == ISD::SETCC)
4447 Cond = LowerSETCC(Cond, DAG);
4449 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4450 // setting operand in place of the X86ISD::SETCC.
4451 if (Cond.getOpcode() == X86ISD::SETCC) {
4452 CC = Cond.getOperand(0);
4454 SDOperand Cmp = Cond.getOperand(1);
4455 unsigned Opc = Cmp.getOpcode();
4456 MVT::ValueType VT = Op.getValueType();
4458 bool IllegalFPCMov = false;
4459 if (MVT::isFloatingPoint(VT) && !MVT::isVector(VT) &&
4460 !isScalarFPTypeInSSEReg(VT)) // FPStack?
4461 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4463 if ((Opc == X86ISD::CMP ||
4464 Opc == X86ISD::COMI ||
4465 Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
4472 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4473 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4476 const MVT::ValueType *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4478 SmallVector<SDOperand, 4> Ops;
4479 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4480 // condition is true.
4481 Ops.push_back(Op.getOperand(2));
4482 Ops.push_back(Op.getOperand(1));
4484 Ops.push_back(Cond);
4485 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
4488 SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
4489 bool addTest = true;
4490 SDOperand Chain = Op.getOperand(0);
4491 SDOperand Cond = Op.getOperand(1);
4492 SDOperand Dest = Op.getOperand(2);
4495 if (Cond.getOpcode() == ISD::SETCC)
4496 Cond = LowerSETCC(Cond, DAG);
4498 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4499 // setting operand in place of the X86ISD::SETCC.
4500 if (Cond.getOpcode() == X86ISD::SETCC) {
4501 CC = Cond.getOperand(0);
4503 SDOperand Cmp = Cond.getOperand(1);
4504 unsigned Opc = Cmp.getOpcode();
4505 if (Opc == X86ISD::CMP ||
4506 Opc == X86ISD::COMI ||
4507 Opc == X86ISD::UCOMI) {
4514 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4515 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4517 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
4518 Chain, Op.getOperand(2), CC, Cond);
4522 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
4523 // Calls to _alloca is needed to probe the stack when allocating more than 4k
4524 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
4525 // that the guard pages used by the OS virtual memory manager are allocated in
4526 // correct sequence.
4528 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDOperand Op,
4529 SelectionDAG &DAG) {
4530 assert(Subtarget->isTargetCygMing() &&
4531 "This should be used only on Cygwin/Mingw targets");
4534 SDOperand Chain = Op.getOperand(0);
4535 SDOperand Size = Op.getOperand(1);
4536 // FIXME: Ensure alignment here
4540 MVT::ValueType IntPtr = getPointerTy();
4541 MVT::ValueType SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
4543 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
4544 Flag = Chain.getValue(1);
4546 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4547 SDOperand Ops[] = { Chain,
4548 DAG.getTargetExternalSymbol("_alloca", IntPtr),
4549 DAG.getRegister(X86::EAX, IntPtr),
4551 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 4);
4552 Flag = Chain.getValue(1);
4554 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
4556 std::vector<MVT::ValueType> Tys;
4557 Tys.push_back(SPTy);
4558 Tys.push_back(MVT::Other);
4559 SDOperand Ops1[2] = { Chain.getValue(0), Chain };
4560 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops1, 2);
4563 SDOperand X86TargetLowering::LowerMEMSET(SDOperand Op, SelectionDAG &DAG) {
4564 SDOperand InFlag(0, 0);
4565 SDOperand Chain = Op.getOperand(0);
4567 (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
4568 if (Align == 0) Align = 1;
4570 ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4571 // If not DWORD aligned or size is more than the threshold, call memset.
4572 // The libc version is likely to be faster for these cases. It can use the
4573 // address value and run time information about the CPU.
4574 if ((Align & 3) != 0 ||
4575 (I && I->getValue() > Subtarget->getMaxInlineSizeThreshold())) {
4576 MVT::ValueType IntPtr = getPointerTy();
4577 const Type *IntPtrTy = getTargetData()->getIntPtrType();
4578 TargetLowering::ArgListTy Args;
4579 TargetLowering::ArgListEntry Entry;
4580 Entry.Node = Op.getOperand(1);
4581 Entry.Ty = IntPtrTy;
4582 Args.push_back(Entry);
4583 // Extend the unsigned i8 argument to be an int value for the call.
4584 Entry.Node = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Op.getOperand(2));
4585 Entry.Ty = IntPtrTy;
4586 Args.push_back(Entry);
4587 Entry.Node = Op.getOperand(3);
4588 Args.push_back(Entry);
4589 std::pair<SDOperand,SDOperand> CallResult =
4590 LowerCallTo(Chain, Type::VoidTy, false, false, false, CallingConv::C,
4591 false, DAG.getExternalSymbol("memset", IntPtr), Args, DAG);
4592 return CallResult.second;
4597 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Op.getOperand(2));
4598 unsigned BytesLeft = 0;
4599 bool TwoRepStos = false;
4602 uint64_t Val = ValC->getValue() & 255;
4604 // If the value is a constant, then we can potentially use larger sets.
4605 switch (Align & 3) {
4606 case 2: // WORD aligned
4609 Val = (Val << 8) | Val;
4611 case 0: // DWORD aligned
4614 Val = (Val << 8) | Val;
4615 Val = (Val << 16) | Val;
4616 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) { // QWORD aligned
4619 Val = (Val << 32) | Val;
4622 default: // Byte aligned
4625 Count = Op.getOperand(3);
4629 if (AVT > MVT::i8) {
4631 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4632 Count = DAG.getIntPtrConstant(I->getValue() / UBytes);
4633 BytesLeft = I->getValue() % UBytes;
4635 assert(AVT >= MVT::i32 &&
4636 "Do not use rep;stos if not at least DWORD aligned");
4637 Count = DAG.getNode(ISD::SRL, Op.getOperand(3).getValueType(),
4638 Op.getOperand(3), DAG.getConstant(2, MVT::i8));
4643 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
4645 InFlag = Chain.getValue(1);
4648 Count = Op.getOperand(3);
4649 Chain = DAG.getCopyToReg(Chain, X86::AL, Op.getOperand(2), InFlag);
4650 InFlag = Chain.getValue(1);
4653 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4655 InFlag = Chain.getValue(1);
4656 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4657 Op.getOperand(1), InFlag);
4658 InFlag = Chain.getValue(1);
4660 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4661 SmallVector<SDOperand, 8> Ops;
4662 Ops.push_back(Chain);
4663 Ops.push_back(DAG.getValueType(AVT));
4664 Ops.push_back(InFlag);
4665 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4668 InFlag = Chain.getValue(1);
4669 Count = Op.getOperand(3);
4670 MVT::ValueType CVT = Count.getValueType();
4671 SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
4672 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
4673 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
4675 InFlag = Chain.getValue(1);
4676 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4678 Ops.push_back(Chain);
4679 Ops.push_back(DAG.getValueType(MVT::i8));
4680 Ops.push_back(InFlag);
4681 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4682 } else if (BytesLeft) {
4683 // Issue stores for the last 1 - 7 bytes.
4685 unsigned Val = ValC->getValue() & 255;
4686 unsigned Offset = I->getValue() - BytesLeft;
4687 SDOperand DstAddr = Op.getOperand(1);
4688 MVT::ValueType AddrVT = DstAddr.getValueType();
4689 if (BytesLeft >= 4) {
4690 Val = (Val << 8) | Val;
4691 Val = (Val << 16) | Val;
4692 Value = DAG.getConstant(Val, MVT::i32);
4693 Chain = DAG.getStore(Chain, Value,
4694 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4695 DAG.getConstant(Offset, AddrVT)),
4700 if (BytesLeft >= 2) {
4701 Value = DAG.getConstant((Val << 8) | Val, MVT::i16);
4702 Chain = DAG.getStore(Chain, Value,
4703 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4704 DAG.getConstant(Offset, AddrVT)),
4709 if (BytesLeft == 1) {
4710 Value = DAG.getConstant(Val, MVT::i8);
4711 Chain = DAG.getStore(Chain, Value,
4712 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4713 DAG.getConstant(Offset, AddrVT)),
4721 SDOperand X86TargetLowering::LowerMEMCPYInline(SDOperand Chain,
4726 SelectionDAG &DAG) {
4728 unsigned BytesLeft = 0;
4729 switch (Align & 3) {
4730 case 2: // WORD aligned
4733 case 0: // DWORD aligned
4735 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) // QWORD aligned
4738 default: // Byte aligned
4743 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4744 SDOperand Count = DAG.getIntPtrConstant(Size / UBytes);
4745 BytesLeft = Size % UBytes;
4747 SDOperand InFlag(0, 0);
4748 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4750 InFlag = Chain.getValue(1);
4751 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4753 InFlag = Chain.getValue(1);
4754 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
4756 InFlag = Chain.getValue(1);
4758 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4759 SmallVector<SDOperand, 8> Ops;
4760 Ops.push_back(Chain);
4761 Ops.push_back(DAG.getValueType(AVT));
4762 Ops.push_back(InFlag);
4763 Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
4766 // Issue loads and stores for the last 1 - 7 bytes.
4767 unsigned Offset = Size - BytesLeft;
4768 SDOperand DstAddr = Dest;
4769 MVT::ValueType DstVT = DstAddr.getValueType();
4770 SDOperand SrcAddr = Source;
4771 MVT::ValueType SrcVT = SrcAddr.getValueType();
4773 if (BytesLeft >= 4) {
4774 Value = DAG.getLoad(MVT::i32, Chain,
4775 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4776 DAG.getConstant(Offset, SrcVT)),
4778 Chain = Value.getValue(1);
4779 Chain = DAG.getStore(Chain, Value,
4780 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4781 DAG.getConstant(Offset, DstVT)),
4786 if (BytesLeft >= 2) {
4787 Value = DAG.getLoad(MVT::i16, Chain,
4788 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4789 DAG.getConstant(Offset, SrcVT)),
4791 Chain = Value.getValue(1);
4792 Chain = DAG.getStore(Chain, Value,
4793 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4794 DAG.getConstant(Offset, DstVT)),
4800 if (BytesLeft == 1) {
4801 Value = DAG.getLoad(MVT::i8, Chain,
4802 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4803 DAG.getConstant(Offset, SrcVT)),
4805 Chain = Value.getValue(1);
4806 Chain = DAG.getStore(Chain, Value,
4807 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4808 DAG.getConstant(Offset, DstVT)),
4816 /// Expand the result of: i64,outchain = READCYCLECOUNTER inchain
4817 SDNode *X86TargetLowering::ExpandREADCYCLECOUNTER(SDNode *N, SelectionDAG &DAG){
4818 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4819 SDOperand TheChain = N->getOperand(0);
4820 SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
4821 if (Subtarget->is64Bit()) {
4822 SDOperand rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
4823 SDOperand rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX,
4824 MVT::i64, rax.getValue(2));
4825 SDOperand Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
4826 DAG.getConstant(32, MVT::i8));
4828 DAG.getNode(ISD::OR, MVT::i64, rax, Tmp), rdx.getValue(1)
4831 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4832 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4835 SDOperand eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
4836 SDOperand edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX,
4837 MVT::i32, eax.getValue(2));
4838 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
4839 SDOperand Ops[] = { eax, edx };
4840 Ops[0] = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2);
4842 // Use a MERGE_VALUES to return the value and chain.
4843 Ops[1] = edx.getValue(1);
4844 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4845 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4848 SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
4849 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4851 if (!Subtarget->is64Bit()) {
4852 // vastart just stores the address of the VarArgsFrameIndex slot into the
4853 // memory location argument.
4854 SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4855 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV, 0);
4859 // gp_offset (0 - 6 * 8)
4860 // fp_offset (48 - 48 + 8 * 16)
4861 // overflow_arg_area (point to parameters coming in memory).
4863 SmallVector<SDOperand, 8> MemOps;
4864 SDOperand FIN = Op.getOperand(1);
4866 SDOperand Store = DAG.getStore(Op.getOperand(0),
4867 DAG.getConstant(VarArgsGPOffset, MVT::i32),
4869 MemOps.push_back(Store);
4872 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
4873 Store = DAG.getStore(Op.getOperand(0),
4874 DAG.getConstant(VarArgsFPOffset, MVT::i32),
4876 MemOps.push_back(Store);
4878 // Store ptr to overflow_arg_area
4879 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
4880 SDOperand OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4881 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV, 0);
4882 MemOps.push_back(Store);
4884 // Store ptr to reg_save_area.
4885 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
4886 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
4887 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV, 0);
4888 MemOps.push_back(Store);
4889 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
4892 SDOperand X86TargetLowering::LowerVACOPY(SDOperand Op, SelectionDAG &DAG) {
4893 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
4894 SDOperand Chain = Op.getOperand(0);
4895 SDOperand DstPtr = Op.getOperand(1);
4896 SDOperand SrcPtr = Op.getOperand(2);
4897 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4898 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4900 SrcPtr = DAG.getLoad(getPointerTy(), Chain, SrcPtr, SrcSV, 0);
4901 Chain = SrcPtr.getValue(1);
4902 for (unsigned i = 0; i < 3; ++i) {
4903 SDOperand Val = DAG.getLoad(MVT::i64, Chain, SrcPtr, SrcSV, 0);
4904 Chain = Val.getValue(1);
4905 Chain = DAG.getStore(Chain, Val, DstPtr, DstSV, 0);
4908 SrcPtr = DAG.getNode(ISD::ADD, getPointerTy(), SrcPtr,
4909 DAG.getIntPtrConstant(8));
4910 DstPtr = DAG.getNode(ISD::ADD, getPointerTy(), DstPtr,
4911 DAG.getIntPtrConstant(8));
4917 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
4918 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
4920 default: return SDOperand(); // Don't custom lower most intrinsics.
4921 // Comparison intrinsics.
4922 case Intrinsic::x86_sse_comieq_ss:
4923 case Intrinsic::x86_sse_comilt_ss:
4924 case Intrinsic::x86_sse_comile_ss:
4925 case Intrinsic::x86_sse_comigt_ss:
4926 case Intrinsic::x86_sse_comige_ss:
4927 case Intrinsic::x86_sse_comineq_ss:
4928 case Intrinsic::x86_sse_ucomieq_ss:
4929 case Intrinsic::x86_sse_ucomilt_ss:
4930 case Intrinsic::x86_sse_ucomile_ss:
4931 case Intrinsic::x86_sse_ucomigt_ss:
4932 case Intrinsic::x86_sse_ucomige_ss:
4933 case Intrinsic::x86_sse_ucomineq_ss:
4934 case Intrinsic::x86_sse2_comieq_sd:
4935 case Intrinsic::x86_sse2_comilt_sd:
4936 case Intrinsic::x86_sse2_comile_sd:
4937 case Intrinsic::x86_sse2_comigt_sd:
4938 case Intrinsic::x86_sse2_comige_sd:
4939 case Intrinsic::x86_sse2_comineq_sd:
4940 case Intrinsic::x86_sse2_ucomieq_sd:
4941 case Intrinsic::x86_sse2_ucomilt_sd:
4942 case Intrinsic::x86_sse2_ucomile_sd:
4943 case Intrinsic::x86_sse2_ucomigt_sd:
4944 case Intrinsic::x86_sse2_ucomige_sd:
4945 case Intrinsic::x86_sse2_ucomineq_sd: {
4947 ISD::CondCode CC = ISD::SETCC_INVALID;
4950 case Intrinsic::x86_sse_comieq_ss:
4951 case Intrinsic::x86_sse2_comieq_sd:
4955 case Intrinsic::x86_sse_comilt_ss:
4956 case Intrinsic::x86_sse2_comilt_sd:
4960 case Intrinsic::x86_sse_comile_ss:
4961 case Intrinsic::x86_sse2_comile_sd:
4965 case Intrinsic::x86_sse_comigt_ss:
4966 case Intrinsic::x86_sse2_comigt_sd:
4970 case Intrinsic::x86_sse_comige_ss:
4971 case Intrinsic::x86_sse2_comige_sd:
4975 case Intrinsic::x86_sse_comineq_ss:
4976 case Intrinsic::x86_sse2_comineq_sd:
4980 case Intrinsic::x86_sse_ucomieq_ss:
4981 case Intrinsic::x86_sse2_ucomieq_sd:
4982 Opc = X86ISD::UCOMI;
4985 case Intrinsic::x86_sse_ucomilt_ss:
4986 case Intrinsic::x86_sse2_ucomilt_sd:
4987 Opc = X86ISD::UCOMI;
4990 case Intrinsic::x86_sse_ucomile_ss:
4991 case Intrinsic::x86_sse2_ucomile_sd:
4992 Opc = X86ISD::UCOMI;
4995 case Intrinsic::x86_sse_ucomigt_ss:
4996 case Intrinsic::x86_sse2_ucomigt_sd:
4997 Opc = X86ISD::UCOMI;
5000 case Intrinsic::x86_sse_ucomige_ss:
5001 case Intrinsic::x86_sse2_ucomige_sd:
5002 Opc = X86ISD::UCOMI;
5005 case Intrinsic::x86_sse_ucomineq_ss:
5006 case Intrinsic::x86_sse2_ucomineq_sd:
5007 Opc = X86ISD::UCOMI;
5013 SDOperand LHS = Op.getOperand(1);
5014 SDOperand RHS = Op.getOperand(2);
5015 translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
5017 SDOperand Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
5018 SDOperand SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
5019 DAG.getConstant(X86CC, MVT::i8), Cond);
5020 return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
5025 SDOperand X86TargetLowering::LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
5026 // Depths > 0 not supported yet!
5027 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5030 // Just load the return address
5031 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5032 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
5035 SDOperand X86TargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG) {
5036 // Depths > 0 not supported yet!
5037 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
5040 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
5041 return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI,
5042 DAG.getIntPtrConstant(4));
5045 SDOperand X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDOperand Op,
5046 SelectionDAG &DAG) {
5047 // Is not yet supported on x86-64
5048 if (Subtarget->is64Bit())
5051 return DAG.getIntPtrConstant(8);
5054 SDOperand X86TargetLowering::LowerEH_RETURN(SDOperand Op, SelectionDAG &DAG)
5056 assert(!Subtarget->is64Bit() &&
5057 "Lowering of eh_return builtin is not supported yet on x86-64");
5059 MachineFunction &MF = DAG.getMachineFunction();
5060 SDOperand Chain = Op.getOperand(0);
5061 SDOperand Offset = Op.getOperand(1);
5062 SDOperand Handler = Op.getOperand(2);
5064 SDOperand Frame = DAG.getRegister(RegInfo->getFrameRegister(MF),
5067 SDOperand StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
5068 DAG.getIntPtrConstant(-4UL));
5069 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
5070 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
5071 Chain = DAG.getCopyToReg(Chain, X86::ECX, StoreAddr);
5072 MF.getRegInfo().addLiveOut(X86::ECX);
5074 return DAG.getNode(X86ISD::EH_RETURN, MVT::Other,
5075 Chain, DAG.getRegister(X86::ECX, getPointerTy()));
5078 SDOperand X86TargetLowering::LowerTRAMPOLINE(SDOperand Op,
5079 SelectionDAG &DAG) {
5080 SDOperand Root = Op.getOperand(0);
5081 SDOperand Trmp = Op.getOperand(1); // trampoline
5082 SDOperand FPtr = Op.getOperand(2); // nested function
5083 SDOperand Nest = Op.getOperand(3); // 'nest' parameter value
5085 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5087 const X86InstrInfo *TII =
5088 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5090 if (Subtarget->is64Bit()) {
5091 SDOperand OutChains[6];
5093 // Large code-model.
5095 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
5096 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
5098 const unsigned char N86R10 =
5099 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(X86::R10);
5100 const unsigned char N86R11 =
5101 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(X86::R11);
5103 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
5105 // Load the pointer to the nested function into R11.
5106 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
5107 SDOperand Addr = Trmp;
5108 OutChains[0] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5111 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(2, MVT::i64));
5112 OutChains[1] = DAG.getStore(Root, FPtr, Addr, TrmpAddr, 2, false, 2);
5114 // Load the 'nest' parameter value into R10.
5115 // R10 is specified in X86CallingConv.td
5116 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
5117 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(10, MVT::i64));
5118 OutChains[2] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5121 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(12, MVT::i64));
5122 OutChains[3] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 12, false, 2);
5124 // Jump to the nested function.
5125 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
5126 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(20, MVT::i64));
5127 OutChains[4] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5130 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
5131 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(22, MVT::i64));
5132 OutChains[5] = DAG.getStore(Root, DAG.getConstant(ModRM, MVT::i8), Addr,
5136 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 6) };
5137 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5139 const Function *Func =
5140 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5141 unsigned CC = Func->getCallingConv();
5146 assert(0 && "Unsupported calling convention");
5147 case CallingConv::C:
5148 case CallingConv::X86_StdCall: {
5149 // Pass 'nest' parameter in ECX.
5150 // Must be kept in sync with X86CallingConv.td
5153 // Check that ECX wasn't needed by an 'inreg' parameter.
5154 const FunctionType *FTy = Func->getFunctionType();
5155 const ParamAttrsList *Attrs = Func->getParamAttrs();
5157 if (Attrs && !Func->isVarArg()) {
5158 unsigned InRegCount = 0;
5161 for (FunctionType::param_iterator I = FTy->param_begin(),
5162 E = FTy->param_end(); I != E; ++I, ++Idx)
5163 if (Attrs->paramHasAttr(Idx, ParamAttr::InReg))
5164 // FIXME: should only count parameters that are lowered to integers.
5165 InRegCount += (getTargetData()->getTypeSizeInBits(*I) + 31) / 32;
5167 if (InRegCount > 2) {
5168 cerr << "Nest register in use - reduce number of inreg parameters!\n";
5174 case CallingConv::X86_FastCall:
5175 // Pass 'nest' parameter in EAX.
5176 // Must be kept in sync with X86CallingConv.td
5181 SDOperand OutChains[4];
5182 SDOperand Addr, Disp;
5184 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5185 Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5187 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
5188 const unsigned char N86Reg =
5189 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(NestReg);
5190 OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
5193 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
5194 OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 1, false, 1);
5196 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
5197 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
5198 OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
5199 TrmpAddr, 5, false, 1);
5201 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
5202 OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpAddr, 6, false, 1);
5205 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
5206 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5210 SDOperand X86TargetLowering::LowerFLT_ROUNDS_(SDOperand Op, SelectionDAG &DAG) {
5212 The rounding mode is in bits 11:10 of FPSR, and has the following
5219 FLT_ROUNDS, on the other hand, expects the following:
5226 To perform the conversion, we do:
5227 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
5230 MachineFunction &MF = DAG.getMachineFunction();
5231 const TargetMachine &TM = MF.getTarget();
5232 const TargetFrameInfo &TFI = *TM.getFrameInfo();
5233 unsigned StackAlignment = TFI.getStackAlignment();
5234 MVT::ValueType VT = Op.getValueType();
5236 // Save FP Control Word to stack slot
5237 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
5238 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5240 SDOperand Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
5241 DAG.getEntryNode(), StackSlot);
5243 // Load FP Control Word from stack slot
5244 SDOperand CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
5246 // Transform as necessary
5248 DAG.getNode(ISD::SRL, MVT::i16,
5249 DAG.getNode(ISD::AND, MVT::i16,
5250 CWD, DAG.getConstant(0x800, MVT::i16)),
5251 DAG.getConstant(11, MVT::i8));
5253 DAG.getNode(ISD::SRL, MVT::i16,
5254 DAG.getNode(ISD::AND, MVT::i16,
5255 CWD, DAG.getConstant(0x400, MVT::i16)),
5256 DAG.getConstant(9, MVT::i8));
5259 DAG.getNode(ISD::AND, MVT::i16,
5260 DAG.getNode(ISD::ADD, MVT::i16,
5261 DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
5262 DAG.getConstant(1, MVT::i16)),
5263 DAG.getConstant(3, MVT::i16));
5266 return DAG.getNode((MVT::getSizeInBits(VT) < 16 ?
5267 ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
5270 SDOperand X86TargetLowering::LowerCTLZ(SDOperand Op, SelectionDAG &DAG) {
5271 MVT::ValueType VT = Op.getValueType();
5272 MVT::ValueType OpVT = VT;
5273 unsigned NumBits = MVT::getSizeInBits(VT);
5275 Op = Op.getOperand(0);
5276 if (VT == MVT::i8) {
5277 // Zero extend to i32 since there is not an i8 bsr.
5279 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5282 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
5283 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5284 Op = DAG.getNode(X86ISD::BSR, VTs, Op);
5286 // If src is zero (i.e. bsr sets ZF), returns NumBits.
5287 SmallVector<SDOperand, 4> Ops;
5289 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
5290 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5291 Ops.push_back(Op.getValue(1));
5292 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5294 // Finally xor with NumBits-1.
5295 Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
5298 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5302 SDOperand X86TargetLowering::LowerCTTZ(SDOperand Op, SelectionDAG &DAG) {
5303 MVT::ValueType VT = Op.getValueType();
5304 MVT::ValueType OpVT = VT;
5305 unsigned NumBits = MVT::getSizeInBits(VT);
5307 Op = Op.getOperand(0);
5308 if (VT == MVT::i8) {
5310 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5313 // Issue a bsf (scan bits forward) which also sets EFLAGS.
5314 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5315 Op = DAG.getNode(X86ISD::BSF, VTs, Op);
5317 // If src is zero (i.e. bsf sets ZF), returns NumBits.
5318 SmallVector<SDOperand, 4> Ops;
5320 Ops.push_back(DAG.getConstant(NumBits, OpVT));
5321 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5322 Ops.push_back(Op.getValue(1));
5323 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5326 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5330 /// LowerOperation - Provide custom lowering hooks for some operations.
5332 SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
5333 switch (Op.getOpcode()) {
5334 default: assert(0 && "Should not custom lower this!");
5335 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5336 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5337 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5338 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5339 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5340 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5341 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5342 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5343 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
5344 case ISD::SHL_PARTS:
5345 case ISD::SRA_PARTS:
5346 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
5347 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
5348 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
5349 case ISD::FABS: return LowerFABS(Op, DAG);
5350 case ISD::FNEG: return LowerFNEG(Op, DAG);
5351 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5352 case ISD::SETCC: return LowerSETCC(Op, DAG);
5353 case ISD::SELECT: return LowerSELECT(Op, DAG);
5354 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
5355 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5356 case ISD::CALL: return LowerCALL(Op, DAG);
5357 case ISD::RET: return LowerRET(Op, DAG);
5358 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
5359 case ISD::MEMSET: return LowerMEMSET(Op, DAG);
5360 case ISD::MEMCPY: return LowerMEMCPY(Op, DAG);
5361 case ISD::VASTART: return LowerVASTART(Op, DAG);
5362 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
5363 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5364 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5365 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5366 case ISD::FRAME_TO_ARGS_OFFSET:
5367 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
5368 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
5369 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
5370 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
5371 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5372 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
5373 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
5375 // FIXME: REMOVE THIS WHEN LegalizeDAGTypes lands.
5376 case ISD::READCYCLECOUNTER:
5377 return SDOperand(ExpandREADCYCLECOUNTER(Op.Val, DAG), 0);
5381 /// ExpandOperation - Provide custom lowering hooks for expanding operations.
5382 SDNode *X86TargetLowering::ExpandOperationResult(SDNode *N, SelectionDAG &DAG) {
5383 switch (N->getOpcode()) {
5384 default: assert(0 && "Should not custom lower this!");
5385 case ISD::FP_TO_SINT: return ExpandFP_TO_SINT(N, DAG);
5386 case ISD::READCYCLECOUNTER: return ExpandREADCYCLECOUNTER(N, DAG);
5390 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
5392 default: return NULL;
5393 case X86ISD::BSF: return "X86ISD::BSF";
5394 case X86ISD::BSR: return "X86ISD::BSR";
5395 case X86ISD::SHLD: return "X86ISD::SHLD";
5396 case X86ISD::SHRD: return "X86ISD::SHRD";
5397 case X86ISD::FAND: return "X86ISD::FAND";
5398 case X86ISD::FOR: return "X86ISD::FOR";
5399 case X86ISD::FXOR: return "X86ISD::FXOR";
5400 case X86ISD::FSRL: return "X86ISD::FSRL";
5401 case X86ISD::FILD: return "X86ISD::FILD";
5402 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
5403 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
5404 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
5405 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
5406 case X86ISD::FLD: return "X86ISD::FLD";
5407 case X86ISD::FST: return "X86ISD::FST";
5408 case X86ISD::FP_GET_RESULT: return "X86ISD::FP_GET_RESULT";
5409 case X86ISD::FP_GET_RESULT2: return "X86ISD::FP_GET_RESULT2";
5410 case X86ISD::FP_SET_RESULT: return "X86ISD::FP_SET_RESULT";
5411 case X86ISD::CALL: return "X86ISD::CALL";
5412 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
5413 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
5414 case X86ISD::CMP: return "X86ISD::CMP";
5415 case X86ISD::COMI: return "X86ISD::COMI";
5416 case X86ISD::UCOMI: return "X86ISD::UCOMI";
5417 case X86ISD::SETCC: return "X86ISD::SETCC";
5418 case X86ISD::CMOV: return "X86ISD::CMOV";
5419 case X86ISD::BRCOND: return "X86ISD::BRCOND";
5420 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
5421 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
5422 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
5423 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
5424 case X86ISD::Wrapper: return "X86ISD::Wrapper";
5425 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
5426 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
5427 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
5428 case X86ISD::PINSRB: return "X86ISD::PINSRB";
5429 case X86ISD::PINSRW: return "X86ISD::PINSRW";
5430 case X86ISD::FMAX: return "X86ISD::FMAX";
5431 case X86ISD::FMIN: return "X86ISD::FMIN";
5432 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
5433 case X86ISD::FRCP: return "X86ISD::FRCP";
5434 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
5435 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
5436 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
5437 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
5438 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
5442 // isLegalAddressingMode - Return true if the addressing mode represented
5443 // by AM is legal for this target, for a load/store of the specified type.
5444 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
5445 const Type *Ty) const {
5446 // X86 supports extremely general addressing modes.
5448 // X86 allows a sign-extended 32-bit immediate field as a displacement.
5449 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
5453 // We can only fold this if we don't need an extra load.
5454 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
5457 // X86-64 only supports addr of globals in small code model.
5458 if (Subtarget->is64Bit()) {
5459 if (getTargetMachine().getCodeModel() != CodeModel::Small)
5461 // If lower 4G is not available, then we must use rip-relative addressing.
5462 if (AM.BaseOffs || AM.Scale > 1)
5473 // These scales always work.
5478 // These scales are formed with basereg+scalereg. Only accept if there is
5483 default: // Other stuff never works.
5491 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
5492 if (!Ty1->isInteger() || !Ty2->isInteger())
5494 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5495 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5496 if (NumBits1 <= NumBits2)
5498 return Subtarget->is64Bit() || NumBits1 < 64;
5501 bool X86TargetLowering::isTruncateFree(MVT::ValueType VT1,
5502 MVT::ValueType VT2) const {
5503 if (!MVT::isInteger(VT1) || !MVT::isInteger(VT2))
5505 unsigned NumBits1 = MVT::getSizeInBits(VT1);
5506 unsigned NumBits2 = MVT::getSizeInBits(VT2);
5507 if (NumBits1 <= NumBits2)
5509 return Subtarget->is64Bit() || NumBits1 < 64;
5512 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5513 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5514 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5515 /// are assumed to be legal.
5517 X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
5518 // Only do shuffles on 128-bit vector types for now.
5519 if (MVT::getSizeInBits(VT) == 64) return false;
5520 return (Mask.Val->getNumOperands() <= 4 ||
5521 isIdentityMask(Mask.Val) ||
5522 isIdentityMask(Mask.Val, true) ||
5523 isSplatMask(Mask.Val) ||
5524 isPSHUFHW_PSHUFLWMask(Mask.Val) ||
5525 X86::isUNPCKLMask(Mask.Val) ||
5526 X86::isUNPCKHMask(Mask.Val) ||
5527 X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
5528 X86::isUNPCKH_v_undef_Mask(Mask.Val));
5531 bool X86TargetLowering::isVectorClearMaskLegal(std::vector<SDOperand> &BVOps,
5533 SelectionDAG &DAG) const {
5534 unsigned NumElts = BVOps.size();
5535 // Only do shuffles on 128-bit vector types for now.
5536 if (MVT::getSizeInBits(EVT) * NumElts == 64) return false;
5537 if (NumElts == 2) return true;
5539 return (isMOVLMask(&BVOps[0], 4) ||
5540 isCommutedMOVL(&BVOps[0], 4, true) ||
5541 isSHUFPMask(&BVOps[0], 4) ||
5542 isCommutedSHUFP(&BVOps[0], 4));
5547 //===----------------------------------------------------------------------===//
5548 // X86 Scheduler Hooks
5549 //===----------------------------------------------------------------------===//
5552 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
5553 MachineBasicBlock *BB) {
5554 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5555 switch (MI->getOpcode()) {
5556 default: assert(false && "Unexpected instr type to insert");
5557 case X86::CMOV_FR32:
5558 case X86::CMOV_FR64:
5559 case X86::CMOV_V4F32:
5560 case X86::CMOV_V2F64:
5561 case X86::CMOV_V2I64: {
5562 // To "insert" a SELECT_CC instruction, we actually have to insert the
5563 // diamond control-flow pattern. The incoming instruction knows the
5564 // destination vreg to set, the condition code register to branch on, the
5565 // true/false values to select between, and a branch opcode to use.
5566 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5567 ilist<MachineBasicBlock>::iterator It = BB;
5573 // cmpTY ccX, r1, r2
5575 // fallthrough --> copy0MBB
5576 MachineBasicBlock *thisMBB = BB;
5577 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
5578 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
5580 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
5581 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
5582 MachineFunction *F = BB->getParent();
5583 F->getBasicBlockList().insert(It, copy0MBB);
5584 F->getBasicBlockList().insert(It, sinkMBB);
5585 // Update machine-CFG edges by first adding all successors of the current
5586 // block to the new block which will contain the Phi node for the select.
5587 for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
5588 e = BB->succ_end(); i != e; ++i)
5589 sinkMBB->addSuccessor(*i);
5590 // Next, remove all successors of the current block, and add the true
5591 // and fallthrough blocks as its successors.
5592 while(!BB->succ_empty())
5593 BB->removeSuccessor(BB->succ_begin());
5594 BB->addSuccessor(copy0MBB);
5595 BB->addSuccessor(sinkMBB);
5598 // %FalseValue = ...
5599 // # fallthrough to sinkMBB
5602 // Update machine-CFG edges
5603 BB->addSuccessor(sinkMBB);
5606 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
5609 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
5610 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
5611 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
5613 delete MI; // The pseudo instruction is gone now.
5617 case X86::FP32_TO_INT16_IN_MEM:
5618 case X86::FP32_TO_INT32_IN_MEM:
5619 case X86::FP32_TO_INT64_IN_MEM:
5620 case X86::FP64_TO_INT16_IN_MEM:
5621 case X86::FP64_TO_INT32_IN_MEM:
5622 case X86::FP64_TO_INT64_IN_MEM:
5623 case X86::FP80_TO_INT16_IN_MEM:
5624 case X86::FP80_TO_INT32_IN_MEM:
5625 case X86::FP80_TO_INT64_IN_MEM: {
5626 // Change the floating point control register to use "round towards zero"
5627 // mode when truncating to an integer value.
5628 MachineFunction *F = BB->getParent();
5629 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
5630 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
5632 // Load the old value of the high byte of the control word...
5634 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
5635 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
5637 // Set the high part to be round to zero...
5638 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
5641 // Reload the modified control word now...
5642 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5644 // Restore the memory image of control word to original value
5645 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
5648 // Get the X86 opcode to use.
5650 switch (MI->getOpcode()) {
5651 default: assert(0 && "illegal opcode!");
5652 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
5653 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
5654 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
5655 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
5656 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
5657 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
5658 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
5659 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
5660 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
5664 MachineOperand &Op = MI->getOperand(0);
5665 if (Op.isRegister()) {
5666 AM.BaseType = X86AddressMode::RegBase;
5667 AM.Base.Reg = Op.getReg();
5669 AM.BaseType = X86AddressMode::FrameIndexBase;
5670 AM.Base.FrameIndex = Op.getIndex();
5672 Op = MI->getOperand(1);
5673 if (Op.isImmediate())
5674 AM.Scale = Op.getImm();
5675 Op = MI->getOperand(2);
5676 if (Op.isImmediate())
5677 AM.IndexReg = Op.getImm();
5678 Op = MI->getOperand(3);
5679 if (Op.isGlobalAddress()) {
5680 AM.GV = Op.getGlobal();
5682 AM.Disp = Op.getImm();
5684 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
5685 .addReg(MI->getOperand(4).getReg());
5687 // Reload the original control word now.
5688 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5690 delete MI; // The pseudo instruction is gone now.
5696 //===----------------------------------------------------------------------===//
5697 // X86 Optimization Hooks
5698 //===----------------------------------------------------------------------===//
5700 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
5704 const SelectionDAG &DAG,
5705 unsigned Depth) const {
5706 unsigned Opc = Op.getOpcode();
5707 assert((Opc >= ISD::BUILTIN_OP_END ||
5708 Opc == ISD::INTRINSIC_WO_CHAIN ||
5709 Opc == ISD::INTRINSIC_W_CHAIN ||
5710 Opc == ISD::INTRINSIC_VOID) &&
5711 "Should use MaskedValueIsZero if you don't know whether Op"
5712 " is a target node!");
5714 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
5718 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
5719 Mask.getBitWidth() - 1);
5724 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5725 /// element of the result of the vector shuffle.
5726 static SDOperand getShuffleScalarElt(SDNode *N, unsigned i, SelectionDAG &DAG) {
5727 MVT::ValueType VT = N->getValueType(0);
5728 SDOperand PermMask = N->getOperand(2);
5729 unsigned NumElems = PermMask.getNumOperands();
5730 SDOperand V = (i < NumElems) ? N->getOperand(0) : N->getOperand(1);
5732 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5734 ? V.getOperand(0) : DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5735 } else if (V.getOpcode() == ISD::VECTOR_SHUFFLE) {
5736 SDOperand Idx = PermMask.getOperand(i);
5737 if (Idx.getOpcode() == ISD::UNDEF)
5738 return DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5739 return getShuffleScalarElt(V.Val,cast<ConstantSDNode>(Idx)->getValue(),DAG);
5744 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
5745 /// node is a GlobalAddress + an offset.
5746 static bool isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) {
5747 unsigned Opc = N->getOpcode();
5748 if (Opc == X86ISD::Wrapper) {
5749 if (dyn_cast<GlobalAddressSDNode>(N->getOperand(0))) {
5750 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
5753 } else if (Opc == ISD::ADD) {
5754 SDOperand N1 = N->getOperand(0);
5755 SDOperand N2 = N->getOperand(1);
5756 if (isGAPlusOffset(N1.Val, GA, Offset)) {
5757 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
5759 Offset += V->getSignExtended();
5762 } else if (isGAPlusOffset(N2.Val, GA, Offset)) {
5763 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
5765 Offset += V->getSignExtended();
5773 /// isConsecutiveLoad - Returns true if N is loading from an address of Base
5775 static bool isConsecutiveLoad(SDNode *N, SDNode *Base, int Dist, int Size,
5776 MachineFrameInfo *MFI) {
5777 if (N->getOperand(0).Val != Base->getOperand(0).Val)
5780 SDOperand Loc = N->getOperand(1);
5781 SDOperand BaseLoc = Base->getOperand(1);
5782 if (Loc.getOpcode() == ISD::FrameIndex) {
5783 if (BaseLoc.getOpcode() != ISD::FrameIndex)
5785 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
5786 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
5787 int FS = MFI->getObjectSize(FI);
5788 int BFS = MFI->getObjectSize(BFI);
5789 if (FS != BFS || FS != Size) return false;
5790 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Size);
5792 GlobalValue *GV1 = NULL;
5793 GlobalValue *GV2 = NULL;
5794 int64_t Offset1 = 0;
5795 int64_t Offset2 = 0;
5796 bool isGA1 = isGAPlusOffset(Loc.Val, GV1, Offset1);
5797 bool isGA2 = isGAPlusOffset(BaseLoc.Val, GV2, Offset2);
5798 if (isGA1 && isGA2 && GV1 == GV2)
5799 return Offset1 == (Offset2 + Dist*Size);
5805 static bool isBaseAlignment16(SDNode *Base, MachineFrameInfo *MFI,
5806 const X86Subtarget *Subtarget) {
5809 if (isGAPlusOffset(Base, GV, Offset))
5810 return (GV->getAlignment() >= 16 && (Offset % 16) == 0);
5811 // DAG combine handles the stack object case.
5816 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
5817 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
5818 /// if the load addresses are consecutive, non-overlapping, and in the right
5820 static SDOperand PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
5821 const X86Subtarget *Subtarget) {
5822 MachineFunction &MF = DAG.getMachineFunction();
5823 MachineFrameInfo *MFI = MF.getFrameInfo();
5824 MVT::ValueType VT = N->getValueType(0);
5825 MVT::ValueType EVT = MVT::getVectorElementType(VT);
5826 SDOperand PermMask = N->getOperand(2);
5827 int NumElems = (int)PermMask.getNumOperands();
5828 SDNode *Base = NULL;
5829 for (int i = 0; i < NumElems; ++i) {
5830 SDOperand Idx = PermMask.getOperand(i);
5831 if (Idx.getOpcode() == ISD::UNDEF) {
5832 if (!Base) return SDOperand();
5835 getShuffleScalarElt(N, cast<ConstantSDNode>(Idx)->getValue(), DAG);
5836 if (!Arg.Val || !ISD::isNON_EXTLoad(Arg.Val))
5840 else if (!isConsecutiveLoad(Arg.Val, Base,
5841 i, MVT::getSizeInBits(EVT)/8,MFI))
5846 bool isAlign16 = isBaseAlignment16(Base->getOperand(1).Val, MFI, Subtarget);
5847 LoadSDNode *LD = cast<LoadSDNode>(Base);
5849 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
5850 LD->getSrcValueOffset(), LD->isVolatile());
5852 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
5853 LD->getSrcValueOffset(), LD->isVolatile(),
5854 LD->getAlignment());
5858 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
5859 static SDOperand PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
5860 const X86Subtarget *Subtarget) {
5861 SDOperand Cond = N->getOperand(0);
5863 // If we have SSE[12] support, try to form min/max nodes.
5864 if (Subtarget->hasSSE2() &&
5865 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
5866 if (Cond.getOpcode() == ISD::SETCC) {
5867 // Get the LHS/RHS of the select.
5868 SDOperand LHS = N->getOperand(1);
5869 SDOperand RHS = N->getOperand(2);
5870 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
5872 unsigned Opcode = 0;
5873 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
5876 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
5879 if (!UnsafeFPMath) break;
5881 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
5883 Opcode = X86ISD::FMIN;
5886 case ISD::SETOGT: // (X > Y) ? X : Y -> max
5889 if (!UnsafeFPMath) break;
5891 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
5893 Opcode = X86ISD::FMAX;
5896 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
5899 case ISD::SETOGT: // (X > Y) ? Y : X -> min
5902 if (!UnsafeFPMath) break;
5904 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
5906 Opcode = X86ISD::FMIN;
5909 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
5912 if (!UnsafeFPMath) break;
5914 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
5916 Opcode = X86ISD::FMAX;
5922 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
5930 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
5931 static SDOperand PerformSTORECombine(StoreSDNode *St, SelectionDAG &DAG,
5932 const X86Subtarget *Subtarget) {
5933 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
5934 // the FP state in cases where an emms may be missing.
5935 // A preferable solution to the general problem is to figure out the right
5936 // places to insert EMMS. This qualifies as a quick hack.
5937 if (MVT::isVector(St->getValue().getValueType()) &&
5938 MVT::getSizeInBits(St->getValue().getValueType()) == 64 &&
5939 isa<LoadSDNode>(St->getValue()) &&
5940 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
5941 St->getChain().hasOneUse() && !St->isVolatile()) {
5942 SDNode* LdVal = St->getValue().Val;
5944 int TokenFactorIndex = -1;
5945 SmallVector<SDOperand, 8> Ops;
5946 SDNode* ChainVal = St->getChain().Val;
5947 // Must be a store of a load. We currently handle two cases: the load
5948 // is a direct child, and it's under an intervening TokenFactor. It is
5949 // possible to dig deeper under nested TokenFactors.
5950 if (ChainVal == LdVal)
5951 Ld = cast<LoadSDNode>(St->getChain());
5952 else if (St->getValue().hasOneUse() &&
5953 ChainVal->getOpcode() == ISD::TokenFactor) {
5954 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
5955 if (ChainVal->getOperand(i).Val == LdVal) {
5956 TokenFactorIndex = i;
5957 Ld = cast<LoadSDNode>(St->getValue());
5959 Ops.push_back(ChainVal->getOperand(i));
5963 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
5964 if (Subtarget->is64Bit()) {
5965 SDOperand NewLd = DAG.getLoad(MVT::i64, Ld->getChain(),
5966 Ld->getBasePtr(), Ld->getSrcValue(),
5967 Ld->getSrcValueOffset(), Ld->isVolatile(),
5968 Ld->getAlignment());
5969 SDOperand NewChain = NewLd.getValue(1);
5970 if (TokenFactorIndex != -1) {
5971 Ops.push_back(NewLd);
5972 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
5975 return DAG.getStore(NewChain, NewLd, St->getBasePtr(),
5976 St->getSrcValue(), St->getSrcValueOffset(),
5977 St->isVolatile(), St->getAlignment());
5980 // Otherwise, lower to two 32-bit copies.
5981 SDOperand LoAddr = Ld->getBasePtr();
5982 SDOperand HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
5983 DAG.getConstant(MVT::i32, 4));
5985 SDOperand LoLd = DAG.getLoad(MVT::i32, Ld->getChain(), LoAddr,
5986 Ld->getSrcValue(), Ld->getSrcValueOffset(),
5987 Ld->isVolatile(), Ld->getAlignment());
5988 SDOperand HiLd = DAG.getLoad(MVT::i32, Ld->getChain(), HiAddr,
5989 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
5991 MinAlign(Ld->getAlignment(), 4));
5993 SDOperand NewChain = LoLd.getValue(1);
5994 if (TokenFactorIndex != -1) {
5995 Ops.push_back(LoLd);
5996 Ops.push_back(HiLd);
5997 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
6001 LoAddr = St->getBasePtr();
6002 HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
6003 DAG.getConstant(MVT::i32, 4));
6005 SDOperand LoSt = DAG.getStore(NewChain, LoLd, LoAddr,
6006 St->getSrcValue(), St->getSrcValueOffset(),
6007 St->isVolatile(), St->getAlignment());
6008 SDOperand HiSt = DAG.getStore(NewChain, HiLd, HiAddr,
6009 St->getSrcValue(), St->getSrcValueOffset()+4,
6011 MinAlign(St->getAlignment(), 4));
6012 return DAG.getNode(ISD::TokenFactor, MVT::Other, LoSt, HiSt);
6018 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
6019 /// X86ISD::FXOR nodes.
6020 static SDOperand PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
6021 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
6022 // F[X]OR(0.0, x) -> x
6023 // F[X]OR(x, 0.0) -> x
6024 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6025 if (C->getValueAPF().isPosZero())
6026 return N->getOperand(1);
6027 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6028 if (C->getValueAPF().isPosZero())
6029 return N->getOperand(0);
6033 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
6034 static SDOperand PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
6035 // FAND(0.0, x) -> 0.0
6036 // FAND(x, 0.0) -> 0.0
6037 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
6038 if (C->getValueAPF().isPosZero())
6039 return N->getOperand(0);
6040 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
6041 if (C->getValueAPF().isPosZero())
6042 return N->getOperand(1);
6047 SDOperand X86TargetLowering::PerformDAGCombine(SDNode *N,
6048 DAGCombinerInfo &DCI) const {
6049 SelectionDAG &DAG = DCI.DAG;
6050 switch (N->getOpcode()) {
6052 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, Subtarget);
6053 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
6055 return PerformSTORECombine(cast<StoreSDNode>(N), DAG, Subtarget);
6057 case X86ISD::FOR: return PerformFORCombine(N, DAG);
6058 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
6064 //===----------------------------------------------------------------------===//
6065 // X86 Inline Assembly Support
6066 //===----------------------------------------------------------------------===//
6068 /// getConstraintType - Given a constraint letter, return the type of
6069 /// constraint it is for this target.
6070 X86TargetLowering::ConstraintType
6071 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
6072 if (Constraint.size() == 1) {
6073 switch (Constraint[0]) {
6082 return C_RegisterClass;
6087 return TargetLowering::getConstraintType(Constraint);
6090 /// LowerXConstraint - try to replace an X constraint, which matches anything,
6091 /// with another that has more specific requirements based on the type of the
6092 /// corresponding operand.
6093 void X86TargetLowering::lowerXConstraint(MVT::ValueType ConstraintVT,
6094 std::string& s) const {
6095 if (MVT::isFloatingPoint(ConstraintVT)) {
6096 if (Subtarget->hasSSE2())
6098 else if (Subtarget->hasSSE1())
6103 return TargetLowering::lowerXConstraint(ConstraintVT, s);
6106 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
6107 /// vector. If it is invalid, don't add anything to Ops.
6108 void X86TargetLowering::LowerAsmOperandForConstraint(SDOperand Op,
6110 std::vector<SDOperand>&Ops,
6111 SelectionDAG &DAG) {
6112 SDOperand Result(0, 0);
6114 switch (Constraint) {
6117 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6118 if (C->getValue() <= 31) {
6119 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6125 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
6126 if (C->getValue() <= 255) {
6127 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
6133 // Literal immediates are always ok.
6134 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
6135 Result = DAG.getTargetConstant(CST->getValue(), Op.getValueType());
6139 // If we are in non-pic codegen mode, we allow the address of a global (with
6140 // an optional displacement) to be used with 'i'.
6141 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
6144 // Match either (GA) or (GA+C)
6146 Offset = GA->getOffset();
6147 } else if (Op.getOpcode() == ISD::ADD) {
6148 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6149 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6151 Offset = GA->getOffset()+C->getValue();
6153 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6154 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6156 Offset = GA->getOffset()+C->getValue();
6163 // If addressing this global requires a load (e.g. in PIC mode), we can't
6165 if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
6169 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
6175 // Otherwise, not valid for this mode.
6181 Ops.push_back(Result);
6184 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6187 std::vector<unsigned> X86TargetLowering::
6188 getRegClassForInlineAsmConstraint(const std::string &Constraint,
6189 MVT::ValueType VT) const {
6190 if (Constraint.size() == 1) {
6191 // FIXME: not handling fp-stack yet!
6192 switch (Constraint[0]) { // GCC X86 Constraint Letters
6193 default: break; // Unknown constraint letter
6194 case 'A': // EAX/EDX
6195 if (VT == MVT::i32 || VT == MVT::i64)
6196 return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
6198 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
6201 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
6202 else if (VT == MVT::i16)
6203 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
6204 else if (VT == MVT::i8)
6205 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
6206 else if (VT == MVT::i64)
6207 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
6212 return std::vector<unsigned>();
6215 std::pair<unsigned, const TargetRegisterClass*>
6216 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
6217 MVT::ValueType VT) const {
6218 // First, see if this is a constraint that directly corresponds to an LLVM
6220 if (Constraint.size() == 1) {
6221 // GCC Constraint Letters
6222 switch (Constraint[0]) {
6224 case 'r': // GENERAL_REGS
6225 case 'R': // LEGACY_REGS
6226 case 'l': // INDEX_REGS
6227 if (VT == MVT::i64 && Subtarget->is64Bit())
6228 return std::make_pair(0U, X86::GR64RegisterClass);
6230 return std::make_pair(0U, X86::GR32RegisterClass);
6231 else if (VT == MVT::i16)
6232 return std::make_pair(0U, X86::GR16RegisterClass);
6233 else if (VT == MVT::i8)
6234 return std::make_pair(0U, X86::GR8RegisterClass);
6236 case 'y': // MMX_REGS if MMX allowed.
6237 if (!Subtarget->hasMMX()) break;
6238 return std::make_pair(0U, X86::VR64RegisterClass);
6240 case 'Y': // SSE_REGS if SSE2 allowed
6241 if (!Subtarget->hasSSE2()) break;
6243 case 'x': // SSE_REGS if SSE1 allowed
6244 if (!Subtarget->hasSSE1()) break;
6248 // Scalar SSE types.
6251 return std::make_pair(0U, X86::FR32RegisterClass);
6254 return std::make_pair(0U, X86::FR64RegisterClass);
6262 return std::make_pair(0U, X86::VR128RegisterClass);
6268 // Use the default implementation in TargetLowering to convert the register
6269 // constraint into a member of a register class.
6270 std::pair<unsigned, const TargetRegisterClass*> Res;
6271 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
6273 // Not found as a standard register?
6274 if (Res.second == 0) {
6275 // GCC calls "st(0)" just plain "st".
6276 if (StringsEqualNoCase("{st}", Constraint)) {
6277 Res.first = X86::ST0;
6278 Res.second = X86::RFP80RegisterClass;
6284 // Otherwise, check to see if this is a register class of the wrong value
6285 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
6286 // turn into {ax},{dx}.
6287 if (Res.second->hasType(VT))
6288 return Res; // Correct type already, nothing to do.
6290 // All of the single-register GCC register classes map their values onto
6291 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
6292 // really want an 8-bit or 32-bit register, map to the appropriate register
6293 // class and return the appropriate register.
6294 if (Res.second != X86::GR16RegisterClass)
6297 if (VT == MVT::i8) {
6298 unsigned DestReg = 0;
6299 switch (Res.first) {
6301 case X86::AX: DestReg = X86::AL; break;
6302 case X86::DX: DestReg = X86::DL; break;
6303 case X86::CX: DestReg = X86::CL; break;
6304 case X86::BX: DestReg = X86::BL; break;
6307 Res.first = DestReg;
6308 Res.second = Res.second = X86::GR8RegisterClass;
6310 } else if (VT == MVT::i32) {
6311 unsigned DestReg = 0;
6312 switch (Res.first) {
6314 case X86::AX: DestReg = X86::EAX; break;
6315 case X86::DX: DestReg = X86::EDX; break;
6316 case X86::CX: DestReg = X86::ECX; break;
6317 case X86::BX: DestReg = X86::EBX; break;
6318 case X86::SI: DestReg = X86::ESI; break;
6319 case X86::DI: DestReg = X86::EDI; break;
6320 case X86::BP: DestReg = X86::EBP; break;
6321 case X86::SP: DestReg = X86::ESP; break;
6324 Res.first = DestReg;
6325 Res.second = Res.second = X86::GR32RegisterClass;
6327 } else if (VT == MVT::i64) {
6328 unsigned DestReg = 0;
6329 switch (Res.first) {
6331 case X86::AX: DestReg = X86::RAX; break;
6332 case X86::DX: DestReg = X86::RDX; break;
6333 case X86::CX: DestReg = X86::RCX; break;
6334 case X86::BX: DestReg = X86::RBX; break;
6335 case X86::SI: DestReg = X86::RSI; break;
6336 case X86::DI: DestReg = X86::RDI; break;
6337 case X86::BP: DestReg = X86::RBP; break;
6338 case X86::SP: DestReg = X86::RSP; break;
6341 Res.first = DestReg;
6342 Res.second = Res.second = X86::GR64RegisterClass;