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/ParameterAttributes.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 multiply, multiply-high, divide, and remainder are
173 // lowered to use operations that produce two results, to match the
174 // available instructions. This exposes the two-result form to trivial
175 // CSE, which is able to combine x/y and x%y into a single instruction,
176 // for example. The single-result multiply instructions are introduced
177 // in X86ISelDAGToDAG.cpp, after CSE, for uses where the the high part
179 setOperationAction(ISD::MUL , MVT::i8 , Expand);
180 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
181 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
182 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
183 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
184 setOperationAction(ISD::SREM , MVT::i8 , Expand);
185 setOperationAction(ISD::UREM , MVT::i8 , Expand);
186 setOperationAction(ISD::MUL , MVT::i16 , Expand);
187 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
188 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
189 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
190 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
191 setOperationAction(ISD::SREM , MVT::i16 , Expand);
192 setOperationAction(ISD::UREM , MVT::i16 , Expand);
193 setOperationAction(ISD::MUL , MVT::i32 , 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::MUL , MVT::i64 , Expand);
201 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
202 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
203 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
204 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
205 setOperationAction(ISD::SREM , MVT::i64 , Expand);
206 setOperationAction(ISD::UREM , MVT::i64 , Expand);
208 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
209 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
210 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
211 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
212 setOperationAction(ISD::MEMMOVE , MVT::Other, Expand);
213 if (Subtarget->is64Bit())
214 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
215 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
216 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
217 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
218 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
219 setOperationAction(ISD::FREM , MVT::f64 , Expand);
220 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
222 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
223 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
224 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
225 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
226 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
227 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
228 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
229 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
230 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
231 if (Subtarget->is64Bit()) {
232 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
233 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
234 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
237 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
238 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
240 // These should be promoted to a larger select which is supported.
241 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
242 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
243 // X86 wants to expand cmov itself.
244 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
245 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
246 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
247 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
248 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
249 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
250 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
251 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
252 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
253 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
254 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
255 if (Subtarget->is64Bit()) {
256 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
257 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
259 // X86 ret instruction may pop stack.
260 setOperationAction(ISD::RET , MVT::Other, Custom);
261 if (!Subtarget->is64Bit())
262 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
265 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
266 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
267 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
268 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
269 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
270 if (Subtarget->is64Bit()) {
271 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
272 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
273 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
274 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
276 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
277 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
278 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
279 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
280 // X86 wants to expand memset / memcpy itself.
281 setOperationAction(ISD::MEMSET , MVT::Other, Custom);
282 setOperationAction(ISD::MEMCPY , MVT::Other, Custom);
284 // Use the default ISD::LOCATION, ISD::DECLARE expansion.
285 setOperationAction(ISD::LOCATION, MVT::Other, Expand);
286 // FIXME - use subtarget debug flags
287 if (!Subtarget->isTargetDarwin() &&
288 !Subtarget->isTargetELF() &&
289 !Subtarget->isTargetCygMing())
290 setOperationAction(ISD::LABEL, MVT::Other, Expand);
292 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
293 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
294 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
295 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
296 if (Subtarget->is64Bit()) {
298 setExceptionPointerRegister(X86::RAX);
299 setExceptionSelectorRegister(X86::RDX);
301 setExceptionPointerRegister(X86::EAX);
302 setExceptionSelectorRegister(X86::EDX);
304 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
306 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
308 setOperationAction(ISD::TRAP, MVT::Other, Legal);
310 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
311 setOperationAction(ISD::VASTART , MVT::Other, Custom);
312 setOperationAction(ISD::VAARG , MVT::Other, Expand);
313 setOperationAction(ISD::VAEND , MVT::Other, Expand);
314 if (Subtarget->is64Bit())
315 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
317 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
319 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
320 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
321 if (Subtarget->is64Bit())
322 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
323 if (Subtarget->isTargetCygMing())
324 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
326 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
328 if (X86ScalarSSEf64) {
329 // f32 and f64 use SSE.
330 // Set up the FP register classes.
331 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
332 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
334 // Use ANDPD to simulate FABS.
335 setOperationAction(ISD::FABS , MVT::f64, Custom);
336 setOperationAction(ISD::FABS , MVT::f32, Custom);
338 // Use XORP to simulate FNEG.
339 setOperationAction(ISD::FNEG , MVT::f64, Custom);
340 setOperationAction(ISD::FNEG , MVT::f32, Custom);
342 // Use ANDPD and ORPD to simulate FCOPYSIGN.
343 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
344 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
346 // We don't support sin/cos/fmod
347 setOperationAction(ISD::FSIN , MVT::f64, Expand);
348 setOperationAction(ISD::FCOS , MVT::f64, Expand);
349 setOperationAction(ISD::FREM , MVT::f64, Expand);
350 setOperationAction(ISD::FSIN , MVT::f32, Expand);
351 setOperationAction(ISD::FCOS , MVT::f32, Expand);
352 setOperationAction(ISD::FREM , MVT::f32, Expand);
354 // Expand FP immediates into loads from the stack, except for the special
356 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
357 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
358 addLegalFPImmediate(APFloat(+0.0)); // xorpd
359 addLegalFPImmediate(APFloat(+0.0f)); // xorps
361 // Floating truncations from f80 and extensions to f80 go through memory.
362 // If optimizing, we lie about this though and handle it in
363 // InstructionSelectPreprocess so that dagcombine2 can hack on these.
365 setConvertAction(MVT::f32, MVT::f80, Expand);
366 setConvertAction(MVT::f64, MVT::f80, Expand);
367 setConvertAction(MVT::f80, MVT::f32, Expand);
368 setConvertAction(MVT::f80, MVT::f64, Expand);
370 } else if (X86ScalarSSEf32) {
371 // Use SSE for f32, x87 for f64.
372 // Set up the FP register classes.
373 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
374 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
376 // Use ANDPS to simulate FABS.
377 setOperationAction(ISD::FABS , MVT::f32, Custom);
379 // Use XORP to simulate FNEG.
380 setOperationAction(ISD::FNEG , MVT::f32, Custom);
382 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
384 // Use ANDPS and ORPS to simulate FCOPYSIGN.
385 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
386 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
388 // We don't support sin/cos/fmod
389 setOperationAction(ISD::FSIN , MVT::f32, Expand);
390 setOperationAction(ISD::FCOS , MVT::f32, Expand);
391 setOperationAction(ISD::FREM , MVT::f32, Expand);
393 // Expand FP immediates into loads from the stack, except for the special
395 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
396 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
397 addLegalFPImmediate(APFloat(+0.0f)); // xorps
398 addLegalFPImmediate(APFloat(+0.0)); // FLD0
399 addLegalFPImmediate(APFloat(+1.0)); // FLD1
400 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
401 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
403 // SSE <-> X87 conversions go through memory. If optimizing, we lie about
404 // this though and handle it in InstructionSelectPreprocess so that
405 // dagcombine2 can hack on these.
407 setConvertAction(MVT::f32, MVT::f64, Expand);
408 setConvertAction(MVT::f32, MVT::f80, Expand);
409 setConvertAction(MVT::f80, MVT::f32, Expand);
410 setConvertAction(MVT::f64, MVT::f32, Expand);
411 // And x87->x87 truncations also.
412 setConvertAction(MVT::f80, MVT::f64, Expand);
416 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
417 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
420 // f32 and f64 in x87.
421 // Set up the FP register classes.
422 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
423 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
425 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
426 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
427 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
428 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
430 // Floating truncations go through memory. If optimizing, we lie about
431 // this though and handle it in InstructionSelectPreprocess so that
432 // dagcombine2 can hack on these.
434 setConvertAction(MVT::f80, MVT::f32, Expand);
435 setConvertAction(MVT::f64, MVT::f32, Expand);
436 setConvertAction(MVT::f80, MVT::f64, Expand);
440 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
441 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
444 setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
445 setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
446 addLegalFPImmediate(APFloat(+0.0)); // FLD0
447 addLegalFPImmediate(APFloat(+1.0)); // FLD1
448 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
449 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
450 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
451 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
452 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
453 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
456 // Long double always uses X87.
457 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
458 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
459 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
461 setOperationAction(ISD::ConstantFP, MVT::f80, Expand);
462 APFloat TmpFlt(+0.0);
463 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
464 addLegalFPImmediate(TmpFlt); // FLD0
466 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
467 APFloat TmpFlt2(+1.0);
468 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
469 addLegalFPImmediate(TmpFlt2); // FLD1
470 TmpFlt2.changeSign();
471 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
475 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
476 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
479 // Always use a library call for pow.
480 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
481 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
482 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
484 // First set operation action for all vector types to expand. Then we
485 // will selectively turn on ones that can be effectively codegen'd.
486 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
487 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
488 setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
489 setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
490 setOperationAction(ISD::FADD, (MVT::ValueType)VT, Expand);
491 setOperationAction(ISD::FNEG, (MVT::ValueType)VT, Expand);
492 setOperationAction(ISD::FSUB, (MVT::ValueType)VT, Expand);
493 setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
494 setOperationAction(ISD::FMUL, (MVT::ValueType)VT, Expand);
495 setOperationAction(ISD::SDIV, (MVT::ValueType)VT, Expand);
496 setOperationAction(ISD::UDIV, (MVT::ValueType)VT, Expand);
497 setOperationAction(ISD::FDIV, (MVT::ValueType)VT, Expand);
498 setOperationAction(ISD::SREM, (MVT::ValueType)VT, Expand);
499 setOperationAction(ISD::UREM, (MVT::ValueType)VT, Expand);
500 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
501 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Expand);
502 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
503 setOperationAction(ISD::INSERT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
504 setOperationAction(ISD::FABS, (MVT::ValueType)VT, Expand);
505 setOperationAction(ISD::FSIN, (MVT::ValueType)VT, Expand);
506 setOperationAction(ISD::FCOS, (MVT::ValueType)VT, Expand);
507 setOperationAction(ISD::FREM, (MVT::ValueType)VT, Expand);
508 setOperationAction(ISD::FPOWI, (MVT::ValueType)VT, Expand);
509 setOperationAction(ISD::FSQRT, (MVT::ValueType)VT, Expand);
510 setOperationAction(ISD::FCOPYSIGN, (MVT::ValueType)VT, Expand);
511 setOperationAction(ISD::SMUL_LOHI, (MVT::ValueType)VT, Expand);
512 setOperationAction(ISD::UMUL_LOHI, (MVT::ValueType)VT, Expand);
513 setOperationAction(ISD::SDIVREM, (MVT::ValueType)VT, Expand);
514 setOperationAction(ISD::UDIVREM, (MVT::ValueType)VT, Expand);
515 setOperationAction(ISD::FPOW, (MVT::ValueType)VT, Expand);
516 setOperationAction(ISD::CTPOP, (MVT::ValueType)VT, Expand);
517 setOperationAction(ISD::CTTZ, (MVT::ValueType)VT, Expand);
518 setOperationAction(ISD::CTLZ, (MVT::ValueType)VT, Expand);
519 setOperationAction(ISD::SHL, (MVT::ValueType)VT, Expand);
520 setOperationAction(ISD::SRA, (MVT::ValueType)VT, Expand);
521 setOperationAction(ISD::SRL, (MVT::ValueType)VT, Expand);
522 setOperationAction(ISD::ROTL, (MVT::ValueType)VT, Expand);
523 setOperationAction(ISD::ROTR, (MVT::ValueType)VT, Expand);
524 setOperationAction(ISD::BSWAP, (MVT::ValueType)VT, Expand);
527 if (Subtarget->hasMMX()) {
528 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
529 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
530 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
531 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
533 // FIXME: add MMX packed arithmetics
535 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
536 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
537 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
538 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
540 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
541 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
542 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
543 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
545 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
546 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
548 setOperationAction(ISD::AND, MVT::v8i8, Promote);
549 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
550 setOperationAction(ISD::AND, MVT::v4i16, Promote);
551 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
552 setOperationAction(ISD::AND, MVT::v2i32, Promote);
553 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
554 setOperationAction(ISD::AND, MVT::v1i64, Legal);
556 setOperationAction(ISD::OR, MVT::v8i8, Promote);
557 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
558 setOperationAction(ISD::OR, MVT::v4i16, Promote);
559 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
560 setOperationAction(ISD::OR, MVT::v2i32, Promote);
561 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
562 setOperationAction(ISD::OR, MVT::v1i64, Legal);
564 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
565 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
566 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
567 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
568 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
569 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
570 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
572 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
573 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
574 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
575 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
576 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
577 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
578 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
580 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
581 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
582 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
583 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
585 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
586 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
587 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
588 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
590 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
591 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
592 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Custom);
593 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
596 if (Subtarget->hasSSE1()) {
597 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
599 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
600 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
601 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
602 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
603 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
604 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
605 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
606 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
607 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
608 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
609 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
612 if (Subtarget->hasSSE2()) {
613 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
614 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
615 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
616 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
617 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
619 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
620 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
621 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
622 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
623 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
624 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
625 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
626 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
627 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
628 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
629 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
630 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
631 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
632 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
633 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
635 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
636 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
637 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
638 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
639 // Implement v4f32 insert_vector_elt in terms of SSE2 v8i16 ones.
640 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
642 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
643 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
644 // Do not attempt to custom lower non-power-of-2 vectors
645 if (!isPowerOf2_32(MVT::getVectorNumElements(VT)))
647 setOperationAction(ISD::BUILD_VECTOR, (MVT::ValueType)VT, Custom);
648 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Custom);
649 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Custom);
651 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
652 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
653 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
654 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
655 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
656 if (Subtarget->is64Bit())
657 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
659 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
660 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
661 setOperationAction(ISD::AND, (MVT::ValueType)VT, Promote);
662 AddPromotedToType (ISD::AND, (MVT::ValueType)VT, MVT::v2i64);
663 setOperationAction(ISD::OR, (MVT::ValueType)VT, Promote);
664 AddPromotedToType (ISD::OR, (MVT::ValueType)VT, MVT::v2i64);
665 setOperationAction(ISD::XOR, (MVT::ValueType)VT, Promote);
666 AddPromotedToType (ISD::XOR, (MVT::ValueType)VT, MVT::v2i64);
667 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Promote);
668 AddPromotedToType (ISD::LOAD, (MVT::ValueType)VT, MVT::v2i64);
669 setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
670 AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v2i64);
673 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
675 // Custom lower v2i64 and v2f64 selects.
676 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
677 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
678 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
679 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
682 if (Subtarget->hasSSE41()) {
683 // FIXME: Do we need to handle scalar-to-vector here?
684 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
686 // i8 and i16 vectors are custom , because the source register and source
687 // source memory operand types are not the same width. f32 vectors are
688 // custom since the immediate controlling the insert encodes additional
690 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
691 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
692 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Legal);
693 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
695 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
696 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
697 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
698 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
700 if (Subtarget->is64Bit()) {
701 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
702 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
704 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
705 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
709 // We want to custom lower some of our intrinsics.
710 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
712 // We have target-specific dag combine patterns for the following nodes:
713 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
714 setTargetDAGCombine(ISD::SELECT);
716 computeRegisterProperties();
718 // FIXME: These should be based on subtarget info. Plus, the values should
719 // be smaller when we are in optimizing for size mode.
720 maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
721 maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
722 maxStoresPerMemmove = 16; // For %llvm.memmove -> sequence of stores
723 allowUnalignedMemoryAccesses = true; // x86 supports it!
726 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
727 /// the desired ByVal argument alignment.
728 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
731 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
732 if (VTy->getBitWidth() == 128)
734 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
735 unsigned EltAlign = 0;
736 getMaxByValAlign(ATy->getElementType(), EltAlign);
737 if (EltAlign > MaxAlign)
739 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
740 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
741 unsigned EltAlign = 0;
742 getMaxByValAlign(STy->getElementType(i), EltAlign);
743 if (EltAlign > MaxAlign)
752 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
753 /// function arguments in the caller parameter area. For X86, aggregates
754 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
755 /// are at 4-byte boundaries.
756 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
757 if (Subtarget->is64Bit())
758 return getTargetData()->getABITypeAlignment(Ty);
760 if (Subtarget->hasSSE1())
761 getMaxByValAlign(Ty, Align);
765 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
767 SDOperand X86TargetLowering::getPICJumpTableRelocBase(SDOperand Table,
768 SelectionDAG &DAG) const {
769 if (usesGlobalOffsetTable())
770 return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
771 if (!Subtarget->isPICStyleRIPRel())
772 return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
776 //===----------------------------------------------------------------------===//
777 // Return Value Calling Convention Implementation
778 //===----------------------------------------------------------------------===//
780 #include "X86GenCallingConv.inc"
782 /// GetPossiblePreceedingTailCall - Get preceeding X86ISD::TAILCALL node if it
783 /// exists skip possible ISD:TokenFactor.
784 static SDOperand GetPossiblePreceedingTailCall(SDOperand Chain) {
785 if (Chain.getOpcode() == X86ISD::TAILCALL) {
787 } else if (Chain.getOpcode() == ISD::TokenFactor) {
788 if (Chain.getNumOperands() &&
789 Chain.getOperand(0).getOpcode() == X86ISD::TAILCALL)
790 return Chain.getOperand(0);
795 /// LowerRET - Lower an ISD::RET node.
796 SDOperand X86TargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG) {
797 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
799 SmallVector<CCValAssign, 16> RVLocs;
800 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
801 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
802 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
803 CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
805 // If this is the first return lowered for this function, add the regs to the
806 // liveout set for the function.
807 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
808 for (unsigned i = 0; i != RVLocs.size(); ++i)
809 if (RVLocs[i].isRegLoc())
810 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
812 SDOperand Chain = Op.getOperand(0);
814 // Handle tail call return.
815 Chain = GetPossiblePreceedingTailCall(Chain);
816 if (Chain.getOpcode() == X86ISD::TAILCALL) {
817 SDOperand TailCall = Chain;
818 SDOperand TargetAddress = TailCall.getOperand(1);
819 SDOperand StackAdjustment = TailCall.getOperand(2);
820 assert(((TargetAddress.getOpcode() == ISD::Register &&
821 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::ECX ||
822 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
823 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
824 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
825 "Expecting an global address, external symbol, or register");
826 assert(StackAdjustment.getOpcode() == ISD::Constant &&
827 "Expecting a const value");
829 SmallVector<SDOperand,8> Operands;
830 Operands.push_back(Chain.getOperand(0));
831 Operands.push_back(TargetAddress);
832 Operands.push_back(StackAdjustment);
833 // Copy registers used by the call. Last operand is a flag so it is not
835 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
836 Operands.push_back(Chain.getOperand(i));
838 return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0],
845 // Copy the result values into the output registers.
846 if (RVLocs.size() != 1 || !RVLocs[0].isRegLoc() ||
847 RVLocs[0].getLocReg() != X86::ST0) {
848 for (unsigned i = 0; i != RVLocs.size(); ++i) {
849 CCValAssign &VA = RVLocs[i];
850 assert(VA.isRegLoc() && "Can only return in registers!");
851 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1),
853 Flag = Chain.getValue(1);
856 // We need to handle a destination of ST0 specially, because it isn't really
858 SDOperand Value = Op.getOperand(1);
860 // an XMM register onto the fp-stack. Do this with an FP_EXTEND to f80.
861 // This will get legalized into a load/store if it can't get optimized away.
862 if (isScalarFPTypeInSSEReg(RVLocs[0].getValVT()))
863 Value = DAG.getNode(ISD::FP_EXTEND, MVT::f80, Value);
865 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
866 SDOperand Ops[] = { Chain, Value };
867 Chain = DAG.getNode(X86ISD::FP_SET_RESULT, Tys, Ops, 2);
868 Flag = Chain.getValue(1);
871 SDOperand BytesToPop = DAG.getConstant(getBytesToPopOnReturn(), MVT::i16);
873 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop, Flag);
875 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop);
879 /// LowerCallResult - Lower the result values of an ISD::CALL into the
880 /// appropriate copies out of appropriate physical registers. This assumes that
881 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
882 /// being lowered. The returns a SDNode with the same number of values as the
884 SDNode *X86TargetLowering::
885 LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall,
886 unsigned CallingConv, SelectionDAG &DAG) {
888 // Assign locations to each value returned by this call.
889 SmallVector<CCValAssign, 16> RVLocs;
890 bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
891 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
892 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
894 SmallVector<SDOperand, 8> ResultVals;
896 // Copy all of the result registers out of their specified physreg.
897 if (RVLocs.size() != 1 || RVLocs[0].getLocReg() != X86::ST0) {
898 for (unsigned i = 0; i != RVLocs.size(); ++i) {
899 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
900 RVLocs[i].getValVT(), InFlag).getValue(1);
901 InFlag = Chain.getValue(2);
902 ResultVals.push_back(Chain.getValue(0));
905 // Copies from the FP stack are special, as ST0 isn't a valid register
906 // before the fp stackifier runs.
908 // Copy ST0 into an RFP register with FP_GET_RESULT. If this will end up
909 // in an SSE register, copy it out as F80 and do a truncate, otherwise use
910 // the specified value type.
911 MVT::ValueType GetResultTy = RVLocs[0].getValVT();
912 if (isScalarFPTypeInSSEReg(GetResultTy))
913 GetResultTy = MVT::f80;
914 SDVTList Tys = DAG.getVTList(GetResultTy, MVT::Other, MVT::Flag);
916 SDOperand GROps[] = { Chain, InFlag };
917 SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, GROps, 2);
918 Chain = RetVal.getValue(1);
919 InFlag = RetVal.getValue(2);
921 // If we want the result in an SSE register, use an FP_TRUNCATE to get it
923 if (GetResultTy != RVLocs[0].getValVT())
924 RetVal = DAG.getNode(ISD::FP_ROUND, RVLocs[0].getValVT(), RetVal,
925 // This truncation won't change the value.
926 DAG.getIntPtrConstant(1));
928 ResultVals.push_back(RetVal);
931 // Merge everything together with a MERGE_VALUES node.
932 ResultVals.push_back(Chain);
933 return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
934 &ResultVals[0], ResultVals.size()).Val;
937 /// LowerCallResultToTwo64BitRegs - Lower the result values of an x86-64
938 /// ISD::CALL where the results are known to be in two 64-bit registers,
939 /// e.g. XMM0 and XMM1. This simplify store the two values back to the
940 /// fixed stack slot allocated for StructRet.
941 SDNode *X86TargetLowering::
942 LowerCallResultToTwo64BitRegs(SDOperand Chain, SDOperand InFlag,
943 SDNode *TheCall, unsigned Reg1, unsigned Reg2,
944 MVT::ValueType VT, SelectionDAG &DAG) {
945 SDOperand RetVal1 = DAG.getCopyFromReg(Chain, Reg1, VT, InFlag);
946 Chain = RetVal1.getValue(1);
947 InFlag = RetVal1.getValue(2);
948 SDOperand RetVal2 = DAG.getCopyFromReg(Chain, Reg2, VT, InFlag);
949 Chain = RetVal2.getValue(1);
950 InFlag = RetVal2.getValue(2);
951 SDOperand FIN = TheCall->getOperand(5);
952 Chain = DAG.getStore(Chain, RetVal1, FIN, NULL, 0);
953 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
954 Chain = DAG.getStore(Chain, RetVal2, FIN, NULL, 0);
958 /// LowerCallResultToTwoX87Regs - Lower the result values of an x86-64 ISD::CALL
959 /// where the results are known to be in ST0 and ST1.
960 SDNode *X86TargetLowering::
961 LowerCallResultToTwoX87Regs(SDOperand Chain, SDOperand InFlag,
962 SDNode *TheCall, SelectionDAG &DAG) {
963 SmallVector<SDOperand, 8> ResultVals;
964 const MVT::ValueType VTs[] = { MVT::f80, MVT::f80, MVT::Other, MVT::Flag };
965 SDVTList Tys = DAG.getVTList(VTs, 4);
966 SDOperand Ops[] = { Chain, InFlag };
967 SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT2, Tys, Ops, 2);
968 Chain = RetVal.getValue(2);
969 SDOperand FIN = TheCall->getOperand(5);
970 Chain = DAG.getStore(Chain, RetVal.getValue(1), FIN, NULL, 0);
971 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(16));
972 Chain = DAG.getStore(Chain, RetVal, FIN, NULL, 0);
976 //===----------------------------------------------------------------------===//
977 // C & StdCall & Fast Calling Convention implementation
978 //===----------------------------------------------------------------------===//
979 // StdCall calling convention seems to be standard for many Windows' API
980 // routines and around. It differs from C calling convention just a little:
981 // callee should clean up the stack, not caller. Symbols should be also
982 // decorated in some fancy way :) It doesn't support any vector arguments.
983 // For info on fast calling convention see Fast Calling Convention (tail call)
984 // implementation LowerX86_32FastCCCallTo.
986 /// AddLiveIn - This helper function adds the specified physical register to the
987 /// MachineFunction as a live in value. It also creates a corresponding virtual
989 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
990 const TargetRegisterClass *RC) {
991 assert(RC->contains(PReg) && "Not the correct regclass!");
992 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
993 MF.getRegInfo().addLiveIn(PReg, VReg);
997 // Determines whether a CALL node uses struct return semantics.
998 static bool CallIsStructReturn(SDOperand Op) {
999 unsigned NumOps = (Op.getNumOperands() - 5) / 2;
1003 ConstantSDNode *Flags = cast<ConstantSDNode>(Op.getOperand(6));
1004 return Flags->getValue() & ISD::ParamFlags::StructReturn;
1007 // Determines whether a FORMAL_ARGUMENTS node uses struct return semantics.
1008 static bool ArgsAreStructReturn(SDOperand Op) {
1009 unsigned NumArgs = Op.Val->getNumValues() - 1;
1013 ConstantSDNode *Flags = cast<ConstantSDNode>(Op.getOperand(3));
1014 return Flags->getValue() & ISD::ParamFlags::StructReturn;
1017 // Determines whether a CALL or FORMAL_ARGUMENTS node requires the callee to pop
1018 // its own arguments. Callee pop is necessary to support tail calls.
1019 bool X86TargetLowering::IsCalleePop(SDOperand Op) {
1020 bool IsVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1024 switch (cast<ConstantSDNode>(Op.getOperand(1))->getValue()) {
1027 case CallingConv::X86_StdCall:
1028 return !Subtarget->is64Bit();
1029 case CallingConv::X86_FastCall:
1030 return !Subtarget->is64Bit();
1031 case CallingConv::Fast:
1032 return PerformTailCallOpt;
1036 // Selects the correct CCAssignFn for a CALL or FORMAL_ARGUMENTS node.
1037 CCAssignFn *X86TargetLowering::CCAssignFnForNode(SDOperand Op) const {
1038 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1040 if (Subtarget->is64Bit())
1041 if (CC == CallingConv::Fast && PerformTailCallOpt)
1042 return CC_X86_64_TailCall;
1046 if (CC == CallingConv::X86_FastCall)
1047 return CC_X86_32_FastCall;
1048 else if (CC == CallingConv::Fast && PerformTailCallOpt)
1049 return CC_X86_32_TailCall;
1054 // Selects the appropriate decoration to apply to a MachineFunction containing a
1055 // given FORMAL_ARGUMENTS node.
1057 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDOperand Op) {
1058 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1059 if (CC == CallingConv::X86_FastCall)
1061 else if (CC == CallingConv::X86_StdCall)
1067 // IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could possibly
1068 // be overwritten when lowering the outgoing arguments in a tail call. Currently
1069 // the implementation of this call is very conservative and assumes all
1070 // arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with virtual
1071 // registers would be overwritten by direct lowering.
1072 // Possible improvement:
1073 // Check FORMAL_ARGUMENTS corresponding MERGE_VALUES for CopyFromReg nodes
1074 // indicating inreg passed arguments which also need not be lowered to a safe
1076 static bool IsPossiblyOverwrittenArgumentOfTailCall(SDOperand Op) {
1077 RegisterSDNode * OpReg = NULL;
1078 if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
1079 (Op.getOpcode()== ISD::CopyFromReg &&
1080 (OpReg = cast<RegisterSDNode>(Op.getOperand(1))) &&
1081 OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister))
1086 // CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1087 // by "Src" to address "Dst" with size and alignment information specified by
1088 // the specific parameter attribute. The copy will be passed as a byval function
1091 CreateCopyOfByValArgument(SDOperand Src, SDOperand Dst, SDOperand Chain,
1092 unsigned Flags, SelectionDAG &DAG) {
1093 unsigned Align = 1 <<
1094 ((Flags & ISD::ParamFlags::ByValAlign) >> ISD::ParamFlags::ByValAlignOffs);
1095 unsigned Size = (Flags & ISD::ParamFlags::ByValSize) >>
1096 ISD::ParamFlags::ByValSizeOffs;
1097 SDOperand AlignNode = DAG.getConstant(Align, MVT::i32);
1098 SDOperand SizeNode = DAG.getConstant(Size, MVT::i32);
1099 SDOperand AlwaysInline = DAG.getConstant(1, MVT::i32);
1100 return DAG.getMemcpy(Chain, Dst, Src, SizeNode, AlignNode, AlwaysInline);
1103 SDOperand X86TargetLowering::LowerMemArgument(SDOperand Op, SelectionDAG &DAG,
1104 const CCValAssign &VA,
1105 MachineFrameInfo *MFI,
1106 SDOperand Root, unsigned i) {
1107 // Create the nodes corresponding to a load from this parameter slot.
1108 unsigned Flags = cast<ConstantSDNode>(Op.getOperand(3 + i))->getValue();
1109 bool isByVal = Flags & ISD::ParamFlags::ByVal;
1111 // FIXME: For now, all byval parameter objects are marked mutable. This
1112 // can be changed with more analysis.
1113 int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
1114 VA.getLocMemOffset(), !isByVal);
1115 SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
1118 return DAG.getLoad(VA.getValVT(), Root, FIN,
1119 PseudoSourceValue::getFixedStack(), FI);
1123 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
1124 MachineFunction &MF = DAG.getMachineFunction();
1125 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1127 const Function* Fn = MF.getFunction();
1128 if (Fn->hasExternalLinkage() &&
1129 Subtarget->isTargetCygMing() &&
1130 Fn->getName() == "main")
1131 FuncInfo->setForceFramePointer(true);
1133 // Decorate the function name.
1134 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1136 MachineFrameInfo *MFI = MF.getFrameInfo();
1137 SDOperand Root = Op.getOperand(0);
1138 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1139 unsigned CC = MF.getFunction()->getCallingConv();
1140 bool Is64Bit = Subtarget->is64Bit();
1142 assert(!(isVarArg && CC == CallingConv::Fast) &&
1143 "Var args not supported with calling convention fastcc");
1145 // Assign locations to all of the incoming arguments.
1146 SmallVector<CCValAssign, 16> ArgLocs;
1147 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1148 CCInfo.AnalyzeFormalArguments(Op.Val, CCAssignFnForNode(Op));
1150 SmallVector<SDOperand, 8> ArgValues;
1151 unsigned LastVal = ~0U;
1152 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1153 CCValAssign &VA = ArgLocs[i];
1154 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1156 assert(VA.getValNo() != LastVal &&
1157 "Don't support value assigned to multiple locs yet");
1158 LastVal = VA.getValNo();
1160 if (VA.isRegLoc()) {
1161 MVT::ValueType RegVT = VA.getLocVT();
1162 TargetRegisterClass *RC;
1163 if (RegVT == MVT::i32)
1164 RC = X86::GR32RegisterClass;
1165 else if (Is64Bit && RegVT == MVT::i64)
1166 RC = X86::GR64RegisterClass;
1167 else if (RegVT == MVT::f32)
1168 RC = X86::FR32RegisterClass;
1169 else if (RegVT == MVT::f64)
1170 RC = X86::FR64RegisterClass;
1172 assert(MVT::isVector(RegVT));
1173 if (Is64Bit && MVT::getSizeInBits(RegVT) == 64) {
1174 RC = X86::GR64RegisterClass; // MMX values are passed in GPRs.
1177 RC = X86::VR128RegisterClass;
1180 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1181 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1183 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1184 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1186 if (VA.getLocInfo() == CCValAssign::SExt)
1187 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1188 DAG.getValueType(VA.getValVT()));
1189 else if (VA.getLocInfo() == CCValAssign::ZExt)
1190 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1191 DAG.getValueType(VA.getValVT()));
1193 if (VA.getLocInfo() != CCValAssign::Full)
1194 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1196 // Handle MMX values passed in GPRs.
1197 if (Is64Bit && RegVT != VA.getLocVT() && RC == X86::GR64RegisterClass &&
1198 MVT::getSizeInBits(RegVT) == 64)
1199 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1201 ArgValues.push_back(ArgValue);
1203 assert(VA.isMemLoc());
1204 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
1208 unsigned StackSize = CCInfo.getNextStackOffset();
1209 // align stack specially for tail calls
1210 if (CC == CallingConv::Fast)
1211 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1213 // If the function takes variable number of arguments, make a frame index for
1214 // the start of the first vararg value... for expansion of llvm.va_start.
1216 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1217 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1220 static const unsigned GPR64ArgRegs[] = {
1221 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1223 static const unsigned XMMArgRegs[] = {
1224 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1225 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1228 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 6);
1229 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1231 // For X86-64, if there are vararg parameters that are passed via
1232 // registers, then we must store them to their spots on the stack so they
1233 // may be loaded by deferencing the result of va_next.
1234 VarArgsGPOffset = NumIntRegs * 8;
1235 VarArgsFPOffset = 6 * 8 + NumXMMRegs * 16;
1236 RegSaveFrameIndex = MFI->CreateStackObject(6 * 8 + 8 * 16, 16);
1238 // Store the integer parameter registers.
1239 SmallVector<SDOperand, 8> MemOps;
1240 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1241 SDOperand FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1242 DAG.getIntPtrConstant(VarArgsGPOffset));
1243 for (; NumIntRegs != 6; ++NumIntRegs) {
1244 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1245 X86::GR64RegisterClass);
1246 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1248 DAG.getStore(Val.getValue(1), Val, FIN,
1249 PseudoSourceValue::getFixedStack(),
1251 MemOps.push_back(Store);
1252 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1253 DAG.getIntPtrConstant(8));
1256 // Now store the XMM (fp + vector) parameter registers.
1257 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1258 DAG.getIntPtrConstant(VarArgsFPOffset));
1259 for (; NumXMMRegs != 8; ++NumXMMRegs) {
1260 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1261 X86::VR128RegisterClass);
1262 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1264 DAG.getStore(Val.getValue(1), Val, FIN,
1265 PseudoSourceValue::getFixedStack(),
1267 MemOps.push_back(Store);
1268 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1269 DAG.getIntPtrConstant(16));
1271 if (!MemOps.empty())
1272 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1273 &MemOps[0], MemOps.size());
1277 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1278 // arguments and the arguments after the retaddr has been pushed are
1280 if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1281 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1282 (StackSize & 7) == 0)
1285 ArgValues.push_back(Root);
1287 // Some CCs need callee pop.
1288 if (IsCalleePop(Op)) {
1289 BytesToPopOnReturn = StackSize; // Callee pops everything.
1290 BytesCallerReserves = 0;
1292 BytesToPopOnReturn = 0; // Callee pops nothing.
1293 // If this is an sret function, the return should pop the hidden pointer.
1294 if (!Is64Bit && ArgsAreStructReturn(Op))
1295 BytesToPopOnReturn = 4;
1296 BytesCallerReserves = StackSize;
1300 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1301 if (CC == CallingConv::X86_FastCall)
1302 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1305 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1307 // Return the new list of results.
1308 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1309 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1313 X86TargetLowering::LowerMemOpCallTo(SDOperand Op, SelectionDAG &DAG,
1314 const SDOperand &StackPtr,
1315 const CCValAssign &VA,
1318 unsigned LocMemOffset = VA.getLocMemOffset();
1319 SDOperand PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1320 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1321 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1322 unsigned Flags = cast<ConstantSDNode>(FlagsOp)->getValue();
1323 if (Flags & ISD::ParamFlags::ByVal) {
1324 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG);
1326 return DAG.getStore(Chain, Arg, PtrOff,
1327 PseudoSourceValue::getStack(), LocMemOffset);
1330 /// ClassifyX86_64SRetCallReturn - Classify how to implement a x86-64
1331 /// struct return call to the specified function. X86-64 ABI specifies
1332 /// some SRet calls are actually returned in registers. Since current
1333 /// LLVM cannot represent multi-value calls, they are represent as
1334 /// calls where the results are passed in a hidden struct provided by
1335 /// the caller. This function examines the type of the struct to
1336 /// determine the correct way to implement the call.
1338 X86TargetLowering::ClassifyX86_64SRetCallReturn(const Function *Fn) {
1339 // FIXME: Disabled for now.
1340 return X86::InMemory;
1342 const PointerType *PTy = cast<PointerType>(Fn->arg_begin()->getType());
1343 const Type *RTy = PTy->getElementType();
1344 unsigned Size = getTargetData()->getABITypeSize(RTy);
1345 if (Size != 16 && Size != 32)
1346 return X86::InMemory;
1349 const StructType *STy = dyn_cast<StructType>(RTy);
1350 if (!STy) return X86::InMemory;
1351 if (STy->getNumElements() == 2 &&
1352 STy->getElementType(0) == Type::X86_FP80Ty &&
1353 STy->getElementType(1) == Type::X86_FP80Ty)
1358 for (Type::subtype_iterator I = RTy->subtype_begin(), E = RTy->subtype_end();
1360 const Type *STy = I->get();
1361 if (!STy->isFPOrFPVector()) {
1369 return X86::InGPR64;
1372 void X86TargetLowering::X86_64AnalyzeSRetCallOperands(SDNode *TheCall,
1375 unsigned NumOps = (TheCall->getNumOperands() - 5) / 2;
1376 for (unsigned i = 1; i != NumOps; ++i) {
1377 MVT::ValueType ArgVT = TheCall->getOperand(5+2*i).getValueType();
1378 SDOperand FlagOp = TheCall->getOperand(5+2*i+1);
1379 unsigned ArgFlags =cast<ConstantSDNode>(FlagOp)->getValue();
1380 if (Fn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo)) {
1381 cerr << "Call operand #" << i << " has unhandled type "
1382 << MVT::getValueTypeString(ArgVT) << "\n";
1388 SDOperand X86TargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
1389 MachineFunction &MF = DAG.getMachineFunction();
1390 SDOperand Chain = Op.getOperand(0);
1391 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1392 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1393 bool IsTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0
1394 && CC == CallingConv::Fast && PerformTailCallOpt;
1395 SDOperand Callee = Op.getOperand(4);
1396 bool Is64Bit = Subtarget->is64Bit();
1397 bool IsStructRet = CallIsStructReturn(Op);
1399 assert(!(isVarArg && CC == CallingConv::Fast) &&
1400 "Var args not supported with calling convention fastcc");
1402 // Analyze operands of the call, assigning locations to each operand.
1403 SmallVector<CCValAssign, 16> ArgLocs;
1404 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1405 CCAssignFn *CCFn = CCAssignFnForNode(Op);
1407 X86::X86_64SRet SRetMethod = X86::InMemory;
1408 if (Is64Bit && IsStructRet)
1409 // FIXME: We can't figure out type of the sret structure for indirect
1410 // calls. We need to copy more information from CallSite to the ISD::CALL
1412 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1414 ClassifyX86_64SRetCallReturn(dyn_cast<Function>(G->getGlobal()));
1416 // UGLY HACK! For x86-64, some 128-bit aggregates are returns in a pair of
1417 // registers. Unfortunately, llvm does not support i128 yet so we pretend it's
1419 if (SRetMethod != X86::InMemory)
1420 X86_64AnalyzeSRetCallOperands(Op.Val, CCFn, CCInfo);
1422 CCInfo.AnalyzeCallOperands(Op.Val, CCFn);
1424 // Get a count of how many bytes are to be pushed on the stack.
1425 unsigned NumBytes = CCInfo.getNextStackOffset();
1426 if (CC == CallingConv::Fast)
1427 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1429 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1430 // arguments and the arguments after the retaddr has been pushed are aligned.
1431 if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1432 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1433 (NumBytes & 7) == 0)
1438 // Lower arguments at fp - stackoffset + fpdiff.
1439 unsigned NumBytesCallerPushed =
1440 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1441 FPDiff = NumBytesCallerPushed - NumBytes;
1443 // Set the delta of movement of the returnaddr stackslot.
1444 // But only set if delta is greater than previous delta.
1445 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1446 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1449 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes));
1451 SDOperand RetAddrFrIdx, NewRetAddrFrIdx;
1453 // Adjust the Return address stack slot.
1455 MVT::ValueType VT = Is64Bit ? MVT::i64 : MVT::i32;
1456 RetAddrFrIdx = getReturnAddressFrameIndex(DAG);
1457 // Load the "old" Return address.
1459 DAG.getLoad(VT, Chain,RetAddrFrIdx, NULL, 0);
1460 // Calculate the new stack slot for the return address.
1461 int SlotSize = Is64Bit ? 8 : 4;
1462 int NewReturnAddrFI =
1463 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1464 NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1465 Chain = SDOperand(RetAddrFrIdx.Val, 1);
1469 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1470 SmallVector<SDOperand, 8> MemOpChains;
1474 // Walk the register/memloc assignments, inserting copies/loads. For tail
1475 // calls, lower arguments which could otherwise be possibly overwritten to the
1476 // stack slot where they would go on normal function calls.
1477 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1478 CCValAssign &VA = ArgLocs[i];
1479 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1481 // Promote the value if needed.
1482 switch (VA.getLocInfo()) {
1483 default: assert(0 && "Unknown loc info!");
1484 case CCValAssign::Full: break;
1485 case CCValAssign::SExt:
1486 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1488 case CCValAssign::ZExt:
1489 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1491 case CCValAssign::AExt:
1492 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1496 if (VA.isRegLoc()) {
1497 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1499 if (!IsTailCall || IsPossiblyOverwrittenArgumentOfTailCall(Arg)) {
1500 assert(VA.isMemLoc());
1501 if (StackPtr.Val == 0)
1502 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1504 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1510 if (!MemOpChains.empty())
1511 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1512 &MemOpChains[0], MemOpChains.size());
1514 // Build a sequence of copy-to-reg nodes chained together with token chain
1515 // and flag operands which copy the outgoing args into registers.
1517 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1518 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1520 InFlag = Chain.getValue(1);
1524 InFlag = SDOperand(); // ??? Isn't this nuking the preceding loop's output?
1526 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1528 // Does not work with tail call since ebx is not restored correctly by
1529 // tailcaller. TODO: at least for x86 - verify for x86-64
1530 if (!IsTailCall && !Is64Bit &&
1531 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1532 Subtarget->isPICStyleGOT()) {
1533 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1534 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1536 InFlag = Chain.getValue(1);
1539 if (Is64Bit && isVarArg) {
1540 // From AMD64 ABI document:
1541 // For calls that may call functions that use varargs or stdargs
1542 // (prototype-less calls or calls to functions containing ellipsis (...) in
1543 // the declaration) %al is used as hidden argument to specify the number
1544 // of SSE registers used. The contents of %al do not need to match exactly
1545 // the number of registers, but must be an ubound on the number of SSE
1546 // registers used and is in the range 0 - 8 inclusive.
1548 // Count the number of XMM registers allocated.
1549 static const unsigned XMMArgRegs[] = {
1550 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1551 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1553 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1555 Chain = DAG.getCopyToReg(Chain, X86::AL,
1556 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1557 InFlag = Chain.getValue(1);
1560 // For tail calls lower the arguments to the 'real' stack slot.
1562 SmallVector<SDOperand, 8> MemOpChains2;
1565 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1566 CCValAssign &VA = ArgLocs[i];
1567 if (!VA.isRegLoc()) {
1568 assert(VA.isMemLoc());
1569 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1570 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1571 unsigned Flags = cast<ConstantSDNode>(FlagsOp)->getValue();
1572 // Create frame index.
1573 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1574 uint32_t OpSize = (MVT::getSizeInBits(VA.getLocVT())+7)/8;
1575 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1576 FIN = DAG.getFrameIndex(FI, MVT::i32);
1577 SDOperand Source = Arg;
1578 if (IsPossiblyOverwrittenArgumentOfTailCall(Arg)) {
1579 // Copy from stack slots to stack slot of a tail called function. This
1580 // needs to be done because if we would lower the arguments directly
1581 // to their real stack slot we might end up overwriting each other.
1582 // Get source stack slot.
1583 Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1584 if (StackPtr.Val == 0)
1585 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1586 Source = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, Source);
1587 if ((Flags & ISD::ParamFlags::ByVal)==0)
1588 Source = DAG.getLoad(VA.getValVT(), Chain, Source, NULL, 0);
1591 if (Flags & ISD::ParamFlags::ByVal) {
1592 // Copy relative to framepointer.
1593 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1596 // Store relative to framepointer.
1597 MemOpChains2.push_back(
1598 DAG.getStore(Chain, Source, FIN,
1599 PseudoSourceValue::getFixedStack(), FI));
1604 if (!MemOpChains2.empty())
1605 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1606 &MemOpChains2[0], MemOpChains2.size());
1608 // Store the return address to the appropriate stack slot.
1610 Chain = DAG.getStore(Chain,RetAddrFrIdx, NewRetAddrFrIdx, NULL, 0);
1613 // If the callee is a GlobalAddress node (quite common, every direct call is)
1614 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1615 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1616 // We should use extra load for direct calls to dllimported functions in
1618 if ((IsTailCall || !Is64Bit ||
1619 getTargetMachine().getCodeModel() != CodeModel::Large)
1620 && !Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1621 getTargetMachine(), true))
1622 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1623 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1624 if (IsTailCall || !Is64Bit ||
1625 getTargetMachine().getCodeModel() != CodeModel::Large)
1626 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1627 } else if (IsTailCall) {
1628 assert(Callee.getOpcode() == ISD::LOAD &&
1629 "Function destination must be loaded into virtual register");
1630 unsigned Opc = Is64Bit ? X86::R9 : X86::ECX;
1632 Chain = DAG.getCopyToReg(Chain,
1633 DAG.getRegister(Opc, getPointerTy()) ,
1635 Callee = DAG.getRegister(Opc, getPointerTy());
1636 // Add register as live out.
1637 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1640 // Returns a chain & a flag for retval copy to use.
1641 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1642 SmallVector<SDOperand, 8> Ops;
1645 Ops.push_back(Chain);
1646 Ops.push_back(DAG.getIntPtrConstant(NumBytes));
1647 Ops.push_back(DAG.getIntPtrConstant(0));
1649 Ops.push_back(InFlag);
1650 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1651 InFlag = Chain.getValue(1);
1653 // Returns a chain & a flag for retval copy to use.
1654 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1658 Ops.push_back(Chain);
1659 Ops.push_back(Callee);
1662 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1664 // Add an implicit use GOT pointer in EBX.
1665 if (!IsTailCall && !Is64Bit &&
1666 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1667 Subtarget->isPICStyleGOT())
1668 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1670 // Add argument registers to the end of the list so that they are known live
1672 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1673 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1674 RegsToPass[i].second.getValueType()));
1677 Ops.push_back(InFlag);
1680 assert(InFlag.Val &&
1681 "Flag must be set. Depend on flag being set in LowerRET");
1682 Chain = DAG.getNode(X86ISD::TAILCALL,
1683 Op.Val->getVTList(), &Ops[0], Ops.size());
1685 return SDOperand(Chain.Val, Op.ResNo);
1688 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1689 InFlag = Chain.getValue(1);
1691 // Create the CALLSEQ_END node.
1692 unsigned NumBytesForCalleeToPush;
1693 if (IsCalleePop(Op))
1694 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1695 else if (!Is64Bit && IsStructRet)
1696 // If this is is a call to a struct-return function, the callee
1697 // pops the hidden struct pointer, so we have to push it back.
1698 // This is common for Darwin/X86, Linux & Mingw32 targets.
1699 NumBytesForCalleeToPush = 4;
1701 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1703 // Returns a flag for retval copy to use.
1704 Chain = DAG.getCALLSEQ_END(Chain,
1705 DAG.getIntPtrConstant(NumBytes),
1706 DAG.getIntPtrConstant(NumBytesForCalleeToPush),
1708 InFlag = Chain.getValue(1);
1710 // Handle result values, copying them out of physregs into vregs that we
1712 switch (SRetMethod) {
1714 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1716 return SDOperand(LowerCallResultToTwo64BitRegs(Chain, InFlag, Op.Val,
1718 MVT::i64, DAG), Op.ResNo);
1720 return SDOperand(LowerCallResultToTwo64BitRegs(Chain, InFlag, Op.Val,
1721 X86::XMM0, X86::XMM1,
1722 MVT::f64, DAG), Op.ResNo);
1724 return SDOperand(LowerCallResultToTwoX87Regs(Chain, InFlag, Op.Val, DAG),
1730 //===----------------------------------------------------------------------===//
1731 // Fast Calling Convention (tail call) implementation
1732 //===----------------------------------------------------------------------===//
1734 // Like std call, callee cleans arguments, convention except that ECX is
1735 // reserved for storing the tail called function address. Only 2 registers are
1736 // free for argument passing (inreg). Tail call optimization is performed
1738 // * tailcallopt is enabled
1739 // * caller/callee are fastcc
1740 // * elf/pic is disabled OR
1741 // * elf/pic enabled + callee is in module + callee has
1742 // visibility protected or hidden
1743 // To keep the stack aligned according to platform abi the function
1744 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1745 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1746 // If a tail called function callee has more arguments than the caller the
1747 // caller needs to make sure that there is room to move the RETADDR to. This is
1748 // achieved by reserving an area the size of the argument delta right after the
1749 // original REtADDR, but before the saved framepointer or the spilled registers
1750 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1762 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1763 /// for a 16 byte align requirement.
1764 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1765 SelectionDAG& DAG) {
1766 if (PerformTailCallOpt) {
1767 MachineFunction &MF = DAG.getMachineFunction();
1768 const TargetMachine &TM = MF.getTarget();
1769 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1770 unsigned StackAlignment = TFI.getStackAlignment();
1771 uint64_t AlignMask = StackAlignment - 1;
1772 int64_t Offset = StackSize;
1773 unsigned SlotSize = Subtarget->is64Bit() ? 8 : 4;
1774 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1775 // Number smaller than 12 so just add the difference.
1776 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1778 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1779 Offset = ((~AlignMask) & Offset) + StackAlignment +
1780 (StackAlignment-SlotSize);
1787 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1788 /// following the call is a return. A function is eligible if caller/callee
1789 /// calling conventions match, currently only fastcc supports tail calls, and
1790 /// the function CALL is immediatly followed by a RET.
1791 bool X86TargetLowering::IsEligibleForTailCallOptimization(SDOperand Call,
1793 SelectionDAG& DAG) const {
1794 if (!PerformTailCallOpt)
1797 // Check whether CALL node immediatly preceeds the RET node and whether the
1798 // return uses the result of the node or is a void return.
1799 unsigned NumOps = Ret.getNumOperands();
1801 (Ret.getOperand(0) == SDOperand(Call.Val,1) ||
1802 Ret.getOperand(0) == SDOperand(Call.Val,0))) ||
1804 Ret.getOperand(0) == SDOperand(Call.Val,Call.Val->getNumValues()-1) &&
1805 Ret.getOperand(1) == SDOperand(Call.Val,0))) {
1806 MachineFunction &MF = DAG.getMachineFunction();
1807 unsigned CallerCC = MF.getFunction()->getCallingConv();
1808 unsigned CalleeCC = cast<ConstantSDNode>(Call.getOperand(1))->getValue();
1809 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1810 SDOperand Callee = Call.getOperand(4);
1811 // On elf/pic %ebx needs to be livein.
1812 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1813 !Subtarget->isPICStyleGOT())
1816 // Can only do local tail calls with PIC.
1817 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1818 return G->getGlobal()->hasHiddenVisibility()
1819 || G->getGlobal()->hasProtectedVisibility();
1826 //===----------------------------------------------------------------------===//
1827 // Other Lowering Hooks
1828 //===----------------------------------------------------------------------===//
1831 SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1832 MachineFunction &MF = DAG.getMachineFunction();
1833 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1834 int ReturnAddrIndex = FuncInfo->getRAIndex();
1836 if (ReturnAddrIndex == 0) {
1837 // Set up a frame object for the return address.
1838 if (Subtarget->is64Bit())
1839 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
1841 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
1843 FuncInfo->setRAIndex(ReturnAddrIndex);
1846 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1851 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1852 /// specific condition code. It returns a false if it cannot do a direct
1853 /// translation. X86CC is the translated CondCode. LHS/RHS are modified as
1855 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1856 unsigned &X86CC, SDOperand &LHS, SDOperand &RHS,
1857 SelectionDAG &DAG) {
1858 X86CC = X86::COND_INVALID;
1860 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1861 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
1862 // X > -1 -> X == 0, jump !sign.
1863 RHS = DAG.getConstant(0, RHS.getValueType());
1864 X86CC = X86::COND_NS;
1866 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
1867 // X < 0 -> X == 0, jump on sign.
1868 X86CC = X86::COND_S;
1870 } else if (SetCCOpcode == ISD::SETLT && RHSC->getValue() == 1) {
1872 RHS = DAG.getConstant(0, RHS.getValueType());
1873 X86CC = X86::COND_LE;
1878 switch (SetCCOpcode) {
1880 case ISD::SETEQ: X86CC = X86::COND_E; break;
1881 case ISD::SETGT: X86CC = X86::COND_G; break;
1882 case ISD::SETGE: X86CC = X86::COND_GE; break;
1883 case ISD::SETLT: X86CC = X86::COND_L; break;
1884 case ISD::SETLE: X86CC = X86::COND_LE; break;
1885 case ISD::SETNE: X86CC = X86::COND_NE; break;
1886 case ISD::SETULT: X86CC = X86::COND_B; break;
1887 case ISD::SETUGT: X86CC = X86::COND_A; break;
1888 case ISD::SETULE: X86CC = X86::COND_BE; break;
1889 case ISD::SETUGE: X86CC = X86::COND_AE; break;
1892 // On a floating point condition, the flags are set as follows:
1894 // 0 | 0 | 0 | X > Y
1895 // 0 | 0 | 1 | X < Y
1896 // 1 | 0 | 0 | X == Y
1897 // 1 | 1 | 1 | unordered
1899 switch (SetCCOpcode) {
1902 case ISD::SETEQ: X86CC = X86::COND_E; break;
1903 case ISD::SETOLT: Flip = true; // Fallthrough
1905 case ISD::SETGT: X86CC = X86::COND_A; break;
1906 case ISD::SETOLE: Flip = true; // Fallthrough
1908 case ISD::SETGE: X86CC = X86::COND_AE; break;
1909 case ISD::SETUGT: Flip = true; // Fallthrough
1911 case ISD::SETLT: X86CC = X86::COND_B; break;
1912 case ISD::SETUGE: Flip = true; // Fallthrough
1914 case ISD::SETLE: X86CC = X86::COND_BE; break;
1916 case ISD::SETNE: X86CC = X86::COND_NE; break;
1917 case ISD::SETUO: X86CC = X86::COND_P; break;
1918 case ISD::SETO: X86CC = X86::COND_NP; break;
1921 std::swap(LHS, RHS);
1924 return X86CC != X86::COND_INVALID;
1927 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
1928 /// code. Current x86 isa includes the following FP cmov instructions:
1929 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
1930 static bool hasFPCMov(unsigned X86CC) {
1946 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
1947 /// true if Op is undef or if its value falls within the specified range (L, H].
1948 static bool isUndefOrInRange(SDOperand Op, unsigned Low, unsigned Hi) {
1949 if (Op.getOpcode() == ISD::UNDEF)
1952 unsigned Val = cast<ConstantSDNode>(Op)->getValue();
1953 return (Val >= Low && Val < Hi);
1956 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
1957 /// true if Op is undef or if its value equal to the specified value.
1958 static bool isUndefOrEqual(SDOperand Op, unsigned Val) {
1959 if (Op.getOpcode() == ISD::UNDEF)
1961 return cast<ConstantSDNode>(Op)->getValue() == Val;
1964 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
1965 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
1966 bool X86::isPSHUFDMask(SDNode *N) {
1967 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1969 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
1972 // Check if the value doesn't reference the second vector.
1973 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1974 SDOperand Arg = N->getOperand(i);
1975 if (Arg.getOpcode() == ISD::UNDEF) continue;
1976 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1977 if (cast<ConstantSDNode>(Arg)->getValue() >= e)
1984 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
1985 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
1986 bool X86::isPSHUFHWMask(SDNode *N) {
1987 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1989 if (N->getNumOperands() != 8)
1992 // Lower quadword copied in order.
1993 for (unsigned i = 0; i != 4; ++i) {
1994 SDOperand Arg = N->getOperand(i);
1995 if (Arg.getOpcode() == ISD::UNDEF) continue;
1996 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1997 if (cast<ConstantSDNode>(Arg)->getValue() != i)
2001 // Upper quadword shuffled.
2002 for (unsigned i = 4; i != 8; ++i) {
2003 SDOperand Arg = N->getOperand(i);
2004 if (Arg.getOpcode() == ISD::UNDEF) continue;
2005 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2006 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2007 if (Val < 4 || Val > 7)
2014 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2015 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2016 bool X86::isPSHUFLWMask(SDNode *N) {
2017 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2019 if (N->getNumOperands() != 8)
2022 // Upper quadword copied in order.
2023 for (unsigned i = 4; i != 8; ++i)
2024 if (!isUndefOrEqual(N->getOperand(i), i))
2027 // Lower quadword shuffled.
2028 for (unsigned i = 0; i != 4; ++i)
2029 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2035 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2036 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2037 static bool isSHUFPMask(const SDOperand *Elems, unsigned NumElems) {
2038 if (NumElems != 2 && NumElems != 4) return false;
2040 unsigned Half = NumElems / 2;
2041 for (unsigned i = 0; i < Half; ++i)
2042 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2044 for (unsigned i = Half; i < NumElems; ++i)
2045 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2051 bool X86::isSHUFPMask(SDNode *N) {
2052 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2053 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2056 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2057 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2058 /// half elements to come from vector 1 (which would equal the dest.) and
2059 /// the upper half to come from vector 2.
2060 static bool isCommutedSHUFP(const SDOperand *Ops, unsigned NumOps) {
2061 if (NumOps != 2 && NumOps != 4) return false;
2063 unsigned Half = NumOps / 2;
2064 for (unsigned i = 0; i < Half; ++i)
2065 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2067 for (unsigned i = Half; i < NumOps; ++i)
2068 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2073 static bool isCommutedSHUFP(SDNode *N) {
2074 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2075 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2078 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2079 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2080 bool X86::isMOVHLPSMask(SDNode *N) {
2081 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2083 if (N->getNumOperands() != 4)
2086 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2087 return isUndefOrEqual(N->getOperand(0), 6) &&
2088 isUndefOrEqual(N->getOperand(1), 7) &&
2089 isUndefOrEqual(N->getOperand(2), 2) &&
2090 isUndefOrEqual(N->getOperand(3), 3);
2093 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2094 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2096 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2097 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2099 if (N->getNumOperands() != 4)
2102 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2103 return isUndefOrEqual(N->getOperand(0), 2) &&
2104 isUndefOrEqual(N->getOperand(1), 3) &&
2105 isUndefOrEqual(N->getOperand(2), 2) &&
2106 isUndefOrEqual(N->getOperand(3), 3);
2109 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2110 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2111 bool X86::isMOVLPMask(SDNode *N) {
2112 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2114 unsigned NumElems = N->getNumOperands();
2115 if (NumElems != 2 && NumElems != 4)
2118 for (unsigned i = 0; i < NumElems/2; ++i)
2119 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2122 for (unsigned i = NumElems/2; i < NumElems; ++i)
2123 if (!isUndefOrEqual(N->getOperand(i), i))
2129 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2130 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2132 bool X86::isMOVHPMask(SDNode *N) {
2133 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2135 unsigned NumElems = N->getNumOperands();
2136 if (NumElems != 2 && NumElems != 4)
2139 for (unsigned i = 0; i < NumElems/2; ++i)
2140 if (!isUndefOrEqual(N->getOperand(i), i))
2143 for (unsigned i = 0; i < NumElems/2; ++i) {
2144 SDOperand Arg = N->getOperand(i + NumElems/2);
2145 if (!isUndefOrEqual(Arg, i + NumElems))
2152 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2153 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2154 bool static isUNPCKLMask(const SDOperand *Elts, unsigned NumElts,
2155 bool V2IsSplat = false) {
2156 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2159 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2160 SDOperand BitI = Elts[i];
2161 SDOperand BitI1 = Elts[i+1];
2162 if (!isUndefOrEqual(BitI, j))
2165 if (isUndefOrEqual(BitI1, NumElts))
2168 if (!isUndefOrEqual(BitI1, j + NumElts))
2176 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2177 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2178 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2181 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2182 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2183 bool static isUNPCKHMask(const SDOperand *Elts, unsigned NumElts,
2184 bool V2IsSplat = false) {
2185 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2188 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2189 SDOperand BitI = Elts[i];
2190 SDOperand BitI1 = Elts[i+1];
2191 if (!isUndefOrEqual(BitI, j + NumElts/2))
2194 if (isUndefOrEqual(BitI1, NumElts))
2197 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2205 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2206 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2207 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2210 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2211 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2213 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2214 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2216 unsigned NumElems = N->getNumOperands();
2217 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2220 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2221 SDOperand BitI = N->getOperand(i);
2222 SDOperand BitI1 = N->getOperand(i+1);
2224 if (!isUndefOrEqual(BitI, j))
2226 if (!isUndefOrEqual(BitI1, j))
2233 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2234 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2236 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2237 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2239 unsigned NumElems = N->getNumOperands();
2240 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2243 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2244 SDOperand BitI = N->getOperand(i);
2245 SDOperand BitI1 = N->getOperand(i + 1);
2247 if (!isUndefOrEqual(BitI, j))
2249 if (!isUndefOrEqual(BitI1, j))
2256 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2257 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2258 /// MOVSD, and MOVD, i.e. setting the lowest element.
2259 static bool isMOVLMask(const SDOperand *Elts, unsigned NumElts) {
2260 if (NumElts != 2 && NumElts != 4)
2263 if (!isUndefOrEqual(Elts[0], NumElts))
2266 for (unsigned i = 1; i < NumElts; ++i) {
2267 if (!isUndefOrEqual(Elts[i], i))
2274 bool X86::isMOVLMask(SDNode *N) {
2275 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2276 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2279 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2280 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2281 /// element of vector 2 and the other elements to come from vector 1 in order.
2282 static bool isCommutedMOVL(const SDOperand *Ops, unsigned NumOps,
2283 bool V2IsSplat = false,
2284 bool V2IsUndef = false) {
2285 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2288 if (!isUndefOrEqual(Ops[0], 0))
2291 for (unsigned i = 1; i < NumOps; ++i) {
2292 SDOperand Arg = Ops[i];
2293 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2294 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2295 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2302 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2303 bool V2IsUndef = false) {
2304 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2305 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2306 V2IsSplat, V2IsUndef);
2309 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2310 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2311 bool X86::isMOVSHDUPMask(SDNode *N) {
2312 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2314 if (N->getNumOperands() != 4)
2317 // Expect 1, 1, 3, 3
2318 for (unsigned i = 0; i < 2; ++i) {
2319 SDOperand Arg = N->getOperand(i);
2320 if (Arg.getOpcode() == ISD::UNDEF) continue;
2321 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2322 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2323 if (Val != 1) return false;
2327 for (unsigned i = 2; i < 4; ++i) {
2328 SDOperand Arg = N->getOperand(i);
2329 if (Arg.getOpcode() == ISD::UNDEF) continue;
2330 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2331 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2332 if (Val != 3) return false;
2336 // Don't use movshdup if it can be done with a shufps.
2340 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2341 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2342 bool X86::isMOVSLDUPMask(SDNode *N) {
2343 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2345 if (N->getNumOperands() != 4)
2348 // Expect 0, 0, 2, 2
2349 for (unsigned i = 0; i < 2; ++i) {
2350 SDOperand Arg = N->getOperand(i);
2351 if (Arg.getOpcode() == ISD::UNDEF) continue;
2352 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2353 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2354 if (Val != 0) return false;
2358 for (unsigned i = 2; i < 4; ++i) {
2359 SDOperand Arg = N->getOperand(i);
2360 if (Arg.getOpcode() == ISD::UNDEF) continue;
2361 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2362 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2363 if (Val != 2) return false;
2367 // Don't use movshdup if it can be done with a shufps.
2371 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2372 /// specifies a identity operation on the LHS or RHS.
2373 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2374 unsigned NumElems = N->getNumOperands();
2375 for (unsigned i = 0; i < NumElems; ++i)
2376 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2381 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2382 /// a splat of a single element.
2383 static bool isSplatMask(SDNode *N) {
2384 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2386 // This is a splat operation if each element of the permute is the same, and
2387 // if the value doesn't reference the second vector.
2388 unsigned NumElems = N->getNumOperands();
2389 SDOperand ElementBase;
2391 for (; i != NumElems; ++i) {
2392 SDOperand Elt = N->getOperand(i);
2393 if (isa<ConstantSDNode>(Elt)) {
2399 if (!ElementBase.Val)
2402 for (; i != NumElems; ++i) {
2403 SDOperand Arg = N->getOperand(i);
2404 if (Arg.getOpcode() == ISD::UNDEF) continue;
2405 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2406 if (Arg != ElementBase) return false;
2409 // Make sure it is a splat of the first vector operand.
2410 return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
2413 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2414 /// a splat of a single element and it's a 2 or 4 element mask.
2415 bool X86::isSplatMask(SDNode *N) {
2416 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2418 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2419 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2421 return ::isSplatMask(N);
2424 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2425 /// specifies a splat of zero element.
2426 bool X86::isSplatLoMask(SDNode *N) {
2427 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2429 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2430 if (!isUndefOrEqual(N->getOperand(i), 0))
2435 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2436 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2438 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2439 unsigned NumOperands = N->getNumOperands();
2440 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2442 for (unsigned i = 0; i < NumOperands; ++i) {
2444 SDOperand Arg = N->getOperand(NumOperands-i-1);
2445 if (Arg.getOpcode() != ISD::UNDEF)
2446 Val = cast<ConstantSDNode>(Arg)->getValue();
2447 if (Val >= NumOperands) Val -= NumOperands;
2449 if (i != NumOperands - 1)
2456 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2457 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2459 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2461 // 8 nodes, but we only care about the last 4.
2462 for (unsigned i = 7; i >= 4; --i) {
2464 SDOperand Arg = N->getOperand(i);
2465 if (Arg.getOpcode() != ISD::UNDEF)
2466 Val = cast<ConstantSDNode>(Arg)->getValue();
2475 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2476 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2478 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2480 // 8 nodes, but we only care about the first 4.
2481 for (int i = 3; i >= 0; --i) {
2483 SDOperand Arg = N->getOperand(i);
2484 if (Arg.getOpcode() != ISD::UNDEF)
2485 Val = cast<ConstantSDNode>(Arg)->getValue();
2494 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2495 /// specifies a 8 element shuffle that can be broken into a pair of
2496 /// PSHUFHW and PSHUFLW.
2497 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2498 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2500 if (N->getNumOperands() != 8)
2503 // Lower quadword shuffled.
2504 for (unsigned i = 0; i != 4; ++i) {
2505 SDOperand Arg = N->getOperand(i);
2506 if (Arg.getOpcode() == ISD::UNDEF) continue;
2507 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2508 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2513 // Upper quadword shuffled.
2514 for (unsigned i = 4; i != 8; ++i) {
2515 SDOperand Arg = N->getOperand(i);
2516 if (Arg.getOpcode() == ISD::UNDEF) continue;
2517 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2518 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2519 if (Val < 4 || Val > 7)
2526 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2527 /// values in ther permute mask.
2528 static SDOperand CommuteVectorShuffle(SDOperand Op, SDOperand &V1,
2529 SDOperand &V2, SDOperand &Mask,
2530 SelectionDAG &DAG) {
2531 MVT::ValueType VT = Op.getValueType();
2532 MVT::ValueType MaskVT = Mask.getValueType();
2533 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2534 unsigned NumElems = Mask.getNumOperands();
2535 SmallVector<SDOperand, 8> MaskVec;
2537 for (unsigned i = 0; i != NumElems; ++i) {
2538 SDOperand Arg = Mask.getOperand(i);
2539 if (Arg.getOpcode() == ISD::UNDEF) {
2540 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2543 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2544 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2546 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2548 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2552 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2553 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2556 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2557 /// the two vector operands have swapped position.
2559 SDOperand CommuteVectorShuffleMask(SDOperand Mask, SelectionDAG &DAG) {
2560 MVT::ValueType MaskVT = Mask.getValueType();
2561 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2562 unsigned NumElems = Mask.getNumOperands();
2563 SmallVector<SDOperand, 8> MaskVec;
2564 for (unsigned i = 0; i != NumElems; ++i) {
2565 SDOperand Arg = Mask.getOperand(i);
2566 if (Arg.getOpcode() == ISD::UNDEF) {
2567 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2570 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2571 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2573 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2575 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2577 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2581 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2582 /// match movhlps. The lower half elements should come from upper half of
2583 /// V1 (and in order), and the upper half elements should come from the upper
2584 /// half of V2 (and in order).
2585 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2586 unsigned NumElems = Mask->getNumOperands();
2589 for (unsigned i = 0, e = 2; i != e; ++i)
2590 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2592 for (unsigned i = 2; i != 4; ++i)
2593 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2598 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2599 /// is promoted to a vector.
2600 static inline bool isScalarLoadToVector(SDNode *N) {
2601 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2602 N = N->getOperand(0).Val;
2603 return ISD::isNON_EXTLoad(N);
2608 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2609 /// match movlp{s|d}. The lower half elements should come from lower half of
2610 /// V1 (and in order), and the upper half elements should come from the upper
2611 /// half of V2 (and in order). And since V1 will become the source of the
2612 /// MOVLP, it must be either a vector load or a scalar load to vector.
2613 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2614 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2616 // Is V2 is a vector load, don't do this transformation. We will try to use
2617 // load folding shufps op.
2618 if (ISD::isNON_EXTLoad(V2))
2621 unsigned NumElems = Mask->getNumOperands();
2622 if (NumElems != 2 && NumElems != 4)
2624 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2625 if (!isUndefOrEqual(Mask->getOperand(i), i))
2627 for (unsigned i = NumElems/2; i != NumElems; ++i)
2628 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2633 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2635 static bool isSplatVector(SDNode *N) {
2636 if (N->getOpcode() != ISD::BUILD_VECTOR)
2639 SDOperand SplatValue = N->getOperand(0);
2640 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2641 if (N->getOperand(i) != SplatValue)
2646 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2648 static bool isUndefShuffle(SDNode *N) {
2649 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2652 SDOperand V1 = N->getOperand(0);
2653 SDOperand V2 = N->getOperand(1);
2654 SDOperand Mask = N->getOperand(2);
2655 unsigned NumElems = Mask.getNumOperands();
2656 for (unsigned i = 0; i != NumElems; ++i) {
2657 SDOperand Arg = Mask.getOperand(i);
2658 if (Arg.getOpcode() != ISD::UNDEF) {
2659 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2660 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2662 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2669 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2671 static inline bool isZeroNode(SDOperand Elt) {
2672 return ((isa<ConstantSDNode>(Elt) &&
2673 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2674 (isa<ConstantFPSDNode>(Elt) &&
2675 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2678 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2679 /// to an zero vector.
2680 static bool isZeroShuffle(SDNode *N) {
2681 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2684 SDOperand V1 = N->getOperand(0);
2685 SDOperand V2 = N->getOperand(1);
2686 SDOperand Mask = N->getOperand(2);
2687 unsigned NumElems = Mask.getNumOperands();
2688 for (unsigned i = 0; i != NumElems; ++i) {
2689 SDOperand Arg = Mask.getOperand(i);
2690 if (Arg.getOpcode() == ISD::UNDEF)
2693 unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
2694 if (Idx < NumElems) {
2695 unsigned Opc = V1.Val->getOpcode();
2696 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.Val))
2698 if (Opc != ISD::BUILD_VECTOR ||
2699 !isZeroNode(V1.Val->getOperand(Idx)))
2701 } else if (Idx >= NumElems) {
2702 unsigned Opc = V2.Val->getOpcode();
2703 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.Val))
2705 if (Opc != ISD::BUILD_VECTOR ||
2706 !isZeroNode(V2.Val->getOperand(Idx - NumElems)))
2713 /// getZeroVector - Returns a vector of specified type with all zero elements.
2715 static SDOperand getZeroVector(MVT::ValueType VT, SelectionDAG &DAG) {
2716 assert(MVT::isVector(VT) && "Expected a vector type");
2718 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2719 // type. This ensures they get CSE'd.
2720 SDOperand Cst = DAG.getTargetConstant(0, MVT::i32);
2722 if (MVT::getSizeInBits(VT) == 64) // MMX
2723 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2725 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2726 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2729 /// getOnesVector - Returns a vector of specified type with all bits set.
2731 static SDOperand getOnesVector(MVT::ValueType VT, SelectionDAG &DAG) {
2732 assert(MVT::isVector(VT) && "Expected a vector type");
2734 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2735 // type. This ensures they get CSE'd.
2736 SDOperand Cst = DAG.getTargetConstant(~0U, MVT::i32);
2738 if (MVT::getSizeInBits(VT) == 64) // MMX
2739 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2741 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2742 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2746 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2747 /// that point to V2 points to its first element.
2748 static SDOperand NormalizeMask(SDOperand Mask, SelectionDAG &DAG) {
2749 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2751 bool Changed = false;
2752 SmallVector<SDOperand, 8> MaskVec;
2753 unsigned NumElems = Mask.getNumOperands();
2754 for (unsigned i = 0; i != NumElems; ++i) {
2755 SDOperand Arg = Mask.getOperand(i);
2756 if (Arg.getOpcode() != ISD::UNDEF) {
2757 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2758 if (Val > NumElems) {
2759 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2763 MaskVec.push_back(Arg);
2767 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2768 &MaskVec[0], MaskVec.size());
2772 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2773 /// operation of specified width.
2774 static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2775 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2776 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2778 SmallVector<SDOperand, 8> MaskVec;
2779 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2780 for (unsigned i = 1; i != NumElems; ++i)
2781 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2782 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2785 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2786 /// of specified width.
2787 static SDOperand getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2788 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2789 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2790 SmallVector<SDOperand, 8> MaskVec;
2791 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2792 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2793 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2795 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2798 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2799 /// of specified width.
2800 static SDOperand getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2801 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2802 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2803 unsigned Half = NumElems/2;
2804 SmallVector<SDOperand, 8> MaskVec;
2805 for (unsigned i = 0; i != Half; ++i) {
2806 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
2807 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2809 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2812 /// PromoteSplat - Promote a splat of v8i16 or v16i8 to v4i32.
2814 static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG) {
2815 SDOperand V1 = Op.getOperand(0);
2816 SDOperand Mask = Op.getOperand(2);
2817 MVT::ValueType VT = Op.getValueType();
2818 unsigned NumElems = Mask.getNumOperands();
2819 Mask = getUnpacklMask(NumElems, DAG);
2820 while (NumElems != 4) {
2821 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2824 V1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, V1);
2826 Mask = getZeroVector(MVT::v4i32, DAG);
2827 SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32, V1,
2828 DAG.getNode(ISD::UNDEF, MVT::v4i32), Mask);
2829 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2832 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2833 /// vector of zero or undef vector. This produces a shuffle where the low
2834 /// element of V2 is swizzled into the zero/undef vector, landing at element
2835 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
2836 static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, MVT::ValueType VT,
2837 unsigned NumElems, unsigned Idx,
2838 bool isZero, SelectionDAG &DAG) {
2839 SDOperand V1 = isZero ? getZeroVector(VT, DAG) : DAG.getNode(ISD::UNDEF, VT);
2840 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2841 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
2842 SmallVector<SDOperand, 16> MaskVec;
2843 for (unsigned i = 0; i != NumElems; ++i)
2844 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
2845 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
2847 MaskVec.push_back(DAG.getConstant(i, EVT));
2848 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2849 &MaskVec[0], MaskVec.size());
2850 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2853 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2855 static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
2856 unsigned NumNonZero, unsigned NumZero,
2857 SelectionDAG &DAG, TargetLowering &TLI) {
2863 for (unsigned i = 0; i < 16; ++i) {
2864 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
2865 if (ThisIsNonZero && First) {
2867 V = getZeroVector(MVT::v8i16, DAG);
2869 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2874 SDOperand ThisElt(0, 0), LastElt(0, 0);
2875 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
2876 if (LastIsNonZero) {
2877 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
2879 if (ThisIsNonZero) {
2880 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
2881 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
2882 ThisElt, DAG.getConstant(8, MVT::i8));
2884 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
2889 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
2890 DAG.getIntPtrConstant(i/2));
2894 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
2897 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
2899 static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
2900 unsigned NumNonZero, unsigned NumZero,
2901 SelectionDAG &DAG, TargetLowering &TLI) {
2907 for (unsigned i = 0; i < 8; ++i) {
2908 bool isNonZero = (NonZeros & (1 << i)) != 0;
2912 V = getZeroVector(MVT::v8i16, DAG);
2914 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2917 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
2918 DAG.getIntPtrConstant(i));
2926 X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
2927 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
2928 if (ISD::isBuildVectorAllZeros(Op.Val) || ISD::isBuildVectorAllOnes(Op.Val)) {
2929 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
2930 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
2931 // eliminated on x86-32 hosts.
2932 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
2935 if (ISD::isBuildVectorAllOnes(Op.Val))
2936 return getOnesVector(Op.getValueType(), DAG);
2937 return getZeroVector(Op.getValueType(), DAG);
2940 MVT::ValueType VT = Op.getValueType();
2941 MVT::ValueType EVT = MVT::getVectorElementType(VT);
2942 unsigned EVTBits = MVT::getSizeInBits(EVT);
2944 unsigned NumElems = Op.getNumOperands();
2945 unsigned NumZero = 0;
2946 unsigned NumNonZero = 0;
2947 unsigned NonZeros = 0;
2948 bool HasNonImms = false;
2949 SmallSet<SDOperand, 8> Values;
2950 for (unsigned i = 0; i < NumElems; ++i) {
2951 SDOperand Elt = Op.getOperand(i);
2952 if (Elt.getOpcode() == ISD::UNDEF)
2955 if (Elt.getOpcode() != ISD::Constant &&
2956 Elt.getOpcode() != ISD::ConstantFP)
2958 if (isZeroNode(Elt))
2961 NonZeros |= (1 << i);
2966 if (NumNonZero == 0) {
2967 // All undef vector. Return an UNDEF. All zero vectors were handled above.
2968 return DAG.getNode(ISD::UNDEF, VT);
2971 // Splat is obviously ok. Let legalizer expand it to a shuffle.
2972 if (Values.size() == 1)
2975 // Special case for single non-zero element.
2976 if (NumNonZero == 1 && NumElems <= 4) {
2977 unsigned Idx = CountTrailingZeros_32(NonZeros);
2978 SDOperand Item = Op.getOperand(Idx);
2979 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
2981 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
2982 return getShuffleVectorZeroOrUndef(Item, VT, NumElems, Idx,
2984 else if (!HasNonImms) // Otherwise, it's better to do a constpool load.
2987 if (EVTBits == 32) {
2988 // Turn it into a shuffle of zero and zero-extended scalar to vector.
2989 Item = getShuffleVectorZeroOrUndef(Item, VT, NumElems, 0, NumZero > 0,
2991 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2992 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
2993 SmallVector<SDOperand, 8> MaskVec;
2994 for (unsigned i = 0; i < NumElems; i++)
2995 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
2996 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2997 &MaskVec[0], MaskVec.size());
2998 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
2999 DAG.getNode(ISD::UNDEF, VT), Mask);
3003 // A vector full of immediates; various special cases are already
3004 // handled, so this is best done with a single constant-pool load.
3008 // Let legalizer expand 2-wide build_vectors.
3012 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3013 if (EVTBits == 8 && NumElems == 16) {
3014 SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3016 if (V.Val) return V;
3019 if (EVTBits == 16 && NumElems == 8) {
3020 SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3022 if (V.Val) return V;
3025 // If element VT is == 32 bits, turn it into a number of shuffles.
3026 SmallVector<SDOperand, 8> V;
3028 if (NumElems == 4 && NumZero > 0) {
3029 for (unsigned i = 0; i < 4; ++i) {
3030 bool isZero = !(NonZeros & (1 << i));
3032 V[i] = getZeroVector(VT, DAG);
3034 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3037 for (unsigned i = 0; i < 2; ++i) {
3038 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3041 V[i] = V[i*2]; // Must be a zero vector.
3044 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3045 getMOVLMask(NumElems, DAG));
3048 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3049 getMOVLMask(NumElems, DAG));
3052 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3053 getUnpacklMask(NumElems, DAG));
3058 // Take advantage of the fact GR32 to VR128 scalar_to_vector (i.e. movd)
3059 // clears the upper bits.
3060 // FIXME: we can do the same for v4f32 case when we know both parts of
3061 // the lower half come from scalar_to_vector (loadf32). We should do
3062 // that in post legalizer dag combiner with target specific hooks.
3063 if (MVT::isInteger(EVT) && (NonZeros & (0x3 << 2)) == 0)
3065 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3066 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
3067 SmallVector<SDOperand, 8> MaskVec;
3068 bool Reverse = (NonZeros & 0x3) == 2;
3069 for (unsigned i = 0; i < 2; ++i)
3071 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3073 MaskVec.push_back(DAG.getConstant(i, EVT));
3074 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3075 for (unsigned i = 0; i < 2; ++i)
3077 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3079 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3080 SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3081 &MaskVec[0], MaskVec.size());
3082 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3085 if (Values.size() > 2) {
3086 // Expand into a number of unpckl*.
3088 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3089 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3090 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3091 SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
3092 for (unsigned i = 0; i < NumElems; ++i)
3093 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3095 while (NumElems != 0) {
3096 for (unsigned i = 0; i < NumElems; ++i)
3097 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3108 SDOperand LowerVECTOR_SHUFFLEv8i16(SDOperand V1, SDOperand V2,
3109 SDOperand PermMask, SelectionDAG &DAG,
3110 TargetLowering &TLI) {
3112 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(8);
3113 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3114 MVT::ValueType PtrVT = TLI.getPointerTy();
3115 SmallVector<SDOperand, 8> MaskElts(PermMask.Val->op_begin(),
3116 PermMask.Val->op_end());
3118 // First record which half of which vector the low elements come from.
3119 SmallVector<unsigned, 4> LowQuad(4);
3120 for (unsigned i = 0; i < 4; ++i) {
3121 SDOperand Elt = MaskElts[i];
3122 if (Elt.getOpcode() == ISD::UNDEF)
3124 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3125 int QuadIdx = EltIdx / 4;
3128 int BestLowQuad = -1;
3129 unsigned MaxQuad = 1;
3130 for (unsigned i = 0; i < 4; ++i) {
3131 if (LowQuad[i] > MaxQuad) {
3133 MaxQuad = LowQuad[i];
3137 // Record which half of which vector the high elements come from.
3138 SmallVector<unsigned, 4> HighQuad(4);
3139 for (unsigned i = 4; i < 8; ++i) {
3140 SDOperand Elt = MaskElts[i];
3141 if (Elt.getOpcode() == ISD::UNDEF)
3143 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3144 int QuadIdx = EltIdx / 4;
3145 ++HighQuad[QuadIdx];
3147 int BestHighQuad = -1;
3149 for (unsigned i = 0; i < 4; ++i) {
3150 if (HighQuad[i] > MaxQuad) {
3152 MaxQuad = HighQuad[i];
3156 // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3157 if (BestLowQuad != -1 || BestHighQuad != -1) {
3158 // First sort the 4 chunks in order using shufpd.
3159 SmallVector<SDOperand, 8> MaskVec;
3160 if (BestLowQuad != -1)
3161 MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3163 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3164 if (BestHighQuad != -1)
3165 MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3167 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3168 SDOperand Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3169 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3170 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3171 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3172 NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3174 // Now sort high and low parts separately.
3175 BitVector InOrder(8);
3176 if (BestLowQuad != -1) {
3177 // Sort lower half in order using PSHUFLW.
3179 bool AnyOutOrder = false;
3180 for (unsigned i = 0; i != 4; ++i) {
3181 SDOperand Elt = MaskElts[i];
3182 if (Elt.getOpcode() == ISD::UNDEF) {
3183 MaskVec.push_back(Elt);
3186 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3189 MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3190 // If this element is in the right place after this shuffle, then
3192 if ((int)(EltIdx / 4) == BestLowQuad)
3197 for (unsigned i = 4; i != 8; ++i)
3198 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3199 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3200 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3204 if (BestHighQuad != -1) {
3205 // Sort high half in order using PSHUFHW if possible.
3207 for (unsigned i = 0; i != 4; ++i)
3208 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3209 bool AnyOutOrder = false;
3210 for (unsigned i = 4; i != 8; ++i) {
3211 SDOperand Elt = MaskElts[i];
3212 if (Elt.getOpcode() == ISD::UNDEF) {
3213 MaskVec.push_back(Elt);
3216 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3219 MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3220 // If this element is in the right place after this shuffle, then
3222 if ((int)(EltIdx / 4) == BestHighQuad)
3227 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3228 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3232 // The other elements are put in the right place using pextrw and pinsrw.
3233 for (unsigned i = 0; i != 8; ++i) {
3236 SDOperand Elt = MaskElts[i];
3237 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3240 SDOperand ExtOp = (EltIdx < 8)
3241 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3242 DAG.getConstant(EltIdx, PtrVT))
3243 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3244 DAG.getConstant(EltIdx - 8, PtrVT));
3245 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3246 DAG.getConstant(i, PtrVT));
3251 // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use
3252 ///as few as possible.
3253 // First, let's find out how many elements are already in the right order.
3254 unsigned V1InOrder = 0;
3255 unsigned V1FromV1 = 0;
3256 unsigned V2InOrder = 0;
3257 unsigned V2FromV2 = 0;
3258 SmallVector<SDOperand, 8> V1Elts;
3259 SmallVector<SDOperand, 8> V2Elts;
3260 for (unsigned i = 0; i < 8; ++i) {
3261 SDOperand Elt = MaskElts[i];
3262 if (Elt.getOpcode() == ISD::UNDEF) {
3263 V1Elts.push_back(Elt);
3264 V2Elts.push_back(Elt);
3269 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3271 V1Elts.push_back(Elt);
3272 V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3274 } else if (EltIdx == i+8) {
3275 V1Elts.push_back(Elt);
3276 V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3278 } else if (EltIdx < 8) {
3279 V1Elts.push_back(Elt);
3282 V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3287 if (V2InOrder > V1InOrder) {
3288 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3290 std::swap(V1Elts, V2Elts);
3291 std::swap(V1FromV1, V2FromV2);
3294 if ((V1FromV1 + V1InOrder) != 8) {
3295 // Some elements are from V2.
3297 // If there are elements that are from V1 but out of place,
3298 // then first sort them in place
3299 SmallVector<SDOperand, 8> MaskVec;
3300 for (unsigned i = 0; i < 8; ++i) {
3301 SDOperand Elt = V1Elts[i];
3302 if (Elt.getOpcode() == ISD::UNDEF) {
3303 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3306 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3308 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3310 MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3312 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3313 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3317 for (unsigned i = 0; i < 8; ++i) {
3318 SDOperand Elt = V1Elts[i];
3319 if (Elt.getOpcode() == ISD::UNDEF)
3321 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3324 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3325 DAG.getConstant(EltIdx - 8, PtrVT));
3326 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3327 DAG.getConstant(i, PtrVT));
3331 // All elements are from V1.
3333 for (unsigned i = 0; i < 8; ++i) {
3334 SDOperand Elt = V1Elts[i];
3335 if (Elt.getOpcode() == ISD::UNDEF)
3337 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3338 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3339 DAG.getConstant(EltIdx, PtrVT));
3340 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3341 DAG.getConstant(i, PtrVT));
3347 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3348 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3349 /// done when every pair / quad of shuffle mask elements point to elements in
3350 /// the right sequence. e.g.
3351 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3353 SDOperand RewriteAsNarrowerShuffle(SDOperand V1, SDOperand V2,
3355 SDOperand PermMask, SelectionDAG &DAG,
3356 TargetLowering &TLI) {
3357 unsigned NumElems = PermMask.getNumOperands();
3358 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3359 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3360 MVT::ValueType NewVT = MaskVT;
3362 case MVT::v4f32: NewVT = MVT::v2f64; break;
3363 case MVT::v4i32: NewVT = MVT::v2i64; break;
3364 case MVT::v8i16: NewVT = MVT::v4i32; break;
3365 case MVT::v16i8: NewVT = MVT::v4i32; break;
3366 default: assert(false && "Unexpected!");
3370 if (MVT::isInteger(VT))
3374 unsigned Scale = NumElems / NewWidth;
3375 SmallVector<SDOperand, 8> MaskVec;
3376 for (unsigned i = 0; i < NumElems; i += Scale) {
3377 unsigned StartIdx = ~0U;
3378 for (unsigned j = 0; j < Scale; ++j) {
3379 SDOperand Elt = PermMask.getOperand(i+j);
3380 if (Elt.getOpcode() == ISD::UNDEF)
3382 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3383 if (StartIdx == ~0U)
3384 StartIdx = EltIdx - (EltIdx % Scale);
3385 if (EltIdx != StartIdx + j)
3388 if (StartIdx == ~0U)
3389 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
3391 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MVT::i32));
3394 V1 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V1);
3395 V2 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V2);
3396 return DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, V1, V2,
3397 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3398 &MaskVec[0], MaskVec.size()));
3402 X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
3403 SDOperand V1 = Op.getOperand(0);
3404 SDOperand V2 = Op.getOperand(1);
3405 SDOperand PermMask = Op.getOperand(2);
3406 MVT::ValueType VT = Op.getValueType();
3407 unsigned NumElems = PermMask.getNumOperands();
3408 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3409 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3410 bool V1IsSplat = false;
3411 bool V2IsSplat = false;
3413 if (isUndefShuffle(Op.Val))
3414 return DAG.getNode(ISD::UNDEF, VT);
3416 if (isZeroShuffle(Op.Val))
3417 return getZeroVector(VT, DAG);
3419 if (isIdentityMask(PermMask.Val))
3421 else if (isIdentityMask(PermMask.Val, true))
3424 if (isSplatMask(PermMask.Val)) {
3425 if (NumElems <= 4) return Op;
3426 // Promote it to a v4i32 splat.
3427 return PromoteSplat(Op, DAG);
3430 // If the shuffle can be profitably rewritten as a narrower shuffle, then
3432 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3433 SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3435 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3436 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3437 // FIXME: Figure out a cleaner way to do this.
3438 // Try to make use of movq to zero out the top part.
3439 if (ISD::isBuildVectorAllZeros(V2.Val)) {
3440 SDOperand NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3442 SDOperand NewV1 = NewOp.getOperand(0);
3443 SDOperand NewV2 = NewOp.getOperand(1);
3444 SDOperand NewMask = NewOp.getOperand(2);
3445 if (isCommutedMOVL(NewMask.Val, true, false)) {
3446 NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
3447 NewOp = DAG.getNode(ISD::VECTOR_SHUFFLE, NewOp.getValueType(),
3448 NewV1, NewV2, getMOVLMask(2, DAG));
3449 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3452 } else if (ISD::isBuildVectorAllZeros(V1.Val)) {
3453 SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3454 if (NewOp.Val && X86::isMOVLMask(NewOp.getOperand(2).Val))
3455 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3459 if (X86::isMOVLMask(PermMask.Val))
3460 return (V1IsUndef) ? V2 : Op;
3462 if (X86::isMOVSHDUPMask(PermMask.Val) ||
3463 X86::isMOVSLDUPMask(PermMask.Val) ||
3464 X86::isMOVHLPSMask(PermMask.Val) ||
3465 X86::isMOVHPMask(PermMask.Val) ||
3466 X86::isMOVLPMask(PermMask.Val))
3469 if (ShouldXformToMOVHLPS(PermMask.Val) ||
3470 ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
3471 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3473 bool Commuted = false;
3474 // FIXME: This should also accept a bitcast of a splat? Be careful, not
3475 // 1,1,1,1 -> v8i16 though.
3476 V1IsSplat = isSplatVector(V1.Val);
3477 V2IsSplat = isSplatVector(V2.Val);
3479 // Canonicalize the splat or undef, if present, to be on the RHS.
3480 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3481 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3482 std::swap(V1IsSplat, V2IsSplat);
3483 std::swap(V1IsUndef, V2IsUndef);
3487 // FIXME: Figure out a cleaner way to do this.
3488 if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
3489 if (V2IsUndef) return V1;
3490 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3492 // V2 is a splat, so the mask may be malformed. That is, it may point
3493 // to any V2 element. The instruction selectior won't like this. Get
3494 // a corrected mask and commute to form a proper MOVS{S|D}.
3495 SDOperand NewMask = getMOVLMask(NumElems, DAG);
3496 if (NewMask.Val != PermMask.Val)
3497 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3502 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3503 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3504 X86::isUNPCKLMask(PermMask.Val) ||
3505 X86::isUNPCKHMask(PermMask.Val))
3509 // Normalize mask so all entries that point to V2 points to its first
3510 // element then try to match unpck{h|l} again. If match, return a
3511 // new vector_shuffle with the corrected mask.
3512 SDOperand NewMask = NormalizeMask(PermMask, DAG);
3513 if (NewMask.Val != PermMask.Val) {
3514 if (X86::isUNPCKLMask(PermMask.Val, true)) {
3515 SDOperand NewMask = getUnpacklMask(NumElems, DAG);
3516 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3517 } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
3518 SDOperand NewMask = getUnpackhMask(NumElems, DAG);
3519 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3524 // Normalize the node to match x86 shuffle ops if needed
3525 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
3526 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3529 // Commute is back and try unpck* again.
3530 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3531 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3532 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3533 X86::isUNPCKLMask(PermMask.Val) ||
3534 X86::isUNPCKHMask(PermMask.Val))
3538 // If VT is integer, try PSHUF* first, then SHUFP*.
3539 if (MVT::isInteger(VT)) {
3540 // MMX doesn't have PSHUFD; it does have PSHUFW. While it's theoretically
3541 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
3542 if (((MVT::getSizeInBits(VT) != 64 || NumElems == 4) &&
3543 X86::isPSHUFDMask(PermMask.Val)) ||
3544 X86::isPSHUFHWMask(PermMask.Val) ||
3545 X86::isPSHUFLWMask(PermMask.Val)) {
3546 if (V2.getOpcode() != ISD::UNDEF)
3547 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3548 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3552 if (X86::isSHUFPMask(PermMask.Val) &&
3553 MVT::getSizeInBits(VT) != 64) // Don't do this for MMX.
3556 // Floating point cases in the other order.
3557 if (X86::isSHUFPMask(PermMask.Val))
3559 if (X86::isPSHUFDMask(PermMask.Val) ||
3560 X86::isPSHUFHWMask(PermMask.Val) ||
3561 X86::isPSHUFLWMask(PermMask.Val)) {
3562 if (V2.getOpcode() != ISD::UNDEF)
3563 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3564 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3569 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
3570 if (VT == MVT::v8i16) {
3571 SDOperand NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
3576 // Handle all 4 wide cases with a number of shuffles.
3577 if (NumElems == 4 && MVT::getSizeInBits(VT) != 64) {
3578 // Don't do this for MMX.
3579 MVT::ValueType MaskVT = PermMask.getValueType();
3580 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3581 SmallVector<std::pair<int, int>, 8> Locs;
3582 Locs.reserve(NumElems);
3583 SmallVector<SDOperand, 8> Mask1(NumElems,
3584 DAG.getNode(ISD::UNDEF, MaskEVT));
3585 SmallVector<SDOperand, 8> Mask2(NumElems,
3586 DAG.getNode(ISD::UNDEF, MaskEVT));
3589 // If no more than two elements come from either vector. This can be
3590 // implemented with two shuffles. First shuffle gather the elements.
3591 // The second shuffle, which takes the first shuffle as both of its
3592 // vector operands, put the elements into the right order.
3593 for (unsigned i = 0; i != NumElems; ++i) {
3594 SDOperand Elt = PermMask.getOperand(i);
3595 if (Elt.getOpcode() == ISD::UNDEF) {
3596 Locs[i] = std::make_pair(-1, -1);
3598 unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3599 if (Val < NumElems) {
3600 Locs[i] = std::make_pair(0, NumLo);
3604 Locs[i] = std::make_pair(1, NumHi);
3605 if (2+NumHi < NumElems)
3606 Mask1[2+NumHi] = Elt;
3611 if (NumLo <= 2 && NumHi <= 2) {
3612 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3613 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3614 &Mask1[0], Mask1.size()));
3615 for (unsigned i = 0; i != NumElems; ++i) {
3616 if (Locs[i].first == -1)
3619 unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
3620 Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
3621 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3625 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3626 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3627 &Mask2[0], Mask2.size()));
3630 // Break it into (shuffle shuffle_hi, shuffle_lo).
3632 SmallVector<SDOperand,8> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3633 SmallVector<SDOperand,8> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3634 SmallVector<SDOperand,8> *MaskPtr = &LoMask;
3635 unsigned MaskIdx = 0;
3637 unsigned HiIdx = NumElems/2;
3638 for (unsigned i = 0; i != NumElems; ++i) {
3639 if (i == NumElems/2) {
3645 SDOperand Elt = PermMask.getOperand(i);
3646 if (Elt.getOpcode() == ISD::UNDEF) {
3647 Locs[i] = std::make_pair(-1, -1);
3648 } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
3649 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3650 (*MaskPtr)[LoIdx] = Elt;
3653 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3654 (*MaskPtr)[HiIdx] = Elt;
3659 SDOperand LoShuffle =
3660 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3661 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3662 &LoMask[0], LoMask.size()));
3663 SDOperand HiShuffle =
3664 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3665 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3666 &HiMask[0], HiMask.size()));
3667 SmallVector<SDOperand, 8> MaskOps;
3668 for (unsigned i = 0; i != NumElems; ++i) {
3669 if (Locs[i].first == -1) {
3670 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3672 unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
3673 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3676 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3677 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3678 &MaskOps[0], MaskOps.size()));
3685 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDOperand Op,
3686 SelectionDAG &DAG) {
3687 MVT::ValueType VT = Op.getValueType();
3688 if (MVT::getSizeInBits(VT) == 8) {
3689 SDOperand Extract = DAG.getNode(X86ISD::PEXTRB, MVT::i32,
3690 Op.getOperand(0), Op.getOperand(1));
3691 SDOperand Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
3692 DAG.getValueType(VT));
3693 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3694 } else if (MVT::getSizeInBits(VT) == 16) {
3695 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, MVT::i32,
3696 Op.getOperand(0), Op.getOperand(1));
3697 SDOperand Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
3698 DAG.getValueType(VT));
3699 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3706 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3707 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3710 if (Subtarget->hasSSE41())
3711 return LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
3713 MVT::ValueType VT = Op.getValueType();
3714 // TODO: handle v16i8.
3715 if (MVT::getSizeInBits(VT) == 16) {
3716 SDOperand Vec = Op.getOperand(0);
3717 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3719 return DAG.getNode(ISD::TRUNCATE, MVT::i16,
3720 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
3721 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
3723 // Transform it so it match pextrw which produces a 32-bit result.
3724 MVT::ValueType EVT = (MVT::ValueType)(VT+1);
3725 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
3726 Op.getOperand(0), Op.getOperand(1));
3727 SDOperand Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
3728 DAG.getValueType(VT));
3729 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3730 } else if (MVT::getSizeInBits(VT) == 32) {
3731 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3734 // SHUFPS the element to the lowest double word, then movss.
3735 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3736 SmallVector<SDOperand, 8> IdxVec;
3738 push_back(DAG.getConstant(Idx, MVT::getVectorElementType(MaskVT)));
3740 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3742 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3744 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3745 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3746 &IdxVec[0], IdxVec.size());
3747 SDOperand Vec = Op.getOperand(0);
3748 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3749 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3750 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3751 DAG.getIntPtrConstant(0));
3752 } else if (MVT::getSizeInBits(VT) == 64) {
3753 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
3754 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
3755 // to match extract_elt for f64.
3756 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3760 // UNPCKHPD the element to the lowest double word, then movsd.
3761 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
3762 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
3763 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3764 SmallVector<SDOperand, 8> IdxVec;
3765 IdxVec.push_back(DAG.getConstant(1, MVT::getVectorElementType(MaskVT)));
3767 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3768 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3769 &IdxVec[0], IdxVec.size());
3770 SDOperand Vec = Op.getOperand(0);
3771 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3772 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3773 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3774 DAG.getIntPtrConstant(0));
3781 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDOperand Op, SelectionDAG &DAG){
3782 MVT::ValueType VT = Op.getValueType();
3783 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3785 SDOperand N0 = Op.getOperand(0);
3786 SDOperand N1 = Op.getOperand(1);
3787 SDOperand N2 = Op.getOperand(2);
3789 if ((MVT::getSizeInBits(EVT) == 8) || (MVT::getSizeInBits(EVT) == 16)) {
3790 unsigned Opc = (MVT::getSizeInBits(EVT) == 8) ? X86ISD::PINSRB
3792 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
3794 if (N1.getValueType() != MVT::i32)
3795 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3796 if (N2.getValueType() != MVT::i32)
3797 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
3798 return DAG.getNode(Opc, VT, N0, N1, N2);
3799 } else if (EVT == MVT::f32) {
3800 // Bits [7:6] of the constant are the source select. This will always be
3801 // zero here. The DAG Combiner may combine an extract_elt index into these
3802 // bits. For example (insert (extract, 3), 2) could be matched by putting
3803 // the '3' into bits [7:6] of X86ISD::INSERTPS.
3804 // Bits [5:4] of the constant are the destination select. This is the
3805 // value of the incoming immediate.
3806 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
3807 // combine either bitwise AND or insert of float 0.0 to set these bits.
3808 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue() << 4);
3809 return DAG.getNode(X86ISD::INSERTPS, VT, N0, N1, N2);
3815 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3816 MVT::ValueType VT = Op.getValueType();
3817 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3819 if (Subtarget->hasSSE41())
3820 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
3825 SDOperand N0 = Op.getOperand(0);
3826 SDOperand N1 = Op.getOperand(1);
3827 SDOperand N2 = Op.getOperand(2);
3829 if (MVT::getSizeInBits(EVT) == 16) {
3830 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
3831 // as its second argument.
3832 if (N1.getValueType() != MVT::i32)
3833 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3834 if (N2.getValueType() != MVT::i32)
3835 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
3836 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
3842 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3843 SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
3844 return DAG.getNode(X86ISD::S2VEC, Op.getValueType(), AnyExt);
3847 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3848 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
3849 // one of the above mentioned nodes. It has to be wrapped because otherwise
3850 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3851 // be used to form addressing mode. These wrapped nodes will be selected
3854 X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
3855 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3856 SDOperand Result = DAG.getTargetConstantPool(CP->getConstVal(),
3858 CP->getAlignment());
3859 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3860 // With PIC, the address is actually $g + Offset.
3861 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3862 !Subtarget->isPICStyleRIPRel()) {
3863 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3864 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3872 X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
3873 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3874 SDOperand Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
3875 // If it's a debug information descriptor, don't mess with it.
3876 if (DAG.isVerifiedDebugInfoDesc(Op))
3878 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3879 // With PIC, the address is actually $g + Offset.
3880 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3881 !Subtarget->isPICStyleRIPRel()) {
3882 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3883 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3887 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
3888 // load the value at address GV, not the value of GV itself. This means that
3889 // the GlobalAddress must be in the base or index register of the address, not
3890 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
3891 // The same applies for external symbols during PIC codegen
3892 if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
3893 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
3894 PseudoSourceValue::getGOT(), 0);
3899 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
3901 LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
3902 const MVT::ValueType PtrVT) {
3904 SDOperand Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
3905 DAG.getNode(X86ISD::GlobalBaseReg,
3907 InFlag = Chain.getValue(1);
3909 // emit leal symbol@TLSGD(,%ebx,1), %eax
3910 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
3911 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
3912 GA->getValueType(0),
3914 SDOperand Ops[] = { Chain, TGA, InFlag };
3915 SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
3916 InFlag = Result.getValue(2);
3917 Chain = Result.getValue(1);
3919 // call ___tls_get_addr. This function receives its argument in
3920 // the register EAX.
3921 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
3922 InFlag = Chain.getValue(1);
3924 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
3925 SDOperand Ops1[] = { Chain,
3926 DAG.getTargetExternalSymbol("___tls_get_addr",
3928 DAG.getRegister(X86::EAX, PtrVT),
3929 DAG.getRegister(X86::EBX, PtrVT),
3931 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
3932 InFlag = Chain.getValue(1);
3934 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
3937 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
3938 // "local exec" model.
3940 LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
3941 const MVT::ValueType PtrVT) {
3942 // Get the Thread Pointer
3943 SDOperand ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
3944 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
3946 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
3947 GA->getValueType(0),
3949 SDOperand Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
3951 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
3952 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
3953 PseudoSourceValue::getGOT(), 0);
3955 // The address of the thread local variable is the add of the thread
3956 // pointer with the offset of the variable.
3957 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
3961 X86TargetLowering::LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
3962 // TODO: implement the "local dynamic" model
3963 // TODO: implement the "initial exec"model for pic executables
3964 assert(!Subtarget->is64Bit() && Subtarget->isTargetELF() &&
3965 "TLS not implemented for non-ELF and 64-bit targets");
3966 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3967 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
3968 // otherwise use the "Local Exec"TLS Model
3969 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
3970 return LowerToTLSGeneralDynamicModel(GA, DAG, getPointerTy());
3972 return LowerToTLSExecModel(GA, DAG, getPointerTy());
3976 X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
3977 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
3978 SDOperand Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
3979 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3980 // With PIC, the address is actually $g + Offset.
3981 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3982 !Subtarget->isPICStyleRIPRel()) {
3983 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3984 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3991 SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
3992 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3993 SDOperand Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
3994 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3995 // With PIC, the address is actually $g + Offset.
3996 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3997 !Subtarget->isPICStyleRIPRel()) {
3998 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3999 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4006 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4007 /// take a 2 x i32 value to shift plus a shift amount.
4008 SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
4009 assert(Op.getNumOperands() == 3 && Op.getValueType() == MVT::i32 &&
4010 "Not an i64 shift!");
4011 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4012 SDOperand ShOpLo = Op.getOperand(0);
4013 SDOperand ShOpHi = Op.getOperand(1);
4014 SDOperand ShAmt = Op.getOperand(2);
4015 SDOperand Tmp1 = isSRA ?
4016 DAG.getNode(ISD::SRA, MVT::i32, ShOpHi, DAG.getConstant(31, MVT::i8)) :
4017 DAG.getConstant(0, MVT::i32);
4019 SDOperand Tmp2, Tmp3;
4020 if (Op.getOpcode() == ISD::SHL_PARTS) {
4021 Tmp2 = DAG.getNode(X86ISD::SHLD, MVT::i32, ShOpHi, ShOpLo, ShAmt);
4022 Tmp3 = DAG.getNode(ISD::SHL, MVT::i32, ShOpLo, ShAmt);
4024 Tmp2 = DAG.getNode(X86ISD::SHRD, MVT::i32, ShOpLo, ShOpHi, ShAmt);
4025 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, MVT::i32, ShOpHi, ShAmt);
4028 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
4029 SDOperand AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4030 DAG.getConstant(32, MVT::i8));
4031 SDOperand Cond = DAG.getNode(X86ISD::CMP, MVT::i32,
4032 AndNode, DAG.getConstant(0, MVT::i8));
4035 SDOperand CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4036 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::Flag);
4037 SmallVector<SDOperand, 4> Ops;
4038 if (Op.getOpcode() == ISD::SHL_PARTS) {
4039 Ops.push_back(Tmp2);
4040 Ops.push_back(Tmp3);
4042 Ops.push_back(Cond);
4043 Hi = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4046 Ops.push_back(Tmp3);
4047 Ops.push_back(Tmp1);
4049 Ops.push_back(Cond);
4050 Lo = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4052 Ops.push_back(Tmp2);
4053 Ops.push_back(Tmp3);
4055 Ops.push_back(Cond);
4056 Lo = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4059 Ops.push_back(Tmp3);
4060 Ops.push_back(Tmp1);
4062 Ops.push_back(Cond);
4063 Hi = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4066 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::i32);
4070 return DAG.getNode(ISD::MERGE_VALUES, VTs, 2, &Ops[0], Ops.size());
4073 SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
4074 assert(Op.getOperand(0).getValueType() <= MVT::i64 &&
4075 Op.getOperand(0).getValueType() >= MVT::i16 &&
4076 "Unknown SINT_TO_FP to lower!");
4079 MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
4080 unsigned Size = MVT::getSizeInBits(SrcVT)/8;
4081 MachineFunction &MF = DAG.getMachineFunction();
4082 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4083 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4084 SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4086 PseudoSourceValue::getFixedStack(),
4089 // These are really Legal; caller falls through into that case.
4090 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4092 if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 &&
4093 Subtarget->is64Bit())
4098 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4100 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4102 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4103 SmallVector<SDOperand, 8> Ops;
4104 Ops.push_back(Chain);
4105 Ops.push_back(StackSlot);
4106 Ops.push_back(DAG.getValueType(SrcVT));
4107 Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG :X86ISD::FILD,
4108 Tys, &Ops[0], Ops.size());
4111 Chain = Result.getValue(1);
4112 SDOperand InFlag = Result.getValue(2);
4114 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4115 // shouldn't be necessary except that RFP cannot be live across
4116 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4117 MachineFunction &MF = DAG.getMachineFunction();
4118 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4119 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4120 Tys = DAG.getVTList(MVT::Other);
4121 SmallVector<SDOperand, 8> Ops;
4122 Ops.push_back(Chain);
4123 Ops.push_back(Result);
4124 Ops.push_back(StackSlot);
4125 Ops.push_back(DAG.getValueType(Op.getValueType()));
4126 Ops.push_back(InFlag);
4127 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4128 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
4129 PseudoSourceValue::getFixedStack(), SSFI);
4135 std::pair<SDOperand,SDOperand> X86TargetLowering::
4136 FP_TO_SINTHelper(SDOperand Op, SelectionDAG &DAG) {
4137 assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
4138 "Unknown FP_TO_SINT to lower!");
4140 // These are really Legal.
4141 if (Op.getValueType() == MVT::i32 &&
4142 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4143 return std::make_pair(SDOperand(), SDOperand());
4144 if (Subtarget->is64Bit() &&
4145 Op.getValueType() == MVT::i64 &&
4146 Op.getOperand(0).getValueType() != MVT::f80)
4147 return std::make_pair(SDOperand(), SDOperand());
4149 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4151 MachineFunction &MF = DAG.getMachineFunction();
4152 unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
4153 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4154 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4156 switch (Op.getValueType()) {
4157 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4158 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4159 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4160 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4163 SDOperand Chain = DAG.getEntryNode();
4164 SDOperand Value = Op.getOperand(0);
4165 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4166 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4167 Chain = DAG.getStore(Chain, Value, StackSlot,
4168 PseudoSourceValue::getFixedStack(), SSFI);
4169 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4171 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4173 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4174 Chain = Value.getValue(1);
4175 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4176 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4179 // Build the FP_TO_INT*_IN_MEM
4180 SDOperand Ops[] = { Chain, Value, StackSlot };
4181 SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4183 return std::make_pair(FIST, StackSlot);
4186 SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
4187 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(Op, DAG);
4188 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4189 if (FIST.Val == 0) return SDOperand();
4192 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4195 SDNode *X86TargetLowering::ExpandFP_TO_SINT(SDNode *N, SelectionDAG &DAG) {
4196 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(SDOperand(N, 0), DAG);
4197 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4198 if (FIST.Val == 0) return 0;
4200 // Return an i64 load from the stack slot.
4201 SDOperand Res = DAG.getLoad(MVT::i64, FIST, StackSlot, NULL, 0);
4203 // Use a MERGE_VALUES node to drop the chain result value.
4204 return DAG.getNode(ISD::MERGE_VALUES, MVT::i64, Res).Val;
4207 SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
4208 MVT::ValueType VT = Op.getValueType();
4209 MVT::ValueType EltVT = VT;
4210 if (MVT::isVector(VT))
4211 EltVT = MVT::getVectorElementType(VT);
4212 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
4213 std::vector<Constant*> CV;
4214 if (EltVT == MVT::f64) {
4215 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, ~(1ULL << 63))));
4219 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, ~(1U << 31))));
4225 Constant *C = ConstantVector::get(CV);
4226 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4227 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4228 PseudoSourceValue::getConstantPool(), 0,
4230 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4233 SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
4234 MVT::ValueType VT = Op.getValueType();
4235 MVT::ValueType EltVT = VT;
4236 unsigned EltNum = 1;
4237 if (MVT::isVector(VT)) {
4238 EltVT = MVT::getVectorElementType(VT);
4239 EltNum = MVT::getVectorNumElements(VT);
4241 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
4242 std::vector<Constant*> CV;
4243 if (EltVT == MVT::f64) {
4244 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, 1ULL << 63)));
4248 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, 1U << 31)));
4254 Constant *C = ConstantVector::get(CV);
4255 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4256 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4257 PseudoSourceValue::getConstantPool(), 0,
4259 if (MVT::isVector(VT)) {
4260 return DAG.getNode(ISD::BIT_CONVERT, VT,
4261 DAG.getNode(ISD::XOR, MVT::v2i64,
4262 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4263 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4265 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4269 SDOperand X86TargetLowering::LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
4270 SDOperand Op0 = Op.getOperand(0);
4271 SDOperand Op1 = Op.getOperand(1);
4272 MVT::ValueType VT = Op.getValueType();
4273 MVT::ValueType SrcVT = Op1.getValueType();
4274 const Type *SrcTy = MVT::getTypeForValueType(SrcVT);
4276 // If second operand is smaller, extend it first.
4277 if (MVT::getSizeInBits(SrcVT) < MVT::getSizeInBits(VT)) {
4278 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4280 SrcTy = MVT::getTypeForValueType(SrcVT);
4282 // And if it is bigger, shrink it first.
4283 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4284 Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1, DAG.getIntPtrConstant(1));
4286 SrcTy = MVT::getTypeForValueType(SrcVT);
4289 // At this point the operands and the result should have the same
4290 // type, and that won't be f80 since that is not custom lowered.
4292 // First get the sign bit of second operand.
4293 std::vector<Constant*> CV;
4294 if (SrcVT == MVT::f64) {
4295 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 1ULL << 63))));
4296 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
4298 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 1U << 31))));
4299 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4300 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4301 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4303 Constant *C = ConstantVector::get(CV);
4304 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4305 SDOperand Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx,
4306 PseudoSourceValue::getConstantPool(), 0,
4308 SDOperand SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4310 // Shift sign bit right or left if the two operands have different types.
4311 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4312 // Op0 is MVT::f32, Op1 is MVT::f64.
4313 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4314 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4315 DAG.getConstant(32, MVT::i32));
4316 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4317 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4318 DAG.getIntPtrConstant(0));
4321 // Clear first operand sign bit.
4323 if (VT == MVT::f64) {
4324 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, ~(1ULL << 63)))));
4325 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
4327 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, ~(1U << 31)))));
4328 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4329 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4330 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4332 C = ConstantVector::get(CV);
4333 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4334 SDOperand Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4335 PseudoSourceValue::getConstantPool(), 0,
4337 SDOperand Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4339 // Or the value with the sign bit.
4340 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4343 SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG) {
4344 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
4346 SDOperand Op0 = Op.getOperand(0);
4347 SDOperand Op1 = Op.getOperand(1);
4348 SDOperand CC = Op.getOperand(2);
4349 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4350 bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
4353 if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
4355 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4356 return DAG.getNode(X86ISD::SETCC, MVT::i8,
4357 DAG.getConstant(X86CC, MVT::i8), Cond);
4360 assert(isFP && "Illegal integer SetCC!");
4362 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4363 switch (SetCCOpcode) {
4364 default: assert(false && "Illegal floating point SetCC!");
4365 case ISD::SETOEQ: { // !PF & ZF
4366 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4367 DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
4368 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4369 DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4370 return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4372 case ISD::SETUNE: { // PF | !ZF
4373 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4374 DAG.getConstant(X86::COND_P, MVT::i8), Cond);
4375 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4376 DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4377 return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4383 SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
4384 bool addTest = true;
4385 SDOperand Cond = Op.getOperand(0);
4388 if (Cond.getOpcode() == ISD::SETCC)
4389 Cond = LowerSETCC(Cond, DAG);
4391 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4392 // setting operand in place of the X86ISD::SETCC.
4393 if (Cond.getOpcode() == X86ISD::SETCC) {
4394 CC = Cond.getOperand(0);
4396 SDOperand Cmp = Cond.getOperand(1);
4397 unsigned Opc = Cmp.getOpcode();
4398 MVT::ValueType VT = Op.getValueType();
4400 bool IllegalFPCMov = false;
4401 if (MVT::isFloatingPoint(VT) && !MVT::isVector(VT) &&
4402 !isScalarFPTypeInSSEReg(VT)) // FPStack?
4403 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4405 if ((Opc == X86ISD::CMP ||
4406 Opc == X86ISD::COMI ||
4407 Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
4414 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4415 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4418 const MVT::ValueType *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4420 SmallVector<SDOperand, 4> Ops;
4421 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4422 // condition is true.
4423 Ops.push_back(Op.getOperand(2));
4424 Ops.push_back(Op.getOperand(1));
4426 Ops.push_back(Cond);
4427 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
4430 SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
4431 bool addTest = true;
4432 SDOperand Chain = Op.getOperand(0);
4433 SDOperand Cond = Op.getOperand(1);
4434 SDOperand Dest = Op.getOperand(2);
4437 if (Cond.getOpcode() == ISD::SETCC)
4438 Cond = LowerSETCC(Cond, DAG);
4440 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4441 // setting operand in place of the X86ISD::SETCC.
4442 if (Cond.getOpcode() == X86ISD::SETCC) {
4443 CC = Cond.getOperand(0);
4445 SDOperand Cmp = Cond.getOperand(1);
4446 unsigned Opc = Cmp.getOpcode();
4447 if (Opc == X86ISD::CMP ||
4448 Opc == X86ISD::COMI ||
4449 Opc == X86ISD::UCOMI) {
4456 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4457 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4459 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
4460 Chain, Op.getOperand(2), CC, Cond);
4464 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
4465 // Calls to _alloca is needed to probe the stack when allocating more than 4k
4466 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
4467 // that the guard pages used by the OS virtual memory manager are allocated in
4468 // correct sequence.
4470 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDOperand Op,
4471 SelectionDAG &DAG) {
4472 assert(Subtarget->isTargetCygMing() &&
4473 "This should be used only on Cygwin/Mingw targets");
4476 SDOperand Chain = Op.getOperand(0);
4477 SDOperand Size = Op.getOperand(1);
4478 // FIXME: Ensure alignment here
4482 MVT::ValueType IntPtr = getPointerTy();
4483 MVT::ValueType SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
4485 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
4486 Flag = Chain.getValue(1);
4488 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4489 SDOperand Ops[] = { Chain,
4490 DAG.getTargetExternalSymbol("_alloca", IntPtr),
4491 DAG.getRegister(X86::EAX, IntPtr),
4493 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 4);
4494 Flag = Chain.getValue(1);
4496 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
4498 std::vector<MVT::ValueType> Tys;
4499 Tys.push_back(SPTy);
4500 Tys.push_back(MVT::Other);
4501 SDOperand Ops1[2] = { Chain.getValue(0), Chain };
4502 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops1, 2);
4505 SDOperand X86TargetLowering::LowerMEMSET(SDOperand Op, SelectionDAG &DAG) {
4506 SDOperand InFlag(0, 0);
4507 SDOperand Chain = Op.getOperand(0);
4509 (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
4510 if (Align == 0) Align = 1;
4512 ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4513 // If not DWORD aligned or size is more than the threshold, call memset.
4514 // The libc version is likely to be faster for these cases. It can use the
4515 // address value and run time information about the CPU.
4516 if ((Align & 3) != 0 ||
4517 (I && I->getValue() > Subtarget->getMaxInlineSizeThreshold())) {
4518 MVT::ValueType IntPtr = getPointerTy();
4519 const Type *IntPtrTy = getTargetData()->getIntPtrType();
4520 TargetLowering::ArgListTy Args;
4521 TargetLowering::ArgListEntry Entry;
4522 Entry.Node = Op.getOperand(1);
4523 Entry.Ty = IntPtrTy;
4524 Args.push_back(Entry);
4525 // Extend the unsigned i8 argument to be an int value for the call.
4526 Entry.Node = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Op.getOperand(2));
4527 Entry.Ty = IntPtrTy;
4528 Args.push_back(Entry);
4529 Entry.Node = Op.getOperand(3);
4530 Args.push_back(Entry);
4531 std::pair<SDOperand,SDOperand> CallResult =
4532 LowerCallTo(Chain, Type::VoidTy, false, false, CallingConv::C, false,
4533 DAG.getExternalSymbol("memset", IntPtr), Args, DAG);
4534 return CallResult.second;
4539 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Op.getOperand(2));
4540 unsigned BytesLeft = 0;
4541 bool TwoRepStos = false;
4544 uint64_t Val = ValC->getValue() & 255;
4546 // If the value is a constant, then we can potentially use larger sets.
4547 switch (Align & 3) {
4548 case 2: // WORD aligned
4551 Val = (Val << 8) | Val;
4553 case 0: // DWORD aligned
4556 Val = (Val << 8) | Val;
4557 Val = (Val << 16) | Val;
4558 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) { // QWORD aligned
4561 Val = (Val << 32) | Val;
4564 default: // Byte aligned
4567 Count = Op.getOperand(3);
4571 if (AVT > MVT::i8) {
4573 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4574 Count = DAG.getIntPtrConstant(I->getValue() / UBytes);
4575 BytesLeft = I->getValue() % UBytes;
4577 assert(AVT >= MVT::i32 &&
4578 "Do not use rep;stos if not at least DWORD aligned");
4579 Count = DAG.getNode(ISD::SRL, Op.getOperand(3).getValueType(),
4580 Op.getOperand(3), DAG.getConstant(2, MVT::i8));
4585 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
4587 InFlag = Chain.getValue(1);
4590 Count = Op.getOperand(3);
4591 Chain = DAG.getCopyToReg(Chain, X86::AL, Op.getOperand(2), InFlag);
4592 InFlag = Chain.getValue(1);
4595 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4597 InFlag = Chain.getValue(1);
4598 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4599 Op.getOperand(1), InFlag);
4600 InFlag = Chain.getValue(1);
4602 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4603 SmallVector<SDOperand, 8> Ops;
4604 Ops.push_back(Chain);
4605 Ops.push_back(DAG.getValueType(AVT));
4606 Ops.push_back(InFlag);
4607 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4610 InFlag = Chain.getValue(1);
4611 Count = Op.getOperand(3);
4612 MVT::ValueType CVT = Count.getValueType();
4613 SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
4614 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
4615 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
4617 InFlag = Chain.getValue(1);
4618 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4620 Ops.push_back(Chain);
4621 Ops.push_back(DAG.getValueType(MVT::i8));
4622 Ops.push_back(InFlag);
4623 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4624 } else if (BytesLeft) {
4625 // Issue stores for the last 1 - 7 bytes.
4627 unsigned Val = ValC->getValue() & 255;
4628 unsigned Offset = I->getValue() - BytesLeft;
4629 SDOperand DstAddr = Op.getOperand(1);
4630 MVT::ValueType AddrVT = DstAddr.getValueType();
4631 if (BytesLeft >= 4) {
4632 Val = (Val << 8) | Val;
4633 Val = (Val << 16) | Val;
4634 Value = DAG.getConstant(Val, MVT::i32);
4635 Chain = DAG.getStore(Chain, Value,
4636 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4637 DAG.getConstant(Offset, AddrVT)),
4642 if (BytesLeft >= 2) {
4643 Value = DAG.getConstant((Val << 8) | Val, MVT::i16);
4644 Chain = DAG.getStore(Chain, Value,
4645 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4646 DAG.getConstant(Offset, AddrVT)),
4651 if (BytesLeft == 1) {
4652 Value = DAG.getConstant(Val, MVT::i8);
4653 Chain = DAG.getStore(Chain, Value,
4654 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4655 DAG.getConstant(Offset, AddrVT)),
4663 SDOperand X86TargetLowering::LowerMEMCPYInline(SDOperand Chain,
4668 SelectionDAG &DAG) {
4670 unsigned BytesLeft = 0;
4671 switch (Align & 3) {
4672 case 2: // WORD aligned
4675 case 0: // DWORD aligned
4677 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) // QWORD aligned
4680 default: // Byte aligned
4685 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4686 SDOperand Count = DAG.getIntPtrConstant(Size / UBytes);
4687 BytesLeft = Size % UBytes;
4689 SDOperand InFlag(0, 0);
4690 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4692 InFlag = Chain.getValue(1);
4693 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4695 InFlag = Chain.getValue(1);
4696 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
4698 InFlag = Chain.getValue(1);
4700 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4701 SmallVector<SDOperand, 8> Ops;
4702 Ops.push_back(Chain);
4703 Ops.push_back(DAG.getValueType(AVT));
4704 Ops.push_back(InFlag);
4705 Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
4708 // Issue loads and stores for the last 1 - 7 bytes.
4709 unsigned Offset = Size - BytesLeft;
4710 SDOperand DstAddr = Dest;
4711 MVT::ValueType DstVT = DstAddr.getValueType();
4712 SDOperand SrcAddr = Source;
4713 MVT::ValueType SrcVT = SrcAddr.getValueType();
4715 if (BytesLeft >= 4) {
4716 Value = DAG.getLoad(MVT::i32, Chain,
4717 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4718 DAG.getConstant(Offset, SrcVT)),
4720 Chain = Value.getValue(1);
4721 Chain = DAG.getStore(Chain, Value,
4722 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4723 DAG.getConstant(Offset, DstVT)),
4728 if (BytesLeft >= 2) {
4729 Value = DAG.getLoad(MVT::i16, Chain,
4730 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4731 DAG.getConstant(Offset, SrcVT)),
4733 Chain = Value.getValue(1);
4734 Chain = DAG.getStore(Chain, Value,
4735 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4736 DAG.getConstant(Offset, DstVT)),
4742 if (BytesLeft == 1) {
4743 Value = DAG.getLoad(MVT::i8, Chain,
4744 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4745 DAG.getConstant(Offset, SrcVT)),
4747 Chain = Value.getValue(1);
4748 Chain = DAG.getStore(Chain, Value,
4749 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4750 DAG.getConstant(Offset, DstVT)),
4758 /// Expand the result of: i64,outchain = READCYCLECOUNTER inchain
4759 SDNode *X86TargetLowering::ExpandREADCYCLECOUNTER(SDNode *N, SelectionDAG &DAG){
4760 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4761 SDOperand TheChain = N->getOperand(0);
4762 SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
4763 if (Subtarget->is64Bit()) {
4764 SDOperand rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
4765 SDOperand rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX,
4766 MVT::i64, rax.getValue(2));
4767 SDOperand Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
4768 DAG.getConstant(32, MVT::i8));
4770 DAG.getNode(ISD::OR, MVT::i64, rax, Tmp), rdx.getValue(1)
4773 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4774 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4777 SDOperand eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
4778 SDOperand edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX,
4779 MVT::i32, eax.getValue(2));
4780 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
4781 SDOperand Ops[] = { eax, edx };
4782 Ops[0] = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2);
4784 // Use a MERGE_VALUES to return the value and chain.
4785 Ops[1] = edx.getValue(1);
4786 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4787 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4790 SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
4791 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4793 if (!Subtarget->is64Bit()) {
4794 // vastart just stores the address of the VarArgsFrameIndex slot into the
4795 // memory location argument.
4796 SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4797 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV, 0);
4801 // gp_offset (0 - 6 * 8)
4802 // fp_offset (48 - 48 + 8 * 16)
4803 // overflow_arg_area (point to parameters coming in memory).
4805 SmallVector<SDOperand, 8> MemOps;
4806 SDOperand FIN = Op.getOperand(1);
4808 SDOperand Store = DAG.getStore(Op.getOperand(0),
4809 DAG.getConstant(VarArgsGPOffset, MVT::i32),
4811 MemOps.push_back(Store);
4814 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
4815 Store = DAG.getStore(Op.getOperand(0),
4816 DAG.getConstant(VarArgsFPOffset, MVT::i32),
4818 MemOps.push_back(Store);
4820 // Store ptr to overflow_arg_area
4821 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
4822 SDOperand OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4823 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV, 0);
4824 MemOps.push_back(Store);
4826 // Store ptr to reg_save_area.
4827 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
4828 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
4829 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV, 0);
4830 MemOps.push_back(Store);
4831 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
4834 SDOperand X86TargetLowering::LowerVACOPY(SDOperand Op, SelectionDAG &DAG) {
4835 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
4836 SDOperand Chain = Op.getOperand(0);
4837 SDOperand DstPtr = Op.getOperand(1);
4838 SDOperand SrcPtr = Op.getOperand(2);
4839 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4840 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4842 SrcPtr = DAG.getLoad(getPointerTy(), Chain, SrcPtr, SrcSV, 0);
4843 Chain = SrcPtr.getValue(1);
4844 for (unsigned i = 0; i < 3; ++i) {
4845 SDOperand Val = DAG.getLoad(MVT::i64, Chain, SrcPtr, SrcSV, 0);
4846 Chain = Val.getValue(1);
4847 Chain = DAG.getStore(Chain, Val, DstPtr, DstSV, 0);
4850 SrcPtr = DAG.getNode(ISD::ADD, getPointerTy(), SrcPtr,
4851 DAG.getIntPtrConstant(8));
4852 DstPtr = DAG.getNode(ISD::ADD, getPointerTy(), DstPtr,
4853 DAG.getIntPtrConstant(8));
4859 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
4860 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
4862 default: return SDOperand(); // Don't custom lower most intrinsics.
4863 // Comparison intrinsics.
4864 case Intrinsic::x86_sse_comieq_ss:
4865 case Intrinsic::x86_sse_comilt_ss:
4866 case Intrinsic::x86_sse_comile_ss:
4867 case Intrinsic::x86_sse_comigt_ss:
4868 case Intrinsic::x86_sse_comige_ss:
4869 case Intrinsic::x86_sse_comineq_ss:
4870 case Intrinsic::x86_sse_ucomieq_ss:
4871 case Intrinsic::x86_sse_ucomilt_ss:
4872 case Intrinsic::x86_sse_ucomile_ss:
4873 case Intrinsic::x86_sse_ucomigt_ss:
4874 case Intrinsic::x86_sse_ucomige_ss:
4875 case Intrinsic::x86_sse_ucomineq_ss:
4876 case Intrinsic::x86_sse2_comieq_sd:
4877 case Intrinsic::x86_sse2_comilt_sd:
4878 case Intrinsic::x86_sse2_comile_sd:
4879 case Intrinsic::x86_sse2_comigt_sd:
4880 case Intrinsic::x86_sse2_comige_sd:
4881 case Intrinsic::x86_sse2_comineq_sd:
4882 case Intrinsic::x86_sse2_ucomieq_sd:
4883 case Intrinsic::x86_sse2_ucomilt_sd:
4884 case Intrinsic::x86_sse2_ucomile_sd:
4885 case Intrinsic::x86_sse2_ucomigt_sd:
4886 case Intrinsic::x86_sse2_ucomige_sd:
4887 case Intrinsic::x86_sse2_ucomineq_sd: {
4889 ISD::CondCode CC = ISD::SETCC_INVALID;
4892 case Intrinsic::x86_sse_comieq_ss:
4893 case Intrinsic::x86_sse2_comieq_sd:
4897 case Intrinsic::x86_sse_comilt_ss:
4898 case Intrinsic::x86_sse2_comilt_sd:
4902 case Intrinsic::x86_sse_comile_ss:
4903 case Intrinsic::x86_sse2_comile_sd:
4907 case Intrinsic::x86_sse_comigt_ss:
4908 case Intrinsic::x86_sse2_comigt_sd:
4912 case Intrinsic::x86_sse_comige_ss:
4913 case Intrinsic::x86_sse2_comige_sd:
4917 case Intrinsic::x86_sse_comineq_ss:
4918 case Intrinsic::x86_sse2_comineq_sd:
4922 case Intrinsic::x86_sse_ucomieq_ss:
4923 case Intrinsic::x86_sse2_ucomieq_sd:
4924 Opc = X86ISD::UCOMI;
4927 case Intrinsic::x86_sse_ucomilt_ss:
4928 case Intrinsic::x86_sse2_ucomilt_sd:
4929 Opc = X86ISD::UCOMI;
4932 case Intrinsic::x86_sse_ucomile_ss:
4933 case Intrinsic::x86_sse2_ucomile_sd:
4934 Opc = X86ISD::UCOMI;
4937 case Intrinsic::x86_sse_ucomigt_ss:
4938 case Intrinsic::x86_sse2_ucomigt_sd:
4939 Opc = X86ISD::UCOMI;
4942 case Intrinsic::x86_sse_ucomige_ss:
4943 case Intrinsic::x86_sse2_ucomige_sd:
4944 Opc = X86ISD::UCOMI;
4947 case Intrinsic::x86_sse_ucomineq_ss:
4948 case Intrinsic::x86_sse2_ucomineq_sd:
4949 Opc = X86ISD::UCOMI;
4955 SDOperand LHS = Op.getOperand(1);
4956 SDOperand RHS = Op.getOperand(2);
4957 translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
4959 SDOperand Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
4960 SDOperand SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
4961 DAG.getConstant(X86CC, MVT::i8), Cond);
4962 return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
4967 SDOperand X86TargetLowering::LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
4968 // Depths > 0 not supported yet!
4969 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
4972 // Just load the return address
4973 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
4974 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
4977 SDOperand X86TargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG) {
4978 // Depths > 0 not supported yet!
4979 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
4982 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
4983 return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI,
4984 DAG.getIntPtrConstant(4));
4987 SDOperand X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDOperand Op,
4988 SelectionDAG &DAG) {
4989 // Is not yet supported on x86-64
4990 if (Subtarget->is64Bit())
4993 return DAG.getIntPtrConstant(8);
4996 SDOperand X86TargetLowering::LowerEH_RETURN(SDOperand Op, SelectionDAG &DAG)
4998 assert(!Subtarget->is64Bit() &&
4999 "Lowering of eh_return builtin is not supported yet on x86-64");
5001 MachineFunction &MF = DAG.getMachineFunction();
5002 SDOperand Chain = Op.getOperand(0);
5003 SDOperand Offset = Op.getOperand(1);
5004 SDOperand Handler = Op.getOperand(2);
5006 SDOperand Frame = DAG.getRegister(RegInfo->getFrameRegister(MF),
5009 SDOperand StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
5010 DAG.getIntPtrConstant(-4UL));
5011 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
5012 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
5013 Chain = DAG.getCopyToReg(Chain, X86::ECX, StoreAddr);
5014 MF.getRegInfo().addLiveOut(X86::ECX);
5016 return DAG.getNode(X86ISD::EH_RETURN, MVT::Other,
5017 Chain, DAG.getRegister(X86::ECX, getPointerTy()));
5020 SDOperand X86TargetLowering::LowerTRAMPOLINE(SDOperand Op,
5021 SelectionDAG &DAG) {
5022 SDOperand Root = Op.getOperand(0);
5023 SDOperand Trmp = Op.getOperand(1); // trampoline
5024 SDOperand FPtr = Op.getOperand(2); // nested function
5025 SDOperand Nest = Op.getOperand(3); // 'nest' parameter value
5027 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5029 const X86InstrInfo *TII =
5030 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5032 if (Subtarget->is64Bit()) {
5033 SDOperand OutChains[6];
5035 // Large code-model.
5037 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
5038 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
5040 const unsigned char N86R10 =
5041 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(X86::R10);
5042 const unsigned char N86R11 =
5043 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(X86::R11);
5045 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
5047 // Load the pointer to the nested function into R11.
5048 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
5049 SDOperand Addr = Trmp;
5050 OutChains[0] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5053 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(2, MVT::i64));
5054 OutChains[1] = DAG.getStore(Root, FPtr, Addr, TrmpAddr, 2, false, 2);
5056 // Load the 'nest' parameter value into R10.
5057 // R10 is specified in X86CallingConv.td
5058 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
5059 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(10, MVT::i64));
5060 OutChains[2] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5063 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(12, MVT::i64));
5064 OutChains[3] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 12, false, 2);
5066 // Jump to the nested function.
5067 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
5068 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(20, MVT::i64));
5069 OutChains[4] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5072 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
5073 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(22, MVT::i64));
5074 OutChains[5] = DAG.getStore(Root, DAG.getConstant(ModRM, MVT::i8), Addr,
5078 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 6) };
5079 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5081 const Function *Func =
5082 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5083 unsigned CC = Func->getCallingConv();
5088 assert(0 && "Unsupported calling convention");
5089 case CallingConv::C:
5090 case CallingConv::X86_StdCall: {
5091 // Pass 'nest' parameter in ECX.
5092 // Must be kept in sync with X86CallingConv.td
5095 // Check that ECX wasn't needed by an 'inreg' parameter.
5096 const FunctionType *FTy = Func->getFunctionType();
5097 const ParamAttrsList *Attrs = Func->getParamAttrs();
5099 if (Attrs && !Func->isVarArg()) {
5100 unsigned InRegCount = 0;
5103 for (FunctionType::param_iterator I = FTy->param_begin(),
5104 E = FTy->param_end(); I != E; ++I, ++Idx)
5105 if (Attrs->paramHasAttr(Idx, ParamAttr::InReg))
5106 // FIXME: should only count parameters that are lowered to integers.
5107 InRegCount += (getTargetData()->getTypeSizeInBits(*I) + 31) / 32;
5109 if (InRegCount > 2) {
5110 cerr << "Nest register in use - reduce number of inreg parameters!\n";
5116 case CallingConv::X86_FastCall:
5117 // Pass 'nest' parameter in EAX.
5118 // Must be kept in sync with X86CallingConv.td
5123 SDOperand OutChains[4];
5124 SDOperand Addr, Disp;
5126 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5127 Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5129 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
5130 const unsigned char N86Reg =
5131 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(NestReg);
5132 OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
5135 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
5136 OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 1, false, 1);
5138 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
5139 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
5140 OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
5141 TrmpAddr, 5, false, 1);
5143 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
5144 OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpAddr, 6, false, 1);
5147 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
5148 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5152 SDOperand X86TargetLowering::LowerFLT_ROUNDS_(SDOperand Op, SelectionDAG &DAG) {
5154 The rounding mode is in bits 11:10 of FPSR, and has the following
5161 FLT_ROUNDS, on the other hand, expects the following:
5168 To perform the conversion, we do:
5169 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
5172 MachineFunction &MF = DAG.getMachineFunction();
5173 const TargetMachine &TM = MF.getTarget();
5174 const TargetFrameInfo &TFI = *TM.getFrameInfo();
5175 unsigned StackAlignment = TFI.getStackAlignment();
5176 MVT::ValueType VT = Op.getValueType();
5178 // Save FP Control Word to stack slot
5179 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
5180 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5182 SDOperand Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
5183 DAG.getEntryNode(), StackSlot);
5185 // Load FP Control Word from stack slot
5186 SDOperand CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
5188 // Transform as necessary
5190 DAG.getNode(ISD::SRL, MVT::i16,
5191 DAG.getNode(ISD::AND, MVT::i16,
5192 CWD, DAG.getConstant(0x800, MVT::i16)),
5193 DAG.getConstant(11, MVT::i8));
5195 DAG.getNode(ISD::SRL, MVT::i16,
5196 DAG.getNode(ISD::AND, MVT::i16,
5197 CWD, DAG.getConstant(0x400, MVT::i16)),
5198 DAG.getConstant(9, MVT::i8));
5201 DAG.getNode(ISD::AND, MVT::i16,
5202 DAG.getNode(ISD::ADD, MVT::i16,
5203 DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
5204 DAG.getConstant(1, MVT::i16)),
5205 DAG.getConstant(3, MVT::i16));
5208 return DAG.getNode((MVT::getSizeInBits(VT) < 16 ?
5209 ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
5212 SDOperand X86TargetLowering::LowerCTLZ(SDOperand Op, SelectionDAG &DAG) {
5213 MVT::ValueType VT = Op.getValueType();
5214 MVT::ValueType OpVT = VT;
5215 unsigned NumBits = MVT::getSizeInBits(VT);
5217 Op = Op.getOperand(0);
5218 if (VT == MVT::i8) {
5219 // Zero extend to i32 since there is not an i8 bsr.
5221 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5224 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
5225 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5226 Op = DAG.getNode(X86ISD::BSR, VTs, Op);
5228 // If src is zero (i.e. bsr sets ZF), returns NumBits.
5229 SmallVector<SDOperand, 4> Ops;
5231 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
5232 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5233 Ops.push_back(Op.getValue(1));
5234 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5236 // Finally xor with NumBits-1.
5237 Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
5240 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5244 SDOperand X86TargetLowering::LowerCTTZ(SDOperand Op, SelectionDAG &DAG) {
5245 MVT::ValueType VT = Op.getValueType();
5246 MVT::ValueType OpVT = VT;
5247 unsigned NumBits = MVT::getSizeInBits(VT);
5249 Op = Op.getOperand(0);
5250 if (VT == MVT::i8) {
5252 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5255 // Issue a bsf (scan bits forward) which also sets EFLAGS.
5256 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5257 Op = DAG.getNode(X86ISD::BSF, VTs, Op);
5259 // If src is zero (i.e. bsf sets ZF), returns NumBits.
5260 SmallVector<SDOperand, 4> Ops;
5262 Ops.push_back(DAG.getConstant(NumBits, OpVT));
5263 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5264 Ops.push_back(Op.getValue(1));
5265 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5268 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5272 /// LowerOperation - Provide custom lowering hooks for some operations.
5274 SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
5275 switch (Op.getOpcode()) {
5276 default: assert(0 && "Should not custom lower this!");
5277 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5278 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5279 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5280 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5281 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5282 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5283 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5284 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5285 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
5286 case ISD::SHL_PARTS:
5287 case ISD::SRA_PARTS:
5288 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
5289 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
5290 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
5291 case ISD::FABS: return LowerFABS(Op, DAG);
5292 case ISD::FNEG: return LowerFNEG(Op, DAG);
5293 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5294 case ISD::SETCC: return LowerSETCC(Op, DAG);
5295 case ISD::SELECT: return LowerSELECT(Op, DAG);
5296 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
5297 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5298 case ISD::CALL: return LowerCALL(Op, DAG);
5299 case ISD::RET: return LowerRET(Op, DAG);
5300 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
5301 case ISD::MEMSET: return LowerMEMSET(Op, DAG);
5302 case ISD::MEMCPY: return LowerMEMCPY(Op, DAG);
5303 case ISD::VASTART: return LowerVASTART(Op, DAG);
5304 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
5305 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5306 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5307 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5308 case ISD::FRAME_TO_ARGS_OFFSET:
5309 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
5310 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
5311 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
5312 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
5313 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5314 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
5315 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
5317 // FIXME: REMOVE THIS WHEN LegalizeDAGTypes lands.
5318 case ISD::READCYCLECOUNTER:
5319 return SDOperand(ExpandREADCYCLECOUNTER(Op.Val, DAG), 0);
5323 /// ExpandOperation - Provide custom lowering hooks for expanding operations.
5324 SDNode *X86TargetLowering::ExpandOperationResult(SDNode *N, SelectionDAG &DAG) {
5325 switch (N->getOpcode()) {
5326 default: assert(0 && "Should not custom lower this!");
5327 case ISD::FP_TO_SINT: return ExpandFP_TO_SINT(N, DAG);
5328 case ISD::READCYCLECOUNTER: return ExpandREADCYCLECOUNTER(N, DAG);
5332 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
5334 default: return NULL;
5335 case X86ISD::BSF: return "X86ISD::BSF";
5336 case X86ISD::BSR: return "X86ISD::BSR";
5337 case X86ISD::SHLD: return "X86ISD::SHLD";
5338 case X86ISD::SHRD: return "X86ISD::SHRD";
5339 case X86ISD::FAND: return "X86ISD::FAND";
5340 case X86ISD::FOR: return "X86ISD::FOR";
5341 case X86ISD::FXOR: return "X86ISD::FXOR";
5342 case X86ISD::FSRL: return "X86ISD::FSRL";
5343 case X86ISD::FILD: return "X86ISD::FILD";
5344 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
5345 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
5346 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
5347 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
5348 case X86ISD::FLD: return "X86ISD::FLD";
5349 case X86ISD::FST: return "X86ISD::FST";
5350 case X86ISD::FP_GET_RESULT: return "X86ISD::FP_GET_RESULT";
5351 case X86ISD::FP_GET_RESULT2: return "X86ISD::FP_GET_RESULT2";
5352 case X86ISD::FP_SET_RESULT: return "X86ISD::FP_SET_RESULT";
5353 case X86ISD::CALL: return "X86ISD::CALL";
5354 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
5355 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
5356 case X86ISD::CMP: return "X86ISD::CMP";
5357 case X86ISD::COMI: return "X86ISD::COMI";
5358 case X86ISD::UCOMI: return "X86ISD::UCOMI";
5359 case X86ISD::SETCC: return "X86ISD::SETCC";
5360 case X86ISD::CMOV: return "X86ISD::CMOV";
5361 case X86ISD::BRCOND: return "X86ISD::BRCOND";
5362 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
5363 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
5364 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
5365 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
5366 case X86ISD::Wrapper: return "X86ISD::Wrapper";
5367 case X86ISD::S2VEC: return "X86ISD::S2VEC";
5368 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
5369 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
5370 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
5371 case X86ISD::PINSRB: return "X86ISD::PINSRB";
5372 case X86ISD::PINSRW: return "X86ISD::PINSRW";
5373 case X86ISD::FMAX: return "X86ISD::FMAX";
5374 case X86ISD::FMIN: return "X86ISD::FMIN";
5375 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
5376 case X86ISD::FRCP: return "X86ISD::FRCP";
5377 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
5378 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
5379 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
5380 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
5381 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
5385 // isLegalAddressingMode - Return true if the addressing mode represented
5386 // by AM is legal for this target, for a load/store of the specified type.
5387 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
5388 const Type *Ty) const {
5389 // X86 supports extremely general addressing modes.
5391 // X86 allows a sign-extended 32-bit immediate field as a displacement.
5392 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
5396 // We can only fold this if we don't need an extra load.
5397 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
5400 // X86-64 only supports addr of globals in small code model.
5401 if (Subtarget->is64Bit()) {
5402 if (getTargetMachine().getCodeModel() != CodeModel::Small)
5404 // If lower 4G is not available, then we must use rip-relative addressing.
5405 if (AM.BaseOffs || AM.Scale > 1)
5416 // These scales always work.
5421 // These scales are formed with basereg+scalereg. Only accept if there is
5426 default: // Other stuff never works.
5434 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
5435 if (!Ty1->isInteger() || !Ty2->isInteger())
5437 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5438 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5439 if (NumBits1 <= NumBits2)
5441 return Subtarget->is64Bit() || NumBits1 < 64;
5444 bool X86TargetLowering::isTruncateFree(MVT::ValueType VT1,
5445 MVT::ValueType VT2) const {
5446 if (!MVT::isInteger(VT1) || !MVT::isInteger(VT2))
5448 unsigned NumBits1 = MVT::getSizeInBits(VT1);
5449 unsigned NumBits2 = MVT::getSizeInBits(VT2);
5450 if (NumBits1 <= NumBits2)
5452 return Subtarget->is64Bit() || NumBits1 < 64;
5455 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5456 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5457 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5458 /// are assumed to be legal.
5460 X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
5461 // Only do shuffles on 128-bit vector types for now.
5462 if (MVT::getSizeInBits(VT) == 64) return false;
5463 return (Mask.Val->getNumOperands() <= 4 ||
5464 isIdentityMask(Mask.Val) ||
5465 isIdentityMask(Mask.Val, true) ||
5466 isSplatMask(Mask.Val) ||
5467 isPSHUFHW_PSHUFLWMask(Mask.Val) ||
5468 X86::isUNPCKLMask(Mask.Val) ||
5469 X86::isUNPCKHMask(Mask.Val) ||
5470 X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
5471 X86::isUNPCKH_v_undef_Mask(Mask.Val));
5474 bool X86TargetLowering::isVectorClearMaskLegal(std::vector<SDOperand> &BVOps,
5476 SelectionDAG &DAG) const {
5477 unsigned NumElts = BVOps.size();
5478 // Only do shuffles on 128-bit vector types for now.
5479 if (MVT::getSizeInBits(EVT) * NumElts == 64) return false;
5480 if (NumElts == 2) return true;
5482 return (isMOVLMask(&BVOps[0], 4) ||
5483 isCommutedMOVL(&BVOps[0], 4, true) ||
5484 isSHUFPMask(&BVOps[0], 4) ||
5485 isCommutedSHUFP(&BVOps[0], 4));
5490 //===----------------------------------------------------------------------===//
5491 // X86 Scheduler Hooks
5492 //===----------------------------------------------------------------------===//
5495 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
5496 MachineBasicBlock *BB) {
5497 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5498 switch (MI->getOpcode()) {
5499 default: assert(false && "Unexpected instr type to insert");
5500 case X86::CMOV_FR32:
5501 case X86::CMOV_FR64:
5502 case X86::CMOV_V4F32:
5503 case X86::CMOV_V2F64:
5504 case X86::CMOV_V2I64: {
5505 // To "insert" a SELECT_CC instruction, we actually have to insert the
5506 // diamond control-flow pattern. The incoming instruction knows the
5507 // destination vreg to set, the condition code register to branch on, the
5508 // true/false values to select between, and a branch opcode to use.
5509 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5510 ilist<MachineBasicBlock>::iterator It = BB;
5516 // cmpTY ccX, r1, r2
5518 // fallthrough --> copy0MBB
5519 MachineBasicBlock *thisMBB = BB;
5520 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
5521 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
5523 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
5524 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
5525 MachineFunction *F = BB->getParent();
5526 F->getBasicBlockList().insert(It, copy0MBB);
5527 F->getBasicBlockList().insert(It, sinkMBB);
5528 // Update machine-CFG edges by first adding all successors of the current
5529 // block to the new block which will contain the Phi node for the select.
5530 for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
5531 e = BB->succ_end(); i != e; ++i)
5532 sinkMBB->addSuccessor(*i);
5533 // Next, remove all successors of the current block, and add the true
5534 // and fallthrough blocks as its successors.
5535 while(!BB->succ_empty())
5536 BB->removeSuccessor(BB->succ_begin());
5537 BB->addSuccessor(copy0MBB);
5538 BB->addSuccessor(sinkMBB);
5541 // %FalseValue = ...
5542 // # fallthrough to sinkMBB
5545 // Update machine-CFG edges
5546 BB->addSuccessor(sinkMBB);
5549 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
5552 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
5553 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
5554 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
5556 delete MI; // The pseudo instruction is gone now.
5560 case X86::FP32_TO_INT16_IN_MEM:
5561 case X86::FP32_TO_INT32_IN_MEM:
5562 case X86::FP32_TO_INT64_IN_MEM:
5563 case X86::FP64_TO_INT16_IN_MEM:
5564 case X86::FP64_TO_INT32_IN_MEM:
5565 case X86::FP64_TO_INT64_IN_MEM:
5566 case X86::FP80_TO_INT16_IN_MEM:
5567 case X86::FP80_TO_INT32_IN_MEM:
5568 case X86::FP80_TO_INT64_IN_MEM: {
5569 // Change the floating point control register to use "round towards zero"
5570 // mode when truncating to an integer value.
5571 MachineFunction *F = BB->getParent();
5572 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
5573 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
5575 // Load the old value of the high byte of the control word...
5577 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
5578 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
5580 // Set the high part to be round to zero...
5581 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
5584 // Reload the modified control word now...
5585 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5587 // Restore the memory image of control word to original value
5588 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
5591 // Get the X86 opcode to use.
5593 switch (MI->getOpcode()) {
5594 default: assert(0 && "illegal opcode!");
5595 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
5596 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
5597 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
5598 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
5599 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
5600 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
5601 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
5602 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
5603 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
5607 MachineOperand &Op = MI->getOperand(0);
5608 if (Op.isRegister()) {
5609 AM.BaseType = X86AddressMode::RegBase;
5610 AM.Base.Reg = Op.getReg();
5612 AM.BaseType = X86AddressMode::FrameIndexBase;
5613 AM.Base.FrameIndex = Op.getIndex();
5615 Op = MI->getOperand(1);
5616 if (Op.isImmediate())
5617 AM.Scale = Op.getImm();
5618 Op = MI->getOperand(2);
5619 if (Op.isImmediate())
5620 AM.IndexReg = Op.getImm();
5621 Op = MI->getOperand(3);
5622 if (Op.isGlobalAddress()) {
5623 AM.GV = Op.getGlobal();
5625 AM.Disp = Op.getImm();
5627 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
5628 .addReg(MI->getOperand(4).getReg());
5630 // Reload the original control word now.
5631 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5633 delete MI; // The pseudo instruction is gone now.
5639 //===----------------------------------------------------------------------===//
5640 // X86 Optimization Hooks
5641 //===----------------------------------------------------------------------===//
5643 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
5645 uint64_t &KnownZero,
5647 const SelectionDAG &DAG,
5648 unsigned Depth) const {
5649 unsigned Opc = Op.getOpcode();
5650 assert((Opc >= ISD::BUILTIN_OP_END ||
5651 Opc == ISD::INTRINSIC_WO_CHAIN ||
5652 Opc == ISD::INTRINSIC_W_CHAIN ||
5653 Opc == ISD::INTRINSIC_VOID) &&
5654 "Should use MaskedValueIsZero if you don't know whether Op"
5655 " is a target node!");
5657 KnownZero = KnownOne = 0; // Don't know anything.
5661 KnownZero |= (MVT::getIntVTBitMask(Op.getValueType()) ^ 1ULL);
5666 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5667 /// element of the result of the vector shuffle.
5668 static SDOperand getShuffleScalarElt(SDNode *N, unsigned i, SelectionDAG &DAG) {
5669 MVT::ValueType VT = N->getValueType(0);
5670 SDOperand PermMask = N->getOperand(2);
5671 unsigned NumElems = PermMask.getNumOperands();
5672 SDOperand V = (i < NumElems) ? N->getOperand(0) : N->getOperand(1);
5674 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5676 ? V.getOperand(0) : DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5677 } else if (V.getOpcode() == ISD::VECTOR_SHUFFLE) {
5678 SDOperand Idx = PermMask.getOperand(i);
5679 if (Idx.getOpcode() == ISD::UNDEF)
5680 return DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5681 return getShuffleScalarElt(V.Val,cast<ConstantSDNode>(Idx)->getValue(),DAG);
5686 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
5687 /// node is a GlobalAddress + an offset.
5688 static bool isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) {
5689 unsigned Opc = N->getOpcode();
5690 if (Opc == X86ISD::Wrapper) {
5691 if (dyn_cast<GlobalAddressSDNode>(N->getOperand(0))) {
5692 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
5695 } else if (Opc == ISD::ADD) {
5696 SDOperand N1 = N->getOperand(0);
5697 SDOperand N2 = N->getOperand(1);
5698 if (isGAPlusOffset(N1.Val, GA, Offset)) {
5699 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
5701 Offset += V->getSignExtended();
5704 } else if (isGAPlusOffset(N2.Val, GA, Offset)) {
5705 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
5707 Offset += V->getSignExtended();
5715 /// isConsecutiveLoad - Returns true if N is loading from an address of Base
5717 static bool isConsecutiveLoad(SDNode *N, SDNode *Base, int Dist, int Size,
5718 MachineFrameInfo *MFI) {
5719 if (N->getOperand(0).Val != Base->getOperand(0).Val)
5722 SDOperand Loc = N->getOperand(1);
5723 SDOperand BaseLoc = Base->getOperand(1);
5724 if (Loc.getOpcode() == ISD::FrameIndex) {
5725 if (BaseLoc.getOpcode() != ISD::FrameIndex)
5727 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
5728 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
5729 int FS = MFI->getObjectSize(FI);
5730 int BFS = MFI->getObjectSize(BFI);
5731 if (FS != BFS || FS != Size) return false;
5732 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Size);
5734 GlobalValue *GV1 = NULL;
5735 GlobalValue *GV2 = NULL;
5736 int64_t Offset1 = 0;
5737 int64_t Offset2 = 0;
5738 bool isGA1 = isGAPlusOffset(Loc.Val, GV1, Offset1);
5739 bool isGA2 = isGAPlusOffset(BaseLoc.Val, GV2, Offset2);
5740 if (isGA1 && isGA2 && GV1 == GV2)
5741 return Offset1 == (Offset2 + Dist*Size);
5747 static bool isBaseAlignment16(SDNode *Base, MachineFrameInfo *MFI,
5748 const X86Subtarget *Subtarget) {
5751 if (isGAPlusOffset(Base, GV, Offset))
5752 return (GV->getAlignment() >= 16 && (Offset % 16) == 0);
5753 // DAG combine handles the stack object case.
5758 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
5759 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
5760 /// if the load addresses are consecutive, non-overlapping, and in the right
5762 static SDOperand PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
5763 const X86Subtarget *Subtarget) {
5764 MachineFunction &MF = DAG.getMachineFunction();
5765 MachineFrameInfo *MFI = MF.getFrameInfo();
5766 MVT::ValueType VT = N->getValueType(0);
5767 MVT::ValueType EVT = MVT::getVectorElementType(VT);
5768 SDOperand PermMask = N->getOperand(2);
5769 int NumElems = (int)PermMask.getNumOperands();
5770 SDNode *Base = NULL;
5771 for (int i = 0; i < NumElems; ++i) {
5772 SDOperand Idx = PermMask.getOperand(i);
5773 if (Idx.getOpcode() == ISD::UNDEF) {
5774 if (!Base) return SDOperand();
5777 getShuffleScalarElt(N, cast<ConstantSDNode>(Idx)->getValue(), DAG);
5778 if (!Arg.Val || !ISD::isNON_EXTLoad(Arg.Val))
5782 else if (!isConsecutiveLoad(Arg.Val, Base,
5783 i, MVT::getSizeInBits(EVT)/8,MFI))
5788 bool isAlign16 = isBaseAlignment16(Base->getOperand(1).Val, MFI, Subtarget);
5789 LoadSDNode *LD = cast<LoadSDNode>(Base);
5791 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
5792 LD->getSrcValueOffset(), LD->isVolatile());
5794 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
5795 LD->getSrcValueOffset(), LD->isVolatile(),
5796 LD->getAlignment());
5800 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
5801 static SDOperand PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
5802 const X86Subtarget *Subtarget) {
5803 SDOperand Cond = N->getOperand(0);
5805 // If we have SSE[12] support, try to form min/max nodes.
5806 if (Subtarget->hasSSE2() &&
5807 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
5808 if (Cond.getOpcode() == ISD::SETCC) {
5809 // Get the LHS/RHS of the select.
5810 SDOperand LHS = N->getOperand(1);
5811 SDOperand RHS = N->getOperand(2);
5812 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
5814 unsigned Opcode = 0;
5815 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
5818 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
5821 if (!UnsafeFPMath) break;
5823 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
5825 Opcode = X86ISD::FMIN;
5828 case ISD::SETOGT: // (X > Y) ? X : Y -> max
5831 if (!UnsafeFPMath) break;
5833 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
5835 Opcode = X86ISD::FMAX;
5838 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
5841 case ISD::SETOGT: // (X > Y) ? Y : X -> min
5844 if (!UnsafeFPMath) break;
5846 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
5848 Opcode = X86ISD::FMIN;
5851 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
5854 if (!UnsafeFPMath) break;
5856 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
5858 Opcode = X86ISD::FMAX;
5864 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
5872 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
5873 /// X86ISD::FXOR nodes.
5874 static SDOperand PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
5875 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
5876 // F[X]OR(0.0, x) -> x
5877 // F[X]OR(x, 0.0) -> x
5878 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
5879 if (C->getValueAPF().isPosZero())
5880 return N->getOperand(1);
5881 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
5882 if (C->getValueAPF().isPosZero())
5883 return N->getOperand(0);
5887 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
5888 static SDOperand PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
5889 // FAND(0.0, x) -> 0.0
5890 // FAND(x, 0.0) -> 0.0
5891 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
5892 if (C->getValueAPF().isPosZero())
5893 return N->getOperand(0);
5894 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
5895 if (C->getValueAPF().isPosZero())
5896 return N->getOperand(1);
5901 SDOperand X86TargetLowering::PerformDAGCombine(SDNode *N,
5902 DAGCombinerInfo &DCI) const {
5903 SelectionDAG &DAG = DCI.DAG;
5904 switch (N->getOpcode()) {
5906 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, Subtarget);
5907 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
5909 case X86ISD::FOR: return PerformFORCombine(N, DAG);
5910 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
5916 //===----------------------------------------------------------------------===//
5917 // X86 Inline Assembly Support
5918 //===----------------------------------------------------------------------===//
5920 /// getConstraintType - Given a constraint letter, return the type of
5921 /// constraint it is for this target.
5922 X86TargetLowering::ConstraintType
5923 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
5924 if (Constraint.size() == 1) {
5925 switch (Constraint[0]) {
5934 return C_RegisterClass;
5939 return TargetLowering::getConstraintType(Constraint);
5942 /// LowerXConstraint - try to replace an X constraint, which matches anything,
5943 /// with another that has more specific requirements based on the type of the
5944 /// corresponding operand.
5945 void X86TargetLowering::lowerXConstraint(MVT::ValueType ConstraintVT,
5946 std::string& s) const {
5947 if (MVT::isFloatingPoint(ConstraintVT)) {
5948 if (Subtarget->hasSSE2())
5950 else if (Subtarget->hasSSE1())
5955 return TargetLowering::lowerXConstraint(ConstraintVT, s);
5958 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5959 /// vector. If it is invalid, don't add anything to Ops.
5960 void X86TargetLowering::LowerAsmOperandForConstraint(SDOperand Op,
5962 std::vector<SDOperand>&Ops,
5963 SelectionDAG &DAG) {
5964 SDOperand Result(0, 0);
5966 switch (Constraint) {
5969 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
5970 if (C->getValue() <= 31) {
5971 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
5977 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
5978 if (C->getValue() <= 255) {
5979 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
5985 // Literal immediates are always ok.
5986 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
5987 Result = DAG.getTargetConstant(CST->getValue(), Op.getValueType());
5991 // If we are in non-pic codegen mode, we allow the address of a global (with
5992 // an optional displacement) to be used with 'i'.
5993 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
5996 // Match either (GA) or (GA+C)
5998 Offset = GA->getOffset();
5999 } else if (Op.getOpcode() == ISD::ADD) {
6000 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6001 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6003 Offset = GA->getOffset()+C->getValue();
6005 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6006 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6008 Offset = GA->getOffset()+C->getValue();
6015 // If addressing this global requires a load (e.g. in PIC mode), we can't
6017 if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
6021 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
6027 // Otherwise, not valid for this mode.
6033 Ops.push_back(Result);
6036 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6039 std::vector<unsigned> X86TargetLowering::
6040 getRegClassForInlineAsmConstraint(const std::string &Constraint,
6041 MVT::ValueType VT) const {
6042 if (Constraint.size() == 1) {
6043 // FIXME: not handling fp-stack yet!
6044 switch (Constraint[0]) { // GCC X86 Constraint Letters
6045 default: break; // Unknown constraint letter
6046 case 'A': // EAX/EDX
6047 if (VT == MVT::i32 || VT == MVT::i64)
6048 return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
6050 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
6053 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
6054 else if (VT == MVT::i16)
6055 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
6056 else if (VT == MVT::i8)
6057 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
6058 else if (VT == MVT::i64)
6059 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
6064 return std::vector<unsigned>();
6067 std::pair<unsigned, const TargetRegisterClass*>
6068 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
6069 MVT::ValueType VT) const {
6070 // First, see if this is a constraint that directly corresponds to an LLVM
6072 if (Constraint.size() == 1) {
6073 // GCC Constraint Letters
6074 switch (Constraint[0]) {
6076 case 'r': // GENERAL_REGS
6077 case 'R': // LEGACY_REGS
6078 case 'l': // INDEX_REGS
6079 if (VT == MVT::i64 && Subtarget->is64Bit())
6080 return std::make_pair(0U, X86::GR64RegisterClass);
6082 return std::make_pair(0U, X86::GR32RegisterClass);
6083 else if (VT == MVT::i16)
6084 return std::make_pair(0U, X86::GR16RegisterClass);
6085 else if (VT == MVT::i8)
6086 return std::make_pair(0U, X86::GR8RegisterClass);
6088 case 'y': // MMX_REGS if MMX allowed.
6089 if (!Subtarget->hasMMX()) break;
6090 return std::make_pair(0U, X86::VR64RegisterClass);
6092 case 'Y': // SSE_REGS if SSE2 allowed
6093 if (!Subtarget->hasSSE2()) break;
6095 case 'x': // SSE_REGS if SSE1 allowed
6096 if (!Subtarget->hasSSE1()) break;
6100 // Scalar SSE types.
6103 return std::make_pair(0U, X86::FR32RegisterClass);
6106 return std::make_pair(0U, X86::FR64RegisterClass);
6114 return std::make_pair(0U, X86::VR128RegisterClass);
6120 // Use the default implementation in TargetLowering to convert the register
6121 // constraint into a member of a register class.
6122 std::pair<unsigned, const TargetRegisterClass*> Res;
6123 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
6125 // Not found as a standard register?
6126 if (Res.second == 0) {
6127 // GCC calls "st(0)" just plain "st".
6128 if (StringsEqualNoCase("{st}", Constraint)) {
6129 Res.first = X86::ST0;
6130 Res.second = X86::RFP80RegisterClass;
6136 // Otherwise, check to see if this is a register class of the wrong value
6137 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
6138 // turn into {ax},{dx}.
6139 if (Res.second->hasType(VT))
6140 return Res; // Correct type already, nothing to do.
6142 // All of the single-register GCC register classes map their values onto
6143 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
6144 // really want an 8-bit or 32-bit register, map to the appropriate register
6145 // class and return the appropriate register.
6146 if (Res.second != X86::GR16RegisterClass)
6149 if (VT == MVT::i8) {
6150 unsigned DestReg = 0;
6151 switch (Res.first) {
6153 case X86::AX: DestReg = X86::AL; break;
6154 case X86::DX: DestReg = X86::DL; break;
6155 case X86::CX: DestReg = X86::CL; break;
6156 case X86::BX: DestReg = X86::BL; break;
6159 Res.first = DestReg;
6160 Res.second = Res.second = X86::GR8RegisterClass;
6162 } else if (VT == MVT::i32) {
6163 unsigned DestReg = 0;
6164 switch (Res.first) {
6166 case X86::AX: DestReg = X86::EAX; break;
6167 case X86::DX: DestReg = X86::EDX; break;
6168 case X86::CX: DestReg = X86::ECX; break;
6169 case X86::BX: DestReg = X86::EBX; break;
6170 case X86::SI: DestReg = X86::ESI; break;
6171 case X86::DI: DestReg = X86::EDI; break;
6172 case X86::BP: DestReg = X86::EBP; break;
6173 case X86::SP: DestReg = X86::ESP; break;
6176 Res.first = DestReg;
6177 Res.second = Res.second = X86::GR32RegisterClass;
6179 } else if (VT == MVT::i64) {
6180 unsigned DestReg = 0;
6181 switch (Res.first) {
6183 case X86::AX: DestReg = X86::RAX; break;
6184 case X86::DX: DestReg = X86::RDX; break;
6185 case X86::CX: DestReg = X86::RCX; break;
6186 case X86::BX: DestReg = X86::RBX; break;
6187 case X86::SI: DestReg = X86::RSI; break;
6188 case X86::DI: DestReg = X86::RDI; break;
6189 case X86::BP: DestReg = X86::RBP; break;
6190 case X86::SP: DestReg = X86::RSP; break;
6193 Res.first = DestReg;
6194 Res.second = Res.second = X86::GR64RegisterClass;