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-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::MULHS , MVT::i8 , Expand);
180 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
181 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
182 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
183 setOperationAction(ISD::SREM , MVT::i8 , Expand);
184 setOperationAction(ISD::UREM , MVT::i8 , Expand);
185 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
186 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
187 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
188 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
189 setOperationAction(ISD::SREM , MVT::i16 , Expand);
190 setOperationAction(ISD::UREM , MVT::i16 , Expand);
191 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
192 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
193 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
194 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
195 setOperationAction(ISD::SREM , MVT::i32 , Expand);
196 setOperationAction(ISD::UREM , MVT::i32 , Expand);
197 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
198 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
199 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
200 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
201 setOperationAction(ISD::SREM , MVT::i64 , Expand);
202 setOperationAction(ISD::UREM , MVT::i64 , Expand);
204 // 8, 16, and 32-bit plain multiply are legal. And 64-bit multiply
205 // is also legal on x86-64.
206 if (!Subtarget->is64Bit())
207 setOperationAction(ISD::MUL , MVT::i64 , Expand);
209 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
210 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
211 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
212 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
213 setOperationAction(ISD::MEMMOVE , MVT::Other, Expand);
214 if (Subtarget->is64Bit())
215 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
216 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
217 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
218 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
219 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
220 setOperationAction(ISD::FREM , MVT::f64 , Expand);
221 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
223 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
224 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
225 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
226 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
227 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
228 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
229 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
230 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
231 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
232 if (Subtarget->is64Bit()) {
233 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
234 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
235 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
238 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
239 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
241 // These should be promoted to a larger select which is supported.
242 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
243 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
244 // X86 wants to expand cmov itself.
245 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
246 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
247 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
248 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
249 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
250 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
251 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
252 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
253 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
254 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
255 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
256 if (Subtarget->is64Bit()) {
257 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
258 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
260 // X86 ret instruction may pop stack.
261 setOperationAction(ISD::RET , MVT::Other, Custom);
262 if (!Subtarget->is64Bit())
263 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
266 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
267 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
268 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
269 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
270 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
271 if (Subtarget->is64Bit()) {
272 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
273 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
274 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
275 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
277 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
278 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
279 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
280 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
281 // X86 wants to expand memset / memcpy itself.
282 setOperationAction(ISD::MEMSET , MVT::Other, Custom);
283 setOperationAction(ISD::MEMCPY , MVT::Other, Custom);
285 if (!Subtarget->hasSSE2())
286 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
289 // Use the default ISD::LOCATION, ISD::DECLARE expansion.
290 setOperationAction(ISD::LOCATION, MVT::Other, Expand);
291 // FIXME - use subtarget debug flags
292 if (!Subtarget->isTargetDarwin() &&
293 !Subtarget->isTargetELF() &&
294 !Subtarget->isTargetCygMing())
295 setOperationAction(ISD::LABEL, MVT::Other, Expand);
297 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
298 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
299 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
300 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
301 if (Subtarget->is64Bit()) {
303 setExceptionPointerRegister(X86::RAX);
304 setExceptionSelectorRegister(X86::RDX);
306 setExceptionPointerRegister(X86::EAX);
307 setExceptionSelectorRegister(X86::EDX);
309 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
311 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
313 setOperationAction(ISD::TRAP, MVT::Other, Legal);
315 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
316 setOperationAction(ISD::VASTART , MVT::Other, Custom);
317 setOperationAction(ISD::VAARG , MVT::Other, Expand);
318 setOperationAction(ISD::VAEND , MVT::Other, Expand);
319 if (Subtarget->is64Bit())
320 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
322 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
324 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
325 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
326 if (Subtarget->is64Bit())
327 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
328 if (Subtarget->isTargetCygMing())
329 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
331 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
333 if (X86ScalarSSEf64) {
334 // f32 and f64 use SSE.
335 // Set up the FP register classes.
336 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
337 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
339 // Use ANDPD to simulate FABS.
340 setOperationAction(ISD::FABS , MVT::f64, Custom);
341 setOperationAction(ISD::FABS , MVT::f32, Custom);
343 // Use XORP to simulate FNEG.
344 setOperationAction(ISD::FNEG , MVT::f64, Custom);
345 setOperationAction(ISD::FNEG , MVT::f32, Custom);
347 // Use ANDPD and ORPD to simulate FCOPYSIGN.
348 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
349 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
351 // We don't support sin/cos/fmod
352 setOperationAction(ISD::FSIN , MVT::f64, Expand);
353 setOperationAction(ISD::FCOS , MVT::f64, Expand);
354 setOperationAction(ISD::FREM , MVT::f64, Expand);
355 setOperationAction(ISD::FSIN , MVT::f32, Expand);
356 setOperationAction(ISD::FCOS , MVT::f32, Expand);
357 setOperationAction(ISD::FREM , MVT::f32, Expand);
359 // Expand FP immediates into loads from the stack, except for the special
361 addLegalFPImmediate(APFloat(+0.0)); // xorpd
362 addLegalFPImmediate(APFloat(+0.0f)); // xorps
364 // Floating truncations from f80 and extensions to f80 go through memory.
365 // If optimizing, we lie about this though and handle it in
366 // InstructionSelectPreprocess so that dagcombine2 can hack on these.
368 setConvertAction(MVT::f32, MVT::f80, Expand);
369 setConvertAction(MVT::f64, MVT::f80, Expand);
370 setConvertAction(MVT::f80, MVT::f32, Expand);
371 setConvertAction(MVT::f80, MVT::f64, Expand);
373 } else if (X86ScalarSSEf32) {
374 // Use SSE for f32, x87 for f64.
375 // Set up the FP register classes.
376 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
377 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
379 // Use ANDPS to simulate FABS.
380 setOperationAction(ISD::FABS , MVT::f32, Custom);
382 // Use XORP to simulate FNEG.
383 setOperationAction(ISD::FNEG , MVT::f32, Custom);
385 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
387 // Use ANDPS and ORPS to simulate FCOPYSIGN.
388 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
389 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
391 // We don't support sin/cos/fmod
392 setOperationAction(ISD::FSIN , MVT::f32, Expand);
393 setOperationAction(ISD::FCOS , MVT::f32, Expand);
394 setOperationAction(ISD::FREM , MVT::f32, Expand);
396 // Special cases we handle for FP constants.
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);
443 addLegalFPImmediate(APFloat(+0.0)); // FLD0
444 addLegalFPImmediate(APFloat(+1.0)); // FLD1
445 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
446 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
447 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
448 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
449 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
450 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
453 // Long double always uses X87.
454 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
455 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
456 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
458 APFloat TmpFlt(+0.0);
459 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
460 addLegalFPImmediate(TmpFlt); // FLD0
462 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
463 APFloat TmpFlt2(+1.0);
464 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven);
465 addLegalFPImmediate(TmpFlt2); // FLD1
466 TmpFlt2.changeSign();
467 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
471 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
472 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
475 // Always use a library call for pow.
476 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
477 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
478 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
480 // First set operation action for all vector types to expand. Then we
481 // will selectively turn on ones that can be effectively codegen'd.
482 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
483 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
484 setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
485 setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
486 setOperationAction(ISD::FADD, (MVT::ValueType)VT, Expand);
487 setOperationAction(ISD::FNEG, (MVT::ValueType)VT, Expand);
488 setOperationAction(ISD::FSUB, (MVT::ValueType)VT, Expand);
489 setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
490 setOperationAction(ISD::FMUL, (MVT::ValueType)VT, Expand);
491 setOperationAction(ISD::SDIV, (MVT::ValueType)VT, Expand);
492 setOperationAction(ISD::UDIV, (MVT::ValueType)VT, Expand);
493 setOperationAction(ISD::FDIV, (MVT::ValueType)VT, Expand);
494 setOperationAction(ISD::SREM, (MVT::ValueType)VT, Expand);
495 setOperationAction(ISD::UREM, (MVT::ValueType)VT, Expand);
496 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
497 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Expand);
498 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
499 setOperationAction(ISD::INSERT_VECTOR_ELT, (MVT::ValueType)VT, Expand);
500 setOperationAction(ISD::FABS, (MVT::ValueType)VT, Expand);
501 setOperationAction(ISD::FSIN, (MVT::ValueType)VT, Expand);
502 setOperationAction(ISD::FCOS, (MVT::ValueType)VT, Expand);
503 setOperationAction(ISD::FREM, (MVT::ValueType)VT, Expand);
504 setOperationAction(ISD::FPOWI, (MVT::ValueType)VT, Expand);
505 setOperationAction(ISD::FSQRT, (MVT::ValueType)VT, Expand);
506 setOperationAction(ISD::FCOPYSIGN, (MVT::ValueType)VT, Expand);
507 setOperationAction(ISD::SMUL_LOHI, (MVT::ValueType)VT, Expand);
508 setOperationAction(ISD::UMUL_LOHI, (MVT::ValueType)VT, Expand);
509 setOperationAction(ISD::SDIVREM, (MVT::ValueType)VT, Expand);
510 setOperationAction(ISD::UDIVREM, (MVT::ValueType)VT, Expand);
511 setOperationAction(ISD::FPOW, (MVT::ValueType)VT, Expand);
512 setOperationAction(ISD::CTPOP, (MVT::ValueType)VT, Expand);
513 setOperationAction(ISD::CTTZ, (MVT::ValueType)VT, Expand);
514 setOperationAction(ISD::CTLZ, (MVT::ValueType)VT, Expand);
515 setOperationAction(ISD::SHL, (MVT::ValueType)VT, Expand);
516 setOperationAction(ISD::SRA, (MVT::ValueType)VT, Expand);
517 setOperationAction(ISD::SRL, (MVT::ValueType)VT, Expand);
518 setOperationAction(ISD::ROTL, (MVT::ValueType)VT, Expand);
519 setOperationAction(ISD::ROTR, (MVT::ValueType)VT, Expand);
520 setOperationAction(ISD::BSWAP, (MVT::ValueType)VT, Expand);
523 if (Subtarget->hasMMX()) {
524 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
525 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
526 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
527 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
529 // FIXME: add MMX packed arithmetics
531 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
532 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
533 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
534 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
536 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
537 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
538 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
539 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
541 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
542 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
544 setOperationAction(ISD::AND, MVT::v8i8, Promote);
545 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
546 setOperationAction(ISD::AND, MVT::v4i16, Promote);
547 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
548 setOperationAction(ISD::AND, MVT::v2i32, Promote);
549 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
550 setOperationAction(ISD::AND, MVT::v1i64, Legal);
552 setOperationAction(ISD::OR, MVT::v8i8, Promote);
553 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
554 setOperationAction(ISD::OR, MVT::v4i16, Promote);
555 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
556 setOperationAction(ISD::OR, MVT::v2i32, Promote);
557 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
558 setOperationAction(ISD::OR, MVT::v1i64, Legal);
560 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
561 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
562 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
563 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
564 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
565 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
566 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
568 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
569 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
570 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
571 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
572 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
573 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
574 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
576 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
577 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
578 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
579 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
581 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
582 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
583 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
584 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
586 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
587 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
588 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2i32, Custom);
589 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
592 if (Subtarget->hasSSE1()) {
593 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
595 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
596 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
597 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
598 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
599 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
600 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
601 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
602 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
603 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
604 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
605 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
608 if (Subtarget->hasSSE2()) {
609 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
610 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
611 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
612 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
613 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
615 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
616 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
617 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
618 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
619 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
620 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
621 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
622 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
623 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
624 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
625 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
626 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
627 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
628 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
629 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
631 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
632 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
633 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
634 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
635 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
637 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
638 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
639 // Do not attempt to custom lower non-power-of-2 vectors
640 if (!isPowerOf2_32(MVT::getVectorNumElements(VT)))
642 setOperationAction(ISD::BUILD_VECTOR, (MVT::ValueType)VT, Custom);
643 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::ValueType)VT, Custom);
644 setOperationAction(ISD::EXTRACT_VECTOR_ELT, (MVT::ValueType)VT, Custom);
646 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
647 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
648 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
649 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
650 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
651 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
652 if (Subtarget->is64Bit()) {
653 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
654 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
657 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
658 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
659 setOperationAction(ISD::AND, (MVT::ValueType)VT, Promote);
660 AddPromotedToType (ISD::AND, (MVT::ValueType)VT, MVT::v2i64);
661 setOperationAction(ISD::OR, (MVT::ValueType)VT, Promote);
662 AddPromotedToType (ISD::OR, (MVT::ValueType)VT, MVT::v2i64);
663 setOperationAction(ISD::XOR, (MVT::ValueType)VT, Promote);
664 AddPromotedToType (ISD::XOR, (MVT::ValueType)VT, MVT::v2i64);
665 setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Promote);
666 AddPromotedToType (ISD::LOAD, (MVT::ValueType)VT, MVT::v2i64);
667 setOperationAction(ISD::SELECT, (MVT::ValueType)VT, Promote);
668 AddPromotedToType (ISD::SELECT, (MVT::ValueType)VT, MVT::v2i64);
671 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
673 // Custom lower v2i64 and v2f64 selects.
674 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
675 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
676 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
677 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
680 if (Subtarget->hasSSE41()) {
681 // FIXME: Do we need to handle scalar-to-vector here?
682 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
684 // i8 and i16 vectors are custom , because the source register and source
685 // source memory operand types are not the same width. f32 vectors are
686 // custom since the immediate controlling the insert encodes additional
688 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
689 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
690 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Legal);
691 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
693 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
694 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
695 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
696 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Legal);
698 if (Subtarget->is64Bit()) {
699 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
700 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
704 // We want to custom lower some of our intrinsics.
705 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
707 // We have target-specific dag combine patterns for the following nodes:
708 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
709 setTargetDAGCombine(ISD::SELECT);
711 computeRegisterProperties();
713 // FIXME: These should be based on subtarget info. Plus, the values should
714 // be smaller when we are in optimizing for size mode.
715 maxStoresPerMemset = 16; // For %llvm.memset -> sequence of stores
716 maxStoresPerMemcpy = 16; // For %llvm.memcpy -> sequence of stores
717 maxStoresPerMemmove = 16; // For %llvm.memmove -> sequence of stores
718 allowUnalignedMemoryAccesses = true; // x86 supports it!
721 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
722 /// the desired ByVal argument alignment.
723 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
726 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
727 if (VTy->getBitWidth() == 128)
729 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
730 unsigned EltAlign = 0;
731 getMaxByValAlign(ATy->getElementType(), EltAlign);
732 if (EltAlign > MaxAlign)
734 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
735 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
736 unsigned EltAlign = 0;
737 getMaxByValAlign(STy->getElementType(i), EltAlign);
738 if (EltAlign > MaxAlign)
747 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
748 /// function arguments in the caller parameter area. For X86, aggregates
749 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
750 /// are at 4-byte boundaries.
751 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
752 if (Subtarget->is64Bit())
753 return getTargetData()->getABITypeAlignment(Ty);
755 if (Subtarget->hasSSE1())
756 getMaxByValAlign(Ty, Align);
760 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
762 SDOperand X86TargetLowering::getPICJumpTableRelocBase(SDOperand Table,
763 SelectionDAG &DAG) const {
764 if (usesGlobalOffsetTable())
765 return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
766 if (!Subtarget->isPICStyleRIPRel())
767 return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
771 //===----------------------------------------------------------------------===//
772 // Return Value Calling Convention Implementation
773 //===----------------------------------------------------------------------===//
775 #include "X86GenCallingConv.inc"
777 /// GetPossiblePreceedingTailCall - Get preceeding X86ISD::TAILCALL node if it
778 /// exists skip possible ISD:TokenFactor.
779 static SDOperand GetPossiblePreceedingTailCall(SDOperand Chain) {
780 if (Chain.getOpcode() == X86ISD::TAILCALL) {
782 } else if (Chain.getOpcode() == ISD::TokenFactor) {
783 if (Chain.getNumOperands() &&
784 Chain.getOperand(0).getOpcode() == X86ISD::TAILCALL)
785 return Chain.getOperand(0);
790 /// LowerRET - Lower an ISD::RET node.
791 SDOperand X86TargetLowering::LowerRET(SDOperand Op, SelectionDAG &DAG) {
792 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
794 SmallVector<CCValAssign, 16> RVLocs;
795 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
796 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
797 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
798 CCInfo.AnalyzeReturn(Op.Val, RetCC_X86);
800 // If this is the first return lowered for this function, add the regs to the
801 // liveout set for the function.
802 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
803 for (unsigned i = 0; i != RVLocs.size(); ++i)
804 if (RVLocs[i].isRegLoc())
805 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
807 SDOperand Chain = Op.getOperand(0);
809 // Handle tail call return.
810 Chain = GetPossiblePreceedingTailCall(Chain);
811 if (Chain.getOpcode() == X86ISD::TAILCALL) {
812 SDOperand TailCall = Chain;
813 SDOperand TargetAddress = TailCall.getOperand(1);
814 SDOperand StackAdjustment = TailCall.getOperand(2);
815 assert(((TargetAddress.getOpcode() == ISD::Register &&
816 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::ECX ||
817 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
818 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
819 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
820 "Expecting an global address, external symbol, or register");
821 assert(StackAdjustment.getOpcode() == ISD::Constant &&
822 "Expecting a const value");
824 SmallVector<SDOperand,8> Operands;
825 Operands.push_back(Chain.getOperand(0));
826 Operands.push_back(TargetAddress);
827 Operands.push_back(StackAdjustment);
828 // Copy registers used by the call. Last operand is a flag so it is not
830 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
831 Operands.push_back(Chain.getOperand(i));
833 return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0],
840 // Copy the result values into the output registers.
841 if (RVLocs.size() != 1 || !RVLocs[0].isRegLoc() ||
842 RVLocs[0].getLocReg() != X86::ST0) {
843 for (unsigned i = 0; i != RVLocs.size(); ++i) {
844 CCValAssign &VA = RVLocs[i];
845 assert(VA.isRegLoc() && "Can only return in registers!");
846 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), Op.getOperand(i*2+1),
848 Flag = Chain.getValue(1);
851 // We need to handle a destination of ST0 specially, because it isn't really
853 SDOperand Value = Op.getOperand(1);
855 // an XMM register onto the fp-stack. Do this with an FP_EXTEND to f80.
856 // This will get legalized into a load/store if it can't get optimized away.
857 if (isScalarFPTypeInSSEReg(RVLocs[0].getValVT()))
858 Value = DAG.getNode(ISD::FP_EXTEND, MVT::f80, Value);
860 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
861 SDOperand Ops[] = { Chain, Value };
862 Chain = DAG.getNode(X86ISD::FP_SET_RESULT, Tys, Ops, 2);
863 Flag = Chain.getValue(1);
866 SDOperand BytesToPop = DAG.getConstant(getBytesToPopOnReturn(), MVT::i16);
868 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop, Flag);
870 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, Chain, BytesToPop);
874 /// LowerCallResult - Lower the result values of an ISD::CALL into the
875 /// appropriate copies out of appropriate physical registers. This assumes that
876 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
877 /// being lowered. The returns a SDNode with the same number of values as the
879 SDNode *X86TargetLowering::
880 LowerCallResult(SDOperand Chain, SDOperand InFlag, SDNode *TheCall,
881 unsigned CallingConv, SelectionDAG &DAG) {
883 // Assign locations to each value returned by this call.
884 SmallVector<CCValAssign, 16> RVLocs;
885 bool isVarArg = cast<ConstantSDNode>(TheCall->getOperand(2))->getValue() != 0;
886 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
887 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
889 SmallVector<SDOperand, 8> ResultVals;
891 // Copy all of the result registers out of their specified physreg.
892 if (RVLocs.size() != 1 || RVLocs[0].getLocReg() != X86::ST0) {
893 for (unsigned i = 0; i != RVLocs.size(); ++i) {
894 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
895 RVLocs[i].getValVT(), InFlag).getValue(1);
896 InFlag = Chain.getValue(2);
897 ResultVals.push_back(Chain.getValue(0));
900 // Copies from the FP stack are special, as ST0 isn't a valid register
901 // before the fp stackifier runs.
903 // Copy ST0 into an RFP register with FP_GET_RESULT. If this will end up
904 // in an SSE register, copy it out as F80 and do a truncate, otherwise use
905 // the specified value type.
906 MVT::ValueType GetResultTy = RVLocs[0].getValVT();
907 if (isScalarFPTypeInSSEReg(GetResultTy))
908 GetResultTy = MVT::f80;
909 SDVTList Tys = DAG.getVTList(GetResultTy, MVT::Other, MVT::Flag);
911 SDOperand GROps[] = { Chain, InFlag };
912 SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT, Tys, GROps, 2);
913 Chain = RetVal.getValue(1);
914 InFlag = RetVal.getValue(2);
916 // If we want the result in an SSE register, use an FP_TRUNCATE to get it
918 if (GetResultTy != RVLocs[0].getValVT())
919 RetVal = DAG.getNode(ISD::FP_ROUND, RVLocs[0].getValVT(), RetVal,
920 // This truncation won't change the value.
921 DAG.getIntPtrConstant(1));
923 ResultVals.push_back(RetVal);
926 // Merge everything together with a MERGE_VALUES node.
927 ResultVals.push_back(Chain);
928 return DAG.getNode(ISD::MERGE_VALUES, TheCall->getVTList(),
929 &ResultVals[0], ResultVals.size()).Val;
932 /// LowerCallResultToTwo64BitRegs - Lower the result values of an x86-64
933 /// ISD::CALL where the results are known to be in two 64-bit registers,
934 /// e.g. XMM0 and XMM1. This simplify store the two values back to the
935 /// fixed stack slot allocated for StructRet.
936 SDNode *X86TargetLowering::
937 LowerCallResultToTwo64BitRegs(SDOperand Chain, SDOperand InFlag,
938 SDNode *TheCall, unsigned Reg1, unsigned Reg2,
939 MVT::ValueType VT, SelectionDAG &DAG) {
940 SDOperand RetVal1 = DAG.getCopyFromReg(Chain, Reg1, VT, InFlag);
941 Chain = RetVal1.getValue(1);
942 InFlag = RetVal1.getValue(2);
943 SDOperand RetVal2 = DAG.getCopyFromReg(Chain, Reg2, VT, InFlag);
944 Chain = RetVal2.getValue(1);
945 InFlag = RetVal2.getValue(2);
946 SDOperand FIN = TheCall->getOperand(5);
947 Chain = DAG.getStore(Chain, RetVal1, FIN, NULL, 0);
948 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
949 Chain = DAG.getStore(Chain, RetVal2, FIN, NULL, 0);
953 /// LowerCallResultToTwoX87Regs - Lower the result values of an x86-64 ISD::CALL
954 /// where the results are known to be in ST0 and ST1.
955 SDNode *X86TargetLowering::
956 LowerCallResultToTwoX87Regs(SDOperand Chain, SDOperand InFlag,
957 SDNode *TheCall, SelectionDAG &DAG) {
958 SmallVector<SDOperand, 8> ResultVals;
959 const MVT::ValueType VTs[] = { MVT::f80, MVT::f80, MVT::Other, MVT::Flag };
960 SDVTList Tys = DAG.getVTList(VTs, 4);
961 SDOperand Ops[] = { Chain, InFlag };
962 SDOperand RetVal = DAG.getNode(X86ISD::FP_GET_RESULT2, Tys, Ops, 2);
963 Chain = RetVal.getValue(2);
964 SDOperand FIN = TheCall->getOperand(5);
965 Chain = DAG.getStore(Chain, RetVal.getValue(1), FIN, NULL, 0);
966 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(16));
967 Chain = DAG.getStore(Chain, RetVal, FIN, NULL, 0);
971 //===----------------------------------------------------------------------===//
972 // C & StdCall & Fast Calling Convention implementation
973 //===----------------------------------------------------------------------===//
974 // StdCall calling convention seems to be standard for many Windows' API
975 // routines and around. It differs from C calling convention just a little:
976 // callee should clean up the stack, not caller. Symbols should be also
977 // decorated in some fancy way :) It doesn't support any vector arguments.
978 // For info on fast calling convention see Fast Calling Convention (tail call)
979 // implementation LowerX86_32FastCCCallTo.
981 /// AddLiveIn - This helper function adds the specified physical register to the
982 /// MachineFunction as a live in value. It also creates a corresponding virtual
984 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
985 const TargetRegisterClass *RC) {
986 assert(RC->contains(PReg) && "Not the correct regclass!");
987 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
988 MF.getRegInfo().addLiveIn(PReg, VReg);
992 // Determines whether a CALL node uses struct return semantics.
993 static bool CallIsStructReturn(SDOperand Op) {
994 unsigned NumOps = (Op.getNumOperands() - 5) / 2;
998 ConstantSDNode *Flags = cast<ConstantSDNode>(Op.getOperand(6));
999 return Flags->getValue() & ISD::ParamFlags::StructReturn;
1002 // Determines whether a FORMAL_ARGUMENTS node uses struct return semantics.
1003 static bool ArgsAreStructReturn(SDOperand Op) {
1004 unsigned NumArgs = Op.Val->getNumValues() - 1;
1008 ConstantSDNode *Flags = cast<ConstantSDNode>(Op.getOperand(3));
1009 return Flags->getValue() & ISD::ParamFlags::StructReturn;
1012 // Determines whether a CALL or FORMAL_ARGUMENTS node requires the callee to pop
1013 // its own arguments. Callee pop is necessary to support tail calls.
1014 bool X86TargetLowering::IsCalleePop(SDOperand Op) {
1015 bool IsVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1019 switch (cast<ConstantSDNode>(Op.getOperand(1))->getValue()) {
1022 case CallingConv::X86_StdCall:
1023 return !Subtarget->is64Bit();
1024 case CallingConv::X86_FastCall:
1025 return !Subtarget->is64Bit();
1026 case CallingConv::Fast:
1027 return PerformTailCallOpt;
1031 // Selects the correct CCAssignFn for a CALL or FORMAL_ARGUMENTS node.
1032 CCAssignFn *X86TargetLowering::CCAssignFnForNode(SDOperand Op) const {
1033 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1035 if (Subtarget->is64Bit())
1036 if (CC == CallingConv::Fast && PerformTailCallOpt)
1037 return CC_X86_64_TailCall;
1041 if (CC == CallingConv::X86_FastCall)
1042 return CC_X86_32_FastCall;
1043 else if (CC == CallingConv::Fast && PerformTailCallOpt)
1044 return CC_X86_32_TailCall;
1049 // Selects the appropriate decoration to apply to a MachineFunction containing a
1050 // given FORMAL_ARGUMENTS node.
1052 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDOperand Op) {
1053 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1054 if (CC == CallingConv::X86_FastCall)
1056 else if (CC == CallingConv::X86_StdCall)
1062 // IsPossiblyOverwrittenArgumentOfTailCall - Check if the operand could possibly
1063 // be overwritten when lowering the outgoing arguments in a tail call. Currently
1064 // the implementation of this call is very conservative and assumes all
1065 // arguments sourcing from FORMAL_ARGUMENTS or a CopyFromReg with virtual
1066 // registers would be overwritten by direct lowering.
1067 // Possible improvement:
1068 // Check FORMAL_ARGUMENTS corresponding MERGE_VALUES for CopyFromReg nodes
1069 // indicating inreg passed arguments which also need not be lowered to a safe
1071 static bool IsPossiblyOverwrittenArgumentOfTailCall(SDOperand Op) {
1072 RegisterSDNode * OpReg = NULL;
1073 if (Op.getOpcode() == ISD::FORMAL_ARGUMENTS ||
1074 (Op.getOpcode()== ISD::CopyFromReg &&
1075 (OpReg = cast<RegisterSDNode>(Op.getOperand(1))) &&
1076 OpReg->getReg() >= TargetRegisterInfo::FirstVirtualRegister))
1081 // CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1082 // by "Src" to address "Dst" with size and alignment information specified by
1083 // the specific parameter attribute. The copy will be passed as a byval function
1086 CreateCopyOfByValArgument(SDOperand Src, SDOperand Dst, SDOperand Chain,
1087 unsigned Flags, SelectionDAG &DAG) {
1088 unsigned Align = 1 <<
1089 ((Flags & ISD::ParamFlags::ByValAlign) >> ISD::ParamFlags::ByValAlignOffs);
1090 unsigned Size = (Flags & ISD::ParamFlags::ByValSize) >>
1091 ISD::ParamFlags::ByValSizeOffs;
1092 SDOperand AlignNode = DAG.getConstant(Align, MVT::i32);
1093 SDOperand SizeNode = DAG.getConstant(Size, MVT::i32);
1094 SDOperand AlwaysInline = DAG.getConstant(1, MVT::i32);
1095 return DAG.getMemcpy(Chain, Dst, Src, SizeNode, AlignNode, AlwaysInline);
1098 SDOperand X86TargetLowering::LowerMemArgument(SDOperand Op, SelectionDAG &DAG,
1099 const CCValAssign &VA,
1100 MachineFrameInfo *MFI,
1101 SDOperand Root, unsigned i) {
1102 // Create the nodes corresponding to a load from this parameter slot.
1103 unsigned Flags = cast<ConstantSDNode>(Op.getOperand(3 + i))->getValue();
1104 bool isByVal = Flags & ISD::ParamFlags::ByVal;
1106 // FIXME: For now, all byval parameter objects are marked mutable. This
1107 // can be changed with more analysis.
1108 int FI = MFI->CreateFixedObject(MVT::getSizeInBits(VA.getValVT())/8,
1109 VA.getLocMemOffset(), !isByVal);
1110 SDOperand FIN = DAG.getFrameIndex(FI, getPointerTy());
1113 return DAG.getLoad(VA.getValVT(), Root, FIN,
1114 PseudoSourceValue::getFixedStack(), FI);
1118 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDOperand Op, SelectionDAG &DAG) {
1119 MachineFunction &MF = DAG.getMachineFunction();
1120 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1122 const Function* Fn = MF.getFunction();
1123 if (Fn->hasExternalLinkage() &&
1124 Subtarget->isTargetCygMing() &&
1125 Fn->getName() == "main")
1126 FuncInfo->setForceFramePointer(true);
1128 // Decorate the function name.
1129 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1131 MachineFrameInfo *MFI = MF.getFrameInfo();
1132 SDOperand Root = Op.getOperand(0);
1133 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1134 unsigned CC = MF.getFunction()->getCallingConv();
1135 bool Is64Bit = Subtarget->is64Bit();
1137 assert(!(isVarArg && CC == CallingConv::Fast) &&
1138 "Var args not supported with calling convention fastcc");
1140 // Assign locations to all of the incoming arguments.
1141 SmallVector<CCValAssign, 16> ArgLocs;
1142 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1143 CCInfo.AnalyzeFormalArguments(Op.Val, CCAssignFnForNode(Op));
1145 SmallVector<SDOperand, 8> ArgValues;
1146 unsigned LastVal = ~0U;
1147 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1148 CCValAssign &VA = ArgLocs[i];
1149 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1151 assert(VA.getValNo() != LastVal &&
1152 "Don't support value assigned to multiple locs yet");
1153 LastVal = VA.getValNo();
1155 if (VA.isRegLoc()) {
1156 MVT::ValueType RegVT = VA.getLocVT();
1157 TargetRegisterClass *RC;
1158 if (RegVT == MVT::i32)
1159 RC = X86::GR32RegisterClass;
1160 else if (Is64Bit && RegVT == MVT::i64)
1161 RC = X86::GR64RegisterClass;
1162 else if (RegVT == MVT::f32)
1163 RC = X86::FR32RegisterClass;
1164 else if (RegVT == MVT::f64)
1165 RC = X86::FR64RegisterClass;
1167 assert(MVT::isVector(RegVT));
1168 if (Is64Bit && MVT::getSizeInBits(RegVT) == 64) {
1169 RC = X86::GR64RegisterClass; // MMX values are passed in GPRs.
1172 RC = X86::VR128RegisterClass;
1175 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1176 SDOperand ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1178 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1179 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1181 if (VA.getLocInfo() == CCValAssign::SExt)
1182 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1183 DAG.getValueType(VA.getValVT()));
1184 else if (VA.getLocInfo() == CCValAssign::ZExt)
1185 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1186 DAG.getValueType(VA.getValVT()));
1188 if (VA.getLocInfo() != CCValAssign::Full)
1189 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1191 // Handle MMX values passed in GPRs.
1192 if (Is64Bit && RegVT != VA.getLocVT() && RC == X86::GR64RegisterClass &&
1193 MVT::getSizeInBits(RegVT) == 64)
1194 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1196 ArgValues.push_back(ArgValue);
1198 assert(VA.isMemLoc());
1199 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, Root, i));
1203 unsigned StackSize = CCInfo.getNextStackOffset();
1204 // align stack specially for tail calls
1205 if (CC == CallingConv::Fast)
1206 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1208 // If the function takes variable number of arguments, make a frame index for
1209 // the start of the first vararg value... for expansion of llvm.va_start.
1211 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1212 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1215 static const unsigned GPR64ArgRegs[] = {
1216 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1218 static const unsigned XMMArgRegs[] = {
1219 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1220 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1223 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs, 6);
1224 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1226 // For X86-64, if there are vararg parameters that are passed via
1227 // registers, then we must store them to their spots on the stack so they
1228 // may be loaded by deferencing the result of va_next.
1229 VarArgsGPOffset = NumIntRegs * 8;
1230 VarArgsFPOffset = 6 * 8 + NumXMMRegs * 16;
1231 RegSaveFrameIndex = MFI->CreateStackObject(6 * 8 + 8 * 16, 16);
1233 // Store the integer parameter registers.
1234 SmallVector<SDOperand, 8> MemOps;
1235 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1236 SDOperand FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1237 DAG.getIntPtrConstant(VarArgsGPOffset));
1238 for (; NumIntRegs != 6; ++NumIntRegs) {
1239 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1240 X86::GR64RegisterClass);
1241 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1243 DAG.getStore(Val.getValue(1), Val, FIN,
1244 PseudoSourceValue::getFixedStack(),
1246 MemOps.push_back(Store);
1247 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1248 DAG.getIntPtrConstant(8));
1251 // Now store the XMM (fp + vector) parameter registers.
1252 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1253 DAG.getIntPtrConstant(VarArgsFPOffset));
1254 for (; NumXMMRegs != 8; ++NumXMMRegs) {
1255 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1256 X86::VR128RegisterClass);
1257 SDOperand Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1259 DAG.getStore(Val.getValue(1), Val, FIN,
1260 PseudoSourceValue::getFixedStack(),
1262 MemOps.push_back(Store);
1263 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1264 DAG.getIntPtrConstant(16));
1266 if (!MemOps.empty())
1267 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1268 &MemOps[0], MemOps.size());
1272 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1273 // arguments and the arguments after the retaddr has been pushed are
1275 if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1276 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1277 (StackSize & 7) == 0)
1280 ArgValues.push_back(Root);
1282 // Some CCs need callee pop.
1283 if (IsCalleePop(Op)) {
1284 BytesToPopOnReturn = StackSize; // Callee pops everything.
1285 BytesCallerReserves = 0;
1287 BytesToPopOnReturn = 0; // Callee pops nothing.
1288 // If this is an sret function, the return should pop the hidden pointer.
1289 if (!Is64Bit && ArgsAreStructReturn(Op))
1290 BytesToPopOnReturn = 4;
1291 BytesCallerReserves = StackSize;
1295 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1296 if (CC == CallingConv::X86_FastCall)
1297 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1300 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1302 // Return the new list of results.
1303 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(),
1304 &ArgValues[0], ArgValues.size()).getValue(Op.ResNo);
1308 X86TargetLowering::LowerMemOpCallTo(SDOperand Op, SelectionDAG &DAG,
1309 const SDOperand &StackPtr,
1310 const CCValAssign &VA,
1313 unsigned LocMemOffset = VA.getLocMemOffset();
1314 SDOperand PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1315 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1316 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1317 unsigned Flags = cast<ConstantSDNode>(FlagsOp)->getValue();
1318 if (Flags & ISD::ParamFlags::ByVal) {
1319 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG);
1321 return DAG.getStore(Chain, Arg, PtrOff,
1322 PseudoSourceValue::getStack(), LocMemOffset);
1325 /// ClassifyX86_64SRetCallReturn - Classify how to implement a x86-64
1326 /// struct return call to the specified function. X86-64 ABI specifies
1327 /// some SRet calls are actually returned in registers. Since current
1328 /// LLVM cannot represent multi-value calls, they are represent as
1329 /// calls where the results are passed in a hidden struct provided by
1330 /// the caller. This function examines the type of the struct to
1331 /// determine the correct way to implement the call.
1333 X86TargetLowering::ClassifyX86_64SRetCallReturn(const Function *Fn) {
1334 // FIXME: Disabled for now.
1335 return X86::InMemory;
1337 const PointerType *PTy = cast<PointerType>(Fn->arg_begin()->getType());
1338 const Type *RTy = PTy->getElementType();
1339 unsigned Size = getTargetData()->getABITypeSize(RTy);
1340 if (Size != 16 && Size != 32)
1341 return X86::InMemory;
1344 const StructType *STy = dyn_cast<StructType>(RTy);
1345 if (!STy) return X86::InMemory;
1346 if (STy->getNumElements() == 2 &&
1347 STy->getElementType(0) == Type::X86_FP80Ty &&
1348 STy->getElementType(1) == Type::X86_FP80Ty)
1353 for (Type::subtype_iterator I = RTy->subtype_begin(), E = RTy->subtype_end();
1355 const Type *STy = I->get();
1356 if (!STy->isFPOrFPVector()) {
1364 return X86::InGPR64;
1367 void X86TargetLowering::X86_64AnalyzeSRetCallOperands(SDNode *TheCall,
1370 unsigned NumOps = (TheCall->getNumOperands() - 5) / 2;
1371 for (unsigned i = 1; i != NumOps; ++i) {
1372 MVT::ValueType ArgVT = TheCall->getOperand(5+2*i).getValueType();
1373 SDOperand FlagOp = TheCall->getOperand(5+2*i+1);
1374 unsigned ArgFlags =cast<ConstantSDNode>(FlagOp)->getValue();
1375 if (Fn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo)) {
1376 cerr << "Call operand #" << i << " has unhandled type "
1377 << MVT::getValueTypeString(ArgVT) << "\n";
1383 SDOperand X86TargetLowering::LowerCALL(SDOperand Op, SelectionDAG &DAG) {
1384 MachineFunction &MF = DAG.getMachineFunction();
1385 SDOperand Chain = Op.getOperand(0);
1386 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
1387 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getValue() != 0;
1388 bool IsTailCall = cast<ConstantSDNode>(Op.getOperand(3))->getValue() != 0
1389 && CC == CallingConv::Fast && PerformTailCallOpt;
1390 SDOperand Callee = Op.getOperand(4);
1391 bool Is64Bit = Subtarget->is64Bit();
1392 bool IsStructRet = CallIsStructReturn(Op);
1394 assert(!(isVarArg && CC == CallingConv::Fast) &&
1395 "Var args not supported with calling convention fastcc");
1397 // Analyze operands of the call, assigning locations to each operand.
1398 SmallVector<CCValAssign, 16> ArgLocs;
1399 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1400 CCAssignFn *CCFn = CCAssignFnForNode(Op);
1402 X86::X86_64SRet SRetMethod = X86::InMemory;
1403 if (Is64Bit && IsStructRet)
1404 // FIXME: We can't figure out type of the sret structure for indirect
1405 // calls. We need to copy more information from CallSite to the ISD::CALL
1407 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1409 ClassifyX86_64SRetCallReturn(dyn_cast<Function>(G->getGlobal()));
1411 // UGLY HACK! For x86-64, some 128-bit aggregates are returns in a pair of
1412 // registers. Unfortunately, llvm does not support i128 yet so we pretend it's
1414 if (SRetMethod != X86::InMemory)
1415 X86_64AnalyzeSRetCallOperands(Op.Val, CCFn, CCInfo);
1417 CCInfo.AnalyzeCallOperands(Op.Val, CCFn);
1419 // Get a count of how many bytes are to be pushed on the stack.
1420 unsigned NumBytes = CCInfo.getNextStackOffset();
1421 if (CC == CallingConv::Fast)
1422 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1424 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
1425 // arguments and the arguments after the retaddr has been pushed are aligned.
1426 if (!Is64Bit && CC == CallingConv::X86_FastCall &&
1427 !Subtarget->isTargetCygMing() && !Subtarget->isTargetWindows() &&
1428 (NumBytes & 7) == 0)
1433 // Lower arguments at fp - stackoffset + fpdiff.
1434 unsigned NumBytesCallerPushed =
1435 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1436 FPDiff = NumBytesCallerPushed - NumBytes;
1438 // Set the delta of movement of the returnaddr stackslot.
1439 // But only set if delta is greater than previous delta.
1440 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1441 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1444 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes));
1446 SDOperand RetAddrFrIdx, NewRetAddrFrIdx;
1448 // Adjust the Return address stack slot.
1450 MVT::ValueType VT = Is64Bit ? MVT::i64 : MVT::i32;
1451 RetAddrFrIdx = getReturnAddressFrameIndex(DAG);
1452 // Load the "old" Return address.
1454 DAG.getLoad(VT, Chain,RetAddrFrIdx, NULL, 0);
1455 // Calculate the new stack slot for the return address.
1456 int SlotSize = Is64Bit ? 8 : 4;
1457 int NewReturnAddrFI =
1458 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1459 NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1460 Chain = SDOperand(RetAddrFrIdx.Val, 1);
1464 SmallVector<std::pair<unsigned, SDOperand>, 8> RegsToPass;
1465 SmallVector<SDOperand, 8> MemOpChains;
1469 // Walk the register/memloc assignments, inserting copies/loads. For tail
1470 // calls, lower arguments which could otherwise be possibly overwritten to the
1471 // stack slot where they would go on normal function calls.
1472 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1473 CCValAssign &VA = ArgLocs[i];
1474 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1476 // Promote the value if needed.
1477 switch (VA.getLocInfo()) {
1478 default: assert(0 && "Unknown loc info!");
1479 case CCValAssign::Full: break;
1480 case CCValAssign::SExt:
1481 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1483 case CCValAssign::ZExt:
1484 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1486 case CCValAssign::AExt:
1487 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1491 if (VA.isRegLoc()) {
1492 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1494 if (!IsTailCall || IsPossiblyOverwrittenArgumentOfTailCall(Arg)) {
1495 assert(VA.isMemLoc());
1496 if (StackPtr.Val == 0)
1497 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1499 MemOpChains.push_back(LowerMemOpCallTo(Op, DAG, StackPtr, VA, Chain,
1505 if (!MemOpChains.empty())
1506 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1507 &MemOpChains[0], MemOpChains.size());
1509 // Build a sequence of copy-to-reg nodes chained together with token chain
1510 // and flag operands which copy the outgoing args into registers.
1512 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1513 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1515 InFlag = Chain.getValue(1);
1519 InFlag = SDOperand(); // ??? Isn't this nuking the preceding loop's output?
1521 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1523 // Does not work with tail call since ebx is not restored correctly by
1524 // tailcaller. TODO: at least for x86 - verify for x86-64
1525 if (!IsTailCall && !Is64Bit &&
1526 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1527 Subtarget->isPICStyleGOT()) {
1528 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1529 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1531 InFlag = Chain.getValue(1);
1534 if (Is64Bit && isVarArg) {
1535 // From AMD64 ABI document:
1536 // For calls that may call functions that use varargs or stdargs
1537 // (prototype-less calls or calls to functions containing ellipsis (...) in
1538 // the declaration) %al is used as hidden argument to specify the number
1539 // of SSE registers used. The contents of %al do not need to match exactly
1540 // the number of registers, but must be an ubound on the number of SSE
1541 // registers used and is in the range 0 - 8 inclusive.
1543 // Count the number of XMM registers allocated.
1544 static const unsigned XMMArgRegs[] = {
1545 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1546 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1548 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1550 Chain = DAG.getCopyToReg(Chain, X86::AL,
1551 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1552 InFlag = Chain.getValue(1);
1555 // For tail calls lower the arguments to the 'real' stack slot.
1557 SmallVector<SDOperand, 8> MemOpChains2;
1560 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1561 CCValAssign &VA = ArgLocs[i];
1562 if (!VA.isRegLoc()) {
1563 assert(VA.isMemLoc());
1564 SDOperand Arg = Op.getOperand(5+2*VA.getValNo());
1565 SDOperand FlagsOp = Op.getOperand(6+2*VA.getValNo());
1566 unsigned Flags = cast<ConstantSDNode>(FlagsOp)->getValue();
1567 // Create frame index.
1568 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1569 uint32_t OpSize = (MVT::getSizeInBits(VA.getLocVT())+7)/8;
1570 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1571 FIN = DAG.getFrameIndex(FI, MVT::i32);
1572 SDOperand Source = Arg;
1573 if (IsPossiblyOverwrittenArgumentOfTailCall(Arg)) {
1574 // Copy from stack slots to stack slot of a tail called function. This
1575 // needs to be done because if we would lower the arguments directly
1576 // to their real stack slot we might end up overwriting each other.
1577 // Get source stack slot.
1578 Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1579 if (StackPtr.Val == 0)
1580 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1581 Source = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, Source);
1582 if ((Flags & ISD::ParamFlags::ByVal)==0)
1583 Source = DAG.getLoad(VA.getValVT(), Chain, Source, NULL, 0);
1586 if (Flags & ISD::ParamFlags::ByVal) {
1587 // Copy relative to framepointer.
1588 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1591 // Store relative to framepointer.
1592 MemOpChains2.push_back(
1593 DAG.getStore(Chain, Source, FIN,
1594 PseudoSourceValue::getFixedStack(), FI));
1599 if (!MemOpChains2.empty())
1600 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1601 &MemOpChains2[0], MemOpChains2.size());
1603 // Store the return address to the appropriate stack slot.
1605 Chain = DAG.getStore(Chain,RetAddrFrIdx, NewRetAddrFrIdx, NULL, 0);
1608 // If the callee is a GlobalAddress node (quite common, every direct call is)
1609 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1610 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1611 // We should use extra load for direct calls to dllimported functions in
1613 if ((IsTailCall || !Is64Bit ||
1614 getTargetMachine().getCodeModel() != CodeModel::Large)
1615 && !Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1616 getTargetMachine(), true))
1617 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy());
1618 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1619 if (IsTailCall || !Is64Bit ||
1620 getTargetMachine().getCodeModel() != CodeModel::Large)
1621 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1622 } else if (IsTailCall) {
1623 assert(Callee.getOpcode() == ISD::LOAD &&
1624 "Function destination must be loaded into virtual register");
1625 unsigned Opc = Is64Bit ? X86::R9 : X86::ECX;
1627 Chain = DAG.getCopyToReg(Chain,
1628 DAG.getRegister(Opc, getPointerTy()) ,
1630 Callee = DAG.getRegister(Opc, getPointerTy());
1631 // Add register as live out.
1632 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1635 // Returns a chain & a flag for retval copy to use.
1636 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1637 SmallVector<SDOperand, 8> Ops;
1640 Ops.push_back(Chain);
1641 Ops.push_back(DAG.getIntPtrConstant(NumBytes));
1642 Ops.push_back(DAG.getIntPtrConstant(0));
1644 Ops.push_back(InFlag);
1645 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1646 InFlag = Chain.getValue(1);
1648 // Returns a chain & a flag for retval copy to use.
1649 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1653 Ops.push_back(Chain);
1654 Ops.push_back(Callee);
1657 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1659 // Add an implicit use GOT pointer in EBX.
1660 if (!IsTailCall && !Is64Bit &&
1661 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1662 Subtarget->isPICStyleGOT())
1663 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1665 // Add argument registers to the end of the list so that they are known live
1667 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1668 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1669 RegsToPass[i].second.getValueType()));
1672 Ops.push_back(InFlag);
1675 assert(InFlag.Val &&
1676 "Flag must be set. Depend on flag being set in LowerRET");
1677 Chain = DAG.getNode(X86ISD::TAILCALL,
1678 Op.Val->getVTList(), &Ops[0], Ops.size());
1680 return SDOperand(Chain.Val, Op.ResNo);
1683 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1684 InFlag = Chain.getValue(1);
1686 // Create the CALLSEQ_END node.
1687 unsigned NumBytesForCalleeToPush;
1688 if (IsCalleePop(Op))
1689 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1690 else if (!Is64Bit && IsStructRet)
1691 // If this is is a call to a struct-return function, the callee
1692 // pops the hidden struct pointer, so we have to push it back.
1693 // This is common for Darwin/X86, Linux & Mingw32 targets.
1694 NumBytesForCalleeToPush = 4;
1696 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1698 // Returns a flag for retval copy to use.
1699 Chain = DAG.getCALLSEQ_END(Chain,
1700 DAG.getIntPtrConstant(NumBytes),
1701 DAG.getIntPtrConstant(NumBytesForCalleeToPush),
1703 InFlag = Chain.getValue(1);
1705 // Handle result values, copying them out of physregs into vregs that we
1707 switch (SRetMethod) {
1709 return SDOperand(LowerCallResult(Chain, InFlag, Op.Val, CC, DAG), Op.ResNo);
1711 return SDOperand(LowerCallResultToTwo64BitRegs(Chain, InFlag, Op.Val,
1713 MVT::i64, DAG), Op.ResNo);
1715 return SDOperand(LowerCallResultToTwo64BitRegs(Chain, InFlag, Op.Val,
1716 X86::XMM0, X86::XMM1,
1717 MVT::f64, DAG), Op.ResNo);
1719 return SDOperand(LowerCallResultToTwoX87Regs(Chain, InFlag, Op.Val, DAG),
1725 //===----------------------------------------------------------------------===//
1726 // Fast Calling Convention (tail call) implementation
1727 //===----------------------------------------------------------------------===//
1729 // Like std call, callee cleans arguments, convention except that ECX is
1730 // reserved for storing the tail called function address. Only 2 registers are
1731 // free for argument passing (inreg). Tail call optimization is performed
1733 // * tailcallopt is enabled
1734 // * caller/callee are fastcc
1735 // * elf/pic is disabled OR
1736 // * elf/pic enabled + callee is in module + callee has
1737 // visibility protected or hidden
1738 // To keep the stack aligned according to platform abi the function
1739 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1740 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1741 // If a tail called function callee has more arguments than the caller the
1742 // caller needs to make sure that there is room to move the RETADDR to. This is
1743 // achieved by reserving an area the size of the argument delta right after the
1744 // original REtADDR, but before the saved framepointer or the spilled registers
1745 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1757 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1758 /// for a 16 byte align requirement.
1759 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1760 SelectionDAG& DAG) {
1761 if (PerformTailCallOpt) {
1762 MachineFunction &MF = DAG.getMachineFunction();
1763 const TargetMachine &TM = MF.getTarget();
1764 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1765 unsigned StackAlignment = TFI.getStackAlignment();
1766 uint64_t AlignMask = StackAlignment - 1;
1767 int64_t Offset = StackSize;
1768 unsigned SlotSize = Subtarget->is64Bit() ? 8 : 4;
1769 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1770 // Number smaller than 12 so just add the difference.
1771 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1773 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1774 Offset = ((~AlignMask) & Offset) + StackAlignment +
1775 (StackAlignment-SlotSize);
1782 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1783 /// following the call is a return. A function is eligible if caller/callee
1784 /// calling conventions match, currently only fastcc supports tail calls, and
1785 /// the function CALL is immediatly followed by a RET.
1786 bool X86TargetLowering::IsEligibleForTailCallOptimization(SDOperand Call,
1788 SelectionDAG& DAG) const {
1789 if (!PerformTailCallOpt)
1792 // Check whether CALL node immediatly preceeds the RET node and whether the
1793 // return uses the result of the node or is a void return.
1794 unsigned NumOps = Ret.getNumOperands();
1796 (Ret.getOperand(0) == SDOperand(Call.Val,1) ||
1797 Ret.getOperand(0) == SDOperand(Call.Val,0))) ||
1799 Ret.getOperand(0) == SDOperand(Call.Val,Call.Val->getNumValues()-1) &&
1800 Ret.getOperand(1) == SDOperand(Call.Val,0))) {
1801 MachineFunction &MF = DAG.getMachineFunction();
1802 unsigned CallerCC = MF.getFunction()->getCallingConv();
1803 unsigned CalleeCC = cast<ConstantSDNode>(Call.getOperand(1))->getValue();
1804 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1805 SDOperand Callee = Call.getOperand(4);
1806 // On elf/pic %ebx needs to be livein.
1807 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1808 !Subtarget->isPICStyleGOT())
1811 // Can only do local tail calls with PIC.
1812 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1813 return G->getGlobal()->hasHiddenVisibility()
1814 || G->getGlobal()->hasProtectedVisibility();
1821 //===----------------------------------------------------------------------===//
1822 // Other Lowering Hooks
1823 //===----------------------------------------------------------------------===//
1826 SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1827 MachineFunction &MF = DAG.getMachineFunction();
1828 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1829 int ReturnAddrIndex = FuncInfo->getRAIndex();
1831 if (ReturnAddrIndex == 0) {
1832 // Set up a frame object for the return address.
1833 if (Subtarget->is64Bit())
1834 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(8, -8);
1836 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
1838 FuncInfo->setRAIndex(ReturnAddrIndex);
1841 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1846 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1847 /// specific condition code. It returns a false if it cannot do a direct
1848 /// translation. X86CC is the translated CondCode. LHS/RHS are modified as
1850 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1851 unsigned &X86CC, SDOperand &LHS, SDOperand &RHS,
1852 SelectionDAG &DAG) {
1853 X86CC = X86::COND_INVALID;
1855 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1856 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
1857 // X > -1 -> X == 0, jump !sign.
1858 RHS = DAG.getConstant(0, RHS.getValueType());
1859 X86CC = X86::COND_NS;
1861 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
1862 // X < 0 -> X == 0, jump on sign.
1863 X86CC = X86::COND_S;
1865 } else if (SetCCOpcode == ISD::SETLT && RHSC->getValue() == 1) {
1867 RHS = DAG.getConstant(0, RHS.getValueType());
1868 X86CC = X86::COND_LE;
1873 switch (SetCCOpcode) {
1875 case ISD::SETEQ: X86CC = X86::COND_E; break;
1876 case ISD::SETGT: X86CC = X86::COND_G; break;
1877 case ISD::SETGE: X86CC = X86::COND_GE; break;
1878 case ISD::SETLT: X86CC = X86::COND_L; break;
1879 case ISD::SETLE: X86CC = X86::COND_LE; break;
1880 case ISD::SETNE: X86CC = X86::COND_NE; break;
1881 case ISD::SETULT: X86CC = X86::COND_B; break;
1882 case ISD::SETUGT: X86CC = X86::COND_A; break;
1883 case ISD::SETULE: X86CC = X86::COND_BE; break;
1884 case ISD::SETUGE: X86CC = X86::COND_AE; break;
1887 // On a floating point condition, the flags are set as follows:
1889 // 0 | 0 | 0 | X > Y
1890 // 0 | 0 | 1 | X < Y
1891 // 1 | 0 | 0 | X == Y
1892 // 1 | 1 | 1 | unordered
1894 switch (SetCCOpcode) {
1897 case ISD::SETEQ: X86CC = X86::COND_E; break;
1898 case ISD::SETOLT: Flip = true; // Fallthrough
1900 case ISD::SETGT: X86CC = X86::COND_A; break;
1901 case ISD::SETOLE: Flip = true; // Fallthrough
1903 case ISD::SETGE: X86CC = X86::COND_AE; break;
1904 case ISD::SETUGT: Flip = true; // Fallthrough
1906 case ISD::SETLT: X86CC = X86::COND_B; break;
1907 case ISD::SETUGE: Flip = true; // Fallthrough
1909 case ISD::SETLE: X86CC = X86::COND_BE; break;
1911 case ISD::SETNE: X86CC = X86::COND_NE; break;
1912 case ISD::SETUO: X86CC = X86::COND_P; break;
1913 case ISD::SETO: X86CC = X86::COND_NP; break;
1916 std::swap(LHS, RHS);
1919 return X86CC != X86::COND_INVALID;
1922 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
1923 /// code. Current x86 isa includes the following FP cmov instructions:
1924 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
1925 static bool hasFPCMov(unsigned X86CC) {
1941 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
1942 /// true if Op is undef or if its value falls within the specified range (L, H].
1943 static bool isUndefOrInRange(SDOperand Op, unsigned Low, unsigned Hi) {
1944 if (Op.getOpcode() == ISD::UNDEF)
1947 unsigned Val = cast<ConstantSDNode>(Op)->getValue();
1948 return (Val >= Low && Val < Hi);
1951 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
1952 /// true if Op is undef or if its value equal to the specified value.
1953 static bool isUndefOrEqual(SDOperand Op, unsigned Val) {
1954 if (Op.getOpcode() == ISD::UNDEF)
1956 return cast<ConstantSDNode>(Op)->getValue() == Val;
1959 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
1960 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
1961 bool X86::isPSHUFDMask(SDNode *N) {
1962 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1964 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
1967 // Check if the value doesn't reference the second vector.
1968 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1969 SDOperand Arg = N->getOperand(i);
1970 if (Arg.getOpcode() == ISD::UNDEF) continue;
1971 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1972 if (cast<ConstantSDNode>(Arg)->getValue() >= e)
1979 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
1980 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
1981 bool X86::isPSHUFHWMask(SDNode *N) {
1982 assert(N->getOpcode() == ISD::BUILD_VECTOR);
1984 if (N->getNumOperands() != 8)
1987 // Lower quadword copied in order.
1988 for (unsigned i = 0; i != 4; ++i) {
1989 SDOperand Arg = N->getOperand(i);
1990 if (Arg.getOpcode() == ISD::UNDEF) continue;
1991 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
1992 if (cast<ConstantSDNode>(Arg)->getValue() != i)
1996 // Upper quadword shuffled.
1997 for (unsigned i = 4; i != 8; ++i) {
1998 SDOperand Arg = N->getOperand(i);
1999 if (Arg.getOpcode() == ISD::UNDEF) continue;
2000 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2001 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2002 if (Val < 4 || Val > 7)
2009 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2010 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2011 bool X86::isPSHUFLWMask(SDNode *N) {
2012 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2014 if (N->getNumOperands() != 8)
2017 // Upper quadword copied in order.
2018 for (unsigned i = 4; i != 8; ++i)
2019 if (!isUndefOrEqual(N->getOperand(i), i))
2022 // Lower quadword shuffled.
2023 for (unsigned i = 0; i != 4; ++i)
2024 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2030 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2031 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2032 static bool isSHUFPMask(const SDOperand *Elems, unsigned NumElems) {
2033 if (NumElems != 2 && NumElems != 4) return false;
2035 unsigned Half = NumElems / 2;
2036 for (unsigned i = 0; i < Half; ++i)
2037 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2039 for (unsigned i = Half; i < NumElems; ++i)
2040 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2046 bool X86::isSHUFPMask(SDNode *N) {
2047 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2048 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2051 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2052 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2053 /// half elements to come from vector 1 (which would equal the dest.) and
2054 /// the upper half to come from vector 2.
2055 static bool isCommutedSHUFP(const SDOperand *Ops, unsigned NumOps) {
2056 if (NumOps != 2 && NumOps != 4) return false;
2058 unsigned Half = NumOps / 2;
2059 for (unsigned i = 0; i < Half; ++i)
2060 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2062 for (unsigned i = Half; i < NumOps; ++i)
2063 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2068 static bool isCommutedSHUFP(SDNode *N) {
2069 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2070 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2073 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2074 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2075 bool X86::isMOVHLPSMask(SDNode *N) {
2076 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2078 if (N->getNumOperands() != 4)
2081 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2082 return isUndefOrEqual(N->getOperand(0), 6) &&
2083 isUndefOrEqual(N->getOperand(1), 7) &&
2084 isUndefOrEqual(N->getOperand(2), 2) &&
2085 isUndefOrEqual(N->getOperand(3), 3);
2088 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2089 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2091 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2092 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2094 if (N->getNumOperands() != 4)
2097 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2098 return isUndefOrEqual(N->getOperand(0), 2) &&
2099 isUndefOrEqual(N->getOperand(1), 3) &&
2100 isUndefOrEqual(N->getOperand(2), 2) &&
2101 isUndefOrEqual(N->getOperand(3), 3);
2104 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2105 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2106 bool X86::isMOVLPMask(SDNode *N) {
2107 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2109 unsigned NumElems = N->getNumOperands();
2110 if (NumElems != 2 && NumElems != 4)
2113 for (unsigned i = 0; i < NumElems/2; ++i)
2114 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2117 for (unsigned i = NumElems/2; i < NumElems; ++i)
2118 if (!isUndefOrEqual(N->getOperand(i), i))
2124 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2125 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2127 bool X86::isMOVHPMask(SDNode *N) {
2128 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2130 unsigned NumElems = N->getNumOperands();
2131 if (NumElems != 2 && NumElems != 4)
2134 for (unsigned i = 0; i < NumElems/2; ++i)
2135 if (!isUndefOrEqual(N->getOperand(i), i))
2138 for (unsigned i = 0; i < NumElems/2; ++i) {
2139 SDOperand Arg = N->getOperand(i + NumElems/2);
2140 if (!isUndefOrEqual(Arg, i + NumElems))
2147 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2148 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2149 bool static isUNPCKLMask(const SDOperand *Elts, unsigned NumElts,
2150 bool V2IsSplat = false) {
2151 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2154 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2155 SDOperand BitI = Elts[i];
2156 SDOperand BitI1 = Elts[i+1];
2157 if (!isUndefOrEqual(BitI, j))
2160 if (isUndefOrEqual(BitI1, NumElts))
2163 if (!isUndefOrEqual(BitI1, j + NumElts))
2171 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2172 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2173 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2176 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2177 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2178 bool static isUNPCKHMask(const SDOperand *Elts, unsigned NumElts,
2179 bool V2IsSplat = false) {
2180 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2183 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2184 SDOperand BitI = Elts[i];
2185 SDOperand BitI1 = Elts[i+1];
2186 if (!isUndefOrEqual(BitI, j + NumElts/2))
2189 if (isUndefOrEqual(BitI1, NumElts))
2192 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2200 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2201 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2202 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2205 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2206 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2208 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2209 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2211 unsigned NumElems = N->getNumOperands();
2212 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2215 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2216 SDOperand BitI = N->getOperand(i);
2217 SDOperand BitI1 = N->getOperand(i+1);
2219 if (!isUndefOrEqual(BitI, j))
2221 if (!isUndefOrEqual(BitI1, j))
2228 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2229 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2231 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2232 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2234 unsigned NumElems = N->getNumOperands();
2235 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2238 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2239 SDOperand BitI = N->getOperand(i);
2240 SDOperand BitI1 = N->getOperand(i + 1);
2242 if (!isUndefOrEqual(BitI, j))
2244 if (!isUndefOrEqual(BitI1, j))
2251 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2252 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2253 /// MOVSD, and MOVD, i.e. setting the lowest element.
2254 static bool isMOVLMask(const SDOperand *Elts, unsigned NumElts) {
2255 if (NumElts != 2 && NumElts != 4)
2258 if (!isUndefOrEqual(Elts[0], NumElts))
2261 for (unsigned i = 1; i < NumElts; ++i) {
2262 if (!isUndefOrEqual(Elts[i], i))
2269 bool X86::isMOVLMask(SDNode *N) {
2270 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2271 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2274 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2275 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2276 /// element of vector 2 and the other elements to come from vector 1 in order.
2277 static bool isCommutedMOVL(const SDOperand *Ops, unsigned NumOps,
2278 bool V2IsSplat = false,
2279 bool V2IsUndef = false) {
2280 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2283 if (!isUndefOrEqual(Ops[0], 0))
2286 for (unsigned i = 1; i < NumOps; ++i) {
2287 SDOperand Arg = Ops[i];
2288 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2289 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2290 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2297 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2298 bool V2IsUndef = false) {
2299 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2300 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2301 V2IsSplat, V2IsUndef);
2304 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2305 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2306 bool X86::isMOVSHDUPMask(SDNode *N) {
2307 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2309 if (N->getNumOperands() != 4)
2312 // Expect 1, 1, 3, 3
2313 for (unsigned i = 0; i < 2; ++i) {
2314 SDOperand Arg = N->getOperand(i);
2315 if (Arg.getOpcode() == ISD::UNDEF) continue;
2316 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2317 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2318 if (Val != 1) return false;
2322 for (unsigned i = 2; i < 4; ++i) {
2323 SDOperand Arg = N->getOperand(i);
2324 if (Arg.getOpcode() == ISD::UNDEF) continue;
2325 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2326 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2327 if (Val != 3) return false;
2331 // Don't use movshdup if it can be done with a shufps.
2335 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2336 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2337 bool X86::isMOVSLDUPMask(SDNode *N) {
2338 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2340 if (N->getNumOperands() != 4)
2343 // Expect 0, 0, 2, 2
2344 for (unsigned i = 0; i < 2; ++i) {
2345 SDOperand Arg = N->getOperand(i);
2346 if (Arg.getOpcode() == ISD::UNDEF) continue;
2347 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2348 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2349 if (Val != 0) return false;
2353 for (unsigned i = 2; i < 4; ++i) {
2354 SDOperand Arg = N->getOperand(i);
2355 if (Arg.getOpcode() == ISD::UNDEF) continue;
2356 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2357 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2358 if (Val != 2) return false;
2362 // Don't use movshdup if it can be done with a shufps.
2366 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2367 /// specifies a identity operation on the LHS or RHS.
2368 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2369 unsigned NumElems = N->getNumOperands();
2370 for (unsigned i = 0; i < NumElems; ++i)
2371 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2376 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2377 /// a splat of a single element.
2378 static bool isSplatMask(SDNode *N) {
2379 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2381 // This is a splat operation if each element of the permute is the same, and
2382 // if the value doesn't reference the second vector.
2383 unsigned NumElems = N->getNumOperands();
2384 SDOperand ElementBase;
2386 for (; i != NumElems; ++i) {
2387 SDOperand Elt = N->getOperand(i);
2388 if (isa<ConstantSDNode>(Elt)) {
2394 if (!ElementBase.Val)
2397 for (; i != NumElems; ++i) {
2398 SDOperand Arg = N->getOperand(i);
2399 if (Arg.getOpcode() == ISD::UNDEF) continue;
2400 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2401 if (Arg != ElementBase) return false;
2404 // Make sure it is a splat of the first vector operand.
2405 return cast<ConstantSDNode>(ElementBase)->getValue() < NumElems;
2408 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2409 /// a splat of a single element and it's a 2 or 4 element mask.
2410 bool X86::isSplatMask(SDNode *N) {
2411 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2413 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2414 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2416 return ::isSplatMask(N);
2419 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2420 /// specifies a splat of zero element.
2421 bool X86::isSplatLoMask(SDNode *N) {
2422 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2424 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2425 if (!isUndefOrEqual(N->getOperand(i), 0))
2430 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2431 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2433 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2434 unsigned NumOperands = N->getNumOperands();
2435 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2437 for (unsigned i = 0; i < NumOperands; ++i) {
2439 SDOperand Arg = N->getOperand(NumOperands-i-1);
2440 if (Arg.getOpcode() != ISD::UNDEF)
2441 Val = cast<ConstantSDNode>(Arg)->getValue();
2442 if (Val >= NumOperands) Val -= NumOperands;
2444 if (i != NumOperands - 1)
2451 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2452 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2454 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2456 // 8 nodes, but we only care about the last 4.
2457 for (unsigned i = 7; i >= 4; --i) {
2459 SDOperand Arg = N->getOperand(i);
2460 if (Arg.getOpcode() != ISD::UNDEF)
2461 Val = cast<ConstantSDNode>(Arg)->getValue();
2470 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2471 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2473 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2475 // 8 nodes, but we only care about the first 4.
2476 for (int i = 3; i >= 0; --i) {
2478 SDOperand Arg = N->getOperand(i);
2479 if (Arg.getOpcode() != ISD::UNDEF)
2480 Val = cast<ConstantSDNode>(Arg)->getValue();
2489 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2490 /// specifies a 8 element shuffle that can be broken into a pair of
2491 /// PSHUFHW and PSHUFLW.
2492 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2493 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2495 if (N->getNumOperands() != 8)
2498 // Lower quadword shuffled.
2499 for (unsigned i = 0; i != 4; ++i) {
2500 SDOperand Arg = N->getOperand(i);
2501 if (Arg.getOpcode() == ISD::UNDEF) continue;
2502 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2503 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2508 // Upper quadword shuffled.
2509 for (unsigned i = 4; i != 8; ++i) {
2510 SDOperand Arg = N->getOperand(i);
2511 if (Arg.getOpcode() == ISD::UNDEF) continue;
2512 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2513 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2514 if (Val < 4 || Val > 7)
2521 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2522 /// values in ther permute mask.
2523 static SDOperand CommuteVectorShuffle(SDOperand Op, SDOperand &V1,
2524 SDOperand &V2, SDOperand &Mask,
2525 SelectionDAG &DAG) {
2526 MVT::ValueType VT = Op.getValueType();
2527 MVT::ValueType MaskVT = Mask.getValueType();
2528 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2529 unsigned NumElems = Mask.getNumOperands();
2530 SmallVector<SDOperand, 8> MaskVec;
2532 for (unsigned i = 0; i != NumElems; ++i) {
2533 SDOperand Arg = Mask.getOperand(i);
2534 if (Arg.getOpcode() == ISD::UNDEF) {
2535 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2538 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2539 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2541 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2543 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2547 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2548 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2551 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2552 /// the two vector operands have swapped position.
2554 SDOperand CommuteVectorShuffleMask(SDOperand Mask, SelectionDAG &DAG) {
2555 MVT::ValueType MaskVT = Mask.getValueType();
2556 MVT::ValueType EltVT = MVT::getVectorElementType(MaskVT);
2557 unsigned NumElems = Mask.getNumOperands();
2558 SmallVector<SDOperand, 8> MaskVec;
2559 for (unsigned i = 0; i != NumElems; ++i) {
2560 SDOperand Arg = Mask.getOperand(i);
2561 if (Arg.getOpcode() == ISD::UNDEF) {
2562 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2565 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2566 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2568 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2570 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2572 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2576 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2577 /// match movhlps. The lower half elements should come from upper half of
2578 /// V1 (and in order), and the upper half elements should come from the upper
2579 /// half of V2 (and in order).
2580 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2581 unsigned NumElems = Mask->getNumOperands();
2584 for (unsigned i = 0, e = 2; i != e; ++i)
2585 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2587 for (unsigned i = 2; i != 4; ++i)
2588 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2593 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2594 /// is promoted to a vector.
2595 static inline bool isScalarLoadToVector(SDNode *N) {
2596 if (N->getOpcode() == ISD::SCALAR_TO_VECTOR) {
2597 N = N->getOperand(0).Val;
2598 return ISD::isNON_EXTLoad(N);
2603 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2604 /// match movlp{s|d}. The lower half elements should come from lower half of
2605 /// V1 (and in order), and the upper half elements should come from the upper
2606 /// half of V2 (and in order). And since V1 will become the source of the
2607 /// MOVLP, it must be either a vector load or a scalar load to vector.
2608 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2609 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2611 // Is V2 is a vector load, don't do this transformation. We will try to use
2612 // load folding shufps op.
2613 if (ISD::isNON_EXTLoad(V2))
2616 unsigned NumElems = Mask->getNumOperands();
2617 if (NumElems != 2 && NumElems != 4)
2619 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2620 if (!isUndefOrEqual(Mask->getOperand(i), i))
2622 for (unsigned i = NumElems/2; i != NumElems; ++i)
2623 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2628 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2630 static bool isSplatVector(SDNode *N) {
2631 if (N->getOpcode() != ISD::BUILD_VECTOR)
2634 SDOperand SplatValue = N->getOperand(0);
2635 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2636 if (N->getOperand(i) != SplatValue)
2641 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2643 static bool isUndefShuffle(SDNode *N) {
2644 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2647 SDOperand V1 = N->getOperand(0);
2648 SDOperand V2 = N->getOperand(1);
2649 SDOperand Mask = N->getOperand(2);
2650 unsigned NumElems = Mask.getNumOperands();
2651 for (unsigned i = 0; i != NumElems; ++i) {
2652 SDOperand Arg = Mask.getOperand(i);
2653 if (Arg.getOpcode() != ISD::UNDEF) {
2654 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2655 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2657 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2664 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2666 static inline bool isZeroNode(SDOperand Elt) {
2667 return ((isa<ConstantSDNode>(Elt) &&
2668 cast<ConstantSDNode>(Elt)->getValue() == 0) ||
2669 (isa<ConstantFPSDNode>(Elt) &&
2670 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2673 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2674 /// to an zero vector.
2675 static bool isZeroShuffle(SDNode *N) {
2676 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2679 SDOperand V1 = N->getOperand(0);
2680 SDOperand V2 = N->getOperand(1);
2681 SDOperand Mask = N->getOperand(2);
2682 unsigned NumElems = Mask.getNumOperands();
2683 for (unsigned i = 0; i != NumElems; ++i) {
2684 SDOperand Arg = Mask.getOperand(i);
2685 if (Arg.getOpcode() == ISD::UNDEF)
2688 unsigned Idx = cast<ConstantSDNode>(Arg)->getValue();
2689 if (Idx < NumElems) {
2690 unsigned Opc = V1.Val->getOpcode();
2691 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.Val))
2693 if (Opc != ISD::BUILD_VECTOR ||
2694 !isZeroNode(V1.Val->getOperand(Idx)))
2696 } else if (Idx >= NumElems) {
2697 unsigned Opc = V2.Val->getOpcode();
2698 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.Val))
2700 if (Opc != ISD::BUILD_VECTOR ||
2701 !isZeroNode(V2.Val->getOperand(Idx - NumElems)))
2708 /// getZeroVector - Returns a vector of specified type with all zero elements.
2710 static SDOperand getZeroVector(MVT::ValueType VT, SelectionDAG &DAG) {
2711 assert(MVT::isVector(VT) && "Expected a vector type");
2713 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2714 // type. This ensures they get CSE'd.
2715 SDOperand Cst = DAG.getTargetConstant(0, MVT::i32);
2717 if (MVT::getSizeInBits(VT) == 64) // MMX
2718 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2720 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2721 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2724 /// getOnesVector - Returns a vector of specified type with all bits set.
2726 static SDOperand getOnesVector(MVT::ValueType VT, SelectionDAG &DAG) {
2727 assert(MVT::isVector(VT) && "Expected a vector type");
2729 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2730 // type. This ensures they get CSE'd.
2731 SDOperand Cst = DAG.getTargetConstant(~0U, MVT::i32);
2733 if (MVT::getSizeInBits(VT) == 64) // MMX
2734 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2736 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2737 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2741 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2742 /// that point to V2 points to its first element.
2743 static SDOperand NormalizeMask(SDOperand Mask, SelectionDAG &DAG) {
2744 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2746 bool Changed = false;
2747 SmallVector<SDOperand, 8> MaskVec;
2748 unsigned NumElems = Mask.getNumOperands();
2749 for (unsigned i = 0; i != NumElems; ++i) {
2750 SDOperand Arg = Mask.getOperand(i);
2751 if (Arg.getOpcode() != ISD::UNDEF) {
2752 unsigned Val = cast<ConstantSDNode>(Arg)->getValue();
2753 if (Val > NumElems) {
2754 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2758 MaskVec.push_back(Arg);
2762 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2763 &MaskVec[0], MaskVec.size());
2767 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2768 /// operation of specified width.
2769 static SDOperand getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2770 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2771 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2773 SmallVector<SDOperand, 8> MaskVec;
2774 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2775 for (unsigned i = 1; i != NumElems; ++i)
2776 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2777 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2780 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2781 /// of specified width.
2782 static SDOperand getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2783 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2784 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2785 SmallVector<SDOperand, 8> MaskVec;
2786 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2787 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2788 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2790 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2793 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2794 /// of specified width.
2795 static SDOperand getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2796 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2797 MVT::ValueType BaseVT = MVT::getVectorElementType(MaskVT);
2798 unsigned Half = NumElems/2;
2799 SmallVector<SDOperand, 8> MaskVec;
2800 for (unsigned i = 0; i != Half; ++i) {
2801 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
2802 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2804 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2807 /// PromoteSplat - Promote a splat of v8i16 or v16i8 to v4i32.
2809 static SDOperand PromoteSplat(SDOperand Op, SelectionDAG &DAG) {
2810 SDOperand V1 = Op.getOperand(0);
2811 SDOperand Mask = Op.getOperand(2);
2812 MVT::ValueType VT = Op.getValueType();
2813 unsigned NumElems = Mask.getNumOperands();
2814 Mask = getUnpacklMask(NumElems, DAG);
2815 while (NumElems != 4) {
2816 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2819 V1 = DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, V1);
2821 Mask = getZeroVector(MVT::v4i32, DAG);
2822 SDOperand Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32, V1,
2823 DAG.getNode(ISD::UNDEF, MVT::v4i32), Mask);
2824 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2827 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
2828 /// vector of zero or undef vector. This produces a shuffle where the low
2829 /// element of V2 is swizzled into the zero/undef vector, landing at element
2830 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
2831 static SDOperand getShuffleVectorZeroOrUndef(SDOperand V2, MVT::ValueType VT,
2832 unsigned NumElems, unsigned Idx,
2833 bool isZero, SelectionDAG &DAG) {
2834 SDOperand V1 = isZero ? getZeroVector(VT, DAG) : DAG.getNode(ISD::UNDEF, VT);
2835 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2836 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
2837 SmallVector<SDOperand, 16> MaskVec;
2838 for (unsigned i = 0; i != NumElems; ++i)
2839 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
2840 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
2842 MaskVec.push_back(DAG.getConstant(i, EVT));
2843 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2844 &MaskVec[0], MaskVec.size());
2845 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2848 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
2850 static SDOperand LowerBuildVectorv16i8(SDOperand Op, unsigned NonZeros,
2851 unsigned NumNonZero, unsigned NumZero,
2852 SelectionDAG &DAG, TargetLowering &TLI) {
2858 for (unsigned i = 0; i < 16; ++i) {
2859 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
2860 if (ThisIsNonZero && First) {
2862 V = getZeroVector(MVT::v8i16, DAG);
2864 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2869 SDOperand ThisElt(0, 0), LastElt(0, 0);
2870 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
2871 if (LastIsNonZero) {
2872 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
2874 if (ThisIsNonZero) {
2875 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
2876 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
2877 ThisElt, DAG.getConstant(8, MVT::i8));
2879 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
2884 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
2885 DAG.getIntPtrConstant(i/2));
2889 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
2892 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
2894 static SDOperand LowerBuildVectorv8i16(SDOperand Op, unsigned NonZeros,
2895 unsigned NumNonZero, unsigned NumZero,
2896 SelectionDAG &DAG, TargetLowering &TLI) {
2902 for (unsigned i = 0; i < 8; ++i) {
2903 bool isNonZero = (NonZeros & (1 << i)) != 0;
2907 V = getZeroVector(MVT::v8i16, DAG);
2909 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
2912 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
2913 DAG.getIntPtrConstant(i));
2921 X86TargetLowering::LowerBUILD_VECTOR(SDOperand Op, SelectionDAG &DAG) {
2922 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
2923 if (ISD::isBuildVectorAllZeros(Op.Val) || ISD::isBuildVectorAllOnes(Op.Val)) {
2924 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
2925 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
2926 // eliminated on x86-32 hosts.
2927 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
2930 if (ISD::isBuildVectorAllOnes(Op.Val))
2931 return getOnesVector(Op.getValueType(), DAG);
2932 return getZeroVector(Op.getValueType(), DAG);
2935 MVT::ValueType VT = Op.getValueType();
2936 MVT::ValueType EVT = MVT::getVectorElementType(VT);
2937 unsigned EVTBits = MVT::getSizeInBits(EVT);
2939 unsigned NumElems = Op.getNumOperands();
2940 unsigned NumZero = 0;
2941 unsigned NumNonZero = 0;
2942 unsigned NonZeros = 0;
2943 bool HasNonImms = false;
2944 SmallSet<SDOperand, 8> Values;
2945 for (unsigned i = 0; i < NumElems; ++i) {
2946 SDOperand Elt = Op.getOperand(i);
2947 if (Elt.getOpcode() == ISD::UNDEF)
2950 if (Elt.getOpcode() != ISD::Constant &&
2951 Elt.getOpcode() != ISD::ConstantFP)
2953 if (isZeroNode(Elt))
2956 NonZeros |= (1 << i);
2961 if (NumNonZero == 0) {
2962 // All undef vector. Return an UNDEF. All zero vectors were handled above.
2963 return DAG.getNode(ISD::UNDEF, VT);
2966 // Splat is obviously ok. Let legalizer expand it to a shuffle.
2967 if (Values.size() == 1)
2970 // Special case for single non-zero element.
2971 if (NumNonZero == 1 && NumElems <= 4) {
2972 unsigned Idx = CountTrailingZeros_32(NonZeros);
2973 SDOperand Item = Op.getOperand(Idx);
2974 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
2976 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
2977 return getShuffleVectorZeroOrUndef(Item, VT, NumElems, Idx,
2979 else if (!HasNonImms) // Otherwise, it's better to do a constpool load.
2982 if (EVTBits == 32) {
2983 // Turn it into a shuffle of zero and zero-extended scalar to vector.
2984 Item = getShuffleVectorZeroOrUndef(Item, VT, NumElems, 0, NumZero > 0,
2986 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2987 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
2988 SmallVector<SDOperand, 8> MaskVec;
2989 for (unsigned i = 0; i < NumElems; i++)
2990 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
2991 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
2992 &MaskVec[0], MaskVec.size());
2993 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
2994 DAG.getNode(ISD::UNDEF, VT), Mask);
2998 // A vector full of immediates; various special cases are already
2999 // handled, so this is best done with a single constant-pool load.
3003 // Let legalizer expand 2-wide build_vectors.
3007 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3008 if (EVTBits == 8 && NumElems == 16) {
3009 SDOperand V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3011 if (V.Val) return V;
3014 if (EVTBits == 16 && NumElems == 8) {
3015 SDOperand V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3017 if (V.Val) return V;
3020 // If element VT is == 32 bits, turn it into a number of shuffles.
3021 SmallVector<SDOperand, 8> V;
3023 if (NumElems == 4 && NumZero > 0) {
3024 for (unsigned i = 0; i < 4; ++i) {
3025 bool isZero = !(NonZeros & (1 << i));
3027 V[i] = getZeroVector(VT, DAG);
3029 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3032 for (unsigned i = 0; i < 2; ++i) {
3033 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3036 V[i] = V[i*2]; // Must be a zero vector.
3039 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3040 getMOVLMask(NumElems, DAG));
3043 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3044 getMOVLMask(NumElems, DAG));
3047 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3048 getUnpacklMask(NumElems, DAG));
3053 // Take advantage of the fact GR32 to VR128 scalar_to_vector (i.e. movd)
3054 // clears the upper bits.
3055 // FIXME: we can do the same for v4f32 case when we know both parts of
3056 // the lower half come from scalar_to_vector (loadf32). We should do
3057 // that in post legalizer dag combiner with target specific hooks.
3058 if (MVT::isInteger(EVT) && (NonZeros & (0x3 << 2)) == 0)
3060 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3061 MVT::ValueType EVT = MVT::getVectorElementType(MaskVT);
3062 SmallVector<SDOperand, 8> MaskVec;
3063 bool Reverse = (NonZeros & 0x3) == 2;
3064 for (unsigned i = 0; i < 2; ++i)
3066 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3068 MaskVec.push_back(DAG.getConstant(i, EVT));
3069 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3070 for (unsigned i = 0; i < 2; ++i)
3072 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3074 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3075 SDOperand ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3076 &MaskVec[0], MaskVec.size());
3077 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3080 if (Values.size() > 2) {
3081 // Expand into a number of unpckl*.
3083 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3084 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3085 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3086 SDOperand UnpckMask = getUnpacklMask(NumElems, DAG);
3087 for (unsigned i = 0; i < NumElems; ++i)
3088 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3090 while (NumElems != 0) {
3091 for (unsigned i = 0; i < NumElems; ++i)
3092 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3103 SDOperand LowerVECTOR_SHUFFLEv8i16(SDOperand V1, SDOperand V2,
3104 SDOperand PermMask, SelectionDAG &DAG,
3105 TargetLowering &TLI) {
3107 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(8);
3108 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3109 MVT::ValueType PtrVT = TLI.getPointerTy();
3110 SmallVector<SDOperand, 8> MaskElts(PermMask.Val->op_begin(),
3111 PermMask.Val->op_end());
3113 // First record which half of which vector the low elements come from.
3114 SmallVector<unsigned, 4> LowQuad(4);
3115 for (unsigned i = 0; i < 4; ++i) {
3116 SDOperand Elt = MaskElts[i];
3117 if (Elt.getOpcode() == ISD::UNDEF)
3119 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3120 int QuadIdx = EltIdx / 4;
3123 int BestLowQuad = -1;
3124 unsigned MaxQuad = 1;
3125 for (unsigned i = 0; i < 4; ++i) {
3126 if (LowQuad[i] > MaxQuad) {
3128 MaxQuad = LowQuad[i];
3132 // Record which half of which vector the high elements come from.
3133 SmallVector<unsigned, 4> HighQuad(4);
3134 for (unsigned i = 4; i < 8; ++i) {
3135 SDOperand Elt = MaskElts[i];
3136 if (Elt.getOpcode() == ISD::UNDEF)
3138 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3139 int QuadIdx = EltIdx / 4;
3140 ++HighQuad[QuadIdx];
3142 int BestHighQuad = -1;
3144 for (unsigned i = 0; i < 4; ++i) {
3145 if (HighQuad[i] > MaxQuad) {
3147 MaxQuad = HighQuad[i];
3151 // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3152 if (BestLowQuad != -1 || BestHighQuad != -1) {
3153 // First sort the 4 chunks in order using shufpd.
3154 SmallVector<SDOperand, 8> MaskVec;
3155 if (BestLowQuad != -1)
3156 MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3158 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3159 if (BestHighQuad != -1)
3160 MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3162 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3163 SDOperand Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3164 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3165 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3166 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3167 NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3169 // Now sort high and low parts separately.
3170 BitVector InOrder(8);
3171 if (BestLowQuad != -1) {
3172 // Sort lower half in order using PSHUFLW.
3174 bool AnyOutOrder = false;
3175 for (unsigned i = 0; i != 4; ++i) {
3176 SDOperand Elt = MaskElts[i];
3177 if (Elt.getOpcode() == ISD::UNDEF) {
3178 MaskVec.push_back(Elt);
3181 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3184 MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3185 // If this element is in the right place after this shuffle, then
3187 if ((int)(EltIdx / 4) == BestLowQuad)
3192 for (unsigned i = 4; i != 8; ++i)
3193 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3194 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3195 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3199 if (BestHighQuad != -1) {
3200 // Sort high half in order using PSHUFHW if possible.
3202 for (unsigned i = 0; i != 4; ++i)
3203 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3204 bool AnyOutOrder = false;
3205 for (unsigned i = 4; i != 8; ++i) {
3206 SDOperand Elt = MaskElts[i];
3207 if (Elt.getOpcode() == ISD::UNDEF) {
3208 MaskVec.push_back(Elt);
3211 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3214 MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3215 // If this element is in the right place after this shuffle, then
3217 if ((int)(EltIdx / 4) == BestHighQuad)
3222 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3223 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3227 // The other elements are put in the right place using pextrw and pinsrw.
3228 for (unsigned i = 0; i != 8; ++i) {
3231 SDOperand Elt = MaskElts[i];
3232 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3235 SDOperand ExtOp = (EltIdx < 8)
3236 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3237 DAG.getConstant(EltIdx, PtrVT))
3238 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3239 DAG.getConstant(EltIdx - 8, PtrVT));
3240 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3241 DAG.getConstant(i, PtrVT));
3246 // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use
3247 ///as few as possible.
3248 // First, let's find out how many elements are already in the right order.
3249 unsigned V1InOrder = 0;
3250 unsigned V1FromV1 = 0;
3251 unsigned V2InOrder = 0;
3252 unsigned V2FromV2 = 0;
3253 SmallVector<SDOperand, 8> V1Elts;
3254 SmallVector<SDOperand, 8> V2Elts;
3255 for (unsigned i = 0; i < 8; ++i) {
3256 SDOperand Elt = MaskElts[i];
3257 if (Elt.getOpcode() == ISD::UNDEF) {
3258 V1Elts.push_back(Elt);
3259 V2Elts.push_back(Elt);
3264 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3266 V1Elts.push_back(Elt);
3267 V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3269 } else if (EltIdx == i+8) {
3270 V1Elts.push_back(Elt);
3271 V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3273 } else if (EltIdx < 8) {
3274 V1Elts.push_back(Elt);
3277 V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3282 if (V2InOrder > V1InOrder) {
3283 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3285 std::swap(V1Elts, V2Elts);
3286 std::swap(V1FromV1, V2FromV2);
3289 if ((V1FromV1 + V1InOrder) != 8) {
3290 // Some elements are from V2.
3292 // If there are elements that are from V1 but out of place,
3293 // then first sort them in place
3294 SmallVector<SDOperand, 8> MaskVec;
3295 for (unsigned i = 0; i < 8; ++i) {
3296 SDOperand Elt = V1Elts[i];
3297 if (Elt.getOpcode() == ISD::UNDEF) {
3298 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3301 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3303 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3305 MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3307 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3308 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3312 for (unsigned i = 0; i < 8; ++i) {
3313 SDOperand Elt = V1Elts[i];
3314 if (Elt.getOpcode() == ISD::UNDEF)
3316 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3319 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3320 DAG.getConstant(EltIdx - 8, PtrVT));
3321 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3322 DAG.getConstant(i, PtrVT));
3326 // All elements are from V1.
3328 for (unsigned i = 0; i < 8; ++i) {
3329 SDOperand Elt = V1Elts[i];
3330 if (Elt.getOpcode() == ISD::UNDEF)
3332 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3333 SDOperand ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3334 DAG.getConstant(EltIdx, PtrVT));
3335 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3336 DAG.getConstant(i, PtrVT));
3342 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3343 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3344 /// done when every pair / quad of shuffle mask elements point to elements in
3345 /// the right sequence. e.g.
3346 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3348 SDOperand RewriteAsNarrowerShuffle(SDOperand V1, SDOperand V2,
3350 SDOperand PermMask, SelectionDAG &DAG,
3351 TargetLowering &TLI) {
3352 unsigned NumElems = PermMask.getNumOperands();
3353 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3354 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3355 MVT::ValueType NewVT = MaskVT;
3357 case MVT::v4f32: NewVT = MVT::v2f64; break;
3358 case MVT::v4i32: NewVT = MVT::v2i64; break;
3359 case MVT::v8i16: NewVT = MVT::v4i32; break;
3360 case MVT::v16i8: NewVT = MVT::v4i32; break;
3361 default: assert(false && "Unexpected!");
3365 if (MVT::isInteger(VT))
3369 unsigned Scale = NumElems / NewWidth;
3370 SmallVector<SDOperand, 8> MaskVec;
3371 for (unsigned i = 0; i < NumElems; i += Scale) {
3372 unsigned StartIdx = ~0U;
3373 for (unsigned j = 0; j < Scale; ++j) {
3374 SDOperand Elt = PermMask.getOperand(i+j);
3375 if (Elt.getOpcode() == ISD::UNDEF)
3377 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getValue();
3378 if (StartIdx == ~0U)
3379 StartIdx = EltIdx - (EltIdx % Scale);
3380 if (EltIdx != StartIdx + j)
3383 if (StartIdx == ~0U)
3384 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
3386 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MVT::i32));
3389 V1 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V1);
3390 V2 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V2);
3391 return DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, V1, V2,
3392 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3393 &MaskVec[0], MaskVec.size()));
3397 X86TargetLowering::LowerVECTOR_SHUFFLE(SDOperand Op, SelectionDAG &DAG) {
3398 SDOperand V1 = Op.getOperand(0);
3399 SDOperand V2 = Op.getOperand(1);
3400 SDOperand PermMask = Op.getOperand(2);
3401 MVT::ValueType VT = Op.getValueType();
3402 unsigned NumElems = PermMask.getNumOperands();
3403 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3404 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3405 bool V1IsSplat = false;
3406 bool V2IsSplat = false;
3408 if (isUndefShuffle(Op.Val))
3409 return DAG.getNode(ISD::UNDEF, VT);
3411 if (isZeroShuffle(Op.Val))
3412 return getZeroVector(VT, DAG);
3414 if (isIdentityMask(PermMask.Val))
3416 else if (isIdentityMask(PermMask.Val, true))
3419 if (isSplatMask(PermMask.Val)) {
3420 if (NumElems <= 4) return Op;
3421 // Promote it to a v4i32 splat.
3422 return PromoteSplat(Op, DAG);
3425 // If the shuffle can be profitably rewritten as a narrower shuffle, then
3427 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3428 SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3430 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3431 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
3432 // FIXME: Figure out a cleaner way to do this.
3433 // Try to make use of movq to zero out the top part.
3434 if (ISD::isBuildVectorAllZeros(V2.Val)) {
3435 SDOperand NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3437 SDOperand NewV1 = NewOp.getOperand(0);
3438 SDOperand NewV2 = NewOp.getOperand(1);
3439 SDOperand NewMask = NewOp.getOperand(2);
3440 if (isCommutedMOVL(NewMask.Val, true, false)) {
3441 NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
3442 NewOp = DAG.getNode(ISD::VECTOR_SHUFFLE, NewOp.getValueType(),
3443 NewV1, NewV2, getMOVLMask(2, DAG));
3444 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3447 } else if (ISD::isBuildVectorAllZeros(V1.Val)) {
3448 SDOperand NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3449 if (NewOp.Val && X86::isMOVLMask(NewOp.getOperand(2).Val))
3450 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
3454 if (X86::isMOVLMask(PermMask.Val))
3455 return (V1IsUndef) ? V2 : Op;
3457 if (X86::isMOVSHDUPMask(PermMask.Val) ||
3458 X86::isMOVSLDUPMask(PermMask.Val) ||
3459 X86::isMOVHLPSMask(PermMask.Val) ||
3460 X86::isMOVHPMask(PermMask.Val) ||
3461 X86::isMOVLPMask(PermMask.Val))
3464 if (ShouldXformToMOVHLPS(PermMask.Val) ||
3465 ShouldXformToMOVLP(V1.Val, V2.Val, PermMask.Val))
3466 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3468 bool Commuted = false;
3469 // FIXME: This should also accept a bitcast of a splat? Be careful, not
3470 // 1,1,1,1 -> v8i16 though.
3471 V1IsSplat = isSplatVector(V1.Val);
3472 V2IsSplat = isSplatVector(V2.Val);
3474 // Canonicalize the splat or undef, if present, to be on the RHS.
3475 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
3476 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3477 std::swap(V1IsSplat, V2IsSplat);
3478 std::swap(V1IsUndef, V2IsUndef);
3482 // FIXME: Figure out a cleaner way to do this.
3483 if (isCommutedMOVL(PermMask.Val, V2IsSplat, V2IsUndef)) {
3484 if (V2IsUndef) return V1;
3485 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3487 // V2 is a splat, so the mask may be malformed. That is, it may point
3488 // to any V2 element. The instruction selectior won't like this. Get
3489 // a corrected mask and commute to form a proper MOVS{S|D}.
3490 SDOperand NewMask = getMOVLMask(NumElems, DAG);
3491 if (NewMask.Val != PermMask.Val)
3492 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3497 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3498 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3499 X86::isUNPCKLMask(PermMask.Val) ||
3500 X86::isUNPCKHMask(PermMask.Val))
3504 // Normalize mask so all entries that point to V2 points to its first
3505 // element then try to match unpck{h|l} again. If match, return a
3506 // new vector_shuffle with the corrected mask.
3507 SDOperand NewMask = NormalizeMask(PermMask, DAG);
3508 if (NewMask.Val != PermMask.Val) {
3509 if (X86::isUNPCKLMask(PermMask.Val, true)) {
3510 SDOperand NewMask = getUnpacklMask(NumElems, DAG);
3511 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3512 } else if (X86::isUNPCKHMask(PermMask.Val, true)) {
3513 SDOperand NewMask = getUnpackhMask(NumElems, DAG);
3514 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
3519 // Normalize the node to match x86 shuffle ops if needed
3520 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.Val))
3521 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3524 // Commute is back and try unpck* again.
3525 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
3526 if (X86::isUNPCKL_v_undef_Mask(PermMask.Val) ||
3527 X86::isUNPCKH_v_undef_Mask(PermMask.Val) ||
3528 X86::isUNPCKLMask(PermMask.Val) ||
3529 X86::isUNPCKHMask(PermMask.Val))
3533 // If VT is integer, try PSHUF* first, then SHUFP*.
3534 if (MVT::isInteger(VT)) {
3535 // MMX doesn't have PSHUFD; it does have PSHUFW. While it's theoretically
3536 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
3537 if (((MVT::getSizeInBits(VT) != 64 || NumElems == 4) &&
3538 X86::isPSHUFDMask(PermMask.Val)) ||
3539 X86::isPSHUFHWMask(PermMask.Val) ||
3540 X86::isPSHUFLWMask(PermMask.Val)) {
3541 if (V2.getOpcode() != ISD::UNDEF)
3542 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3543 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3547 if (X86::isSHUFPMask(PermMask.Val) &&
3548 MVT::getSizeInBits(VT) != 64) // Don't do this for MMX.
3551 // Floating point cases in the other order.
3552 if (X86::isSHUFPMask(PermMask.Val))
3554 if (X86::isPSHUFDMask(PermMask.Val) ||
3555 X86::isPSHUFHWMask(PermMask.Val) ||
3556 X86::isPSHUFLWMask(PermMask.Val)) {
3557 if (V2.getOpcode() != ISD::UNDEF)
3558 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
3559 DAG.getNode(ISD::UNDEF, V1.getValueType()),PermMask);
3564 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
3565 if (VT == MVT::v8i16) {
3566 SDOperand NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
3571 // Handle all 4 wide cases with a number of shuffles.
3572 if (NumElems == 4 && MVT::getSizeInBits(VT) != 64) {
3573 // Don't do this for MMX.
3574 MVT::ValueType MaskVT = PermMask.getValueType();
3575 MVT::ValueType MaskEVT = MVT::getVectorElementType(MaskVT);
3576 SmallVector<std::pair<int, int>, 8> Locs;
3577 Locs.reserve(NumElems);
3578 SmallVector<SDOperand, 8> Mask1(NumElems,
3579 DAG.getNode(ISD::UNDEF, MaskEVT));
3580 SmallVector<SDOperand, 8> Mask2(NumElems,
3581 DAG.getNode(ISD::UNDEF, MaskEVT));
3584 // If no more than two elements come from either vector. This can be
3585 // implemented with two shuffles. First shuffle gather the elements.
3586 // The second shuffle, which takes the first shuffle as both of its
3587 // vector operands, put the elements into the right order.
3588 for (unsigned i = 0; i != NumElems; ++i) {
3589 SDOperand Elt = PermMask.getOperand(i);
3590 if (Elt.getOpcode() == ISD::UNDEF) {
3591 Locs[i] = std::make_pair(-1, -1);
3593 unsigned Val = cast<ConstantSDNode>(Elt)->getValue();
3594 if (Val < NumElems) {
3595 Locs[i] = std::make_pair(0, NumLo);
3599 Locs[i] = std::make_pair(1, NumHi);
3600 if (2+NumHi < NumElems)
3601 Mask1[2+NumHi] = Elt;
3606 if (NumLo <= 2 && NumHi <= 2) {
3607 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3608 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3609 &Mask1[0], Mask1.size()));
3610 for (unsigned i = 0; i != NumElems; ++i) {
3611 if (Locs[i].first == -1)
3614 unsigned Idx = (i < NumElems/2) ? 0 : NumElems;
3615 Idx += Locs[i].first * (NumElems/2) + Locs[i].second;
3616 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3620 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3621 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3622 &Mask2[0], Mask2.size()));
3625 // Break it into (shuffle shuffle_hi, shuffle_lo).
3627 SmallVector<SDOperand,8> LoMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3628 SmallVector<SDOperand,8> HiMask(NumElems, DAG.getNode(ISD::UNDEF, MaskEVT));
3629 SmallVector<SDOperand,8> *MaskPtr = &LoMask;
3630 unsigned MaskIdx = 0;
3632 unsigned HiIdx = NumElems/2;
3633 for (unsigned i = 0; i != NumElems; ++i) {
3634 if (i == NumElems/2) {
3640 SDOperand Elt = PermMask.getOperand(i);
3641 if (Elt.getOpcode() == ISD::UNDEF) {
3642 Locs[i] = std::make_pair(-1, -1);
3643 } else if (cast<ConstantSDNode>(Elt)->getValue() < NumElems) {
3644 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3645 (*MaskPtr)[LoIdx] = Elt;
3648 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3649 (*MaskPtr)[HiIdx] = Elt;
3654 SDOperand LoShuffle =
3655 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3656 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3657 &LoMask[0], LoMask.size()));
3658 SDOperand HiShuffle =
3659 DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3660 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3661 &HiMask[0], HiMask.size()));
3662 SmallVector<SDOperand, 8> MaskOps;
3663 for (unsigned i = 0; i != NumElems; ++i) {
3664 if (Locs[i].first == -1) {
3665 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3667 unsigned Idx = Locs[i].first * NumElems + Locs[i].second;
3668 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3671 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3672 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3673 &MaskOps[0], MaskOps.size()));
3680 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDOperand Op,
3681 SelectionDAG &DAG) {
3682 MVT::ValueType VT = Op.getValueType();
3683 if (MVT::getSizeInBits(VT) == 8) {
3684 SDOperand Extract = DAG.getNode(X86ISD::PEXTRB, MVT::i32,
3685 Op.getOperand(0), Op.getOperand(1));
3686 SDOperand Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
3687 DAG.getValueType(VT));
3688 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3689 } else if (MVT::getSizeInBits(VT) == 16) {
3690 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, MVT::i32,
3691 Op.getOperand(0), Op.getOperand(1));
3692 SDOperand Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
3693 DAG.getValueType(VT));
3694 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3701 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3702 if (!isa<ConstantSDNode>(Op.getOperand(1)))
3705 if (Subtarget->hasSSE41())
3706 return LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
3708 MVT::ValueType VT = Op.getValueType();
3709 // TODO: handle v16i8.
3710 if (MVT::getSizeInBits(VT) == 16) {
3711 SDOperand Vec = Op.getOperand(0);
3712 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3714 return DAG.getNode(ISD::TRUNCATE, MVT::i16,
3715 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
3716 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
3718 // Transform it so it match pextrw which produces a 32-bit result.
3719 MVT::ValueType EVT = (MVT::ValueType)(VT+1);
3720 SDOperand Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
3721 Op.getOperand(0), Op.getOperand(1));
3722 SDOperand Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
3723 DAG.getValueType(VT));
3724 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
3725 } else if (MVT::getSizeInBits(VT) == 32) {
3726 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3729 // SHUFPS the element to the lowest double word, then movss.
3730 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3731 SmallVector<SDOperand, 8> IdxVec;
3733 push_back(DAG.getConstant(Idx, MVT::getVectorElementType(MaskVT)));
3735 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3737 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3739 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3740 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3741 &IdxVec[0], IdxVec.size());
3742 SDOperand Vec = Op.getOperand(0);
3743 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3744 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3745 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3746 DAG.getIntPtrConstant(0));
3747 } else if (MVT::getSizeInBits(VT) == 64) {
3748 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
3749 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
3750 // to match extract_elt for f64.
3751 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getValue();
3755 // UNPCKHPD the element to the lowest double word, then movsd.
3756 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
3757 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
3758 MVT::ValueType MaskVT = MVT::getIntVectorWithNumElements(4);
3759 SmallVector<SDOperand, 8> IdxVec;
3760 IdxVec.push_back(DAG.getConstant(1, MVT::getVectorElementType(MaskVT)));
3762 push_back(DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(MaskVT)));
3763 SDOperand Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3764 &IdxVec[0], IdxVec.size());
3765 SDOperand Vec = Op.getOperand(0);
3766 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
3767 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
3768 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
3769 DAG.getIntPtrConstant(0));
3776 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDOperand Op, SelectionDAG &DAG){
3777 MVT::ValueType VT = Op.getValueType();
3778 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3780 SDOperand N0 = Op.getOperand(0);
3781 SDOperand N1 = Op.getOperand(1);
3782 SDOperand N2 = Op.getOperand(2);
3784 if ((MVT::getSizeInBits(EVT) == 8) || (MVT::getSizeInBits(EVT) == 16)) {
3785 unsigned Opc = (MVT::getSizeInBits(EVT) == 8) ? X86ISD::PINSRB
3787 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
3789 if (N1.getValueType() != MVT::i32)
3790 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3791 if (N2.getValueType() != MVT::i32)
3792 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
3793 return DAG.getNode(Opc, VT, N0, N1, N2);
3794 } else if (EVT == MVT::f32) {
3795 // Bits [7:6] of the constant are the source select. This will always be
3796 // zero here. The DAG Combiner may combine an extract_elt index into these
3797 // bits. For example (insert (extract, 3), 2) could be matched by putting
3798 // the '3' into bits [7:6] of X86ISD::INSERTPS.
3799 // Bits [5:4] of the constant are the destination select. This is the
3800 // value of the incoming immediate.
3801 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
3802 // combine either bitwise AND or insert of float 0.0 to set these bits.
3803 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue() << 4);
3804 return DAG.getNode(X86ISD::INSERTPS, VT, N0, N1, N2);
3810 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDOperand Op, SelectionDAG &DAG) {
3811 MVT::ValueType VT = Op.getValueType();
3812 MVT::ValueType EVT = MVT::getVectorElementType(VT);
3814 if (Subtarget->hasSSE41())
3815 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
3820 SDOperand N0 = Op.getOperand(0);
3821 SDOperand N1 = Op.getOperand(1);
3822 SDOperand N2 = Op.getOperand(2);
3824 if (MVT::getSizeInBits(EVT) == 16) {
3825 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
3826 // as its second argument.
3827 if (N1.getValueType() != MVT::i32)
3828 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
3829 if (N2.getValueType() != MVT::i32)
3830 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getValue());
3831 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
3837 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDOperand Op, SelectionDAG &DAG) {
3838 SDOperand AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
3839 return DAG.getNode(X86ISD::S2VEC, Op.getValueType(), AnyExt);
3842 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
3843 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
3844 // one of the above mentioned nodes. It has to be wrapped because otherwise
3845 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
3846 // be used to form addressing mode. These wrapped nodes will be selected
3849 X86TargetLowering::LowerConstantPool(SDOperand Op, SelectionDAG &DAG) {
3850 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3851 SDOperand Result = DAG.getTargetConstantPool(CP->getConstVal(),
3853 CP->getAlignment());
3854 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3855 // With PIC, the address is actually $g + Offset.
3856 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3857 !Subtarget->isPICStyleRIPRel()) {
3858 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3859 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3867 X86TargetLowering::LowerGlobalAddress(SDOperand Op, SelectionDAG &DAG) {
3868 GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3869 SDOperand Result = DAG.getTargetGlobalAddress(GV, getPointerTy());
3870 // If it's a debug information descriptor, don't mess with it.
3871 if (DAG.isVerifiedDebugInfoDesc(Op))
3873 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3874 // With PIC, the address is actually $g + Offset.
3875 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3876 !Subtarget->isPICStyleRIPRel()) {
3877 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3878 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3882 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
3883 // load the value at address GV, not the value of GV itself. This means that
3884 // the GlobalAddress must be in the base or index register of the address, not
3885 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
3886 // The same applies for external symbols during PIC codegen
3887 if (Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false))
3888 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
3889 PseudoSourceValue::getGOT(), 0);
3894 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
3896 LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
3897 const MVT::ValueType PtrVT) {
3899 SDOperand Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
3900 DAG.getNode(X86ISD::GlobalBaseReg,
3902 InFlag = Chain.getValue(1);
3904 // emit leal symbol@TLSGD(,%ebx,1), %eax
3905 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
3906 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
3907 GA->getValueType(0),
3909 SDOperand Ops[] = { Chain, TGA, InFlag };
3910 SDOperand Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
3911 InFlag = Result.getValue(2);
3912 Chain = Result.getValue(1);
3914 // call ___tls_get_addr. This function receives its argument in
3915 // the register EAX.
3916 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
3917 InFlag = Chain.getValue(1);
3919 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
3920 SDOperand Ops1[] = { Chain,
3921 DAG.getTargetExternalSymbol("___tls_get_addr",
3923 DAG.getRegister(X86::EAX, PtrVT),
3924 DAG.getRegister(X86::EBX, PtrVT),
3926 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
3927 InFlag = Chain.getValue(1);
3929 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
3932 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
3933 // "local exec" model.
3935 LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
3936 const MVT::ValueType PtrVT) {
3937 // Get the Thread Pointer
3938 SDOperand ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
3939 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
3941 SDOperand TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
3942 GA->getValueType(0),
3944 SDOperand Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
3946 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
3947 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
3948 PseudoSourceValue::getGOT(), 0);
3950 // The address of the thread local variable is the add of the thread
3951 // pointer with the offset of the variable.
3952 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
3956 X86TargetLowering::LowerGlobalTLSAddress(SDOperand Op, SelectionDAG &DAG) {
3957 // TODO: implement the "local dynamic" model
3958 // TODO: implement the "initial exec"model for pic executables
3959 assert(!Subtarget->is64Bit() && Subtarget->isTargetELF() &&
3960 "TLS not implemented for non-ELF and 64-bit targets");
3961 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3962 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
3963 // otherwise use the "Local Exec"TLS Model
3964 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
3965 return LowerToTLSGeneralDynamicModel(GA, DAG, getPointerTy());
3967 return LowerToTLSExecModel(GA, DAG, getPointerTy());
3971 X86TargetLowering::LowerExternalSymbol(SDOperand Op, SelectionDAG &DAG) {
3972 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
3973 SDOperand Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
3974 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3975 // With PIC, the address is actually $g + Offset.
3976 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3977 !Subtarget->isPICStyleRIPRel()) {
3978 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3979 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
3986 SDOperand X86TargetLowering::LowerJumpTable(SDOperand Op, SelectionDAG &DAG) {
3987 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3988 SDOperand Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
3989 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
3990 // With PIC, the address is actually $g + Offset.
3991 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
3992 !Subtarget->isPICStyleRIPRel()) {
3993 Result = DAG.getNode(ISD::ADD, getPointerTy(),
3994 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4001 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4002 /// take a 2 x i32 value to shift plus a shift amount.
4003 SDOperand X86TargetLowering::LowerShift(SDOperand Op, SelectionDAG &DAG) {
4004 assert(Op.getNumOperands() == 3 && Op.getValueType() == MVT::i32 &&
4005 "Not an i64 shift!");
4006 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4007 SDOperand ShOpLo = Op.getOperand(0);
4008 SDOperand ShOpHi = Op.getOperand(1);
4009 SDOperand ShAmt = Op.getOperand(2);
4010 SDOperand Tmp1 = isSRA ?
4011 DAG.getNode(ISD::SRA, MVT::i32, ShOpHi, DAG.getConstant(31, MVT::i8)) :
4012 DAG.getConstant(0, MVT::i32);
4014 SDOperand Tmp2, Tmp3;
4015 if (Op.getOpcode() == ISD::SHL_PARTS) {
4016 Tmp2 = DAG.getNode(X86ISD::SHLD, MVT::i32, ShOpHi, ShOpLo, ShAmt);
4017 Tmp3 = DAG.getNode(ISD::SHL, MVT::i32, ShOpLo, ShAmt);
4019 Tmp2 = DAG.getNode(X86ISD::SHRD, MVT::i32, ShOpLo, ShOpHi, ShAmt);
4020 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, MVT::i32, ShOpHi, ShAmt);
4023 const MVT::ValueType *VTs = DAG.getNodeValueTypes(MVT::Other, MVT::Flag);
4024 SDOperand AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4025 DAG.getConstant(32, MVT::i8));
4026 SDOperand Cond = DAG.getNode(X86ISD::CMP, MVT::i32,
4027 AndNode, DAG.getConstant(0, MVT::i8));
4030 SDOperand CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4031 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::Flag);
4032 SmallVector<SDOperand, 4> Ops;
4033 if (Op.getOpcode() == ISD::SHL_PARTS) {
4034 Ops.push_back(Tmp2);
4035 Ops.push_back(Tmp3);
4037 Ops.push_back(Cond);
4038 Hi = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4041 Ops.push_back(Tmp3);
4042 Ops.push_back(Tmp1);
4044 Ops.push_back(Cond);
4045 Lo = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4047 Ops.push_back(Tmp2);
4048 Ops.push_back(Tmp3);
4050 Ops.push_back(Cond);
4051 Lo = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4054 Ops.push_back(Tmp3);
4055 Ops.push_back(Tmp1);
4057 Ops.push_back(Cond);
4058 Hi = DAG.getNode(X86ISD::CMOV, MVT::i32, &Ops[0], Ops.size());
4061 VTs = DAG.getNodeValueTypes(MVT::i32, MVT::i32);
4065 return DAG.getNode(ISD::MERGE_VALUES, VTs, 2, &Ops[0], Ops.size());
4068 SDOperand X86TargetLowering::LowerSINT_TO_FP(SDOperand Op, SelectionDAG &DAG) {
4069 assert(Op.getOperand(0).getValueType() <= MVT::i64 &&
4070 Op.getOperand(0).getValueType() >= MVT::i16 &&
4071 "Unknown SINT_TO_FP to lower!");
4074 MVT::ValueType SrcVT = Op.getOperand(0).getValueType();
4075 unsigned Size = MVT::getSizeInBits(SrcVT)/8;
4076 MachineFunction &MF = DAG.getMachineFunction();
4077 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4078 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4079 SDOperand Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4081 PseudoSourceValue::getFixedStack(),
4084 // These are really Legal; caller falls through into that case.
4085 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4087 if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 &&
4088 Subtarget->is64Bit())
4093 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4095 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4097 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4098 SmallVector<SDOperand, 8> Ops;
4099 Ops.push_back(Chain);
4100 Ops.push_back(StackSlot);
4101 Ops.push_back(DAG.getValueType(SrcVT));
4102 Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG :X86ISD::FILD,
4103 Tys, &Ops[0], Ops.size());
4106 Chain = Result.getValue(1);
4107 SDOperand InFlag = Result.getValue(2);
4109 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4110 // shouldn't be necessary except that RFP cannot be live across
4111 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4112 MachineFunction &MF = DAG.getMachineFunction();
4113 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4114 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4115 Tys = DAG.getVTList(MVT::Other);
4116 SmallVector<SDOperand, 8> Ops;
4117 Ops.push_back(Chain);
4118 Ops.push_back(Result);
4119 Ops.push_back(StackSlot);
4120 Ops.push_back(DAG.getValueType(Op.getValueType()));
4121 Ops.push_back(InFlag);
4122 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4123 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
4124 PseudoSourceValue::getFixedStack(), SSFI);
4130 std::pair<SDOperand,SDOperand> X86TargetLowering::
4131 FP_TO_SINTHelper(SDOperand Op, SelectionDAG &DAG) {
4132 assert(Op.getValueType() <= MVT::i64 && Op.getValueType() >= MVT::i16 &&
4133 "Unknown FP_TO_SINT to lower!");
4135 // These are really Legal.
4136 if (Op.getValueType() == MVT::i32 &&
4137 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4138 return std::make_pair(SDOperand(), SDOperand());
4139 if (Subtarget->is64Bit() &&
4140 Op.getValueType() == MVT::i64 &&
4141 Op.getOperand(0).getValueType() != MVT::f80)
4142 return std::make_pair(SDOperand(), SDOperand());
4144 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4146 MachineFunction &MF = DAG.getMachineFunction();
4147 unsigned MemSize = MVT::getSizeInBits(Op.getValueType())/8;
4148 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4149 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4151 switch (Op.getValueType()) {
4152 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4153 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4154 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4155 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4158 SDOperand Chain = DAG.getEntryNode();
4159 SDOperand Value = Op.getOperand(0);
4160 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4161 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4162 Chain = DAG.getStore(Chain, Value, StackSlot,
4163 PseudoSourceValue::getFixedStack(), SSFI);
4164 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4166 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4168 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4169 Chain = Value.getValue(1);
4170 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4171 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4174 // Build the FP_TO_INT*_IN_MEM
4175 SDOperand Ops[] = { Chain, Value, StackSlot };
4176 SDOperand FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4178 return std::make_pair(FIST, StackSlot);
4181 SDOperand X86TargetLowering::LowerFP_TO_SINT(SDOperand Op, SelectionDAG &DAG) {
4182 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(Op, DAG);
4183 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4184 if (FIST.Val == 0) return SDOperand();
4187 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4190 SDNode *X86TargetLowering::ExpandFP_TO_SINT(SDNode *N, SelectionDAG &DAG) {
4191 std::pair<SDOperand,SDOperand> Vals = FP_TO_SINTHelper(SDOperand(N, 0), DAG);
4192 SDOperand FIST = Vals.first, StackSlot = Vals.second;
4193 if (FIST.Val == 0) return 0;
4195 // Return an i64 load from the stack slot.
4196 SDOperand Res = DAG.getLoad(MVT::i64, FIST, StackSlot, NULL, 0);
4198 // Use a MERGE_VALUES node to drop the chain result value.
4199 return DAG.getNode(ISD::MERGE_VALUES, MVT::i64, Res).Val;
4202 SDOperand X86TargetLowering::LowerFABS(SDOperand Op, SelectionDAG &DAG) {
4203 MVT::ValueType VT = Op.getValueType();
4204 MVT::ValueType EltVT = VT;
4205 if (MVT::isVector(VT))
4206 EltVT = MVT::getVectorElementType(VT);
4207 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
4208 std::vector<Constant*> CV;
4209 if (EltVT == MVT::f64) {
4210 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, ~(1ULL << 63))));
4214 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, ~(1U << 31))));
4220 Constant *C = ConstantVector::get(CV);
4221 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4222 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4223 PseudoSourceValue::getConstantPool(), 0,
4225 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4228 SDOperand X86TargetLowering::LowerFNEG(SDOperand Op, SelectionDAG &DAG) {
4229 MVT::ValueType VT = Op.getValueType();
4230 MVT::ValueType EltVT = VT;
4231 unsigned EltNum = 1;
4232 if (MVT::isVector(VT)) {
4233 EltVT = MVT::getVectorElementType(VT);
4234 EltNum = MVT::getVectorNumElements(VT);
4236 const Type *OpNTy = MVT::getTypeForValueType(EltVT);
4237 std::vector<Constant*> CV;
4238 if (EltVT == MVT::f64) {
4239 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(64, 1ULL << 63)));
4243 Constant *C = ConstantFP::get(OpNTy, APFloat(APInt(32, 1U << 31)));
4249 Constant *C = ConstantVector::get(CV);
4250 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4251 SDOperand Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4252 PseudoSourceValue::getConstantPool(), 0,
4254 if (MVT::isVector(VT)) {
4255 return DAG.getNode(ISD::BIT_CONVERT, VT,
4256 DAG.getNode(ISD::XOR, MVT::v2i64,
4257 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4258 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4260 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4264 SDOperand X86TargetLowering::LowerFCOPYSIGN(SDOperand Op, SelectionDAG &DAG) {
4265 SDOperand Op0 = Op.getOperand(0);
4266 SDOperand Op1 = Op.getOperand(1);
4267 MVT::ValueType VT = Op.getValueType();
4268 MVT::ValueType SrcVT = Op1.getValueType();
4269 const Type *SrcTy = MVT::getTypeForValueType(SrcVT);
4271 // If second operand is smaller, extend it first.
4272 if (MVT::getSizeInBits(SrcVT) < MVT::getSizeInBits(VT)) {
4273 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4275 SrcTy = MVT::getTypeForValueType(SrcVT);
4277 // And if it is bigger, shrink it first.
4278 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4279 Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1, DAG.getIntPtrConstant(1));
4281 SrcTy = MVT::getTypeForValueType(SrcVT);
4284 // At this point the operands and the result should have the same
4285 // type, and that won't be f80 since that is not custom lowered.
4287 // First get the sign bit of second operand.
4288 std::vector<Constant*> CV;
4289 if (SrcVT == MVT::f64) {
4290 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 1ULL << 63))));
4291 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
4293 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 1U << 31))));
4294 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4295 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4296 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4298 Constant *C = ConstantVector::get(CV);
4299 SDOperand CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4300 SDOperand Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx,
4301 PseudoSourceValue::getConstantPool(), 0,
4303 SDOperand SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4305 // Shift sign bit right or left if the two operands have different types.
4306 if (MVT::getSizeInBits(SrcVT) > MVT::getSizeInBits(VT)) {
4307 // Op0 is MVT::f32, Op1 is MVT::f64.
4308 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4309 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4310 DAG.getConstant(32, MVT::i32));
4311 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4312 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4313 DAG.getIntPtrConstant(0));
4316 // Clear first operand sign bit.
4318 if (VT == MVT::f64) {
4319 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, ~(1ULL << 63)))));
4320 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(64, 0))));
4322 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, ~(1U << 31)))));
4323 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4324 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4325 CV.push_back(ConstantFP::get(SrcTy, APFloat(APInt(32, 0))));
4327 C = ConstantVector::get(CV);
4328 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4329 SDOperand Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4330 PseudoSourceValue::getConstantPool(), 0,
4332 SDOperand Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4334 // Or the value with the sign bit.
4335 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
4338 SDOperand X86TargetLowering::LowerSETCC(SDOperand Op, SelectionDAG &DAG) {
4339 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
4341 SDOperand Op0 = Op.getOperand(0);
4342 SDOperand Op1 = Op.getOperand(1);
4343 SDOperand CC = Op.getOperand(2);
4344 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
4345 bool isFP = MVT::isFloatingPoint(Op.getOperand(1).getValueType());
4348 if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
4350 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4351 return DAG.getNode(X86ISD::SETCC, MVT::i8,
4352 DAG.getConstant(X86CC, MVT::i8), Cond);
4355 assert(isFP && "Illegal integer SetCC!");
4357 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
4358 switch (SetCCOpcode) {
4359 default: assert(false && "Illegal floating point SetCC!");
4360 case ISD::SETOEQ: { // !PF & ZF
4361 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4362 DAG.getConstant(X86::COND_NP, MVT::i8), Cond);
4363 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4364 DAG.getConstant(X86::COND_E, MVT::i8), Cond);
4365 return DAG.getNode(ISD::AND, MVT::i8, Tmp1, Tmp2);
4367 case ISD::SETUNE: { // PF | !ZF
4368 SDOperand Tmp1 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4369 DAG.getConstant(X86::COND_P, MVT::i8), Cond);
4370 SDOperand Tmp2 = DAG.getNode(X86ISD::SETCC, MVT::i8,
4371 DAG.getConstant(X86::COND_NE, MVT::i8), Cond);
4372 return DAG.getNode(ISD::OR, MVT::i8, Tmp1, Tmp2);
4378 SDOperand X86TargetLowering::LowerSELECT(SDOperand Op, SelectionDAG &DAG) {
4379 bool addTest = true;
4380 SDOperand Cond = Op.getOperand(0);
4383 if (Cond.getOpcode() == ISD::SETCC)
4384 Cond = LowerSETCC(Cond, DAG);
4386 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4387 // setting operand in place of the X86ISD::SETCC.
4388 if (Cond.getOpcode() == X86ISD::SETCC) {
4389 CC = Cond.getOperand(0);
4391 SDOperand Cmp = Cond.getOperand(1);
4392 unsigned Opc = Cmp.getOpcode();
4393 MVT::ValueType VT = Op.getValueType();
4395 bool IllegalFPCMov = false;
4396 if (MVT::isFloatingPoint(VT) && !MVT::isVector(VT) &&
4397 !isScalarFPTypeInSSEReg(VT)) // FPStack?
4398 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSignExtended());
4400 if ((Opc == X86ISD::CMP ||
4401 Opc == X86ISD::COMI ||
4402 Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
4409 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4410 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4413 const MVT::ValueType *VTs = DAG.getNodeValueTypes(Op.getValueType(),
4415 SmallVector<SDOperand, 4> Ops;
4416 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
4417 // condition is true.
4418 Ops.push_back(Op.getOperand(2));
4419 Ops.push_back(Op.getOperand(1));
4421 Ops.push_back(Cond);
4422 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
4425 SDOperand X86TargetLowering::LowerBRCOND(SDOperand Op, SelectionDAG &DAG) {
4426 bool addTest = true;
4427 SDOperand Chain = Op.getOperand(0);
4428 SDOperand Cond = Op.getOperand(1);
4429 SDOperand Dest = Op.getOperand(2);
4432 if (Cond.getOpcode() == ISD::SETCC)
4433 Cond = LowerSETCC(Cond, DAG);
4435 // If condition flag is set by a X86ISD::CMP, then use it as the condition
4436 // setting operand in place of the X86ISD::SETCC.
4437 if (Cond.getOpcode() == X86ISD::SETCC) {
4438 CC = Cond.getOperand(0);
4440 SDOperand Cmp = Cond.getOperand(1);
4441 unsigned Opc = Cmp.getOpcode();
4442 if (Opc == X86ISD::CMP ||
4443 Opc == X86ISD::COMI ||
4444 Opc == X86ISD::UCOMI) {
4451 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4452 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
4454 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
4455 Chain, Op.getOperand(2), CC, Cond);
4459 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
4460 // Calls to _alloca is needed to probe the stack when allocating more than 4k
4461 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
4462 // that the guard pages used by the OS virtual memory manager are allocated in
4463 // correct sequence.
4465 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDOperand Op,
4466 SelectionDAG &DAG) {
4467 assert(Subtarget->isTargetCygMing() &&
4468 "This should be used only on Cygwin/Mingw targets");
4471 SDOperand Chain = Op.getOperand(0);
4472 SDOperand Size = Op.getOperand(1);
4473 // FIXME: Ensure alignment here
4477 MVT::ValueType IntPtr = getPointerTy();
4478 MVT::ValueType SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
4480 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
4481 Flag = Chain.getValue(1);
4483 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4484 SDOperand Ops[] = { Chain,
4485 DAG.getTargetExternalSymbol("_alloca", IntPtr),
4486 DAG.getRegister(X86::EAX, IntPtr),
4488 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 4);
4489 Flag = Chain.getValue(1);
4491 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
4493 std::vector<MVT::ValueType> Tys;
4494 Tys.push_back(SPTy);
4495 Tys.push_back(MVT::Other);
4496 SDOperand Ops1[2] = { Chain.getValue(0), Chain };
4497 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops1, 2);
4500 SDOperand X86TargetLowering::LowerMEMSET(SDOperand Op, SelectionDAG &DAG) {
4501 SDOperand InFlag(0, 0);
4502 SDOperand Chain = Op.getOperand(0);
4504 (unsigned)cast<ConstantSDNode>(Op.getOperand(4))->getValue();
4505 if (Align == 0) Align = 1;
4507 ConstantSDNode *I = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4508 // If not DWORD aligned or size is more than the threshold, call memset.
4509 // The libc version is likely to be faster for these cases. It can use the
4510 // address value and run time information about the CPU.
4511 if ((Align & 3) != 0 ||
4512 (I && I->getValue() > Subtarget->getMaxInlineSizeThreshold())) {
4513 MVT::ValueType IntPtr = getPointerTy();
4514 const Type *IntPtrTy = getTargetData()->getIntPtrType();
4515 TargetLowering::ArgListTy Args;
4516 TargetLowering::ArgListEntry Entry;
4517 Entry.Node = Op.getOperand(1);
4518 Entry.Ty = IntPtrTy;
4519 Args.push_back(Entry);
4520 // Extend the unsigned i8 argument to be an int value for the call.
4521 Entry.Node = DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Op.getOperand(2));
4522 Entry.Ty = IntPtrTy;
4523 Args.push_back(Entry);
4524 Entry.Node = Op.getOperand(3);
4525 Args.push_back(Entry);
4526 std::pair<SDOperand,SDOperand> CallResult =
4527 LowerCallTo(Chain, Type::VoidTy, false, false, false, CallingConv::C,
4528 false, DAG.getExternalSymbol("memset", IntPtr), Args, DAG);
4529 return CallResult.second;
4534 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Op.getOperand(2));
4535 unsigned BytesLeft = 0;
4536 bool TwoRepStos = false;
4539 uint64_t Val = ValC->getValue() & 255;
4541 // If the value is a constant, then we can potentially use larger sets.
4542 switch (Align & 3) {
4543 case 2: // WORD aligned
4546 Val = (Val << 8) | Val;
4548 case 0: // DWORD aligned
4551 Val = (Val << 8) | Val;
4552 Val = (Val << 16) | Val;
4553 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) { // QWORD aligned
4556 Val = (Val << 32) | Val;
4559 default: // Byte aligned
4562 Count = Op.getOperand(3);
4566 if (AVT > MVT::i8) {
4568 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4569 Count = DAG.getIntPtrConstant(I->getValue() / UBytes);
4570 BytesLeft = I->getValue() % UBytes;
4572 assert(AVT >= MVT::i32 &&
4573 "Do not use rep;stos if not at least DWORD aligned");
4574 Count = DAG.getNode(ISD::SRL, Op.getOperand(3).getValueType(),
4575 Op.getOperand(3), DAG.getConstant(2, MVT::i8));
4580 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
4582 InFlag = Chain.getValue(1);
4585 Count = Op.getOperand(3);
4586 Chain = DAG.getCopyToReg(Chain, X86::AL, Op.getOperand(2), InFlag);
4587 InFlag = Chain.getValue(1);
4590 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4592 InFlag = Chain.getValue(1);
4593 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4594 Op.getOperand(1), InFlag);
4595 InFlag = Chain.getValue(1);
4597 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4598 SmallVector<SDOperand, 8> Ops;
4599 Ops.push_back(Chain);
4600 Ops.push_back(DAG.getValueType(AVT));
4601 Ops.push_back(InFlag);
4602 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4605 InFlag = Chain.getValue(1);
4606 Count = Op.getOperand(3);
4607 MVT::ValueType CVT = Count.getValueType();
4608 SDOperand Left = DAG.getNode(ISD::AND, CVT, Count,
4609 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
4610 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
4612 InFlag = Chain.getValue(1);
4613 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4615 Ops.push_back(Chain);
4616 Ops.push_back(DAG.getValueType(MVT::i8));
4617 Ops.push_back(InFlag);
4618 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
4619 } else if (BytesLeft) {
4620 // Issue stores for the last 1 - 7 bytes.
4622 unsigned Val = ValC->getValue() & 255;
4623 unsigned Offset = I->getValue() - BytesLeft;
4624 SDOperand DstAddr = Op.getOperand(1);
4625 MVT::ValueType AddrVT = DstAddr.getValueType();
4626 if (BytesLeft >= 4) {
4627 Val = (Val << 8) | Val;
4628 Val = (Val << 16) | Val;
4629 Value = DAG.getConstant(Val, MVT::i32);
4630 Chain = DAG.getStore(Chain, Value,
4631 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4632 DAG.getConstant(Offset, AddrVT)),
4637 if (BytesLeft >= 2) {
4638 Value = DAG.getConstant((Val << 8) | Val, MVT::i16);
4639 Chain = DAG.getStore(Chain, Value,
4640 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4641 DAG.getConstant(Offset, AddrVT)),
4646 if (BytesLeft == 1) {
4647 Value = DAG.getConstant(Val, MVT::i8);
4648 Chain = DAG.getStore(Chain, Value,
4649 DAG.getNode(ISD::ADD, AddrVT, DstAddr,
4650 DAG.getConstant(Offset, AddrVT)),
4658 SDOperand X86TargetLowering::LowerMEMCPYInline(SDOperand Chain,
4663 SelectionDAG &DAG) {
4665 unsigned BytesLeft = 0;
4666 switch (Align & 3) {
4667 case 2: // WORD aligned
4670 case 0: // DWORD aligned
4672 if (Subtarget->is64Bit() && ((Align & 0xF) == 0)) // QWORD aligned
4675 default: // Byte aligned
4680 unsigned UBytes = MVT::getSizeInBits(AVT) / 8;
4681 SDOperand Count = DAG.getIntPtrConstant(Size / UBytes);
4682 BytesLeft = Size % UBytes;
4684 SDOperand InFlag(0, 0);
4685 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
4687 InFlag = Chain.getValue(1);
4688 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
4690 InFlag = Chain.getValue(1);
4691 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
4693 InFlag = Chain.getValue(1);
4695 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4696 SmallVector<SDOperand, 8> Ops;
4697 Ops.push_back(Chain);
4698 Ops.push_back(DAG.getValueType(AVT));
4699 Ops.push_back(InFlag);
4700 Chain = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
4703 // Issue loads and stores for the last 1 - 7 bytes.
4704 unsigned Offset = Size - BytesLeft;
4705 SDOperand DstAddr = Dest;
4706 MVT::ValueType DstVT = DstAddr.getValueType();
4707 SDOperand SrcAddr = Source;
4708 MVT::ValueType SrcVT = SrcAddr.getValueType();
4710 if (BytesLeft >= 4) {
4711 Value = DAG.getLoad(MVT::i32, Chain,
4712 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4713 DAG.getConstant(Offset, SrcVT)),
4715 Chain = Value.getValue(1);
4716 Chain = DAG.getStore(Chain, Value,
4717 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4718 DAG.getConstant(Offset, DstVT)),
4723 if (BytesLeft >= 2) {
4724 Value = DAG.getLoad(MVT::i16, Chain,
4725 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4726 DAG.getConstant(Offset, SrcVT)),
4728 Chain = Value.getValue(1);
4729 Chain = DAG.getStore(Chain, Value,
4730 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4731 DAG.getConstant(Offset, DstVT)),
4737 if (BytesLeft == 1) {
4738 Value = DAG.getLoad(MVT::i8, Chain,
4739 DAG.getNode(ISD::ADD, SrcVT, SrcAddr,
4740 DAG.getConstant(Offset, SrcVT)),
4742 Chain = Value.getValue(1);
4743 Chain = DAG.getStore(Chain, Value,
4744 DAG.getNode(ISD::ADD, DstVT, DstAddr,
4745 DAG.getConstant(Offset, DstVT)),
4753 /// Expand the result of: i64,outchain = READCYCLECOUNTER inchain
4754 SDNode *X86TargetLowering::ExpandREADCYCLECOUNTER(SDNode *N, SelectionDAG &DAG){
4755 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
4756 SDOperand TheChain = N->getOperand(0);
4757 SDOperand rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
4758 if (Subtarget->is64Bit()) {
4759 SDOperand rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
4760 SDOperand rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX,
4761 MVT::i64, rax.getValue(2));
4762 SDOperand Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
4763 DAG.getConstant(32, MVT::i8));
4765 DAG.getNode(ISD::OR, MVT::i64, rax, Tmp), rdx.getValue(1)
4768 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4769 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4772 SDOperand eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
4773 SDOperand edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX,
4774 MVT::i32, eax.getValue(2));
4775 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
4776 SDOperand Ops[] = { eax, edx };
4777 Ops[0] = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2);
4779 // Use a MERGE_VALUES to return the value and chain.
4780 Ops[1] = edx.getValue(1);
4781 Tys = DAG.getVTList(MVT::i64, MVT::Other);
4782 return DAG.getNode(ISD::MERGE_VALUES, Tys, Ops, 2).Val;
4785 SDOperand X86TargetLowering::LowerVASTART(SDOperand Op, SelectionDAG &DAG) {
4786 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4788 if (!Subtarget->is64Bit()) {
4789 // vastart just stores the address of the VarArgsFrameIndex slot into the
4790 // memory location argument.
4791 SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4792 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV, 0);
4796 // gp_offset (0 - 6 * 8)
4797 // fp_offset (48 - 48 + 8 * 16)
4798 // overflow_arg_area (point to parameters coming in memory).
4800 SmallVector<SDOperand, 8> MemOps;
4801 SDOperand FIN = Op.getOperand(1);
4803 SDOperand Store = DAG.getStore(Op.getOperand(0),
4804 DAG.getConstant(VarArgsGPOffset, MVT::i32),
4806 MemOps.push_back(Store);
4809 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
4810 Store = DAG.getStore(Op.getOperand(0),
4811 DAG.getConstant(VarArgsFPOffset, MVT::i32),
4813 MemOps.push_back(Store);
4815 // Store ptr to overflow_arg_area
4816 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
4817 SDOperand OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
4818 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV, 0);
4819 MemOps.push_back(Store);
4821 // Store ptr to reg_save_area.
4822 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
4823 SDOperand RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
4824 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV, 0);
4825 MemOps.push_back(Store);
4826 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
4829 SDOperand X86TargetLowering::LowerVACOPY(SDOperand Op, SelectionDAG &DAG) {
4830 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
4831 SDOperand Chain = Op.getOperand(0);
4832 SDOperand DstPtr = Op.getOperand(1);
4833 SDOperand SrcPtr = Op.getOperand(2);
4834 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4835 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4837 SrcPtr = DAG.getLoad(getPointerTy(), Chain, SrcPtr, SrcSV, 0);
4838 Chain = SrcPtr.getValue(1);
4839 for (unsigned i = 0; i < 3; ++i) {
4840 SDOperand Val = DAG.getLoad(MVT::i64, Chain, SrcPtr, SrcSV, 0);
4841 Chain = Val.getValue(1);
4842 Chain = DAG.getStore(Chain, Val, DstPtr, DstSV, 0);
4845 SrcPtr = DAG.getNode(ISD::ADD, getPointerTy(), SrcPtr,
4846 DAG.getIntPtrConstant(8));
4847 DstPtr = DAG.getNode(ISD::ADD, getPointerTy(), DstPtr,
4848 DAG.getIntPtrConstant(8));
4854 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDOperand Op, SelectionDAG &DAG) {
4855 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getValue();
4857 default: return SDOperand(); // Don't custom lower most intrinsics.
4858 // Comparison intrinsics.
4859 case Intrinsic::x86_sse_comieq_ss:
4860 case Intrinsic::x86_sse_comilt_ss:
4861 case Intrinsic::x86_sse_comile_ss:
4862 case Intrinsic::x86_sse_comigt_ss:
4863 case Intrinsic::x86_sse_comige_ss:
4864 case Intrinsic::x86_sse_comineq_ss:
4865 case Intrinsic::x86_sse_ucomieq_ss:
4866 case Intrinsic::x86_sse_ucomilt_ss:
4867 case Intrinsic::x86_sse_ucomile_ss:
4868 case Intrinsic::x86_sse_ucomigt_ss:
4869 case Intrinsic::x86_sse_ucomige_ss:
4870 case Intrinsic::x86_sse_ucomineq_ss:
4871 case Intrinsic::x86_sse2_comieq_sd:
4872 case Intrinsic::x86_sse2_comilt_sd:
4873 case Intrinsic::x86_sse2_comile_sd:
4874 case Intrinsic::x86_sse2_comigt_sd:
4875 case Intrinsic::x86_sse2_comige_sd:
4876 case Intrinsic::x86_sse2_comineq_sd:
4877 case Intrinsic::x86_sse2_ucomieq_sd:
4878 case Intrinsic::x86_sse2_ucomilt_sd:
4879 case Intrinsic::x86_sse2_ucomile_sd:
4880 case Intrinsic::x86_sse2_ucomigt_sd:
4881 case Intrinsic::x86_sse2_ucomige_sd:
4882 case Intrinsic::x86_sse2_ucomineq_sd: {
4884 ISD::CondCode CC = ISD::SETCC_INVALID;
4887 case Intrinsic::x86_sse_comieq_ss:
4888 case Intrinsic::x86_sse2_comieq_sd:
4892 case Intrinsic::x86_sse_comilt_ss:
4893 case Intrinsic::x86_sse2_comilt_sd:
4897 case Intrinsic::x86_sse_comile_ss:
4898 case Intrinsic::x86_sse2_comile_sd:
4902 case Intrinsic::x86_sse_comigt_ss:
4903 case Intrinsic::x86_sse2_comigt_sd:
4907 case Intrinsic::x86_sse_comige_ss:
4908 case Intrinsic::x86_sse2_comige_sd:
4912 case Intrinsic::x86_sse_comineq_ss:
4913 case Intrinsic::x86_sse2_comineq_sd:
4917 case Intrinsic::x86_sse_ucomieq_ss:
4918 case Intrinsic::x86_sse2_ucomieq_sd:
4919 Opc = X86ISD::UCOMI;
4922 case Intrinsic::x86_sse_ucomilt_ss:
4923 case Intrinsic::x86_sse2_ucomilt_sd:
4924 Opc = X86ISD::UCOMI;
4927 case Intrinsic::x86_sse_ucomile_ss:
4928 case Intrinsic::x86_sse2_ucomile_sd:
4929 Opc = X86ISD::UCOMI;
4932 case Intrinsic::x86_sse_ucomigt_ss:
4933 case Intrinsic::x86_sse2_ucomigt_sd:
4934 Opc = X86ISD::UCOMI;
4937 case Intrinsic::x86_sse_ucomige_ss:
4938 case Intrinsic::x86_sse2_ucomige_sd:
4939 Opc = X86ISD::UCOMI;
4942 case Intrinsic::x86_sse_ucomineq_ss:
4943 case Intrinsic::x86_sse2_ucomineq_sd:
4944 Opc = X86ISD::UCOMI;
4950 SDOperand LHS = Op.getOperand(1);
4951 SDOperand RHS = Op.getOperand(2);
4952 translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
4954 SDOperand Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
4955 SDOperand SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
4956 DAG.getConstant(X86CC, MVT::i8), Cond);
4957 return DAG.getNode(ISD::ANY_EXTEND, MVT::i32, SetCC);
4962 SDOperand X86TargetLowering::LowerRETURNADDR(SDOperand Op, SelectionDAG &DAG) {
4963 // Depths > 0 not supported yet!
4964 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
4967 // Just load the return address
4968 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
4969 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
4972 SDOperand X86TargetLowering::LowerFRAMEADDR(SDOperand Op, SelectionDAG &DAG) {
4973 // Depths > 0 not supported yet!
4974 if (cast<ConstantSDNode>(Op.getOperand(0))->getValue() > 0)
4977 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
4978 return DAG.getNode(ISD::SUB, getPointerTy(), RetAddrFI,
4979 DAG.getIntPtrConstant(4));
4982 SDOperand X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDOperand Op,
4983 SelectionDAG &DAG) {
4984 // Is not yet supported on x86-64
4985 if (Subtarget->is64Bit())
4988 return DAG.getIntPtrConstant(8);
4991 SDOperand X86TargetLowering::LowerEH_RETURN(SDOperand Op, SelectionDAG &DAG)
4993 assert(!Subtarget->is64Bit() &&
4994 "Lowering of eh_return builtin is not supported yet on x86-64");
4996 MachineFunction &MF = DAG.getMachineFunction();
4997 SDOperand Chain = Op.getOperand(0);
4998 SDOperand Offset = Op.getOperand(1);
4999 SDOperand Handler = Op.getOperand(2);
5001 SDOperand Frame = DAG.getRegister(RegInfo->getFrameRegister(MF),
5004 SDOperand StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
5005 DAG.getIntPtrConstant(-4UL));
5006 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
5007 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
5008 Chain = DAG.getCopyToReg(Chain, X86::ECX, StoreAddr);
5009 MF.getRegInfo().addLiveOut(X86::ECX);
5011 return DAG.getNode(X86ISD::EH_RETURN, MVT::Other,
5012 Chain, DAG.getRegister(X86::ECX, getPointerTy()));
5015 SDOperand X86TargetLowering::LowerTRAMPOLINE(SDOperand Op,
5016 SelectionDAG &DAG) {
5017 SDOperand Root = Op.getOperand(0);
5018 SDOperand Trmp = Op.getOperand(1); // trampoline
5019 SDOperand FPtr = Op.getOperand(2); // nested function
5020 SDOperand Nest = Op.getOperand(3); // 'nest' parameter value
5022 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5024 const X86InstrInfo *TII =
5025 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5027 if (Subtarget->is64Bit()) {
5028 SDOperand OutChains[6];
5030 // Large code-model.
5032 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
5033 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
5035 const unsigned char N86R10 =
5036 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(X86::R10);
5037 const unsigned char N86R11 =
5038 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(X86::R11);
5040 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
5042 // Load the pointer to the nested function into R11.
5043 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
5044 SDOperand Addr = Trmp;
5045 OutChains[0] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5048 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(2, MVT::i64));
5049 OutChains[1] = DAG.getStore(Root, FPtr, Addr, TrmpAddr, 2, false, 2);
5051 // Load the 'nest' parameter value into R10.
5052 // R10 is specified in X86CallingConv.td
5053 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
5054 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(10, MVT::i64));
5055 OutChains[2] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5058 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(12, MVT::i64));
5059 OutChains[3] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 12, false, 2);
5061 // Jump to the nested function.
5062 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
5063 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(20, MVT::i64));
5064 OutChains[4] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5067 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
5068 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(22, MVT::i64));
5069 OutChains[5] = DAG.getStore(Root, DAG.getConstant(ModRM, MVT::i8), Addr,
5073 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 6) };
5074 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5076 const Function *Func =
5077 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5078 unsigned CC = Func->getCallingConv();
5083 assert(0 && "Unsupported calling convention");
5084 case CallingConv::C:
5085 case CallingConv::X86_StdCall: {
5086 // Pass 'nest' parameter in ECX.
5087 // Must be kept in sync with X86CallingConv.td
5090 // Check that ECX wasn't needed by an 'inreg' parameter.
5091 const FunctionType *FTy = Func->getFunctionType();
5092 const ParamAttrsList *Attrs = Func->getParamAttrs();
5094 if (Attrs && !Func->isVarArg()) {
5095 unsigned InRegCount = 0;
5098 for (FunctionType::param_iterator I = FTy->param_begin(),
5099 E = FTy->param_end(); I != E; ++I, ++Idx)
5100 if (Attrs->paramHasAttr(Idx, ParamAttr::InReg))
5101 // FIXME: should only count parameters that are lowered to integers.
5102 InRegCount += (getTargetData()->getTypeSizeInBits(*I) + 31) / 32;
5104 if (InRegCount > 2) {
5105 cerr << "Nest register in use - reduce number of inreg parameters!\n";
5111 case CallingConv::X86_FastCall:
5112 // Pass 'nest' parameter in EAX.
5113 // Must be kept in sync with X86CallingConv.td
5118 SDOperand OutChains[4];
5119 SDOperand Addr, Disp;
5121 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5122 Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5124 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
5125 const unsigned char N86Reg =
5126 ((const X86RegisterInfo*)RegInfo)->getX86RegNum(NestReg);
5127 OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
5130 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
5131 OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 1, false, 1);
5133 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
5134 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
5135 OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
5136 TrmpAddr, 5, false, 1);
5138 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
5139 OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpAddr, 6, false, 1);
5142 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
5143 return DAG.getNode(ISD::MERGE_VALUES, Op.Val->getVTList(), Ops, 2);
5147 SDOperand X86TargetLowering::LowerFLT_ROUNDS_(SDOperand Op, SelectionDAG &DAG) {
5149 The rounding mode is in bits 11:10 of FPSR, and has the following
5156 FLT_ROUNDS, on the other hand, expects the following:
5163 To perform the conversion, we do:
5164 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
5167 MachineFunction &MF = DAG.getMachineFunction();
5168 const TargetMachine &TM = MF.getTarget();
5169 const TargetFrameInfo &TFI = *TM.getFrameInfo();
5170 unsigned StackAlignment = TFI.getStackAlignment();
5171 MVT::ValueType VT = Op.getValueType();
5173 // Save FP Control Word to stack slot
5174 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
5175 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5177 SDOperand Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
5178 DAG.getEntryNode(), StackSlot);
5180 // Load FP Control Word from stack slot
5181 SDOperand CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
5183 // Transform as necessary
5185 DAG.getNode(ISD::SRL, MVT::i16,
5186 DAG.getNode(ISD::AND, MVT::i16,
5187 CWD, DAG.getConstant(0x800, MVT::i16)),
5188 DAG.getConstant(11, MVT::i8));
5190 DAG.getNode(ISD::SRL, MVT::i16,
5191 DAG.getNode(ISD::AND, MVT::i16,
5192 CWD, DAG.getConstant(0x400, MVT::i16)),
5193 DAG.getConstant(9, MVT::i8));
5196 DAG.getNode(ISD::AND, MVT::i16,
5197 DAG.getNode(ISD::ADD, MVT::i16,
5198 DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
5199 DAG.getConstant(1, MVT::i16)),
5200 DAG.getConstant(3, MVT::i16));
5203 return DAG.getNode((MVT::getSizeInBits(VT) < 16 ?
5204 ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
5207 SDOperand X86TargetLowering::LowerCTLZ(SDOperand Op, SelectionDAG &DAG) {
5208 MVT::ValueType VT = Op.getValueType();
5209 MVT::ValueType OpVT = VT;
5210 unsigned NumBits = MVT::getSizeInBits(VT);
5212 Op = Op.getOperand(0);
5213 if (VT == MVT::i8) {
5214 // Zero extend to i32 since there is not an i8 bsr.
5216 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5219 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
5220 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5221 Op = DAG.getNode(X86ISD::BSR, VTs, Op);
5223 // If src is zero (i.e. bsr sets ZF), returns NumBits.
5224 SmallVector<SDOperand, 4> Ops;
5226 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
5227 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5228 Ops.push_back(Op.getValue(1));
5229 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5231 // Finally xor with NumBits-1.
5232 Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
5235 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5239 SDOperand X86TargetLowering::LowerCTTZ(SDOperand Op, SelectionDAG &DAG) {
5240 MVT::ValueType VT = Op.getValueType();
5241 MVT::ValueType OpVT = VT;
5242 unsigned NumBits = MVT::getSizeInBits(VT);
5244 Op = Op.getOperand(0);
5245 if (VT == MVT::i8) {
5247 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
5250 // Issue a bsf (scan bits forward) which also sets EFLAGS.
5251 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
5252 Op = DAG.getNode(X86ISD::BSF, VTs, Op);
5254 // If src is zero (i.e. bsf sets ZF), returns NumBits.
5255 SmallVector<SDOperand, 4> Ops;
5257 Ops.push_back(DAG.getConstant(NumBits, OpVT));
5258 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
5259 Ops.push_back(Op.getValue(1));
5260 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
5263 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
5267 /// LowerOperation - Provide custom lowering hooks for some operations.
5269 SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
5270 switch (Op.getOpcode()) {
5271 default: assert(0 && "Should not custom lower this!");
5272 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
5273 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
5274 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
5275 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
5276 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
5277 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
5278 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
5279 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
5280 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
5281 case ISD::SHL_PARTS:
5282 case ISD::SRA_PARTS:
5283 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
5284 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
5285 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
5286 case ISD::FABS: return LowerFABS(Op, DAG);
5287 case ISD::FNEG: return LowerFNEG(Op, DAG);
5288 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
5289 case ISD::SETCC: return LowerSETCC(Op, DAG);
5290 case ISD::SELECT: return LowerSELECT(Op, DAG);
5291 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
5292 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
5293 case ISD::CALL: return LowerCALL(Op, DAG);
5294 case ISD::RET: return LowerRET(Op, DAG);
5295 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
5296 case ISD::MEMSET: return LowerMEMSET(Op, DAG);
5297 case ISD::MEMCPY: return LowerMEMCPY(Op, DAG);
5298 case ISD::VASTART: return LowerVASTART(Op, DAG);
5299 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
5300 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
5301 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
5302 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
5303 case ISD::FRAME_TO_ARGS_OFFSET:
5304 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
5305 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
5306 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
5307 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
5308 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
5309 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
5310 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
5312 // FIXME: REMOVE THIS WHEN LegalizeDAGTypes lands.
5313 case ISD::READCYCLECOUNTER:
5314 return SDOperand(ExpandREADCYCLECOUNTER(Op.Val, DAG), 0);
5318 /// ExpandOperation - Provide custom lowering hooks for expanding operations.
5319 SDNode *X86TargetLowering::ExpandOperationResult(SDNode *N, SelectionDAG &DAG) {
5320 switch (N->getOpcode()) {
5321 default: assert(0 && "Should not custom lower this!");
5322 case ISD::FP_TO_SINT: return ExpandFP_TO_SINT(N, DAG);
5323 case ISD::READCYCLECOUNTER: return ExpandREADCYCLECOUNTER(N, DAG);
5327 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
5329 default: return NULL;
5330 case X86ISD::BSF: return "X86ISD::BSF";
5331 case X86ISD::BSR: return "X86ISD::BSR";
5332 case X86ISD::SHLD: return "X86ISD::SHLD";
5333 case X86ISD::SHRD: return "X86ISD::SHRD";
5334 case X86ISD::FAND: return "X86ISD::FAND";
5335 case X86ISD::FOR: return "X86ISD::FOR";
5336 case X86ISD::FXOR: return "X86ISD::FXOR";
5337 case X86ISD::FSRL: return "X86ISD::FSRL";
5338 case X86ISD::FILD: return "X86ISD::FILD";
5339 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
5340 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
5341 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
5342 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
5343 case X86ISD::FLD: return "X86ISD::FLD";
5344 case X86ISD::FST: return "X86ISD::FST";
5345 case X86ISD::FP_GET_RESULT: return "X86ISD::FP_GET_RESULT";
5346 case X86ISD::FP_GET_RESULT2: return "X86ISD::FP_GET_RESULT2";
5347 case X86ISD::FP_SET_RESULT: return "X86ISD::FP_SET_RESULT";
5348 case X86ISD::CALL: return "X86ISD::CALL";
5349 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
5350 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
5351 case X86ISD::CMP: return "X86ISD::CMP";
5352 case X86ISD::COMI: return "X86ISD::COMI";
5353 case X86ISD::UCOMI: return "X86ISD::UCOMI";
5354 case X86ISD::SETCC: return "X86ISD::SETCC";
5355 case X86ISD::CMOV: return "X86ISD::CMOV";
5356 case X86ISD::BRCOND: return "X86ISD::BRCOND";
5357 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
5358 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
5359 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
5360 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
5361 case X86ISD::Wrapper: return "X86ISD::Wrapper";
5362 case X86ISD::S2VEC: return "X86ISD::S2VEC";
5363 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
5364 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
5365 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
5366 case X86ISD::PINSRB: return "X86ISD::PINSRB";
5367 case X86ISD::PINSRW: return "X86ISD::PINSRW";
5368 case X86ISD::FMAX: return "X86ISD::FMAX";
5369 case X86ISD::FMIN: return "X86ISD::FMIN";
5370 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
5371 case X86ISD::FRCP: return "X86ISD::FRCP";
5372 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
5373 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
5374 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
5375 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
5376 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
5380 // isLegalAddressingMode - Return true if the addressing mode represented
5381 // by AM is legal for this target, for a load/store of the specified type.
5382 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
5383 const Type *Ty) const {
5384 // X86 supports extremely general addressing modes.
5386 // X86 allows a sign-extended 32-bit immediate field as a displacement.
5387 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
5391 // We can only fold this if we don't need an extra load.
5392 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
5395 // X86-64 only supports addr of globals in small code model.
5396 if (Subtarget->is64Bit()) {
5397 if (getTargetMachine().getCodeModel() != CodeModel::Small)
5399 // If lower 4G is not available, then we must use rip-relative addressing.
5400 if (AM.BaseOffs || AM.Scale > 1)
5411 // These scales always work.
5416 // These scales are formed with basereg+scalereg. Only accept if there is
5421 default: // Other stuff never works.
5429 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
5430 if (!Ty1->isInteger() || !Ty2->isInteger())
5432 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5433 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5434 if (NumBits1 <= NumBits2)
5436 return Subtarget->is64Bit() || NumBits1 < 64;
5439 bool X86TargetLowering::isTruncateFree(MVT::ValueType VT1,
5440 MVT::ValueType VT2) const {
5441 if (!MVT::isInteger(VT1) || !MVT::isInteger(VT2))
5443 unsigned NumBits1 = MVT::getSizeInBits(VT1);
5444 unsigned NumBits2 = MVT::getSizeInBits(VT2);
5445 if (NumBits1 <= NumBits2)
5447 return Subtarget->is64Bit() || NumBits1 < 64;
5450 /// isShuffleMaskLegal - Targets can use this to indicate that they only
5451 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
5452 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
5453 /// are assumed to be legal.
5455 X86TargetLowering::isShuffleMaskLegal(SDOperand Mask, MVT::ValueType VT) const {
5456 // Only do shuffles on 128-bit vector types for now.
5457 if (MVT::getSizeInBits(VT) == 64) return false;
5458 return (Mask.Val->getNumOperands() <= 4 ||
5459 isIdentityMask(Mask.Val) ||
5460 isIdentityMask(Mask.Val, true) ||
5461 isSplatMask(Mask.Val) ||
5462 isPSHUFHW_PSHUFLWMask(Mask.Val) ||
5463 X86::isUNPCKLMask(Mask.Val) ||
5464 X86::isUNPCKHMask(Mask.Val) ||
5465 X86::isUNPCKL_v_undef_Mask(Mask.Val) ||
5466 X86::isUNPCKH_v_undef_Mask(Mask.Val));
5469 bool X86TargetLowering::isVectorClearMaskLegal(std::vector<SDOperand> &BVOps,
5471 SelectionDAG &DAG) const {
5472 unsigned NumElts = BVOps.size();
5473 // Only do shuffles on 128-bit vector types for now.
5474 if (MVT::getSizeInBits(EVT) * NumElts == 64) return false;
5475 if (NumElts == 2) return true;
5477 return (isMOVLMask(&BVOps[0], 4) ||
5478 isCommutedMOVL(&BVOps[0], 4, true) ||
5479 isSHUFPMask(&BVOps[0], 4) ||
5480 isCommutedSHUFP(&BVOps[0], 4));
5485 //===----------------------------------------------------------------------===//
5486 // X86 Scheduler Hooks
5487 //===----------------------------------------------------------------------===//
5490 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
5491 MachineBasicBlock *BB) {
5492 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
5493 switch (MI->getOpcode()) {
5494 default: assert(false && "Unexpected instr type to insert");
5495 case X86::CMOV_FR32:
5496 case X86::CMOV_FR64:
5497 case X86::CMOV_V4F32:
5498 case X86::CMOV_V2F64:
5499 case X86::CMOV_V2I64: {
5500 // To "insert" a SELECT_CC instruction, we actually have to insert the
5501 // diamond control-flow pattern. The incoming instruction knows the
5502 // destination vreg to set, the condition code register to branch on, the
5503 // true/false values to select between, and a branch opcode to use.
5504 const BasicBlock *LLVM_BB = BB->getBasicBlock();
5505 ilist<MachineBasicBlock>::iterator It = BB;
5511 // cmpTY ccX, r1, r2
5513 // fallthrough --> copy0MBB
5514 MachineBasicBlock *thisMBB = BB;
5515 MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
5516 MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
5518 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
5519 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
5520 MachineFunction *F = BB->getParent();
5521 F->getBasicBlockList().insert(It, copy0MBB);
5522 F->getBasicBlockList().insert(It, sinkMBB);
5523 // Update machine-CFG edges by first adding all successors of the current
5524 // block to the new block which will contain the Phi node for the select.
5525 for(MachineBasicBlock::succ_iterator i = BB->succ_begin(),
5526 e = BB->succ_end(); i != e; ++i)
5527 sinkMBB->addSuccessor(*i);
5528 // Next, remove all successors of the current block, and add the true
5529 // and fallthrough blocks as its successors.
5530 while(!BB->succ_empty())
5531 BB->removeSuccessor(BB->succ_begin());
5532 BB->addSuccessor(copy0MBB);
5533 BB->addSuccessor(sinkMBB);
5536 // %FalseValue = ...
5537 // # fallthrough to sinkMBB
5540 // Update machine-CFG edges
5541 BB->addSuccessor(sinkMBB);
5544 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
5547 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
5548 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
5549 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
5551 delete MI; // The pseudo instruction is gone now.
5555 case X86::FP32_TO_INT16_IN_MEM:
5556 case X86::FP32_TO_INT32_IN_MEM:
5557 case X86::FP32_TO_INT64_IN_MEM:
5558 case X86::FP64_TO_INT16_IN_MEM:
5559 case X86::FP64_TO_INT32_IN_MEM:
5560 case X86::FP64_TO_INT64_IN_MEM:
5561 case X86::FP80_TO_INT16_IN_MEM:
5562 case X86::FP80_TO_INT32_IN_MEM:
5563 case X86::FP80_TO_INT64_IN_MEM: {
5564 // Change the floating point control register to use "round towards zero"
5565 // mode when truncating to an integer value.
5566 MachineFunction *F = BB->getParent();
5567 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
5568 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
5570 // Load the old value of the high byte of the control word...
5572 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
5573 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
5575 // Set the high part to be round to zero...
5576 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
5579 // Reload the modified control word now...
5580 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5582 // Restore the memory image of control word to original value
5583 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
5586 // Get the X86 opcode to use.
5588 switch (MI->getOpcode()) {
5589 default: assert(0 && "illegal opcode!");
5590 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
5591 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
5592 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
5593 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
5594 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
5595 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
5596 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
5597 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
5598 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
5602 MachineOperand &Op = MI->getOperand(0);
5603 if (Op.isRegister()) {
5604 AM.BaseType = X86AddressMode::RegBase;
5605 AM.Base.Reg = Op.getReg();
5607 AM.BaseType = X86AddressMode::FrameIndexBase;
5608 AM.Base.FrameIndex = Op.getIndex();
5610 Op = MI->getOperand(1);
5611 if (Op.isImmediate())
5612 AM.Scale = Op.getImm();
5613 Op = MI->getOperand(2);
5614 if (Op.isImmediate())
5615 AM.IndexReg = Op.getImm();
5616 Op = MI->getOperand(3);
5617 if (Op.isGlobalAddress()) {
5618 AM.GV = Op.getGlobal();
5620 AM.Disp = Op.getImm();
5622 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
5623 .addReg(MI->getOperand(4).getReg());
5625 // Reload the original control word now.
5626 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
5628 delete MI; // The pseudo instruction is gone now.
5634 //===----------------------------------------------------------------------===//
5635 // X86 Optimization Hooks
5636 //===----------------------------------------------------------------------===//
5638 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDOperand Op,
5642 const SelectionDAG &DAG,
5643 unsigned Depth) const {
5644 unsigned Opc = Op.getOpcode();
5645 assert((Opc >= ISD::BUILTIN_OP_END ||
5646 Opc == ISD::INTRINSIC_WO_CHAIN ||
5647 Opc == ISD::INTRINSIC_W_CHAIN ||
5648 Opc == ISD::INTRINSIC_VOID) &&
5649 "Should use MaskedValueIsZero if you don't know whether Op"
5650 " is a target node!");
5652 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
5656 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
5657 Mask.getBitWidth() - 1);
5662 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5663 /// element of the result of the vector shuffle.
5664 static SDOperand getShuffleScalarElt(SDNode *N, unsigned i, SelectionDAG &DAG) {
5665 MVT::ValueType VT = N->getValueType(0);
5666 SDOperand PermMask = N->getOperand(2);
5667 unsigned NumElems = PermMask.getNumOperands();
5668 SDOperand V = (i < NumElems) ? N->getOperand(0) : N->getOperand(1);
5670 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5672 ? V.getOperand(0) : DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5673 } else if (V.getOpcode() == ISD::VECTOR_SHUFFLE) {
5674 SDOperand Idx = PermMask.getOperand(i);
5675 if (Idx.getOpcode() == ISD::UNDEF)
5676 return DAG.getNode(ISD::UNDEF, MVT::getVectorElementType(VT));
5677 return getShuffleScalarElt(V.Val,cast<ConstantSDNode>(Idx)->getValue(),DAG);
5682 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
5683 /// node is a GlobalAddress + an offset.
5684 static bool isGAPlusOffset(SDNode *N, GlobalValue* &GA, int64_t &Offset) {
5685 unsigned Opc = N->getOpcode();
5686 if (Opc == X86ISD::Wrapper) {
5687 if (dyn_cast<GlobalAddressSDNode>(N->getOperand(0))) {
5688 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
5691 } else if (Opc == ISD::ADD) {
5692 SDOperand N1 = N->getOperand(0);
5693 SDOperand N2 = N->getOperand(1);
5694 if (isGAPlusOffset(N1.Val, GA, Offset)) {
5695 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N2);
5697 Offset += V->getSignExtended();
5700 } else if (isGAPlusOffset(N2.Val, GA, Offset)) {
5701 ConstantSDNode *V = dyn_cast<ConstantSDNode>(N1);
5703 Offset += V->getSignExtended();
5711 /// isConsecutiveLoad - Returns true if N is loading from an address of Base
5713 static bool isConsecutiveLoad(SDNode *N, SDNode *Base, int Dist, int Size,
5714 MachineFrameInfo *MFI) {
5715 if (N->getOperand(0).Val != Base->getOperand(0).Val)
5718 SDOperand Loc = N->getOperand(1);
5719 SDOperand BaseLoc = Base->getOperand(1);
5720 if (Loc.getOpcode() == ISD::FrameIndex) {
5721 if (BaseLoc.getOpcode() != ISD::FrameIndex)
5723 int FI = cast<FrameIndexSDNode>(Loc)->getIndex();
5724 int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
5725 int FS = MFI->getObjectSize(FI);
5726 int BFS = MFI->getObjectSize(BFI);
5727 if (FS != BFS || FS != Size) return false;
5728 return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Size);
5730 GlobalValue *GV1 = NULL;
5731 GlobalValue *GV2 = NULL;
5732 int64_t Offset1 = 0;
5733 int64_t Offset2 = 0;
5734 bool isGA1 = isGAPlusOffset(Loc.Val, GV1, Offset1);
5735 bool isGA2 = isGAPlusOffset(BaseLoc.Val, GV2, Offset2);
5736 if (isGA1 && isGA2 && GV1 == GV2)
5737 return Offset1 == (Offset2 + Dist*Size);
5743 static bool isBaseAlignment16(SDNode *Base, MachineFrameInfo *MFI,
5744 const X86Subtarget *Subtarget) {
5747 if (isGAPlusOffset(Base, GV, Offset))
5748 return (GV->getAlignment() >= 16 && (Offset % 16) == 0);
5749 // DAG combine handles the stack object case.
5754 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
5755 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
5756 /// if the load addresses are consecutive, non-overlapping, and in the right
5758 static SDOperand PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
5759 const X86Subtarget *Subtarget) {
5760 MachineFunction &MF = DAG.getMachineFunction();
5761 MachineFrameInfo *MFI = MF.getFrameInfo();
5762 MVT::ValueType VT = N->getValueType(0);
5763 MVT::ValueType EVT = MVT::getVectorElementType(VT);
5764 SDOperand PermMask = N->getOperand(2);
5765 int NumElems = (int)PermMask.getNumOperands();
5766 SDNode *Base = NULL;
5767 for (int i = 0; i < NumElems; ++i) {
5768 SDOperand Idx = PermMask.getOperand(i);
5769 if (Idx.getOpcode() == ISD::UNDEF) {
5770 if (!Base) return SDOperand();
5773 getShuffleScalarElt(N, cast<ConstantSDNode>(Idx)->getValue(), DAG);
5774 if (!Arg.Val || !ISD::isNON_EXTLoad(Arg.Val))
5778 else if (!isConsecutiveLoad(Arg.Val, Base,
5779 i, MVT::getSizeInBits(EVT)/8,MFI))
5784 bool isAlign16 = isBaseAlignment16(Base->getOperand(1).Val, MFI, Subtarget);
5785 LoadSDNode *LD = cast<LoadSDNode>(Base);
5787 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
5788 LD->getSrcValueOffset(), LD->isVolatile());
5790 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
5791 LD->getSrcValueOffset(), LD->isVolatile(),
5792 LD->getAlignment());
5796 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
5797 static SDOperand PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
5798 const X86Subtarget *Subtarget) {
5799 SDOperand Cond = N->getOperand(0);
5801 // If we have SSE[12] support, try to form min/max nodes.
5802 if (Subtarget->hasSSE2() &&
5803 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
5804 if (Cond.getOpcode() == ISD::SETCC) {
5805 // Get the LHS/RHS of the select.
5806 SDOperand LHS = N->getOperand(1);
5807 SDOperand RHS = N->getOperand(2);
5808 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
5810 unsigned Opcode = 0;
5811 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
5814 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
5817 if (!UnsafeFPMath) break;
5819 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
5821 Opcode = X86ISD::FMIN;
5824 case ISD::SETOGT: // (X > Y) ? X : Y -> max
5827 if (!UnsafeFPMath) break;
5829 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
5831 Opcode = X86ISD::FMAX;
5834 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
5837 case ISD::SETOGT: // (X > Y) ? Y : X -> min
5840 if (!UnsafeFPMath) break;
5842 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
5844 Opcode = X86ISD::FMIN;
5847 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
5850 if (!UnsafeFPMath) break;
5852 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
5854 Opcode = X86ISD::FMAX;
5860 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
5868 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
5869 /// X86ISD::FXOR nodes.
5870 static SDOperand PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
5871 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
5872 // F[X]OR(0.0, x) -> x
5873 // F[X]OR(x, 0.0) -> x
5874 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
5875 if (C->getValueAPF().isPosZero())
5876 return N->getOperand(1);
5877 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
5878 if (C->getValueAPF().isPosZero())
5879 return N->getOperand(0);
5883 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
5884 static SDOperand PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
5885 // FAND(0.0, x) -> 0.0
5886 // FAND(x, 0.0) -> 0.0
5887 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
5888 if (C->getValueAPF().isPosZero())
5889 return N->getOperand(0);
5890 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
5891 if (C->getValueAPF().isPosZero())
5892 return N->getOperand(1);
5897 SDOperand X86TargetLowering::PerformDAGCombine(SDNode *N,
5898 DAGCombinerInfo &DCI) const {
5899 SelectionDAG &DAG = DCI.DAG;
5900 switch (N->getOpcode()) {
5902 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, Subtarget);
5903 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
5905 case X86ISD::FOR: return PerformFORCombine(N, DAG);
5906 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
5912 //===----------------------------------------------------------------------===//
5913 // X86 Inline Assembly Support
5914 //===----------------------------------------------------------------------===//
5916 /// getConstraintType - Given a constraint letter, return the type of
5917 /// constraint it is for this target.
5918 X86TargetLowering::ConstraintType
5919 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
5920 if (Constraint.size() == 1) {
5921 switch (Constraint[0]) {
5930 return C_RegisterClass;
5935 return TargetLowering::getConstraintType(Constraint);
5938 /// LowerXConstraint - try to replace an X constraint, which matches anything,
5939 /// with another that has more specific requirements based on the type of the
5940 /// corresponding operand.
5941 void X86TargetLowering::lowerXConstraint(MVT::ValueType ConstraintVT,
5942 std::string& s) const {
5943 if (MVT::isFloatingPoint(ConstraintVT)) {
5944 if (Subtarget->hasSSE2())
5946 else if (Subtarget->hasSSE1())
5951 return TargetLowering::lowerXConstraint(ConstraintVT, s);
5954 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5955 /// vector. If it is invalid, don't add anything to Ops.
5956 void X86TargetLowering::LowerAsmOperandForConstraint(SDOperand Op,
5958 std::vector<SDOperand>&Ops,
5959 SelectionDAG &DAG) {
5960 SDOperand Result(0, 0);
5962 switch (Constraint) {
5965 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
5966 if (C->getValue() <= 31) {
5967 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
5973 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
5974 if (C->getValue() <= 255) {
5975 Result = DAG.getTargetConstant(C->getValue(), Op.getValueType());
5981 // Literal immediates are always ok.
5982 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
5983 Result = DAG.getTargetConstant(CST->getValue(), Op.getValueType());
5987 // If we are in non-pic codegen mode, we allow the address of a global (with
5988 // an optional displacement) to be used with 'i'.
5989 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
5992 // Match either (GA) or (GA+C)
5994 Offset = GA->getOffset();
5995 } else if (Op.getOpcode() == ISD::ADD) {
5996 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5997 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
5999 Offset = GA->getOffset()+C->getValue();
6001 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6002 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
6004 Offset = GA->getOffset()+C->getValue();
6011 // If addressing this global requires a load (e.g. in PIC mode), we can't
6013 if (Subtarget->GVRequiresExtraLoad(GA->getGlobal(), getTargetMachine(),
6017 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
6023 // Otherwise, not valid for this mode.
6029 Ops.push_back(Result);
6032 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
6035 std::vector<unsigned> X86TargetLowering::
6036 getRegClassForInlineAsmConstraint(const std::string &Constraint,
6037 MVT::ValueType VT) const {
6038 if (Constraint.size() == 1) {
6039 // FIXME: not handling fp-stack yet!
6040 switch (Constraint[0]) { // GCC X86 Constraint Letters
6041 default: break; // Unknown constraint letter
6042 case 'A': // EAX/EDX
6043 if (VT == MVT::i32 || VT == MVT::i64)
6044 return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
6046 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
6049 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
6050 else if (VT == MVT::i16)
6051 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
6052 else if (VT == MVT::i8)
6053 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
6054 else if (VT == MVT::i64)
6055 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
6060 return std::vector<unsigned>();
6063 std::pair<unsigned, const TargetRegisterClass*>
6064 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
6065 MVT::ValueType VT) const {
6066 // First, see if this is a constraint that directly corresponds to an LLVM
6068 if (Constraint.size() == 1) {
6069 // GCC Constraint Letters
6070 switch (Constraint[0]) {
6072 case 'r': // GENERAL_REGS
6073 case 'R': // LEGACY_REGS
6074 case 'l': // INDEX_REGS
6075 if (VT == MVT::i64 && Subtarget->is64Bit())
6076 return std::make_pair(0U, X86::GR64RegisterClass);
6078 return std::make_pair(0U, X86::GR32RegisterClass);
6079 else if (VT == MVT::i16)
6080 return std::make_pair(0U, X86::GR16RegisterClass);
6081 else if (VT == MVT::i8)
6082 return std::make_pair(0U, X86::GR8RegisterClass);
6084 case 'y': // MMX_REGS if MMX allowed.
6085 if (!Subtarget->hasMMX()) break;
6086 return std::make_pair(0U, X86::VR64RegisterClass);
6088 case 'Y': // SSE_REGS if SSE2 allowed
6089 if (!Subtarget->hasSSE2()) break;
6091 case 'x': // SSE_REGS if SSE1 allowed
6092 if (!Subtarget->hasSSE1()) break;
6096 // Scalar SSE types.
6099 return std::make_pair(0U, X86::FR32RegisterClass);
6102 return std::make_pair(0U, X86::FR64RegisterClass);
6110 return std::make_pair(0U, X86::VR128RegisterClass);
6116 // Use the default implementation in TargetLowering to convert the register
6117 // constraint into a member of a register class.
6118 std::pair<unsigned, const TargetRegisterClass*> Res;
6119 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
6121 // Not found as a standard register?
6122 if (Res.second == 0) {
6123 // GCC calls "st(0)" just plain "st".
6124 if (StringsEqualNoCase("{st}", Constraint)) {
6125 Res.first = X86::ST0;
6126 Res.second = X86::RFP80RegisterClass;
6132 // Otherwise, check to see if this is a register class of the wrong value
6133 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
6134 // turn into {ax},{dx}.
6135 if (Res.second->hasType(VT))
6136 return Res; // Correct type already, nothing to do.
6138 // All of the single-register GCC register classes map their values onto
6139 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
6140 // really want an 8-bit or 32-bit register, map to the appropriate register
6141 // class and return the appropriate register.
6142 if (Res.second != X86::GR16RegisterClass)
6145 if (VT == MVT::i8) {
6146 unsigned DestReg = 0;
6147 switch (Res.first) {
6149 case X86::AX: DestReg = X86::AL; break;
6150 case X86::DX: DestReg = X86::DL; break;
6151 case X86::CX: DestReg = X86::CL; break;
6152 case X86::BX: DestReg = X86::BL; break;
6155 Res.first = DestReg;
6156 Res.second = Res.second = X86::GR8RegisterClass;
6158 } else if (VT == MVT::i32) {
6159 unsigned DestReg = 0;
6160 switch (Res.first) {
6162 case X86::AX: DestReg = X86::EAX; break;
6163 case X86::DX: DestReg = X86::EDX; break;
6164 case X86::CX: DestReg = X86::ECX; break;
6165 case X86::BX: DestReg = X86::EBX; break;
6166 case X86::SI: DestReg = X86::ESI; break;
6167 case X86::DI: DestReg = X86::EDI; break;
6168 case X86::BP: DestReg = X86::EBP; break;
6169 case X86::SP: DestReg = X86::ESP; break;
6172 Res.first = DestReg;
6173 Res.second = Res.second = X86::GR32RegisterClass;
6175 } else if (VT == MVT::i64) {
6176 unsigned DestReg = 0;
6177 switch (Res.first) {
6179 case X86::AX: DestReg = X86::RAX; break;
6180 case X86::DX: DestReg = X86::RDX; break;
6181 case X86::CX: DestReg = X86::RCX; break;
6182 case X86::BX: DestReg = X86::RBX; break;
6183 case X86::SI: DestReg = X86::RSI; break;
6184 case X86::DI: DestReg = X86::RDI; break;
6185 case X86::BP: DestReg = X86::RBP; break;
6186 case X86::SP: DestReg = X86::RSP; break;
6189 Res.first = DestReg;
6190 Res.second = Res.second = X86::GR64RegisterClass;