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/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/PseudoSourceValue.h"
35 #include "llvm/CodeGen/SelectionDAG.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Target/TargetOptions.h"
39 #include "llvm/ADT/SmallSet.h"
40 #include "llvm/ADT/StringExtras.h"
43 // Forward declarations.
44 static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG);
46 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
47 : TargetLowering(TM) {
48 Subtarget = &TM.getSubtarget<X86Subtarget>();
49 X86ScalarSSEf64 = Subtarget->hasSSE2();
50 X86ScalarSSEf32 = Subtarget->hasSSE1();
51 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
55 RegInfo = TM.getRegisterInfo();
58 // Set up the TargetLowering object.
60 // X86 is weird, it always uses i8 for shift amounts and setcc results.
61 setShiftAmountType(MVT::i8);
62 setSetCCResultContents(ZeroOrOneSetCCResult);
63 setSchedulingPreference(SchedulingForRegPressure);
64 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
65 setStackPointerRegisterToSaveRestore(X86StackPtr);
67 if (Subtarget->isTargetDarwin()) {
68 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
69 setUseUnderscoreSetJmp(false);
70 setUseUnderscoreLongJmp(false);
71 } else if (Subtarget->isTargetMingw()) {
72 // MS runtime is weird: it exports _setjmp, but longjmp!
73 setUseUnderscoreSetJmp(true);
74 setUseUnderscoreLongJmp(false);
76 setUseUnderscoreSetJmp(true);
77 setUseUnderscoreLongJmp(true);
80 // Set up the register classes.
81 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
82 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
83 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
84 if (Subtarget->is64Bit())
85 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
87 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
89 // We don't accept any truncstore of integer registers.
90 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
91 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
92 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
93 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
94 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
95 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
97 // SETOEQ and SETUNE require checking two conditions.
98 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
99 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
100 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
101 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
102 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
103 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
105 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
107 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
108 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
109 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
111 if (Subtarget->is64Bit()) {
112 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
113 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
115 if (X86ScalarSSEf64) {
116 // We have an impenetrably clever algorithm for ui64->double only.
117 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
118 // If SSE i64 SINT_TO_FP is not available, expand i32 UINT_TO_FP.
119 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Expand);
121 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
124 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
126 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
127 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
128 // SSE has no i16 to fp conversion, only i32
129 if (X86ScalarSSEf32) {
130 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
131 // f32 and f64 cases are Legal, f80 case is not
132 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
134 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
135 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
138 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
139 // are Legal, f80 is custom lowered.
140 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
141 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
143 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
145 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
146 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
148 if (X86ScalarSSEf32) {
149 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
150 // f32 and f64 cases are Legal, f80 case is not
151 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
153 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
154 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
157 // Handle FP_TO_UINT by promoting the destination to a larger signed
159 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
160 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
161 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
163 if (Subtarget->is64Bit()) {
164 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
165 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
167 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
168 // Expand FP_TO_UINT into a select.
169 // FIXME: We would like to use a Custom expander here eventually to do
170 // the optimal thing for SSE vs. the default expansion in the legalizer.
171 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
173 // With SSE3 we can use fisttpll to convert to a signed i64.
174 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
177 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
178 if (!X86ScalarSSEf64) {
179 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
180 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
183 // Scalar integer divide and remainder are lowered to use operations that
184 // produce two results, to match the available instructions. This exposes
185 // the two-result form to trivial CSE, which is able to combine x/y and x%y
186 // into a single instruction.
188 // Scalar integer multiply-high is also lowered to use two-result
189 // operations, to match the available instructions. However, plain multiply
190 // (low) operations are left as Legal, as there are single-result
191 // instructions for this in x86. Using the two-result multiply instructions
192 // when both high and low results are needed must be arranged by dagcombine.
193 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
194 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
195 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
196 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
197 setOperationAction(ISD::SREM , MVT::i8 , Expand);
198 setOperationAction(ISD::UREM , MVT::i8 , Expand);
199 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
200 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
201 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
202 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
203 setOperationAction(ISD::SREM , MVT::i16 , Expand);
204 setOperationAction(ISD::UREM , MVT::i16 , Expand);
205 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
206 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
207 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
208 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
209 setOperationAction(ISD::SREM , MVT::i32 , Expand);
210 setOperationAction(ISD::UREM , MVT::i32 , Expand);
211 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
212 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
213 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
214 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
215 setOperationAction(ISD::SREM , MVT::i64 , Expand);
216 setOperationAction(ISD::UREM , MVT::i64 , Expand);
218 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
219 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
220 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
221 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
222 if (Subtarget->is64Bit())
223 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
224 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
225 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
226 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
227 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
228 setOperationAction(ISD::FREM , MVT::f32 , Expand);
229 setOperationAction(ISD::FREM , MVT::f64 , Expand);
230 setOperationAction(ISD::FREM , MVT::f80 , Expand);
231 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
233 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
234 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
235 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
236 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
237 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
238 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
239 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
240 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
241 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
242 if (Subtarget->is64Bit()) {
243 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
244 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
245 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
248 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
249 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
251 // These should be promoted to a larger select which is supported.
252 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
253 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
254 // X86 wants to expand cmov itself.
255 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
256 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
257 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
258 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
259 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
260 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
261 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
262 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
263 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
264 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
265 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
266 if (Subtarget->is64Bit()) {
267 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
268 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
270 // X86 ret instruction may pop stack.
271 setOperationAction(ISD::RET , MVT::Other, Custom);
272 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
275 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
276 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
277 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
278 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
279 if (Subtarget->is64Bit())
280 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
281 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
282 if (Subtarget->is64Bit()) {
283 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
284 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
285 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
286 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
288 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
289 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
290 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
291 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
292 if (Subtarget->is64Bit()) {
293 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
294 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
295 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
298 if (Subtarget->hasSSE1())
299 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
301 if (!Subtarget->hasSSE2())
302 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
304 // Expand certain atomics
305 setOperationAction(ISD::ATOMIC_CMP_SWAP_8 , MVT::i8, Custom);
306 setOperationAction(ISD::ATOMIC_CMP_SWAP_16, MVT::i16, Custom);
307 setOperationAction(ISD::ATOMIC_CMP_SWAP_32, MVT::i32, Custom);
308 setOperationAction(ISD::ATOMIC_CMP_SWAP_64, MVT::i64, Custom);
310 setOperationAction(ISD::ATOMIC_LOAD_SUB_8 , MVT::i8, Custom);
311 setOperationAction(ISD::ATOMIC_LOAD_SUB_16, MVT::i16, Custom);
312 setOperationAction(ISD::ATOMIC_LOAD_SUB_32, MVT::i32, Custom);
313 setOperationAction(ISD::ATOMIC_LOAD_SUB_64, MVT::i64, Custom);
315 if (!Subtarget->is64Bit()) {
316 setOperationAction(ISD::ATOMIC_LOAD_ADD_64, MVT::i64, Custom);
317 setOperationAction(ISD::ATOMIC_LOAD_SUB_64, MVT::i64, Custom);
318 setOperationAction(ISD::ATOMIC_LOAD_AND_64, MVT::i64, Custom);
319 setOperationAction(ISD::ATOMIC_LOAD_OR_64, MVT::i64, Custom);
320 setOperationAction(ISD::ATOMIC_LOAD_XOR_64, MVT::i64, Custom);
321 setOperationAction(ISD::ATOMIC_LOAD_NAND_64, MVT::i64, Custom);
322 setOperationAction(ISD::ATOMIC_SWAP_64, MVT::i64, Custom);
325 // Use the default ISD::DBG_STOPPOINT, ISD::DECLARE expansion.
326 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
327 // FIXME - use subtarget debug flags
328 if (!Subtarget->isTargetDarwin() &&
329 !Subtarget->isTargetELF() &&
330 !Subtarget->isTargetCygMing()) {
331 setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
332 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
335 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
336 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
337 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
338 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
339 if (Subtarget->is64Bit()) {
340 setExceptionPointerRegister(X86::RAX);
341 setExceptionSelectorRegister(X86::RDX);
343 setExceptionPointerRegister(X86::EAX);
344 setExceptionSelectorRegister(X86::EDX);
346 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
347 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
349 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
351 setOperationAction(ISD::TRAP, MVT::Other, Legal);
353 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
354 setOperationAction(ISD::VASTART , MVT::Other, Custom);
355 setOperationAction(ISD::VAEND , MVT::Other, Expand);
356 if (Subtarget->is64Bit()) {
357 setOperationAction(ISD::VAARG , MVT::Other, Custom);
358 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
360 setOperationAction(ISD::VAARG , MVT::Other, Expand);
361 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
364 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
365 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
366 if (Subtarget->is64Bit())
367 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
368 if (Subtarget->isTargetCygMing())
369 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
371 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
373 if (X86ScalarSSEf64) {
374 // f32 and f64 use SSE.
375 // Set up the FP register classes.
376 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
377 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
379 // Use ANDPD to simulate FABS.
380 setOperationAction(ISD::FABS , MVT::f64, Custom);
381 setOperationAction(ISD::FABS , MVT::f32, Custom);
383 // Use XORP to simulate FNEG.
384 setOperationAction(ISD::FNEG , MVT::f64, Custom);
385 setOperationAction(ISD::FNEG , MVT::f32, Custom);
387 // Use ANDPD and ORPD to simulate FCOPYSIGN.
388 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
389 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
391 // We don't support sin/cos/fmod
392 setOperationAction(ISD::FSIN , MVT::f64, Expand);
393 setOperationAction(ISD::FCOS , MVT::f64, Expand);
394 setOperationAction(ISD::FSIN , MVT::f32, Expand);
395 setOperationAction(ISD::FCOS , MVT::f32, Expand);
397 // Expand FP immediates into loads from the stack, except for the special
399 addLegalFPImmediate(APFloat(+0.0)); // xorpd
400 addLegalFPImmediate(APFloat(+0.0f)); // xorps
402 // Floating truncations from f80 and extensions to f80 go through memory.
403 // If optimizing, we lie about this though and handle it in
404 // InstructionSelectPreprocess so that dagcombine2 can hack on these.
406 setConvertAction(MVT::f32, MVT::f80, Expand);
407 setConvertAction(MVT::f64, MVT::f80, Expand);
408 setConvertAction(MVT::f80, MVT::f32, Expand);
409 setConvertAction(MVT::f80, MVT::f64, Expand);
411 } else if (X86ScalarSSEf32) {
412 // Use SSE for f32, x87 for f64.
413 // Set up the FP register classes.
414 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
415 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
417 // Use ANDPS to simulate FABS.
418 setOperationAction(ISD::FABS , MVT::f32, Custom);
420 // Use XORP to simulate FNEG.
421 setOperationAction(ISD::FNEG , MVT::f32, Custom);
423 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
425 // Use ANDPS and ORPS to simulate FCOPYSIGN.
426 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
427 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
429 // We don't support sin/cos/fmod
430 setOperationAction(ISD::FSIN , MVT::f32, Expand);
431 setOperationAction(ISD::FCOS , MVT::f32, Expand);
433 // Special cases we handle for FP constants.
434 addLegalFPImmediate(APFloat(+0.0f)); // xorps
435 addLegalFPImmediate(APFloat(+0.0)); // FLD0
436 addLegalFPImmediate(APFloat(+1.0)); // FLD1
437 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
438 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
440 // SSE <-> X87 conversions go through memory. If optimizing, we lie about
441 // this though and handle it in InstructionSelectPreprocess so that
442 // dagcombine2 can hack on these.
444 setConvertAction(MVT::f32, MVT::f64, Expand);
445 setConvertAction(MVT::f32, MVT::f80, Expand);
446 setConvertAction(MVT::f80, MVT::f32, Expand);
447 setConvertAction(MVT::f64, MVT::f32, Expand);
448 // And x87->x87 truncations also.
449 setConvertAction(MVT::f80, MVT::f64, Expand);
453 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
454 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
457 // f32 and f64 in x87.
458 // Set up the FP register classes.
459 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
460 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
462 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
463 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
464 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
465 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
467 // Floating truncations go through memory. If optimizing, we lie about
468 // this though and handle it in InstructionSelectPreprocess so that
469 // dagcombine2 can hack on these.
471 setConvertAction(MVT::f80, MVT::f32, Expand);
472 setConvertAction(MVT::f64, MVT::f32, Expand);
473 setConvertAction(MVT::f80, MVT::f64, Expand);
477 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
478 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
480 addLegalFPImmediate(APFloat(+0.0)); // FLD0
481 addLegalFPImmediate(APFloat(+1.0)); // FLD1
482 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
483 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
484 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
485 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
486 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
487 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
490 // Long double always uses X87.
491 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
492 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
493 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
496 APFloat TmpFlt(+0.0);
497 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
499 addLegalFPImmediate(TmpFlt); // FLD0
501 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
502 APFloat TmpFlt2(+1.0);
503 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
505 addLegalFPImmediate(TmpFlt2); // FLD1
506 TmpFlt2.changeSign();
507 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
511 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
512 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
515 // Always use a library call for pow.
516 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
517 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
518 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
520 setOperationAction(ISD::FLOG, MVT::f80, Expand);
521 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
522 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
523 setOperationAction(ISD::FEXP, MVT::f80, Expand);
524 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
526 // First set operation action for all vector types to either to promote
527 // (for widening) or expand (for scalarization). Then we will selectively
528 // turn on ones that can be effectively codegen'd.
529 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
530 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
531 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
532 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
533 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
534 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
535 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
536 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
537 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
538 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
539 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
540 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
541 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
542 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
543 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
544 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
545 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
546 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
547 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT, Expand);
548 setOperationAction(ISD::CONCAT_VECTORS,(MVT::SimpleValueType)VT, Expand);
549 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
550 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
551 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
552 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
553 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
554 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
555 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
556 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
557 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
558 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
559 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
560 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
561 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
562 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
563 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
564 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
565 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
566 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
567 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
568 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
569 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
570 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
571 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
572 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
573 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
574 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
575 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
578 if (Subtarget->hasMMX()) {
579 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
580 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
581 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
582 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
583 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
585 // FIXME: add MMX packed arithmetics
587 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
588 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
589 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
590 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
592 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
593 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
594 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
595 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
597 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
598 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
600 setOperationAction(ISD::AND, MVT::v8i8, Promote);
601 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
602 setOperationAction(ISD::AND, MVT::v4i16, Promote);
603 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
604 setOperationAction(ISD::AND, MVT::v2i32, Promote);
605 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
606 setOperationAction(ISD::AND, MVT::v1i64, Legal);
608 setOperationAction(ISD::OR, MVT::v8i8, Promote);
609 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
610 setOperationAction(ISD::OR, MVT::v4i16, Promote);
611 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
612 setOperationAction(ISD::OR, MVT::v2i32, Promote);
613 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
614 setOperationAction(ISD::OR, MVT::v1i64, Legal);
616 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
617 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
618 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
619 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
620 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
621 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
622 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
624 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
625 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
626 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
627 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
628 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
629 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
630 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
631 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
632 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
634 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
635 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
636 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
637 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
638 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
640 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
641 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
642 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
643 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
645 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
646 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
647 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
648 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
650 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
653 if (Subtarget->hasSSE1()) {
654 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
656 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
657 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
658 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
659 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
660 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
661 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
662 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
663 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
664 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
665 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
666 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
667 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
670 if (Subtarget->hasSSE2()) {
671 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
672 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
673 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
674 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
675 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
677 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
678 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
679 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
680 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
681 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
682 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
683 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
684 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
685 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
686 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
687 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
688 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
689 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
690 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
691 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
693 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
694 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
695 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
696 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
698 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
699 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
700 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
701 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
702 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
704 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
705 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
706 MVT VT = (MVT::SimpleValueType)i;
707 // Do not attempt to custom lower non-power-of-2 vectors
708 if (!isPowerOf2_32(VT.getVectorNumElements()))
710 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
711 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
712 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
714 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
715 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
716 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
717 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
718 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
719 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
720 if (Subtarget->is64Bit()) {
721 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
722 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
725 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
726 for (unsigned VT = (unsigned)MVT::v16i8; VT != (unsigned)MVT::v2i64; VT++) {
727 setOperationAction(ISD::AND, (MVT::SimpleValueType)VT, Promote);
728 AddPromotedToType (ISD::AND, (MVT::SimpleValueType)VT, MVT::v2i64);
729 setOperationAction(ISD::OR, (MVT::SimpleValueType)VT, Promote);
730 AddPromotedToType (ISD::OR, (MVT::SimpleValueType)VT, MVT::v2i64);
731 setOperationAction(ISD::XOR, (MVT::SimpleValueType)VT, Promote);
732 AddPromotedToType (ISD::XOR, (MVT::SimpleValueType)VT, MVT::v2i64);
733 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Promote);
734 AddPromotedToType (ISD::LOAD, (MVT::SimpleValueType)VT, MVT::v2i64);
735 setOperationAction(ISD::SELECT, (MVT::SimpleValueType)VT, Promote);
736 AddPromotedToType (ISD::SELECT, (MVT::SimpleValueType)VT, MVT::v2i64);
739 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
741 // Custom lower v2i64 and v2f64 selects.
742 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
743 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
744 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
745 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
749 if (Subtarget->hasSSE41()) {
750 // FIXME: Do we need to handle scalar-to-vector here?
751 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
752 setOperationAction(ISD::MUL, MVT::v2i64, Legal);
754 // i8 and i16 vectors are custom , because the source register and source
755 // source memory operand types are not the same width. f32 vectors are
756 // custom since the immediate controlling the insert encodes additional
758 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
759 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
760 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Legal);
761 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
763 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
764 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
765 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Legal);
766 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
768 if (Subtarget->is64Bit()) {
769 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
770 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
774 if (Subtarget->hasSSE42()) {
775 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
778 // We want to custom lower some of our intrinsics.
779 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
781 // We have target-specific dag combine patterns for the following nodes:
782 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
783 setTargetDAGCombine(ISD::BUILD_VECTOR);
784 setTargetDAGCombine(ISD::SELECT);
785 setTargetDAGCombine(ISD::STORE);
787 computeRegisterProperties();
789 // FIXME: These should be based on subtarget info. Plus, the values should
790 // be smaller when we are in optimizing for size mode.
791 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
792 maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
793 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
794 allowUnalignedMemoryAccesses = true; // x86 supports it!
795 setPrefLoopAlignment(16);
799 MVT X86TargetLowering::getSetCCResultType(const SDValue &) const {
804 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
805 /// the desired ByVal argument alignment.
806 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
809 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
810 if (VTy->getBitWidth() == 128)
812 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
813 unsigned EltAlign = 0;
814 getMaxByValAlign(ATy->getElementType(), EltAlign);
815 if (EltAlign > MaxAlign)
817 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
818 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
819 unsigned EltAlign = 0;
820 getMaxByValAlign(STy->getElementType(i), EltAlign);
821 if (EltAlign > MaxAlign)
830 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
831 /// function arguments in the caller parameter area. For X86, aggregates
832 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
833 /// are at 4-byte boundaries.
834 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
835 if (Subtarget->is64Bit()) {
836 // Max of 8 and alignment of type.
837 unsigned TyAlign = TD->getABITypeAlignment(Ty);
844 if (Subtarget->hasSSE1())
845 getMaxByValAlign(Ty, Align);
849 /// getOptimalMemOpType - Returns the target specific optimal type for load
850 /// and store operations as a result of memset, memcpy, and memmove
851 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
854 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
855 bool isSrcConst, bool isSrcStr) const {
856 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
857 // linux. This is because the stack realignment code can't handle certain
858 // cases like PR2962. This should be removed when PR2962 is fixed.
859 if (Subtarget->getStackAlignment() >= 16) {
860 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
862 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
865 if (Subtarget->is64Bit() && Size >= 8)
871 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
873 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
874 SelectionDAG &DAG) const {
875 if (usesGlobalOffsetTable())
876 return DAG.getNode(ISD::GLOBAL_OFFSET_TABLE, getPointerTy());
877 if (!Subtarget->isPICStyleRIPRel())
878 return DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy());
882 //===----------------------------------------------------------------------===//
883 // Return Value Calling Convention Implementation
884 //===----------------------------------------------------------------------===//
886 #include "X86GenCallingConv.inc"
888 /// LowerRET - Lower an ISD::RET node.
889 SDValue X86TargetLowering::LowerRET(SDValue Op, SelectionDAG &DAG) {
890 assert((Op.getNumOperands() & 1) == 1 && "ISD::RET should have odd # args");
892 SmallVector<CCValAssign, 16> RVLocs;
893 unsigned CC = DAG.getMachineFunction().getFunction()->getCallingConv();
894 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
895 CCState CCInfo(CC, isVarArg, getTargetMachine(), RVLocs);
896 CCInfo.AnalyzeReturn(Op.getNode(), RetCC_X86);
898 // If this is the first return lowered for this function, add the regs to the
899 // liveout set for the function.
900 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
901 for (unsigned i = 0; i != RVLocs.size(); ++i)
902 if (RVLocs[i].isRegLoc())
903 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
905 SDValue Chain = Op.getOperand(0);
907 // Handle tail call return.
908 Chain = GetPossiblePreceedingTailCall(Chain, X86ISD::TAILCALL);
909 if (Chain.getOpcode() == X86ISD::TAILCALL) {
910 SDValue TailCall = Chain;
911 SDValue TargetAddress = TailCall.getOperand(1);
912 SDValue StackAdjustment = TailCall.getOperand(2);
913 assert(((TargetAddress.getOpcode() == ISD::Register &&
914 (cast<RegisterSDNode>(TargetAddress)->getReg() == X86::EAX ||
915 cast<RegisterSDNode>(TargetAddress)->getReg() == X86::R9)) ||
916 TargetAddress.getOpcode() == ISD::TargetExternalSymbol ||
917 TargetAddress.getOpcode() == ISD::TargetGlobalAddress) &&
918 "Expecting an global address, external symbol, or register");
919 assert(StackAdjustment.getOpcode() == ISD::Constant &&
920 "Expecting a const value");
922 SmallVector<SDValue,8> Operands;
923 Operands.push_back(Chain.getOperand(0));
924 Operands.push_back(TargetAddress);
925 Operands.push_back(StackAdjustment);
926 // Copy registers used by the call. Last operand is a flag so it is not
928 for (unsigned i=3; i < TailCall.getNumOperands()-1; i++) {
929 Operands.push_back(Chain.getOperand(i));
931 return DAG.getNode(X86ISD::TC_RETURN, MVT::Other, &Operands[0],
938 SmallVector<SDValue, 6> RetOps;
939 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
940 // Operand #1 = Bytes To Pop
941 RetOps.push_back(DAG.getConstant(getBytesToPopOnReturn(), MVT::i16));
943 // Copy the result values into the output registers.
944 for (unsigned i = 0; i != RVLocs.size(); ++i) {
945 CCValAssign &VA = RVLocs[i];
946 assert(VA.isRegLoc() && "Can only return in registers!");
947 SDValue ValToCopy = Op.getOperand(i*2+1);
949 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
950 // the RET instruction and handled by the FP Stackifier.
951 if (RVLocs[i].getLocReg() == X86::ST0 ||
952 RVLocs[i].getLocReg() == X86::ST1) {
953 // If this is a copy from an xmm register to ST(0), use an FPExtend to
954 // change the value to the FP stack register class.
955 if (isScalarFPTypeInSSEReg(RVLocs[i].getValVT()))
956 ValToCopy = DAG.getNode(ISD::FP_EXTEND, MVT::f80, ValToCopy);
957 RetOps.push_back(ValToCopy);
958 // Don't emit a copytoreg.
962 Chain = DAG.getCopyToReg(Chain, VA.getLocReg(), ValToCopy, Flag);
963 Flag = Chain.getValue(1);
966 // The x86-64 ABI for returning structs by value requires that we copy
967 // the sret argument into %rax for the return. We saved the argument into
968 // a virtual register in the entry block, so now we copy the value out
970 if (Subtarget->is64Bit() &&
971 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
972 MachineFunction &MF = DAG.getMachineFunction();
973 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
974 unsigned Reg = FuncInfo->getSRetReturnReg();
976 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
977 FuncInfo->setSRetReturnReg(Reg);
979 SDValue Val = DAG.getCopyFromReg(Chain, Reg, getPointerTy());
981 Chain = DAG.getCopyToReg(Chain, X86::RAX, Val, Flag);
982 Flag = Chain.getValue(1);
985 RetOps[0] = Chain; // Update chain.
987 // Add the flag if we have it.
989 RetOps.push_back(Flag);
991 return DAG.getNode(X86ISD::RET_FLAG, MVT::Other, &RetOps[0], RetOps.size());
995 /// LowerCallResult - Lower the result values of an ISD::CALL into the
996 /// appropriate copies out of appropriate physical registers. This assumes that
997 /// Chain/InFlag are the input chain/flag to use, and that TheCall is the call
998 /// being lowered. The returns a SDNode with the same number of values as the
1000 SDNode *X86TargetLowering::
1001 LowerCallResult(SDValue Chain, SDValue InFlag, CallSDNode *TheCall,
1002 unsigned CallingConv, SelectionDAG &DAG) {
1004 // Assign locations to each value returned by this call.
1005 SmallVector<CCValAssign, 16> RVLocs;
1006 bool isVarArg = TheCall->isVarArg();
1007 CCState CCInfo(CallingConv, isVarArg, getTargetMachine(), RVLocs);
1008 CCInfo.AnalyzeCallResult(TheCall, RetCC_X86);
1010 SmallVector<SDValue, 8> ResultVals;
1012 // Copy all of the result registers out of their specified physreg.
1013 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1014 MVT CopyVT = RVLocs[i].getValVT();
1016 // If this is a call to a function that returns an fp value on the floating
1017 // point stack, but where we prefer to use the value in xmm registers, copy
1018 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1019 if ((RVLocs[i].getLocReg() == X86::ST0 ||
1020 RVLocs[i].getLocReg() == X86::ST1) &&
1021 isScalarFPTypeInSSEReg(RVLocs[i].getValVT())) {
1025 Chain = DAG.getCopyFromReg(Chain, RVLocs[i].getLocReg(),
1026 CopyVT, InFlag).getValue(1);
1027 SDValue Val = Chain.getValue(0);
1028 InFlag = Chain.getValue(2);
1030 if (CopyVT != RVLocs[i].getValVT()) {
1031 // Round the F80 the right size, which also moves to the appropriate xmm
1033 Val = DAG.getNode(ISD::FP_ROUND, RVLocs[i].getValVT(), Val,
1034 // This truncation won't change the value.
1035 DAG.getIntPtrConstant(1));
1038 ResultVals.push_back(Val);
1041 // Merge everything together with a MERGE_VALUES node.
1042 ResultVals.push_back(Chain);
1043 return DAG.getMergeValues(TheCall->getVTList(), &ResultVals[0],
1044 ResultVals.size()).getNode();
1048 //===----------------------------------------------------------------------===//
1049 // C & StdCall & Fast Calling Convention implementation
1050 //===----------------------------------------------------------------------===//
1051 // StdCall calling convention seems to be standard for many Windows' API
1052 // routines and around. It differs from C calling convention just a little:
1053 // callee should clean up the stack, not caller. Symbols should be also
1054 // decorated in some fancy way :) It doesn't support any vector arguments.
1055 // For info on fast calling convention see Fast Calling Convention (tail call)
1056 // implementation LowerX86_32FastCCCallTo.
1058 /// AddLiveIn - This helper function adds the specified physical register to the
1059 /// MachineFunction as a live in value. It also creates a corresponding virtual
1060 /// register for it.
1061 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
1062 const TargetRegisterClass *RC) {
1063 assert(RC->contains(PReg) && "Not the correct regclass!");
1064 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
1065 MF.getRegInfo().addLiveIn(PReg, VReg);
1069 /// CallIsStructReturn - Determines whether a CALL node uses struct return
1071 static bool CallIsStructReturn(CallSDNode *TheCall) {
1072 unsigned NumOps = TheCall->getNumArgs();
1076 return TheCall->getArgFlags(0).isSRet();
1079 /// ArgsAreStructReturn - Determines whether a FORMAL_ARGUMENTS node uses struct
1080 /// return semantics.
1081 static bool ArgsAreStructReturn(SDValue Op) {
1082 unsigned NumArgs = Op.getNode()->getNumValues() - 1;
1086 return cast<ARG_FLAGSSDNode>(Op.getOperand(3))->getArgFlags().isSRet();
1089 /// IsCalleePop - Determines whether a CALL or FORMAL_ARGUMENTS node requires
1090 /// the callee to pop its own arguments. Callee pop is necessary to support tail
1092 bool X86TargetLowering::IsCalleePop(bool IsVarArg, unsigned CallingConv) {
1096 switch (CallingConv) {
1099 case CallingConv::X86_StdCall:
1100 return !Subtarget->is64Bit();
1101 case CallingConv::X86_FastCall:
1102 return !Subtarget->is64Bit();
1103 case CallingConv::Fast:
1104 return PerformTailCallOpt;
1108 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1109 /// given CallingConvention value.
1110 CCAssignFn *X86TargetLowering::CCAssignFnForNode(unsigned CC) const {
1111 if (Subtarget->is64Bit()) {
1112 if (Subtarget->isTargetWin64())
1113 return CC_X86_Win64_C;
1114 else if (CC == CallingConv::Fast && PerformTailCallOpt)
1115 return CC_X86_64_TailCall;
1120 if (CC == CallingConv::X86_FastCall)
1121 return CC_X86_32_FastCall;
1122 else if (CC == CallingConv::Fast)
1123 return CC_X86_32_FastCC;
1128 /// NameDecorationForFORMAL_ARGUMENTS - Selects the appropriate decoration to
1129 /// apply to a MachineFunction containing a given FORMAL_ARGUMENTS node.
1131 X86TargetLowering::NameDecorationForFORMAL_ARGUMENTS(SDValue Op) {
1132 unsigned CC = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
1133 if (CC == CallingConv::X86_FastCall)
1135 else if (CC == CallingConv::X86_StdCall)
1141 /// CallRequiresGOTInRegister - Check whether the call requires the GOT pointer
1142 /// in a register before calling.
1143 bool X86TargetLowering::CallRequiresGOTPtrInReg(bool Is64Bit, bool IsTailCall) {
1144 return !IsTailCall && !Is64Bit &&
1145 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1146 Subtarget->isPICStyleGOT();
1149 /// CallRequiresFnAddressInReg - Check whether the call requires the function
1150 /// address to be loaded in a register.
1152 X86TargetLowering::CallRequiresFnAddressInReg(bool Is64Bit, bool IsTailCall) {
1153 return !Is64Bit && IsTailCall &&
1154 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1155 Subtarget->isPICStyleGOT();
1158 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1159 /// by "Src" to address "Dst" with size and alignment information specified by
1160 /// the specific parameter attribute. The copy will be passed as a byval
1161 /// function parameter.
1163 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1164 ISD::ArgFlagsTy Flags, SelectionDAG &DAG) {
1165 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1166 return DAG.getMemcpy(Chain, Dst, Src, SizeNode, Flags.getByValAlign(),
1167 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1170 SDValue X86TargetLowering::LowerMemArgument(SDValue Op, SelectionDAG &DAG,
1171 const CCValAssign &VA,
1172 MachineFrameInfo *MFI,
1174 SDValue Root, unsigned i) {
1175 // Create the nodes corresponding to a load from this parameter slot.
1176 ISD::ArgFlagsTy Flags =
1177 cast<ARG_FLAGSSDNode>(Op.getOperand(3 + i))->getArgFlags();
1178 bool AlwaysUseMutable = (CC==CallingConv::Fast) && PerformTailCallOpt;
1179 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1181 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1182 // changed with more analysis.
1183 // In case of tail call optimization mark all arguments mutable. Since they
1184 // could be overwritten by lowering of arguments in case of a tail call.
1185 int FI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
1186 VA.getLocMemOffset(), isImmutable);
1187 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1188 if (Flags.isByVal())
1190 return DAG.getLoad(VA.getValVT(), Root, FIN,
1191 PseudoSourceValue::getFixedStack(FI), 0);
1195 X86TargetLowering::LowerFORMAL_ARGUMENTS(SDValue Op, SelectionDAG &DAG) {
1196 MachineFunction &MF = DAG.getMachineFunction();
1197 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1199 const Function* Fn = MF.getFunction();
1200 if (Fn->hasExternalLinkage() &&
1201 Subtarget->isTargetCygMing() &&
1202 Fn->getName() == "main")
1203 FuncInfo->setForceFramePointer(true);
1205 // Decorate the function name.
1206 FuncInfo->setDecorationStyle(NameDecorationForFORMAL_ARGUMENTS(Op));
1208 MachineFrameInfo *MFI = MF.getFrameInfo();
1209 SDValue Root = Op.getOperand(0);
1210 bool isVarArg = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() != 0;
1211 unsigned CC = MF.getFunction()->getCallingConv();
1212 bool Is64Bit = Subtarget->is64Bit();
1213 bool IsWin64 = Subtarget->isTargetWin64();
1215 assert(!(isVarArg && CC == CallingConv::Fast) &&
1216 "Var args not supported with calling convention fastcc");
1218 // Assign locations to all of the incoming arguments.
1219 SmallVector<CCValAssign, 16> ArgLocs;
1220 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1221 CCInfo.AnalyzeFormalArguments(Op.getNode(), CCAssignFnForNode(CC));
1223 SmallVector<SDValue, 8> ArgValues;
1224 unsigned LastVal = ~0U;
1225 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1226 CCValAssign &VA = ArgLocs[i];
1227 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1229 assert(VA.getValNo() != LastVal &&
1230 "Don't support value assigned to multiple locs yet");
1231 LastVal = VA.getValNo();
1233 if (VA.isRegLoc()) {
1234 MVT RegVT = VA.getLocVT();
1235 TargetRegisterClass *RC;
1236 if (RegVT == MVT::i32)
1237 RC = X86::GR32RegisterClass;
1238 else if (Is64Bit && RegVT == MVT::i64)
1239 RC = X86::GR64RegisterClass;
1240 else if (RegVT == MVT::f32)
1241 RC = X86::FR32RegisterClass;
1242 else if (RegVT == MVT::f64)
1243 RC = X86::FR64RegisterClass;
1244 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1245 RC = X86::VR128RegisterClass;
1246 else if (RegVT.isVector()) {
1247 assert(RegVT.getSizeInBits() == 64);
1249 RC = X86::VR64RegisterClass; // MMX values are passed in MMXs.
1251 // Darwin calling convention passes MMX values in either GPRs or
1252 // XMMs in x86-64. Other targets pass them in memory.
1253 if (RegVT != MVT::v1i64 && Subtarget->hasSSE2()) {
1254 RC = X86::VR128RegisterClass; // MMX values are passed in XMMs.
1257 RC = X86::GR64RegisterClass; // v1i64 values are passed in GPRs.
1262 assert(0 && "Unknown argument type!");
1265 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), VA.getLocReg(), RC);
1266 SDValue ArgValue = DAG.getCopyFromReg(Root, Reg, RegVT);
1268 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1269 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1271 if (VA.getLocInfo() == CCValAssign::SExt)
1272 ArgValue = DAG.getNode(ISD::AssertSext, RegVT, ArgValue,
1273 DAG.getValueType(VA.getValVT()));
1274 else if (VA.getLocInfo() == CCValAssign::ZExt)
1275 ArgValue = DAG.getNode(ISD::AssertZext, RegVT, ArgValue,
1276 DAG.getValueType(VA.getValVT()));
1278 if (VA.getLocInfo() != CCValAssign::Full)
1279 ArgValue = DAG.getNode(ISD::TRUNCATE, VA.getValVT(), ArgValue);
1281 // Handle MMX values passed in GPRs.
1282 if (Is64Bit && RegVT != VA.getLocVT()) {
1283 if (RegVT.getSizeInBits() == 64 && RC == X86::GR64RegisterClass)
1284 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1285 else if (RC == X86::VR128RegisterClass) {
1286 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i64, ArgValue,
1287 DAG.getConstant(0, MVT::i64));
1288 ArgValue = DAG.getNode(ISD::BIT_CONVERT, VA.getLocVT(), ArgValue);
1292 ArgValues.push_back(ArgValue);
1294 assert(VA.isMemLoc());
1295 ArgValues.push_back(LowerMemArgument(Op, DAG, VA, MFI, CC, Root, i));
1299 // The x86-64 ABI for returning structs by value requires that we copy
1300 // the sret argument into %rax for the return. Save the argument into
1301 // a virtual register so that we can access it from the return points.
1302 if (Is64Bit && DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1303 MachineFunction &MF = DAG.getMachineFunction();
1304 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1305 unsigned Reg = FuncInfo->getSRetReturnReg();
1307 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1308 FuncInfo->setSRetReturnReg(Reg);
1310 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), Reg, ArgValues[0]);
1311 Root = DAG.getNode(ISD::TokenFactor, MVT::Other, Copy, Root);
1314 unsigned StackSize = CCInfo.getNextStackOffset();
1315 // align stack specially for tail calls
1316 if (PerformTailCallOpt && CC == CallingConv::Fast)
1317 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1319 // If the function takes variable number of arguments, make a frame index for
1320 // the start of the first vararg value... for expansion of llvm.va_start.
1322 if (Is64Bit || CC != CallingConv::X86_FastCall) {
1323 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1326 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1328 // FIXME: We should really autogenerate these arrays
1329 static const unsigned GPR64ArgRegsWin64[] = {
1330 X86::RCX, X86::RDX, X86::R8, X86::R9
1332 static const unsigned XMMArgRegsWin64[] = {
1333 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1335 static const unsigned GPR64ArgRegs64Bit[] = {
1336 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1338 static const unsigned XMMArgRegs64Bit[] = {
1339 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1340 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1342 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1345 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1346 GPR64ArgRegs = GPR64ArgRegsWin64;
1347 XMMArgRegs = XMMArgRegsWin64;
1349 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1350 GPR64ArgRegs = GPR64ArgRegs64Bit;
1351 XMMArgRegs = XMMArgRegs64Bit;
1353 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1355 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1358 // For X86-64, if there are vararg parameters that are passed via
1359 // registers, then we must store them to their spots on the stack so they
1360 // may be loaded by deferencing the result of va_next.
1361 VarArgsGPOffset = NumIntRegs * 8;
1362 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1363 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1364 TotalNumXMMRegs * 16, 16);
1366 // Store the integer parameter registers.
1367 SmallVector<SDValue, 8> MemOps;
1368 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1369 SDValue FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1370 DAG.getIntPtrConstant(VarArgsGPOffset));
1371 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1372 unsigned VReg = AddLiveIn(MF, GPR64ArgRegs[NumIntRegs],
1373 X86::GR64RegisterClass);
1374 SDValue Val = DAG.getCopyFromReg(Root, VReg, MVT::i64);
1376 DAG.getStore(Val.getValue(1), Val, FIN,
1377 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1378 MemOps.push_back(Store);
1379 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1380 DAG.getIntPtrConstant(8));
1383 // Now store the XMM (fp + vector) parameter registers.
1384 FIN = DAG.getNode(ISD::ADD, getPointerTy(), RSFIN,
1385 DAG.getIntPtrConstant(VarArgsFPOffset));
1386 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1387 unsigned VReg = AddLiveIn(MF, XMMArgRegs[NumXMMRegs],
1388 X86::VR128RegisterClass);
1389 SDValue Val = DAG.getCopyFromReg(Root, VReg, MVT::v4f32);
1391 DAG.getStore(Val.getValue(1), Val, FIN,
1392 PseudoSourceValue::getFixedStack(RegSaveFrameIndex), 0);
1393 MemOps.push_back(Store);
1394 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN,
1395 DAG.getIntPtrConstant(16));
1397 if (!MemOps.empty())
1398 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
1399 &MemOps[0], MemOps.size());
1403 ArgValues.push_back(Root);
1405 // Some CCs need callee pop.
1406 if (IsCalleePop(isVarArg, CC)) {
1407 BytesToPopOnReturn = StackSize; // Callee pops everything.
1408 BytesCallerReserves = 0;
1410 BytesToPopOnReturn = 0; // Callee pops nothing.
1411 // If this is an sret function, the return should pop the hidden pointer.
1412 if (!Is64Bit && CC != CallingConv::Fast && ArgsAreStructReturn(Op))
1413 BytesToPopOnReturn = 4;
1414 BytesCallerReserves = StackSize;
1418 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1419 if (CC == CallingConv::X86_FastCall)
1420 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1423 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1425 // Return the new list of results.
1426 return DAG.getMergeValues(Op.getNode()->getVTList(), &ArgValues[0],
1427 ArgValues.size()).getValue(Op.getResNo());
1431 X86TargetLowering::LowerMemOpCallTo(CallSDNode *TheCall, SelectionDAG &DAG,
1432 const SDValue &StackPtr,
1433 const CCValAssign &VA,
1435 SDValue Arg, ISD::ArgFlagsTy Flags) {
1436 unsigned LocMemOffset = VA.getLocMemOffset();
1437 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1438 PtrOff = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, PtrOff);
1439 if (Flags.isByVal()) {
1440 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG);
1442 return DAG.getStore(Chain, Arg, PtrOff,
1443 PseudoSourceValue::getStack(), LocMemOffset);
1446 /// EmitTailCallLoadRetAddr - Emit a load of return adress if tail call
1447 /// optimization is performed and it is required.
1449 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1450 SDValue &OutRetAddr,
1455 if (!IsTailCall || FPDiff==0) return Chain;
1457 // Adjust the Return address stack slot.
1458 MVT VT = getPointerTy();
1459 OutRetAddr = getReturnAddressFrameIndex(DAG);
1460 // Load the "old" Return address.
1461 OutRetAddr = DAG.getLoad(VT, Chain,OutRetAddr, NULL, 0);
1462 return SDValue(OutRetAddr.getNode(), 1);
1465 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1466 /// optimization is performed and it is required (FPDiff!=0).
1468 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1469 SDValue Chain, SDValue RetAddrFrIdx,
1470 bool Is64Bit, int FPDiff) {
1471 // Store the return address to the appropriate stack slot.
1472 if (!FPDiff) return Chain;
1473 // Calculate the new stack slot for the return address.
1474 int SlotSize = Is64Bit ? 8 : 4;
1475 int NewReturnAddrFI =
1476 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1477 MVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1478 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1479 Chain = DAG.getStore(Chain, RetAddrFrIdx, NewRetAddrFrIdx,
1480 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1484 SDValue X86TargetLowering::LowerCALL(SDValue Op, SelectionDAG &DAG) {
1485 MachineFunction &MF = DAG.getMachineFunction();
1486 CallSDNode *TheCall = cast<CallSDNode>(Op.getNode());
1487 SDValue Chain = TheCall->getChain();
1488 unsigned CC = TheCall->getCallingConv();
1489 bool isVarArg = TheCall->isVarArg();
1490 bool IsTailCall = TheCall->isTailCall() &&
1491 CC == CallingConv::Fast && PerformTailCallOpt;
1492 SDValue Callee = TheCall->getCallee();
1493 bool Is64Bit = Subtarget->is64Bit();
1494 bool IsStructRet = CallIsStructReturn(TheCall);
1496 assert(!(isVarArg && CC == CallingConv::Fast) &&
1497 "Var args not supported with calling convention fastcc");
1499 // Analyze operands of the call, assigning locations to each operand.
1500 SmallVector<CCValAssign, 16> ArgLocs;
1501 CCState CCInfo(CC, isVarArg, getTargetMachine(), ArgLocs);
1502 CCInfo.AnalyzeCallOperands(TheCall, CCAssignFnForNode(CC));
1504 // Get a count of how many bytes are to be pushed on the stack.
1505 unsigned NumBytes = CCInfo.getNextStackOffset();
1506 if (PerformTailCallOpt && CC == CallingConv::Fast)
1507 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1511 // Lower arguments at fp - stackoffset + fpdiff.
1512 unsigned NumBytesCallerPushed =
1513 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1514 FPDiff = NumBytesCallerPushed - NumBytes;
1516 // Set the delta of movement of the returnaddr stackslot.
1517 // But only set if delta is greater than previous delta.
1518 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1519 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1522 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1524 SDValue RetAddrFrIdx;
1525 // Load return adress for tail calls.
1526 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, IsTailCall, Is64Bit,
1529 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1530 SmallVector<SDValue, 8> MemOpChains;
1533 // Walk the register/memloc assignments, inserting copies/loads. In the case
1534 // of tail call optimization arguments are handle later.
1535 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1536 CCValAssign &VA = ArgLocs[i];
1537 SDValue Arg = TheCall->getArg(i);
1538 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1539 bool isByVal = Flags.isByVal();
1541 // Promote the value if needed.
1542 switch (VA.getLocInfo()) {
1543 default: assert(0 && "Unknown loc info!");
1544 case CCValAssign::Full: break;
1545 case CCValAssign::SExt:
1546 Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
1548 case CCValAssign::ZExt:
1549 Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
1551 case CCValAssign::AExt:
1552 Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
1556 if (VA.isRegLoc()) {
1558 MVT RegVT = VA.getLocVT();
1559 if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1560 switch (VA.getLocReg()) {
1563 case X86::RDI: case X86::RSI: case X86::RDX: case X86::RCX:
1565 // Special case: passing MMX values in GPR registers.
1566 Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1569 case X86::XMM0: case X86::XMM1: case X86::XMM2: case X86::XMM3:
1570 case X86::XMM4: case X86::XMM5: case X86::XMM6: case X86::XMM7: {
1571 // Special case: passing MMX values in XMM registers.
1572 Arg = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Arg);
1573 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2i64, Arg);
1574 Arg = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
1575 DAG.getNode(ISD::UNDEF, MVT::v2i64), Arg,
1576 getMOVLMask(2, DAG));
1581 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1583 if (!IsTailCall || (IsTailCall && isByVal)) {
1584 assert(VA.isMemLoc());
1585 if (StackPtr.getNode() == 0)
1586 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1588 MemOpChains.push_back(LowerMemOpCallTo(TheCall, DAG, StackPtr, VA,
1589 Chain, Arg, Flags));
1594 if (!MemOpChains.empty())
1595 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1596 &MemOpChains[0], MemOpChains.size());
1598 // Build a sequence of copy-to-reg nodes chained together with token chain
1599 // and flag operands which copy the outgoing args into registers.
1601 // Tail call byval lowering might overwrite argument registers so in case of
1602 // tail call optimization the copies to registers are lowered later.
1604 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1605 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1607 InFlag = Chain.getValue(1);
1610 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1612 if (CallRequiresGOTPtrInReg(Is64Bit, IsTailCall)) {
1613 Chain = DAG.getCopyToReg(Chain, X86::EBX,
1614 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
1616 InFlag = Chain.getValue(1);
1618 // If we are tail calling and generating PIC/GOT style code load the address
1619 // of the callee into ecx. The value in ecx is used as target of the tail
1620 // jump. This is done to circumvent the ebx/callee-saved problem for tail
1621 // calls on PIC/GOT architectures. Normally we would just put the address of
1622 // GOT into ebx and then call target@PLT. But for tail callss ebx would be
1623 // restored (since ebx is callee saved) before jumping to the target@PLT.
1624 if (CallRequiresFnAddressInReg(Is64Bit, IsTailCall)) {
1625 // Note: The actual moving to ecx is done further down.
1626 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1627 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1628 !G->getGlobal()->hasProtectedVisibility())
1629 Callee = LowerGlobalAddress(Callee, DAG);
1630 else if (isa<ExternalSymbolSDNode>(Callee))
1631 Callee = LowerExternalSymbol(Callee,DAG);
1634 if (Is64Bit && isVarArg) {
1635 // From AMD64 ABI document:
1636 // For calls that may call functions that use varargs or stdargs
1637 // (prototype-less calls or calls to functions containing ellipsis (...) in
1638 // the declaration) %al is used as hidden argument to specify the number
1639 // of SSE registers used. The contents of %al do not need to match exactly
1640 // the number of registers, but must be an ubound on the number of SSE
1641 // registers used and is in the range 0 - 8 inclusive.
1643 // FIXME: Verify this on Win64
1644 // Count the number of XMM registers allocated.
1645 static const unsigned XMMArgRegs[] = {
1646 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1647 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1649 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1651 Chain = DAG.getCopyToReg(Chain, X86::AL,
1652 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1653 InFlag = Chain.getValue(1);
1657 // For tail calls lower the arguments to the 'real' stack slot.
1659 SmallVector<SDValue, 8> MemOpChains2;
1662 // Do not flag preceeding copytoreg stuff together with the following stuff.
1664 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1665 CCValAssign &VA = ArgLocs[i];
1666 if (!VA.isRegLoc()) {
1667 assert(VA.isMemLoc());
1668 SDValue Arg = TheCall->getArg(i);
1669 ISD::ArgFlagsTy Flags = TheCall->getArgFlags(i);
1670 // Create frame index.
1671 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1672 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1673 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1674 FIN = DAG.getFrameIndex(FI, getPointerTy());
1676 if (Flags.isByVal()) {
1677 // Copy relative to framepointer.
1678 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1679 if (StackPtr.getNode() == 0)
1680 StackPtr = DAG.getCopyFromReg(Chain, X86StackPtr, getPointerTy());
1681 Source = DAG.getNode(ISD::ADD, getPointerTy(), StackPtr, Source);
1683 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN, Chain,
1686 // Store relative to framepointer.
1687 MemOpChains2.push_back(
1688 DAG.getStore(Chain, Arg, FIN,
1689 PseudoSourceValue::getFixedStack(FI), 0));
1694 if (!MemOpChains2.empty())
1695 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
1696 &MemOpChains2[0], MemOpChains2.size());
1698 // Copy arguments to their registers.
1699 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1700 Chain = DAG.getCopyToReg(Chain, RegsToPass[i].first, RegsToPass[i].second,
1702 InFlag = Chain.getValue(1);
1706 // Store the return address to the appropriate stack slot.
1707 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1711 // If the callee is a GlobalAddress node (quite common, every direct call is)
1712 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1713 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1714 // We should use extra load for direct calls to dllimported functions in
1716 if (!Subtarget->GVRequiresExtraLoad(G->getGlobal(),
1717 getTargetMachine(), true))
1718 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), getPointerTy(),
1720 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1721 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy());
1722 } else if (IsTailCall) {
1723 unsigned Opc = Is64Bit ? X86::R9 : X86::EAX;
1725 Chain = DAG.getCopyToReg(Chain,
1726 DAG.getRegister(Opc, getPointerTy()),
1728 Callee = DAG.getRegister(Opc, getPointerTy());
1729 // Add register as live out.
1730 DAG.getMachineFunction().getRegInfo().addLiveOut(Opc);
1733 // Returns a chain & a flag for retval copy to use.
1734 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1735 SmallVector<SDValue, 8> Ops;
1738 Ops.push_back(Chain);
1739 Ops.push_back(DAG.getIntPtrConstant(NumBytes, true));
1740 Ops.push_back(DAG.getIntPtrConstant(0, true));
1741 if (InFlag.getNode())
1742 Ops.push_back(InFlag);
1743 Chain = DAG.getNode(ISD::CALLSEQ_END, NodeTys, &Ops[0], Ops.size());
1744 InFlag = Chain.getValue(1);
1746 // Returns a chain & a flag for retval copy to use.
1747 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1751 Ops.push_back(Chain);
1752 Ops.push_back(Callee);
1755 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
1757 // Add argument registers to the end of the list so that they are known live
1759 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1760 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1761 RegsToPass[i].second.getValueType()));
1763 // Add an implicit use GOT pointer in EBX.
1764 if (!IsTailCall && !Is64Bit &&
1765 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1766 Subtarget->isPICStyleGOT())
1767 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
1769 // Add an implicit use of AL for x86 vararg functions.
1770 if (Is64Bit && isVarArg)
1771 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
1773 if (InFlag.getNode())
1774 Ops.push_back(InFlag);
1777 assert(InFlag.getNode() &&
1778 "Flag must be set. Depend on flag being set in LowerRET");
1779 Chain = DAG.getNode(X86ISD::TAILCALL,
1780 TheCall->getVTList(), &Ops[0], Ops.size());
1782 return SDValue(Chain.getNode(), Op.getResNo());
1785 Chain = DAG.getNode(X86ISD::CALL, NodeTys, &Ops[0], Ops.size());
1786 InFlag = Chain.getValue(1);
1788 // Create the CALLSEQ_END node.
1789 unsigned NumBytesForCalleeToPush;
1790 if (IsCalleePop(isVarArg, CC))
1791 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
1792 else if (!Is64Bit && CC != CallingConv::Fast && IsStructRet)
1793 // If this is is a call to a struct-return function, the callee
1794 // pops the hidden struct pointer, so we have to push it back.
1795 // This is common for Darwin/X86, Linux & Mingw32 targets.
1796 NumBytesForCalleeToPush = 4;
1798 NumBytesForCalleeToPush = 0; // Callee pops nothing.
1800 // Returns a flag for retval copy to use.
1801 Chain = DAG.getCALLSEQ_END(Chain,
1802 DAG.getIntPtrConstant(NumBytes, true),
1803 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
1806 InFlag = Chain.getValue(1);
1808 // Handle result values, copying them out of physregs into vregs that we
1810 return SDValue(LowerCallResult(Chain, InFlag, TheCall, CC, DAG),
1815 //===----------------------------------------------------------------------===//
1816 // Fast Calling Convention (tail call) implementation
1817 //===----------------------------------------------------------------------===//
1819 // Like std call, callee cleans arguments, convention except that ECX is
1820 // reserved for storing the tail called function address. Only 2 registers are
1821 // free for argument passing (inreg). Tail call optimization is performed
1823 // * tailcallopt is enabled
1824 // * caller/callee are fastcc
1825 // On X86_64 architecture with GOT-style position independent code only local
1826 // (within module) calls are supported at the moment.
1827 // To keep the stack aligned according to platform abi the function
1828 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
1829 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
1830 // If a tail called function callee has more arguments than the caller the
1831 // caller needs to make sure that there is room to move the RETADDR to. This is
1832 // achieved by reserving an area the size of the argument delta right after the
1833 // original REtADDR, but before the saved framepointer or the spilled registers
1834 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
1846 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
1847 /// for a 16 byte align requirement.
1848 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
1849 SelectionDAG& DAG) {
1850 MachineFunction &MF = DAG.getMachineFunction();
1851 const TargetMachine &TM = MF.getTarget();
1852 const TargetFrameInfo &TFI = *TM.getFrameInfo();
1853 unsigned StackAlignment = TFI.getStackAlignment();
1854 uint64_t AlignMask = StackAlignment - 1;
1855 int64_t Offset = StackSize;
1856 uint64_t SlotSize = TD->getPointerSize();
1857 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
1858 // Number smaller than 12 so just add the difference.
1859 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
1861 // Mask out lower bits, add stackalignment once plus the 12 bytes.
1862 Offset = ((~AlignMask) & Offset) + StackAlignment +
1863 (StackAlignment-SlotSize);
1868 /// IsEligibleForTailCallElimination - Check to see whether the next instruction
1869 /// following the call is a return. A function is eligible if caller/callee
1870 /// calling conventions match, currently only fastcc supports tail calls, and
1871 /// the function CALL is immediatly followed by a RET.
1872 bool X86TargetLowering::IsEligibleForTailCallOptimization(CallSDNode *TheCall,
1874 SelectionDAG& DAG) const {
1875 if (!PerformTailCallOpt)
1878 if (CheckTailCallReturnConstraints(TheCall, Ret)) {
1879 MachineFunction &MF = DAG.getMachineFunction();
1880 unsigned CallerCC = MF.getFunction()->getCallingConv();
1881 unsigned CalleeCC= TheCall->getCallingConv();
1882 if (CalleeCC == CallingConv::Fast && CallerCC == CalleeCC) {
1883 SDValue Callee = TheCall->getCallee();
1884 // On x86/32Bit PIC/GOT tail calls are supported.
1885 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ ||
1886 !Subtarget->isPICStyleGOT()|| !Subtarget->is64Bit())
1889 // Can only do local tail calls (in same module, hidden or protected) on
1890 // x86_64 PIC/GOT at the moment.
1891 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1892 return G->getGlobal()->hasHiddenVisibility()
1893 || G->getGlobal()->hasProtectedVisibility();
1901 X86TargetLowering::createFastISel(MachineFunction &mf,
1902 MachineModuleInfo *mmo,
1903 DenseMap<const Value *, unsigned> &vm,
1904 DenseMap<const BasicBlock *,
1905 MachineBasicBlock *> &bm,
1906 DenseMap<const AllocaInst *, int> &am
1908 , SmallSet<Instruction*, 8> &cil
1911 return X86::createFastISel(mf, mmo, vm, bm, am
1919 //===----------------------------------------------------------------------===//
1920 // Other Lowering Hooks
1921 //===----------------------------------------------------------------------===//
1924 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
1925 MachineFunction &MF = DAG.getMachineFunction();
1926 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1927 int ReturnAddrIndex = FuncInfo->getRAIndex();
1928 uint64_t SlotSize = TD->getPointerSize();
1930 if (ReturnAddrIndex == 0) {
1931 // Set up a frame object for the return address.
1932 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize);
1933 FuncInfo->setRAIndex(ReturnAddrIndex);
1936 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
1940 /// translateX86CC - do a one to one translation of a ISD::CondCode to the X86
1941 /// specific condition code. It returns a false if it cannot do a direct
1942 /// translation. X86CC is the translated CondCode. LHS/RHS are modified as
1944 static bool translateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
1945 unsigned &X86CC, SDValue &LHS, SDValue &RHS,
1946 SelectionDAG &DAG) {
1947 X86CC = X86::COND_INVALID;
1949 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
1950 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
1951 // X > -1 -> X == 0, jump !sign.
1952 RHS = DAG.getConstant(0, RHS.getValueType());
1953 X86CC = X86::COND_NS;
1955 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
1956 // X < 0 -> X == 0, jump on sign.
1957 X86CC = X86::COND_S;
1959 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
1961 RHS = DAG.getConstant(0, RHS.getValueType());
1962 X86CC = X86::COND_LE;
1967 switch (SetCCOpcode) {
1969 case ISD::SETEQ: X86CC = X86::COND_E; break;
1970 case ISD::SETGT: X86CC = X86::COND_G; break;
1971 case ISD::SETGE: X86CC = X86::COND_GE; break;
1972 case ISD::SETLT: X86CC = X86::COND_L; break;
1973 case ISD::SETLE: X86CC = X86::COND_LE; break;
1974 case ISD::SETNE: X86CC = X86::COND_NE; break;
1975 case ISD::SETULT: X86CC = X86::COND_B; break;
1976 case ISD::SETUGT: X86CC = X86::COND_A; break;
1977 case ISD::SETULE: X86CC = X86::COND_BE; break;
1978 case ISD::SETUGE: X86CC = X86::COND_AE; break;
1981 // First determine if it is required or is profitable to flip the operands.
1983 // If LHS is a foldable load, but RHS is not, flip the condition.
1984 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
1985 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
1986 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
1987 std::swap(LHS, RHS);
1990 switch (SetCCOpcode) {
1996 std::swap(LHS, RHS);
2000 // On a floating point condition, the flags are set as follows:
2002 // 0 | 0 | 0 | X > Y
2003 // 0 | 0 | 1 | X < Y
2004 // 1 | 0 | 0 | X == Y
2005 // 1 | 1 | 1 | unordered
2006 switch (SetCCOpcode) {
2010 X86CC = X86::COND_E;
2012 case ISD::SETOLT: // flipped
2015 X86CC = X86::COND_A;
2017 case ISD::SETOLE: // flipped
2020 X86CC = X86::COND_AE;
2022 case ISD::SETUGT: // flipped
2025 X86CC = X86::COND_B;
2027 case ISD::SETUGE: // flipped
2030 X86CC = X86::COND_BE;
2034 X86CC = X86::COND_NE;
2037 X86CC = X86::COND_P;
2040 X86CC = X86::COND_NP;
2045 return X86CC != X86::COND_INVALID;
2048 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2049 /// code. Current x86 isa includes the following FP cmov instructions:
2050 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2051 static bool hasFPCMov(unsigned X86CC) {
2067 /// isUndefOrInRange - Op is either an undef node or a ConstantSDNode. Return
2068 /// true if Op is undef or if its value falls within the specified range (L, H].
2069 static bool isUndefOrInRange(SDValue Op, unsigned Low, unsigned Hi) {
2070 if (Op.getOpcode() == ISD::UNDEF)
2073 unsigned Val = cast<ConstantSDNode>(Op)->getZExtValue();
2074 return (Val >= Low && Val < Hi);
2077 /// isUndefOrEqual - Op is either an undef node or a ConstantSDNode. Return
2078 /// true if Op is undef or if its value equal to the specified value.
2079 static bool isUndefOrEqual(SDValue Op, unsigned Val) {
2080 if (Op.getOpcode() == ISD::UNDEF)
2082 return cast<ConstantSDNode>(Op)->getZExtValue() == Val;
2085 /// isPSHUFDMask - Return true if the specified VECTOR_SHUFFLE operand
2086 /// specifies a shuffle of elements that is suitable for input to PSHUFD.
2087 bool X86::isPSHUFDMask(SDNode *N) {
2088 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2090 if (N->getNumOperands() != 2 && N->getNumOperands() != 4)
2093 // Check if the value doesn't reference the second vector.
2094 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2095 SDValue Arg = N->getOperand(i);
2096 if (Arg.getOpcode() == ISD::UNDEF) continue;
2097 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2098 if (cast<ConstantSDNode>(Arg)->getZExtValue() >= e)
2105 /// isPSHUFHWMask - Return true if the specified VECTOR_SHUFFLE operand
2106 /// specifies a shuffle of elements that is suitable for input to PSHUFHW.
2107 bool X86::isPSHUFHWMask(SDNode *N) {
2108 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2110 if (N->getNumOperands() != 8)
2113 // Lower quadword copied in order.
2114 for (unsigned i = 0; i != 4; ++i) {
2115 SDValue Arg = N->getOperand(i);
2116 if (Arg.getOpcode() == ISD::UNDEF) continue;
2117 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2118 if (cast<ConstantSDNode>(Arg)->getZExtValue() != i)
2122 // Upper quadword shuffled.
2123 for (unsigned i = 4; i != 8; ++i) {
2124 SDValue Arg = N->getOperand(i);
2125 if (Arg.getOpcode() == ISD::UNDEF) continue;
2126 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2127 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2128 if (Val < 4 || Val > 7)
2135 /// isPSHUFLWMask - Return true if the specified VECTOR_SHUFFLE operand
2136 /// specifies a shuffle of elements that is suitable for input to PSHUFLW.
2137 bool X86::isPSHUFLWMask(SDNode *N) {
2138 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2140 if (N->getNumOperands() != 8)
2143 // Upper quadword copied in order.
2144 for (unsigned i = 4; i != 8; ++i)
2145 if (!isUndefOrEqual(N->getOperand(i), i))
2148 // Lower quadword shuffled.
2149 for (unsigned i = 0; i != 4; ++i)
2150 if (!isUndefOrInRange(N->getOperand(i), 0, 4))
2156 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2157 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2158 static bool isSHUFPMask(SDOperandPtr Elems, unsigned NumElems) {
2159 if (NumElems != 2 && NumElems != 4) return false;
2161 unsigned Half = NumElems / 2;
2162 for (unsigned i = 0; i < Half; ++i)
2163 if (!isUndefOrInRange(Elems[i], 0, NumElems))
2165 for (unsigned i = Half; i < NumElems; ++i)
2166 if (!isUndefOrInRange(Elems[i], NumElems, NumElems*2))
2172 bool X86::isSHUFPMask(SDNode *N) {
2173 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2174 return ::isSHUFPMask(N->op_begin(), N->getNumOperands());
2177 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2178 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2179 /// half elements to come from vector 1 (which would equal the dest.) and
2180 /// the upper half to come from vector 2.
2181 static bool isCommutedSHUFP(SDOperandPtr Ops, unsigned NumOps) {
2182 if (NumOps != 2 && NumOps != 4) return false;
2184 unsigned Half = NumOps / 2;
2185 for (unsigned i = 0; i < Half; ++i)
2186 if (!isUndefOrInRange(Ops[i], NumOps, NumOps*2))
2188 for (unsigned i = Half; i < NumOps; ++i)
2189 if (!isUndefOrInRange(Ops[i], 0, NumOps))
2194 static bool isCommutedSHUFP(SDNode *N) {
2195 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2196 return isCommutedSHUFP(N->op_begin(), N->getNumOperands());
2199 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2200 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2201 bool X86::isMOVHLPSMask(SDNode *N) {
2202 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2204 if (N->getNumOperands() != 4)
2207 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2208 return isUndefOrEqual(N->getOperand(0), 6) &&
2209 isUndefOrEqual(N->getOperand(1), 7) &&
2210 isUndefOrEqual(N->getOperand(2), 2) &&
2211 isUndefOrEqual(N->getOperand(3), 3);
2214 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2215 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2217 bool X86::isMOVHLPS_v_undef_Mask(SDNode *N) {
2218 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2220 if (N->getNumOperands() != 4)
2223 // Expect bit0 == 2, bit1 == 3, bit2 == 2, bit3 == 3
2224 return isUndefOrEqual(N->getOperand(0), 2) &&
2225 isUndefOrEqual(N->getOperand(1), 3) &&
2226 isUndefOrEqual(N->getOperand(2), 2) &&
2227 isUndefOrEqual(N->getOperand(3), 3);
2230 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2231 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2232 bool X86::isMOVLPMask(SDNode *N) {
2233 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2235 unsigned NumElems = N->getNumOperands();
2236 if (NumElems != 2 && NumElems != 4)
2239 for (unsigned i = 0; i < NumElems/2; ++i)
2240 if (!isUndefOrEqual(N->getOperand(i), i + NumElems))
2243 for (unsigned i = NumElems/2; i < NumElems; ++i)
2244 if (!isUndefOrEqual(N->getOperand(i), i))
2250 /// isMOVHPMask - Return true if the specified VECTOR_SHUFFLE operand
2251 /// specifies a shuffle of elements that is suitable for input to MOVHP{S|D}
2253 bool X86::isMOVHPMask(SDNode *N) {
2254 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2256 unsigned NumElems = N->getNumOperands();
2257 if (NumElems != 2 && NumElems != 4)
2260 for (unsigned i = 0; i < NumElems/2; ++i)
2261 if (!isUndefOrEqual(N->getOperand(i), i))
2264 for (unsigned i = 0; i < NumElems/2; ++i) {
2265 SDValue Arg = N->getOperand(i + NumElems/2);
2266 if (!isUndefOrEqual(Arg, i + NumElems))
2273 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2274 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2275 bool static isUNPCKLMask(SDOperandPtr Elts, unsigned NumElts,
2276 bool V2IsSplat = false) {
2277 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2280 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2281 SDValue BitI = Elts[i];
2282 SDValue BitI1 = Elts[i+1];
2283 if (!isUndefOrEqual(BitI, j))
2286 if (isUndefOrEqual(BitI1, NumElts))
2289 if (!isUndefOrEqual(BitI1, j + NumElts))
2297 bool X86::isUNPCKLMask(SDNode *N, bool V2IsSplat) {
2298 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2299 return ::isUNPCKLMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2302 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2303 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2304 bool static isUNPCKHMask(SDOperandPtr Elts, unsigned NumElts,
2305 bool V2IsSplat = false) {
2306 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2309 for (unsigned i = 0, j = 0; i != NumElts; i += 2, ++j) {
2310 SDValue BitI = Elts[i];
2311 SDValue BitI1 = Elts[i+1];
2312 if (!isUndefOrEqual(BitI, j + NumElts/2))
2315 if (isUndefOrEqual(BitI1, NumElts))
2318 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2326 bool X86::isUNPCKHMask(SDNode *N, bool V2IsSplat) {
2327 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2328 return ::isUNPCKHMask(N->op_begin(), N->getNumOperands(), V2IsSplat);
2331 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2332 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2334 bool X86::isUNPCKL_v_undef_Mask(SDNode *N) {
2335 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2337 unsigned NumElems = N->getNumOperands();
2338 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2341 for (unsigned i = 0, j = 0; i != NumElems; i += 2, ++j) {
2342 SDValue BitI = N->getOperand(i);
2343 SDValue BitI1 = N->getOperand(i+1);
2345 if (!isUndefOrEqual(BitI, j))
2347 if (!isUndefOrEqual(BitI1, j))
2354 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2355 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2357 bool X86::isUNPCKH_v_undef_Mask(SDNode *N) {
2358 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2360 unsigned NumElems = N->getNumOperands();
2361 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2364 for (unsigned i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2365 SDValue BitI = N->getOperand(i);
2366 SDValue BitI1 = N->getOperand(i + 1);
2368 if (!isUndefOrEqual(BitI, j))
2370 if (!isUndefOrEqual(BitI1, j))
2377 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2378 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2379 /// MOVSD, and MOVD, i.e. setting the lowest element.
2380 static bool isMOVLMask(SDOperandPtr Elts, unsigned NumElts) {
2381 if (NumElts != 2 && NumElts != 4)
2384 if (!isUndefOrEqual(Elts[0], NumElts))
2387 for (unsigned i = 1; i < NumElts; ++i) {
2388 if (!isUndefOrEqual(Elts[i], i))
2395 bool X86::isMOVLMask(SDNode *N) {
2396 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2397 return ::isMOVLMask(N->op_begin(), N->getNumOperands());
2400 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2401 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2402 /// element of vector 2 and the other elements to come from vector 1 in order.
2403 static bool isCommutedMOVL(SDOperandPtr Ops, unsigned NumOps,
2404 bool V2IsSplat = false,
2405 bool V2IsUndef = false) {
2406 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2409 if (!isUndefOrEqual(Ops[0], 0))
2412 for (unsigned i = 1; i < NumOps; ++i) {
2413 SDValue Arg = Ops[i];
2414 if (!(isUndefOrEqual(Arg, i+NumOps) ||
2415 (V2IsUndef && isUndefOrInRange(Arg, NumOps, NumOps*2)) ||
2416 (V2IsSplat && isUndefOrEqual(Arg, NumOps))))
2423 static bool isCommutedMOVL(SDNode *N, bool V2IsSplat = false,
2424 bool V2IsUndef = false) {
2425 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2426 return isCommutedMOVL(N->op_begin(), N->getNumOperands(),
2427 V2IsSplat, V2IsUndef);
2430 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2431 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2432 bool X86::isMOVSHDUPMask(SDNode *N) {
2433 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2435 if (N->getNumOperands() != 4)
2438 // Expect 1, 1, 3, 3
2439 for (unsigned i = 0; i < 2; ++i) {
2440 SDValue Arg = N->getOperand(i);
2441 if (Arg.getOpcode() == ISD::UNDEF) continue;
2442 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2443 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2444 if (Val != 1) return false;
2448 for (unsigned i = 2; i < 4; ++i) {
2449 SDValue Arg = N->getOperand(i);
2450 if (Arg.getOpcode() == ISD::UNDEF) continue;
2451 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2452 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2453 if (Val != 3) return false;
2457 // Don't use movshdup if it can be done with a shufps.
2461 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2462 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2463 bool X86::isMOVSLDUPMask(SDNode *N) {
2464 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2466 if (N->getNumOperands() != 4)
2469 // Expect 0, 0, 2, 2
2470 for (unsigned i = 0; i < 2; ++i) {
2471 SDValue Arg = N->getOperand(i);
2472 if (Arg.getOpcode() == ISD::UNDEF) continue;
2473 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2474 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2475 if (Val != 0) return false;
2479 for (unsigned i = 2; i < 4; ++i) {
2480 SDValue Arg = N->getOperand(i);
2481 if (Arg.getOpcode() == ISD::UNDEF) continue;
2482 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2483 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2484 if (Val != 2) return false;
2488 // Don't use movshdup if it can be done with a shufps.
2492 /// isIdentityMask - Return true if the specified VECTOR_SHUFFLE operand
2493 /// specifies a identity operation on the LHS or RHS.
2494 static bool isIdentityMask(SDNode *N, bool RHS = false) {
2495 unsigned NumElems = N->getNumOperands();
2496 for (unsigned i = 0; i < NumElems; ++i)
2497 if (!isUndefOrEqual(N->getOperand(i), i + (RHS ? NumElems : 0)))
2502 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2503 /// a splat of a single element.
2504 static bool isSplatMask(SDNode *N) {
2505 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2507 // This is a splat operation if each element of the permute is the same, and
2508 // if the value doesn't reference the second vector.
2509 unsigned NumElems = N->getNumOperands();
2510 SDValue ElementBase;
2512 for (; i != NumElems; ++i) {
2513 SDValue Elt = N->getOperand(i);
2514 if (isa<ConstantSDNode>(Elt)) {
2520 if (!ElementBase.getNode())
2523 for (; i != NumElems; ++i) {
2524 SDValue Arg = N->getOperand(i);
2525 if (Arg.getOpcode() == ISD::UNDEF) continue;
2526 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2527 if (Arg != ElementBase) return false;
2530 // Make sure it is a splat of the first vector operand.
2531 return cast<ConstantSDNode>(ElementBase)->getZExtValue() < NumElems;
2534 /// isSplatMask - Return true if the specified VECTOR_SHUFFLE operand specifies
2535 /// a splat of a single element and it's a 2 or 4 element mask.
2536 bool X86::isSplatMask(SDNode *N) {
2537 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2539 // We can only splat 64-bit, and 32-bit quantities with a single instruction.
2540 if (N->getNumOperands() != 4 && N->getNumOperands() != 2)
2542 return ::isSplatMask(N);
2545 /// isSplatLoMask - Return true if the specified VECTOR_SHUFFLE operand
2546 /// specifies a splat of zero element.
2547 bool X86::isSplatLoMask(SDNode *N) {
2548 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2550 for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
2551 if (!isUndefOrEqual(N->getOperand(i), 0))
2556 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2557 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2558 bool X86::isMOVDDUPMask(SDNode *N) {
2559 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2561 unsigned e = N->getNumOperands() / 2;
2562 for (unsigned i = 0; i < e; ++i)
2563 if (!isUndefOrEqual(N->getOperand(i), i))
2565 for (unsigned i = 0; i < e; ++i)
2566 if (!isUndefOrEqual(N->getOperand(e+i), i))
2571 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2572 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUF* and SHUFP*
2574 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2575 unsigned NumOperands = N->getNumOperands();
2576 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2578 for (unsigned i = 0; i < NumOperands; ++i) {
2580 SDValue Arg = N->getOperand(NumOperands-i-1);
2581 if (Arg.getOpcode() != ISD::UNDEF)
2582 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2583 if (Val >= NumOperands) Val -= NumOperands;
2585 if (i != NumOperands - 1)
2592 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2593 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFHW
2595 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2597 // 8 nodes, but we only care about the last 4.
2598 for (unsigned i = 7; i >= 4; --i) {
2600 SDValue Arg = N->getOperand(i);
2601 if (Arg.getOpcode() != ISD::UNDEF)
2602 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2611 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2612 /// the specified isShuffleMask VECTOR_SHUFFLE mask with PSHUFLW
2614 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2616 // 8 nodes, but we only care about the first 4.
2617 for (int i = 3; i >= 0; --i) {
2619 SDValue Arg = N->getOperand(i);
2620 if (Arg.getOpcode() != ISD::UNDEF)
2621 Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2630 /// isPSHUFHW_PSHUFLWMask - true if the specified VECTOR_SHUFFLE operand
2631 /// specifies a 8 element shuffle that can be broken into a pair of
2632 /// PSHUFHW and PSHUFLW.
2633 static bool isPSHUFHW_PSHUFLWMask(SDNode *N) {
2634 assert(N->getOpcode() == ISD::BUILD_VECTOR);
2636 if (N->getNumOperands() != 8)
2639 // Lower quadword shuffled.
2640 for (unsigned i = 0; i != 4; ++i) {
2641 SDValue Arg = N->getOperand(i);
2642 if (Arg.getOpcode() == ISD::UNDEF) continue;
2643 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2644 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2649 // Upper quadword shuffled.
2650 for (unsigned i = 4; i != 8; ++i) {
2651 SDValue Arg = N->getOperand(i);
2652 if (Arg.getOpcode() == ISD::UNDEF) continue;
2653 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2654 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2655 if (Val < 4 || Val > 7)
2662 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as
2663 /// values in ther permute mask.
2664 static SDValue CommuteVectorShuffle(SDValue Op, SDValue &V1,
2665 SDValue &V2, SDValue &Mask,
2666 SelectionDAG &DAG) {
2667 MVT VT = Op.getValueType();
2668 MVT MaskVT = Mask.getValueType();
2669 MVT EltVT = MaskVT.getVectorElementType();
2670 unsigned NumElems = Mask.getNumOperands();
2671 SmallVector<SDValue, 8> MaskVec;
2673 for (unsigned i = 0; i != NumElems; ++i) {
2674 SDValue Arg = Mask.getOperand(i);
2675 if (Arg.getOpcode() == ISD::UNDEF) {
2676 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2679 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2680 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2682 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2684 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2688 Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2689 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
2692 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2693 /// the two vector operands have swapped position.
2695 SDValue CommuteVectorShuffleMask(SDValue Mask, SelectionDAG &DAG) {
2696 MVT MaskVT = Mask.getValueType();
2697 MVT EltVT = MaskVT.getVectorElementType();
2698 unsigned NumElems = Mask.getNumOperands();
2699 SmallVector<SDValue, 8> MaskVec;
2700 for (unsigned i = 0; i != NumElems; ++i) {
2701 SDValue Arg = Mask.getOperand(i);
2702 if (Arg.getOpcode() == ISD::UNDEF) {
2703 MaskVec.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2706 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2707 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2709 MaskVec.push_back(DAG.getConstant(Val + NumElems, EltVT));
2711 MaskVec.push_back(DAG.getConstant(Val - NumElems, EltVT));
2713 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], NumElems);
2717 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2718 /// match movhlps. The lower half elements should come from upper half of
2719 /// V1 (and in order), and the upper half elements should come from the upper
2720 /// half of V2 (and in order).
2721 static bool ShouldXformToMOVHLPS(SDNode *Mask) {
2722 unsigned NumElems = Mask->getNumOperands();
2725 for (unsigned i = 0, e = 2; i != e; ++i)
2726 if (!isUndefOrEqual(Mask->getOperand(i), i+2))
2728 for (unsigned i = 2; i != 4; ++i)
2729 if (!isUndefOrEqual(Mask->getOperand(i), i+4))
2734 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2735 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2737 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2738 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
2740 N = N->getOperand(0).getNode();
2741 if (!ISD::isNON_EXTLoad(N))
2744 *LD = cast<LoadSDNode>(N);
2748 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2749 /// match movlp{s|d}. The lower half elements should come from lower half of
2750 /// V1 (and in order), and the upper half elements should come from the upper
2751 /// half of V2 (and in order). And since V1 will become the source of the
2752 /// MOVLP, it must be either a vector load or a scalar load to vector.
2753 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2, SDNode *Mask) {
2754 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2756 // Is V2 is a vector load, don't do this transformation. We will try to use
2757 // load folding shufps op.
2758 if (ISD::isNON_EXTLoad(V2))
2761 unsigned NumElems = Mask->getNumOperands();
2762 if (NumElems != 2 && NumElems != 4)
2764 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2765 if (!isUndefOrEqual(Mask->getOperand(i), i))
2767 for (unsigned i = NumElems/2; i != NumElems; ++i)
2768 if (!isUndefOrEqual(Mask->getOperand(i), i+NumElems))
2773 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2775 static bool isSplatVector(SDNode *N) {
2776 if (N->getOpcode() != ISD::BUILD_VECTOR)
2779 SDValue SplatValue = N->getOperand(0);
2780 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2781 if (N->getOperand(i) != SplatValue)
2786 /// isUndefShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2788 static bool isUndefShuffle(SDNode *N) {
2789 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2792 SDValue V1 = N->getOperand(0);
2793 SDValue V2 = N->getOperand(1);
2794 SDValue Mask = N->getOperand(2);
2795 unsigned NumElems = Mask.getNumOperands();
2796 for (unsigned i = 0; i != NumElems; ++i) {
2797 SDValue Arg = Mask.getOperand(i);
2798 if (Arg.getOpcode() != ISD::UNDEF) {
2799 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2800 if (Val < NumElems && V1.getOpcode() != ISD::UNDEF)
2802 else if (Val >= NumElems && V2.getOpcode() != ISD::UNDEF)
2809 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2811 static inline bool isZeroNode(SDValue Elt) {
2812 return ((isa<ConstantSDNode>(Elt) &&
2813 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2814 (isa<ConstantFPSDNode>(Elt) &&
2815 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2818 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2819 /// to an zero vector.
2820 static bool isZeroShuffle(SDNode *N) {
2821 if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
2824 SDValue V1 = N->getOperand(0);
2825 SDValue V2 = N->getOperand(1);
2826 SDValue Mask = N->getOperand(2);
2827 unsigned NumElems = Mask.getNumOperands();
2828 for (unsigned i = 0; i != NumElems; ++i) {
2829 SDValue Arg = Mask.getOperand(i);
2830 if (Arg.getOpcode() == ISD::UNDEF)
2833 unsigned Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2834 if (Idx < NumElems) {
2835 unsigned Opc = V1.getNode()->getOpcode();
2836 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
2838 if (Opc != ISD::BUILD_VECTOR ||
2839 !isZeroNode(V1.getNode()->getOperand(Idx)))
2841 } else if (Idx >= NumElems) {
2842 unsigned Opc = V2.getNode()->getOpcode();
2843 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
2845 if (Opc != ISD::BUILD_VECTOR ||
2846 !isZeroNode(V2.getNode()->getOperand(Idx - NumElems)))
2853 /// getZeroVector - Returns a vector of specified type with all zero elements.
2855 static SDValue getZeroVector(MVT VT, bool HasSSE2, SelectionDAG &DAG) {
2856 assert(VT.isVector() && "Expected a vector type");
2858 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2859 // type. This ensures they get CSE'd.
2861 if (VT.getSizeInBits() == 64) { // MMX
2862 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2863 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2864 } else if (HasSSE2) { // SSE2
2865 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
2866 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2868 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
2869 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4f32, Cst, Cst, Cst, Cst);
2871 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2874 /// getOnesVector - Returns a vector of specified type with all bits set.
2876 static SDValue getOnesVector(MVT VT, SelectionDAG &DAG) {
2877 assert(VT.isVector() && "Expected a vector type");
2879 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
2880 // type. This ensures they get CSE'd.
2881 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
2883 if (VT.getSizeInBits() == 64) // MMX
2884 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
2886 Vec = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst, Cst, Cst, Cst);
2887 return DAG.getNode(ISD::BIT_CONVERT, VT, Vec);
2891 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
2892 /// that point to V2 points to its first element.
2893 static SDValue NormalizeMask(SDValue Mask, SelectionDAG &DAG) {
2894 assert(Mask.getOpcode() == ISD::BUILD_VECTOR);
2896 bool Changed = false;
2897 SmallVector<SDValue, 8> MaskVec;
2898 unsigned NumElems = Mask.getNumOperands();
2899 for (unsigned i = 0; i != NumElems; ++i) {
2900 SDValue Arg = Mask.getOperand(i);
2901 if (Arg.getOpcode() != ISD::UNDEF) {
2902 unsigned Val = cast<ConstantSDNode>(Arg)->getZExtValue();
2903 if (Val > NumElems) {
2904 Arg = DAG.getConstant(NumElems, Arg.getValueType());
2908 MaskVec.push_back(Arg);
2912 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2913 &MaskVec[0], MaskVec.size());
2917 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
2918 /// operation of specified width.
2919 static SDValue getMOVLMask(unsigned NumElems, SelectionDAG &DAG) {
2920 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2921 MVT BaseVT = MaskVT.getVectorElementType();
2923 SmallVector<SDValue, 8> MaskVec;
2924 MaskVec.push_back(DAG.getConstant(NumElems, BaseVT));
2925 for (unsigned i = 1; i != NumElems; ++i)
2926 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2927 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2930 /// getUnpacklMask - Returns a vector_shuffle mask for an unpackl operation
2931 /// of specified width.
2932 static SDValue getUnpacklMask(unsigned NumElems, SelectionDAG &DAG) {
2933 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2934 MVT BaseVT = MaskVT.getVectorElementType();
2935 SmallVector<SDValue, 8> MaskVec;
2936 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
2937 MaskVec.push_back(DAG.getConstant(i, BaseVT));
2938 MaskVec.push_back(DAG.getConstant(i + NumElems, BaseVT));
2940 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2943 /// getUnpackhMask - Returns a vector_shuffle mask for an unpackh operation
2944 /// of specified width.
2945 static SDValue getUnpackhMask(unsigned NumElems, SelectionDAG &DAG) {
2946 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2947 MVT BaseVT = MaskVT.getVectorElementType();
2948 unsigned Half = NumElems/2;
2949 SmallVector<SDValue, 8> MaskVec;
2950 for (unsigned i = 0; i != Half; ++i) {
2951 MaskVec.push_back(DAG.getConstant(i + Half, BaseVT));
2952 MaskVec.push_back(DAG.getConstant(i + NumElems + Half, BaseVT));
2954 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2957 /// getSwapEltZeroMask - Returns a vector_shuffle mask for a shuffle that swaps
2958 /// element #0 of a vector with the specified index, leaving the rest of the
2959 /// elements in place.
2960 static SDValue getSwapEltZeroMask(unsigned NumElems, unsigned DestElt,
2961 SelectionDAG &DAG) {
2962 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
2963 MVT BaseVT = MaskVT.getVectorElementType();
2964 SmallVector<SDValue, 8> MaskVec;
2965 // Element #0 of the result gets the elt we are replacing.
2966 MaskVec.push_back(DAG.getConstant(DestElt, BaseVT));
2967 for (unsigned i = 1; i != NumElems; ++i)
2968 MaskVec.push_back(DAG.getConstant(i == DestElt ? 0 : i, BaseVT));
2969 return DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], MaskVec.size());
2972 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
2973 static SDValue PromoteSplat(SDValue Op, SelectionDAG &DAG, bool HasSSE2) {
2974 MVT PVT = HasSSE2 ? MVT::v4i32 : MVT::v4f32;
2975 MVT VT = Op.getValueType();
2978 SDValue V1 = Op.getOperand(0);
2979 SDValue Mask = Op.getOperand(2);
2980 unsigned NumElems = Mask.getNumOperands();
2981 // Special handling of v4f32 -> v4i32.
2982 if (VT != MVT::v4f32) {
2983 Mask = getUnpacklMask(NumElems, DAG);
2984 while (NumElems > 4) {
2985 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1, Mask);
2988 Mask = getZeroVector(MVT::v4i32, true, DAG);
2991 V1 = DAG.getNode(ISD::BIT_CONVERT, PVT, V1);
2992 SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, PVT, V1,
2993 DAG.getNode(ISD::UNDEF, PVT), Mask);
2994 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
2997 /// isVectorLoad - Returns true if the node is a vector load, a scalar
2998 /// load that's promoted to vector, or a load bitcasted.
2999 static bool isVectorLoad(SDValue Op) {
3000 assert(Op.getValueType().isVector() && "Expected a vector type");
3001 if (Op.getOpcode() == ISD::SCALAR_TO_VECTOR ||
3002 Op.getOpcode() == ISD::BIT_CONVERT) {
3003 return isa<LoadSDNode>(Op.getOperand(0));
3005 return isa<LoadSDNode>(Op);
3009 /// CanonicalizeMovddup - Cannonicalize movddup shuffle to v2f64.
3011 static SDValue CanonicalizeMovddup(SDValue Op, SDValue V1, SDValue Mask,
3012 SelectionDAG &DAG, bool HasSSE3) {
3013 // If we have sse3 and shuffle has more than one use or input is a load, then
3014 // use movddup. Otherwise, use movlhps.
3015 bool UseMovddup = HasSSE3 && (!Op.hasOneUse() || isVectorLoad(V1));
3016 MVT PVT = UseMovddup ? MVT::v2f64 : MVT::v4f32;
3017 MVT VT = Op.getValueType();
3020 unsigned NumElems = PVT.getVectorNumElements();
3021 if (NumElems == 2) {
3022 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3023 Mask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, Cst, Cst);
3025 assert(NumElems == 4);
3026 SDValue Cst0 = DAG.getTargetConstant(0, MVT::i32);
3027 SDValue Cst1 = DAG.getTargetConstant(1, MVT::i32);
3028 Mask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, Cst0, Cst1, Cst0, Cst1);
3031 V1 = DAG.getNode(ISD::BIT_CONVERT, PVT, V1);
3032 SDValue Shuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, PVT, V1,
3033 DAG.getNode(ISD::UNDEF, PVT), Mask);
3034 return DAG.getNode(ISD::BIT_CONVERT, VT, Shuffle);
3037 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3038 /// vector of zero or undef vector. This produces a shuffle where the low
3039 /// element of V2 is swizzled into the zero/undef vector, landing at element
3040 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3041 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3042 bool isZero, bool HasSSE2,
3043 SelectionDAG &DAG) {
3044 MVT VT = V2.getValueType();
3046 ? getZeroVector(VT, HasSSE2, DAG) : DAG.getNode(ISD::UNDEF, VT);
3047 unsigned NumElems = V2.getValueType().getVectorNumElements();
3048 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3049 MVT EVT = MaskVT.getVectorElementType();
3050 SmallVector<SDValue, 16> MaskVec;
3051 for (unsigned i = 0; i != NumElems; ++i)
3052 if (i == Idx) // If this is the insertion idx, put the low elt of V2 here.
3053 MaskVec.push_back(DAG.getConstant(NumElems, EVT));
3055 MaskVec.push_back(DAG.getConstant(i, EVT));
3056 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3057 &MaskVec[0], MaskVec.size());
3058 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, Mask);
3061 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3062 /// a shuffle that is zero.
3064 unsigned getNumOfConsecutiveZeros(SDValue Op, SDValue Mask,
3065 unsigned NumElems, bool Low,
3066 SelectionDAG &DAG) {
3067 unsigned NumZeros = 0;
3068 for (unsigned i = 0; i < NumElems; ++i) {
3069 unsigned Index = Low ? i : NumElems-i-1;
3070 SDValue Idx = Mask.getOperand(Index);
3071 if (Idx.getOpcode() == ISD::UNDEF) {
3075 SDValue Elt = DAG.getShuffleScalarElt(Op.getNode(), Index);
3076 if (Elt.getNode() && isZeroNode(Elt))
3084 /// isVectorShift - Returns true if the shuffle can be implemented as a
3085 /// logical left or right shift of a vector.
3086 static bool isVectorShift(SDValue Op, SDValue Mask, SelectionDAG &DAG,
3087 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3088 unsigned NumElems = Mask.getNumOperands();
3091 unsigned NumZeros= getNumOfConsecutiveZeros(Op, Mask, NumElems, true, DAG);
3094 NumZeros = getNumOfConsecutiveZeros(Op, Mask, NumElems, false, DAG);
3099 bool SeenV1 = false;
3100 bool SeenV2 = false;
3101 for (unsigned i = NumZeros; i < NumElems; ++i) {
3102 unsigned Val = isLeft ? (i - NumZeros) : i;
3103 SDValue Idx = Mask.getOperand(isLeft ? i : (i - NumZeros));
3104 if (Idx.getOpcode() == ISD::UNDEF)
3106 unsigned Index = cast<ConstantSDNode>(Idx)->getZExtValue();
3107 if (Index < NumElems)
3116 if (SeenV1 && SeenV2)
3119 ShVal = SeenV1 ? Op.getOperand(0) : Op.getOperand(1);
3125 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3127 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3128 unsigned NumNonZero, unsigned NumZero,
3129 SelectionDAG &DAG, TargetLowering &TLI) {
3135 for (unsigned i = 0; i < 16; ++i) {
3136 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3137 if (ThisIsNonZero && First) {
3139 V = getZeroVector(MVT::v8i16, true, DAG);
3141 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3146 SDValue ThisElt(0, 0), LastElt(0, 0);
3147 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3148 if (LastIsNonZero) {
3149 LastElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i-1));
3151 if (ThisIsNonZero) {
3152 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, MVT::i16, Op.getOperand(i));
3153 ThisElt = DAG.getNode(ISD::SHL, MVT::i16,
3154 ThisElt, DAG.getConstant(8, MVT::i8));
3156 ThisElt = DAG.getNode(ISD::OR, MVT::i16, ThisElt, LastElt);
3160 if (ThisElt.getNode())
3161 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, ThisElt,
3162 DAG.getIntPtrConstant(i/2));
3166 return DAG.getNode(ISD::BIT_CONVERT, MVT::v16i8, V);
3169 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3171 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3172 unsigned NumNonZero, unsigned NumZero,
3173 SelectionDAG &DAG, TargetLowering &TLI) {
3179 for (unsigned i = 0; i < 8; ++i) {
3180 bool isNonZero = (NonZeros & (1 << i)) != 0;
3184 V = getZeroVector(MVT::v8i16, true, DAG);
3186 V = DAG.getNode(ISD::UNDEF, MVT::v8i16);
3189 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, V, Op.getOperand(i),
3190 DAG.getIntPtrConstant(i));
3197 /// getVShift - Return a vector logical shift node.
3199 static SDValue getVShift(bool isLeft, MVT VT, SDValue SrcOp,
3200 unsigned NumBits, SelectionDAG &DAG,
3201 const TargetLowering &TLI) {
3202 bool isMMX = VT.getSizeInBits() == 64;
3203 MVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3204 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3205 SrcOp = DAG.getNode(ISD::BIT_CONVERT, ShVT, SrcOp);
3206 return DAG.getNode(ISD::BIT_CONVERT, VT,
3207 DAG.getNode(Opc, ShVT, SrcOp,
3208 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3212 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3213 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3214 if (ISD::isBuildVectorAllZeros(Op.getNode())
3215 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3216 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3217 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3218 // eliminated on x86-32 hosts.
3219 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3222 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3223 return getOnesVector(Op.getValueType(), DAG);
3224 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG);
3227 MVT VT = Op.getValueType();
3228 MVT EVT = VT.getVectorElementType();
3229 unsigned EVTBits = EVT.getSizeInBits();
3231 unsigned NumElems = Op.getNumOperands();
3232 unsigned NumZero = 0;
3233 unsigned NumNonZero = 0;
3234 unsigned NonZeros = 0;
3235 bool IsAllConstants = true;
3236 SmallSet<SDValue, 8> Values;
3237 for (unsigned i = 0; i < NumElems; ++i) {
3238 SDValue Elt = Op.getOperand(i);
3239 if (Elt.getOpcode() == ISD::UNDEF)
3242 if (Elt.getOpcode() != ISD::Constant &&
3243 Elt.getOpcode() != ISD::ConstantFP)
3244 IsAllConstants = false;
3245 if (isZeroNode(Elt))
3248 NonZeros |= (1 << i);
3253 if (NumNonZero == 0) {
3254 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3255 return DAG.getNode(ISD::UNDEF, VT);
3258 // Special case for single non-zero, non-undef, element.
3259 if (NumNonZero == 1 && NumElems <= 4) {
3260 unsigned Idx = CountTrailingZeros_32(NonZeros);
3261 SDValue Item = Op.getOperand(Idx);
3263 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3264 // the value are obviously zero, truncate the value to i32 and do the
3265 // insertion that way. Only do this if the value is non-constant or if the
3266 // value is a constant being inserted into element 0. It is cheaper to do
3267 // a constant pool load than it is to do a movd + shuffle.
3268 if (EVT == MVT::i64 && !Subtarget->is64Bit() &&
3269 (!IsAllConstants || Idx == 0)) {
3270 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3271 // Handle MMX and SSE both.
3272 MVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3273 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3275 // Truncate the value (which may itself be a constant) to i32, and
3276 // convert it to a vector with movd (S2V+shuffle to zero extend).
3277 Item = DAG.getNode(ISD::TRUNCATE, MVT::i32, Item);
3278 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VecVT, Item);
3279 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3280 Subtarget->hasSSE2(), DAG);
3282 // Now we have our 32-bit value zero extended in the low element of
3283 // a vector. If Idx != 0, swizzle it into place.
3286 Item, DAG.getNode(ISD::UNDEF, Item.getValueType()),
3287 getSwapEltZeroMask(VecElts, Idx, DAG)
3289 Item = DAG.getNode(ISD::VECTOR_SHUFFLE, VecVT, Ops, 3);
3291 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(), Item);
3295 // If we have a constant or non-constant insertion into the low element of
3296 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3297 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3298 // depending on what the source datatype is. Because we can only get here
3299 // when NumElems <= 4, this only needs to handle i32/f32/i64/f64.
3301 // Don't do this for i64 values on x86-32.
3302 (EVT != MVT::i64 || Subtarget->is64Bit())) {
3303 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3304 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3305 return getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3306 Subtarget->hasSSE2(), DAG);
3309 // Is it a vector logical left shift?
3310 if (NumElems == 2 && Idx == 1 &&
3311 isZeroNode(Op.getOperand(0)) && !isZeroNode(Op.getOperand(1))) {
3312 unsigned NumBits = VT.getSizeInBits();
3313 return getVShift(true, VT,
3314 DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(1)),
3315 NumBits/2, DAG, *this);
3318 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3321 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3322 // is a non-constant being inserted into an element other than the low one,
3323 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3324 // movd/movss) to move this into the low element, then shuffle it into
3326 if (EVTBits == 32) {
3327 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Item);
3329 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3330 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3331 Subtarget->hasSSE2(), DAG);
3332 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3333 MVT MaskEVT = MaskVT.getVectorElementType();
3334 SmallVector<SDValue, 8> MaskVec;
3335 for (unsigned i = 0; i < NumElems; i++)
3336 MaskVec.push_back(DAG.getConstant((i == Idx) ? 0 : 1, MaskEVT));
3337 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3338 &MaskVec[0], MaskVec.size());
3339 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Item,
3340 DAG.getNode(ISD::UNDEF, VT), Mask);
3344 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3345 if (Values.size() == 1)
3348 // A vector full of immediates; various special cases are already
3349 // handled, so this is best done with a single constant-pool load.
3353 // Let legalizer expand 2-wide build_vectors.
3354 if (EVTBits == 64) {
3355 if (NumNonZero == 1) {
3356 // One half is zero or undef.
3357 unsigned Idx = CountTrailingZeros_32(NonZeros);
3358 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT,
3359 Op.getOperand(Idx));
3360 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3361 Subtarget->hasSSE2(), DAG);
3366 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3367 if (EVTBits == 8 && NumElems == 16) {
3368 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3370 if (V.getNode()) return V;
3373 if (EVTBits == 16 && NumElems == 8) {
3374 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3376 if (V.getNode()) return V;
3379 // If element VT is == 32 bits, turn it into a number of shuffles.
3380 SmallVector<SDValue, 8> V;
3382 if (NumElems == 4 && NumZero > 0) {
3383 for (unsigned i = 0; i < 4; ++i) {
3384 bool isZero = !(NonZeros & (1 << i));
3386 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG);
3388 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3391 for (unsigned i = 0; i < 2; ++i) {
3392 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3395 V[i] = V[i*2]; // Must be a zero vector.
3398 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2+1], V[i*2],
3399 getMOVLMask(NumElems, DAG));
3402 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3403 getMOVLMask(NumElems, DAG));
3406 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i*2], V[i*2+1],
3407 getUnpacklMask(NumElems, DAG));
3412 MVT MaskVT = MVT::getIntVectorWithNumElements(NumElems);
3413 MVT EVT = MaskVT.getVectorElementType();
3414 SmallVector<SDValue, 8> MaskVec;
3415 bool Reverse = (NonZeros & 0x3) == 2;
3416 for (unsigned i = 0; i < 2; ++i)
3418 MaskVec.push_back(DAG.getConstant(1-i, EVT));
3420 MaskVec.push_back(DAG.getConstant(i, EVT));
3421 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3422 for (unsigned i = 0; i < 2; ++i)
3424 MaskVec.push_back(DAG.getConstant(1-i+NumElems, EVT));
3426 MaskVec.push_back(DAG.getConstant(i+NumElems, EVT));
3427 SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3428 &MaskVec[0], MaskVec.size());
3429 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[0], V[1], ShufMask);
3432 if (Values.size() > 2) {
3433 // Expand into a number of unpckl*.
3435 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3436 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3437 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3438 SDValue UnpckMask = getUnpacklMask(NumElems, DAG);
3439 for (unsigned i = 0; i < NumElems; ++i)
3440 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Op.getOperand(i));
3442 while (NumElems != 0) {
3443 for (unsigned i = 0; i < NumElems; ++i)
3444 V[i] = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V[i], V[i + NumElems],
3455 SDValue LowerVECTOR_SHUFFLEv8i16(SDValue V1, SDValue V2,
3456 SDValue PermMask, SelectionDAG &DAG,
3457 TargetLowering &TLI) {
3459 MVT MaskVT = MVT::getIntVectorWithNumElements(8);
3460 MVT MaskEVT = MaskVT.getVectorElementType();
3461 MVT PtrVT = TLI.getPointerTy();
3462 SmallVector<SDValue, 8> MaskElts(PermMask.getNode()->op_begin(),
3463 PermMask.getNode()->op_end());
3465 // First record which half of which vector the low elements come from.
3466 SmallVector<unsigned, 4> LowQuad(4);
3467 for (unsigned i = 0; i < 4; ++i) {
3468 SDValue Elt = MaskElts[i];
3469 if (Elt.getOpcode() == ISD::UNDEF)
3471 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3472 int QuadIdx = EltIdx / 4;
3476 int BestLowQuad = -1;
3477 unsigned MaxQuad = 1;
3478 for (unsigned i = 0; i < 4; ++i) {
3479 if (LowQuad[i] > MaxQuad) {
3481 MaxQuad = LowQuad[i];
3485 // Record which half of which vector the high elements come from.
3486 SmallVector<unsigned, 4> HighQuad(4);
3487 for (unsigned i = 4; i < 8; ++i) {
3488 SDValue Elt = MaskElts[i];
3489 if (Elt.getOpcode() == ISD::UNDEF)
3491 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3492 int QuadIdx = EltIdx / 4;
3493 ++HighQuad[QuadIdx];
3496 int BestHighQuad = -1;
3498 for (unsigned i = 0; i < 4; ++i) {
3499 if (HighQuad[i] > MaxQuad) {
3501 MaxQuad = HighQuad[i];
3505 // If it's possible to sort parts of either half with PSHUF{H|L}W, then do it.
3506 if (BestLowQuad != -1 || BestHighQuad != -1) {
3507 // First sort the 4 chunks in order using shufpd.
3508 SmallVector<SDValue, 8> MaskVec;
3510 if (BestLowQuad != -1)
3511 MaskVec.push_back(DAG.getConstant(BestLowQuad, MVT::i32));
3513 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
3515 if (BestHighQuad != -1)
3516 MaskVec.push_back(DAG.getConstant(BestHighQuad, MVT::i32));
3518 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
3520 SDValue Mask= DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec[0],2);
3521 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2i64,
3522 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V1),
3523 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, V2), Mask);
3524 NewV = DAG.getNode(ISD::BIT_CONVERT, MVT::v8i16, NewV);
3526 // Now sort high and low parts separately.
3527 BitVector InOrder(8);
3528 if (BestLowQuad != -1) {
3529 // Sort lower half in order using PSHUFLW.
3531 bool AnyOutOrder = false;
3533 for (unsigned i = 0; i != 4; ++i) {
3534 SDValue Elt = MaskElts[i];
3535 if (Elt.getOpcode() == ISD::UNDEF) {
3536 MaskVec.push_back(Elt);
3539 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3543 MaskVec.push_back(DAG.getConstant(EltIdx % 4, MaskEVT));
3545 // If this element is in the right place after this shuffle, then
3547 if ((int)(EltIdx / 4) == BestLowQuad)
3552 for (unsigned i = 4; i != 8; ++i)
3553 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3554 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3555 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3559 if (BestHighQuad != -1) {
3560 // Sort high half in order using PSHUFHW if possible.
3563 for (unsigned i = 0; i != 4; ++i)
3564 MaskVec.push_back(DAG.getConstant(i, MaskEVT));
3566 bool AnyOutOrder = false;
3567 for (unsigned i = 4; i != 8; ++i) {
3568 SDValue Elt = MaskElts[i];
3569 if (Elt.getOpcode() == ISD::UNDEF) {
3570 MaskVec.push_back(Elt);
3573 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3577 MaskVec.push_back(DAG.getConstant((EltIdx % 4) + 4, MaskEVT));
3579 // If this element is in the right place after this shuffle, then
3581 if ((int)(EltIdx / 4) == BestHighQuad)
3587 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3588 NewV = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, NewV, NewV, Mask);
3592 // The other elements are put in the right place using pextrw and pinsrw.
3593 for (unsigned i = 0; i != 8; ++i) {
3596 SDValue Elt = MaskElts[i];
3597 if (Elt.getOpcode() == ISD::UNDEF)
3599 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3600 SDValue ExtOp = (EltIdx < 8)
3601 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3602 DAG.getConstant(EltIdx, PtrVT))
3603 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3604 DAG.getConstant(EltIdx - 8, PtrVT));
3605 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3606 DAG.getConstant(i, PtrVT));
3612 // PSHUF{H|L}W are not used. Lower into extracts and inserts but try to use as
3613 // few as possible. First, let's find out how many elements are already in the
3615 unsigned V1InOrder = 0;
3616 unsigned V1FromV1 = 0;
3617 unsigned V2InOrder = 0;
3618 unsigned V2FromV2 = 0;
3619 SmallVector<SDValue, 8> V1Elts;
3620 SmallVector<SDValue, 8> V2Elts;
3621 for (unsigned i = 0; i < 8; ++i) {
3622 SDValue Elt = MaskElts[i];
3623 if (Elt.getOpcode() == ISD::UNDEF) {
3624 V1Elts.push_back(Elt);
3625 V2Elts.push_back(Elt);
3630 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3632 V1Elts.push_back(Elt);
3633 V2Elts.push_back(DAG.getConstant(i+8, MaskEVT));
3635 } else if (EltIdx == i+8) {
3636 V1Elts.push_back(Elt);
3637 V2Elts.push_back(DAG.getConstant(i, MaskEVT));
3639 } else if (EltIdx < 8) {
3640 V1Elts.push_back(Elt);
3643 V2Elts.push_back(DAG.getConstant(EltIdx-8, MaskEVT));
3648 if (V2InOrder > V1InOrder) {
3649 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3651 std::swap(V1Elts, V2Elts);
3652 std::swap(V1FromV1, V2FromV2);
3655 if ((V1FromV1 + V1InOrder) != 8) {
3656 // Some elements are from V2.
3658 // If there are elements that are from V1 but out of place,
3659 // then first sort them in place
3660 SmallVector<SDValue, 8> MaskVec;
3661 for (unsigned i = 0; i < 8; ++i) {
3662 SDValue Elt = V1Elts[i];
3663 if (Elt.getOpcode() == ISD::UNDEF) {
3664 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3667 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3669 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3671 MaskVec.push_back(DAG.getConstant(EltIdx, MaskEVT));
3673 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &MaskVec[0], 8);
3674 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v8i16, V1, V1, Mask);
3678 for (unsigned i = 0; i < 8; ++i) {
3679 SDValue Elt = V1Elts[i];
3680 if (Elt.getOpcode() == ISD::UNDEF)
3682 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3685 SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V2,
3686 DAG.getConstant(EltIdx - 8, PtrVT));
3687 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3688 DAG.getConstant(i, PtrVT));
3692 // All elements are from V1.
3694 for (unsigned i = 0; i < 8; ++i) {
3695 SDValue Elt = V1Elts[i];
3696 if (Elt.getOpcode() == ISD::UNDEF)
3698 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3699 SDValue ExtOp = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i16, V1,
3700 DAG.getConstant(EltIdx, PtrVT));
3701 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, MVT::v8i16, NewV, ExtOp,
3702 DAG.getConstant(i, PtrVT));
3708 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3709 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3710 /// done when every pair / quad of shuffle mask elements point to elements in
3711 /// the right sequence. e.g.
3712 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3714 SDValue RewriteAsNarrowerShuffle(SDValue V1, SDValue V2,
3716 SDValue PermMask, SelectionDAG &DAG,
3717 TargetLowering &TLI) {
3718 unsigned NumElems = PermMask.getNumOperands();
3719 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3720 MVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3721 MVT MaskEltVT = MaskVT.getVectorElementType();
3723 switch (VT.getSimpleVT()) {
3724 default: assert(false && "Unexpected!");
3725 case MVT::v4f32: NewVT = MVT::v2f64; break;
3726 case MVT::v4i32: NewVT = MVT::v2i64; break;
3727 case MVT::v8i16: NewVT = MVT::v4i32; break;
3728 case MVT::v16i8: NewVT = MVT::v4i32; break;
3731 if (NewWidth == 2) {
3737 unsigned Scale = NumElems / NewWidth;
3738 SmallVector<SDValue, 8> MaskVec;
3739 for (unsigned i = 0; i < NumElems; i += Scale) {
3740 unsigned StartIdx = ~0U;
3741 for (unsigned j = 0; j < Scale; ++j) {
3742 SDValue Elt = PermMask.getOperand(i+j);
3743 if (Elt.getOpcode() == ISD::UNDEF)
3745 unsigned EltIdx = cast<ConstantSDNode>(Elt)->getZExtValue();
3746 if (StartIdx == ~0U)
3747 StartIdx = EltIdx - (EltIdx % Scale);
3748 if (EltIdx != StartIdx + j)
3751 if (StartIdx == ~0U)
3752 MaskVec.push_back(DAG.getNode(ISD::UNDEF, MaskEltVT));
3754 MaskVec.push_back(DAG.getConstant(StartIdx / Scale, MaskEltVT));
3757 V1 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V1);
3758 V2 = DAG.getNode(ISD::BIT_CONVERT, NewVT, V2);
3759 return DAG.getNode(ISD::VECTOR_SHUFFLE, NewVT, V1, V2,
3760 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3761 &MaskVec[0], MaskVec.size()));
3764 /// getVZextMovL - Return a zero-extending vector move low node.
3766 static SDValue getVZextMovL(MVT VT, MVT OpVT,
3767 SDValue SrcOp, SelectionDAG &DAG,
3768 const X86Subtarget *Subtarget) {
3769 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
3770 LoadSDNode *LD = NULL;
3771 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
3772 LD = dyn_cast<LoadSDNode>(SrcOp);
3774 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
3776 MVT EVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
3777 if ((EVT != MVT::i64 || Subtarget->is64Bit()) &&
3778 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
3779 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
3780 SrcOp.getOperand(0).getOperand(0).getValueType() == EVT) {
3782 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
3783 return DAG.getNode(ISD::BIT_CONVERT, VT,
3784 DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
3785 DAG.getNode(ISD::SCALAR_TO_VECTOR, OpVT,
3792 return DAG.getNode(ISD::BIT_CONVERT, VT,
3793 DAG.getNode(X86ISD::VZEXT_MOVL, OpVT,
3794 DAG.getNode(ISD::BIT_CONVERT, OpVT, SrcOp)));
3797 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
3800 LowerVECTOR_SHUFFLE_4wide(SDValue V1, SDValue V2,
3801 SDValue PermMask, MVT VT, SelectionDAG &DAG) {
3802 MVT MaskVT = PermMask.getValueType();
3803 MVT MaskEVT = MaskVT.getVectorElementType();
3804 SmallVector<std::pair<int, int>, 8> Locs;
3806 SmallVector<SDValue, 8> Mask1(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3809 for (unsigned i = 0; i != 4; ++i) {
3810 SDValue Elt = PermMask.getOperand(i);
3811 if (Elt.getOpcode() == ISD::UNDEF) {
3812 Locs[i] = std::make_pair(-1, -1);
3814 unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
3815 assert(Val < 8 && "Invalid VECTOR_SHUFFLE index!");
3817 Locs[i] = std::make_pair(0, NumLo);
3821 Locs[i] = std::make_pair(1, NumHi);
3823 Mask1[2+NumHi] = Elt;
3829 if (NumLo <= 2 && NumHi <= 2) {
3830 // If no more than two elements come from either vector. This can be
3831 // implemented with two shuffles. First shuffle gather the elements.
3832 // The second shuffle, which takes the first shuffle as both of its
3833 // vector operands, put the elements into the right order.
3834 V1 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3835 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3836 &Mask1[0], Mask1.size()));
3838 SmallVector<SDValue, 8> Mask2(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3839 for (unsigned i = 0; i != 4; ++i) {
3840 if (Locs[i].first == -1)
3843 unsigned Idx = (i < 2) ? 0 : 4;
3844 Idx += Locs[i].first * 2 + Locs[i].second;
3845 Mask2[i] = DAG.getConstant(Idx, MaskEVT);
3849 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V1,
3850 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3851 &Mask2[0], Mask2.size()));
3852 } else if (NumLo == 3 || NumHi == 3) {
3853 // Otherwise, we must have three elements from one vector, call it X, and
3854 // one element from the other, call it Y. First, use a shufps to build an
3855 // intermediate vector with the one element from Y and the element from X
3856 // that will be in the same half in the final destination (the indexes don't
3857 // matter). Then, use a shufps to build the final vector, taking the half
3858 // containing the element from Y from the intermediate, and the other half
3861 // Normalize it so the 3 elements come from V1.
3862 PermMask = CommuteVectorShuffleMask(PermMask, DAG);
3866 // Find the element from V2.
3868 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
3869 SDValue Elt = PermMask.getOperand(HiIndex);
3870 if (Elt.getOpcode() == ISD::UNDEF)
3872 unsigned Val = cast<ConstantSDNode>(Elt)->getZExtValue();
3877 Mask1[0] = PermMask.getOperand(HiIndex);
3878 Mask1[1] = DAG.getNode(ISD::UNDEF, MaskEVT);
3879 Mask1[2] = PermMask.getOperand(HiIndex^1);
3880 Mask1[3] = DAG.getNode(ISD::UNDEF, MaskEVT);
3881 V2 = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3882 DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3885 Mask1[0] = PermMask.getOperand(0);
3886 Mask1[1] = PermMask.getOperand(1);
3887 Mask1[2] = DAG.getConstant(HiIndex & 1 ? 6 : 4, MaskEVT);
3888 Mask1[3] = DAG.getConstant(HiIndex & 1 ? 4 : 6, MaskEVT);
3889 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3890 DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3892 Mask1[0] = DAG.getConstant(HiIndex & 1 ? 2 : 0, MaskEVT);
3893 Mask1[1] = DAG.getConstant(HiIndex & 1 ? 0 : 2, MaskEVT);
3894 Mask1[2] = PermMask.getOperand(2);
3895 Mask1[3] = PermMask.getOperand(3);
3896 if (Mask1[2].getOpcode() != ISD::UNDEF)
3898 DAG.getConstant(cast<ConstantSDNode>(Mask1[2])->getZExtValue()+4,
3900 if (Mask1[3].getOpcode() != ISD::UNDEF)
3902 DAG.getConstant(cast<ConstantSDNode>(Mask1[3])->getZExtValue()+4,
3904 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V2, V1,
3905 DAG.getNode(ISD::BUILD_VECTOR, MaskVT, &Mask1[0], 4));
3909 // Break it into (shuffle shuffle_hi, shuffle_lo).
3911 SmallVector<SDValue,8> LoMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3912 SmallVector<SDValue,8> HiMask(4, DAG.getNode(ISD::UNDEF, MaskEVT));
3913 SmallVector<SDValue,8> *MaskPtr = &LoMask;
3914 unsigned MaskIdx = 0;
3917 for (unsigned i = 0; i != 4; ++i) {
3924 SDValue Elt = PermMask.getOperand(i);
3925 if (Elt.getOpcode() == ISD::UNDEF) {
3926 Locs[i] = std::make_pair(-1, -1);
3927 } else if (cast<ConstantSDNode>(Elt)->getZExtValue() < 4) {
3928 Locs[i] = std::make_pair(MaskIdx, LoIdx);
3929 (*MaskPtr)[LoIdx] = Elt;
3932 Locs[i] = std::make_pair(MaskIdx, HiIdx);
3933 (*MaskPtr)[HiIdx] = Elt;
3938 SDValue LoShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3939 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3940 &LoMask[0], LoMask.size()));
3941 SDValue HiShuffle = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2,
3942 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3943 &HiMask[0], HiMask.size()));
3944 SmallVector<SDValue, 8> MaskOps;
3945 for (unsigned i = 0; i != 4; ++i) {
3946 if (Locs[i].first == -1) {
3947 MaskOps.push_back(DAG.getNode(ISD::UNDEF, MaskEVT));
3949 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
3950 MaskOps.push_back(DAG.getConstant(Idx, MaskEVT));
3953 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, LoShuffle, HiShuffle,
3954 DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
3955 &MaskOps[0], MaskOps.size()));
3959 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
3960 SDValue V1 = Op.getOperand(0);
3961 SDValue V2 = Op.getOperand(1);
3962 SDValue PermMask = Op.getOperand(2);
3963 MVT VT = Op.getValueType();
3964 unsigned NumElems = PermMask.getNumOperands();
3965 bool isMMX = VT.getSizeInBits() == 64;
3966 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
3967 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
3968 bool V1IsSplat = false;
3969 bool V2IsSplat = false;
3971 if (isUndefShuffle(Op.getNode()))
3972 return DAG.getNode(ISD::UNDEF, VT);
3974 if (isZeroShuffle(Op.getNode()))
3975 return getZeroVector(VT, Subtarget->hasSSE2(), DAG);
3977 if (isIdentityMask(PermMask.getNode()))
3979 else if (isIdentityMask(PermMask.getNode(), true))
3982 // Canonicalize movddup shuffles.
3983 if (V2IsUndef && Subtarget->hasSSE2() &&
3984 VT.getSizeInBits() == 128 &&
3985 X86::isMOVDDUPMask(PermMask.getNode()))
3986 return CanonicalizeMovddup(Op, V1, PermMask, DAG, Subtarget->hasSSE3());
3988 if (isSplatMask(PermMask.getNode())) {
3989 if (isMMX || NumElems < 4) return Op;
3990 // Promote it to a v4{if}32 splat.
3991 return PromoteSplat(Op, DAG, Subtarget->hasSSE2());
3994 // If the shuffle can be profitably rewritten as a narrower shuffle, then
3996 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
3997 SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask, DAG, *this);
3998 if (NewOp.getNode())
3999 return DAG.getNode(ISD::BIT_CONVERT, VT, LowerVECTOR_SHUFFLE(NewOp, DAG));
4000 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4001 // FIXME: Figure out a cleaner way to do this.
4002 // Try to make use of movq to zero out the top part.
4003 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4004 SDValue NewOp = RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
4006 if (NewOp.getNode()) {
4007 SDValue NewV1 = NewOp.getOperand(0);
4008 SDValue NewV2 = NewOp.getOperand(1);
4009 SDValue NewMask = NewOp.getOperand(2);
4010 if (isCommutedMOVL(NewMask.getNode(), true, false)) {
4011 NewOp = CommuteVectorShuffle(NewOp, NewV1, NewV2, NewMask, DAG);
4012 return getVZextMovL(VT, NewOp.getValueType(), NewV2, DAG, Subtarget);
4015 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4016 SDValue NewOp= RewriteAsNarrowerShuffle(V1, V2, VT, PermMask,
4018 if (NewOp.getNode() && X86::isMOVLMask(NewOp.getOperand(2).getNode()))
4019 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4024 // Check if this can be converted into a logical shift.
4025 bool isLeft = false;
4028 bool isShift = isVectorShift(Op, PermMask, DAG, isLeft, ShVal, ShAmt);
4029 if (isShift && ShVal.hasOneUse()) {
4030 // If the shifted value has multiple uses, it may be cheaper to use
4031 // v_set0 + movlhps or movhlps, etc.
4032 MVT EVT = VT.getVectorElementType();
4033 ShAmt *= EVT.getSizeInBits();
4034 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this);
4037 if (X86::isMOVLMask(PermMask.getNode())) {
4040 if (ISD::isBuildVectorAllZeros(V1.getNode()))
4041 return getVZextMovL(VT, VT, V2, DAG, Subtarget);
4046 if (!isMMX && (X86::isMOVSHDUPMask(PermMask.getNode()) ||
4047 X86::isMOVSLDUPMask(PermMask.getNode()) ||
4048 X86::isMOVHLPSMask(PermMask.getNode()) ||
4049 X86::isMOVHPMask(PermMask.getNode()) ||
4050 X86::isMOVLPMask(PermMask.getNode())))
4053 if (ShouldXformToMOVHLPS(PermMask.getNode()) ||
4054 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), PermMask.getNode()))
4055 return CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4058 // No better options. Use a vshl / vsrl.
4059 MVT EVT = VT.getVectorElementType();
4060 ShAmt *= EVT.getSizeInBits();
4061 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this);
4064 bool Commuted = false;
4065 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4066 // 1,1,1,1 -> v8i16 though.
4067 V1IsSplat = isSplatVector(V1.getNode());
4068 V2IsSplat = isSplatVector(V2.getNode());
4070 // Canonicalize the splat or undef, if present, to be on the RHS.
4071 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4072 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4073 std::swap(V1IsSplat, V2IsSplat);
4074 std::swap(V1IsUndef, V2IsUndef);
4078 // FIXME: Figure out a cleaner way to do this.
4079 if (isCommutedMOVL(PermMask.getNode(), V2IsSplat, V2IsUndef)) {
4080 if (V2IsUndef) return V1;
4081 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4083 // V2 is a splat, so the mask may be malformed. That is, it may point
4084 // to any V2 element. The instruction selectior won't like this. Get
4085 // a corrected mask and commute to form a proper MOVS{S|D}.
4086 SDValue NewMask = getMOVLMask(NumElems, DAG);
4087 if (NewMask.getNode() != PermMask.getNode())
4088 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
4093 if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
4094 X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
4095 X86::isUNPCKLMask(PermMask.getNode()) ||
4096 X86::isUNPCKHMask(PermMask.getNode()))
4100 // Normalize mask so all entries that point to V2 points to its first
4101 // element then try to match unpck{h|l} again. If match, return a
4102 // new vector_shuffle with the corrected mask.
4103 SDValue NewMask = NormalizeMask(PermMask, DAG);
4104 if (NewMask.getNode() != PermMask.getNode()) {
4105 if (X86::isUNPCKLMask(PermMask.getNode(), true)) {
4106 SDValue NewMask = getUnpacklMask(NumElems, DAG);
4107 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
4108 } else if (X86::isUNPCKHMask(PermMask.getNode(), true)) {
4109 SDValue NewMask = getUnpackhMask(NumElems, DAG);
4110 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1, V2, NewMask);
4115 // Normalize the node to match x86 shuffle ops if needed
4116 if (V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(PermMask.getNode()))
4117 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4120 // Commute is back and try unpck* again.
4121 Op = CommuteVectorShuffle(Op, V1, V2, PermMask, DAG);
4122 if (X86::isUNPCKL_v_undef_Mask(PermMask.getNode()) ||
4123 X86::isUNPCKH_v_undef_Mask(PermMask.getNode()) ||
4124 X86::isUNPCKLMask(PermMask.getNode()) ||
4125 X86::isUNPCKHMask(PermMask.getNode()))
4129 // Try PSHUF* first, then SHUFP*.
4130 // MMX doesn't have PSHUFD but it does have PSHUFW. While it's theoretically
4131 // possible to shuffle a v2i32 using PSHUFW, that's not yet implemented.
4132 if (isMMX && NumElems == 4 && X86::isPSHUFDMask(PermMask.getNode())) {
4133 if (V2.getOpcode() != ISD::UNDEF)
4134 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, V1,
4135 DAG.getNode(ISD::UNDEF, VT), PermMask);
4140 if (Subtarget->hasSSE2() &&
4141 (X86::isPSHUFDMask(PermMask.getNode()) ||
4142 X86::isPSHUFHWMask(PermMask.getNode()) ||
4143 X86::isPSHUFLWMask(PermMask.getNode()))) {
4145 if (VT == MVT::v4f32) {
4147 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT,
4148 DAG.getNode(ISD::BIT_CONVERT, RVT, V1),
4149 DAG.getNode(ISD::UNDEF, RVT), PermMask);
4150 } else if (V2.getOpcode() != ISD::UNDEF)
4151 Op = DAG.getNode(ISD::VECTOR_SHUFFLE, RVT, V1,
4152 DAG.getNode(ISD::UNDEF, RVT), PermMask);
4154 Op = DAG.getNode(ISD::BIT_CONVERT, VT, Op);
4158 // Binary or unary shufps.
4159 if (X86::isSHUFPMask(PermMask.getNode()) ||
4160 (V2.getOpcode() == ISD::UNDEF && X86::isPSHUFDMask(PermMask.getNode())))
4164 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4165 if (VT == MVT::v8i16) {
4166 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(V1, V2, PermMask, DAG, *this);
4167 if (NewOp.getNode())
4171 // Handle all 4 wide cases with a number of shuffles except for MMX.
4172 if (NumElems == 4 && !isMMX)
4173 return LowerVECTOR_SHUFFLE_4wide(V1, V2, PermMask, VT, DAG);
4179 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4180 SelectionDAG &DAG) {
4181 MVT VT = Op.getValueType();
4182 if (VT.getSizeInBits() == 8) {
4183 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, MVT::i32,
4184 Op.getOperand(0), Op.getOperand(1));
4185 SDValue Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
4186 DAG.getValueType(VT));
4187 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4188 } else if (VT.getSizeInBits() == 16) {
4189 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, MVT::i32,
4190 Op.getOperand(0), Op.getOperand(1));
4191 SDValue Assert = DAG.getNode(ISD::AssertZext, MVT::i32, Extract,
4192 DAG.getValueType(VT));
4193 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4194 } else if (VT == MVT::f32) {
4195 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4196 // the result back to FR32 register. It's only worth matching if the
4197 // result has a single use which is a store or a bitcast to i32.
4198 if (!Op.hasOneUse())
4200 SDNode *User = *Op.getNode()->use_begin();
4201 if (User->getOpcode() != ISD::STORE &&
4202 (User->getOpcode() != ISD::BIT_CONVERT ||
4203 User->getValueType(0) != MVT::i32))
4205 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
4206 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Op.getOperand(0)),
4208 return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, Extract);
4215 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4216 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4219 if (Subtarget->hasSSE41()) {
4220 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4225 MVT VT = Op.getValueType();
4226 // TODO: handle v16i8.
4227 if (VT.getSizeInBits() == 16) {
4228 SDValue Vec = Op.getOperand(0);
4229 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4231 return DAG.getNode(ISD::TRUNCATE, MVT::i16,
4232 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::i32,
4233 DAG.getNode(ISD::BIT_CONVERT, MVT::v4i32, Vec),
4235 // Transform it so it match pextrw which produces a 32-bit result.
4236 MVT EVT = (MVT::SimpleValueType)(VT.getSimpleVT()+1);
4237 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, EVT,
4238 Op.getOperand(0), Op.getOperand(1));
4239 SDValue Assert = DAG.getNode(ISD::AssertZext, EVT, Extract,
4240 DAG.getValueType(VT));
4241 return DAG.getNode(ISD::TRUNCATE, VT, Assert);
4242 } else if (VT.getSizeInBits() == 32) {
4243 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4246 // SHUFPS the element to the lowest double word, then movss.
4247 MVT MaskVT = MVT::getIntVectorWithNumElements(4);
4248 SmallVector<SDValue, 8> IdxVec;
4250 push_back(DAG.getConstant(Idx, MaskVT.getVectorElementType()));
4252 push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4254 push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4256 push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4257 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4258 &IdxVec[0], IdxVec.size());
4259 SDValue Vec = Op.getOperand(0);
4260 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
4261 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
4262 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
4263 DAG.getIntPtrConstant(0));
4264 } else if (VT.getSizeInBits() == 64) {
4265 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4266 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4267 // to match extract_elt for f64.
4268 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4272 // UNPCKHPD the element to the lowest double word, then movsd.
4273 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4274 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4275 MVT MaskVT = MVT::getIntVectorWithNumElements(2);
4276 SmallVector<SDValue, 8> IdxVec;
4277 IdxVec.push_back(DAG.getConstant(1, MaskVT.getVectorElementType()));
4279 push_back(DAG.getNode(ISD::UNDEF, MaskVT.getVectorElementType()));
4280 SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
4281 &IdxVec[0], IdxVec.size());
4282 SDValue Vec = Op.getOperand(0);
4283 Vec = DAG.getNode(ISD::VECTOR_SHUFFLE, Vec.getValueType(),
4284 Vec, DAG.getNode(ISD::UNDEF, Vec.getValueType()), Mask);
4285 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, VT, Vec,
4286 DAG.getIntPtrConstant(0));
4293 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4294 MVT VT = Op.getValueType();
4295 MVT EVT = VT.getVectorElementType();
4297 SDValue N0 = Op.getOperand(0);
4298 SDValue N1 = Op.getOperand(1);
4299 SDValue N2 = Op.getOperand(2);
4301 if ((EVT.getSizeInBits() == 8 || EVT.getSizeInBits() == 16) &&
4302 isa<ConstantSDNode>(N2)) {
4303 unsigned Opc = (EVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4305 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4307 if (N1.getValueType() != MVT::i32)
4308 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
4309 if (N2.getValueType() != MVT::i32)
4310 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4311 return DAG.getNode(Opc, VT, N0, N1, N2);
4312 } else if (EVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4313 // Bits [7:6] of the constant are the source select. This will always be
4314 // zero here. The DAG Combiner may combine an extract_elt index into these
4315 // bits. For example (insert (extract, 3), 2) could be matched by putting
4316 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4317 // Bits [5:4] of the constant are the destination select. This is the
4318 // value of the incoming immediate.
4319 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4320 // combine either bitwise AND or insert of float 0.0 to set these bits.
4321 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4322 return DAG.getNode(X86ISD::INSERTPS, VT, N0, N1, N2);
4328 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4329 MVT VT = Op.getValueType();
4330 MVT EVT = VT.getVectorElementType();
4332 if (Subtarget->hasSSE41())
4333 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4338 SDValue N0 = Op.getOperand(0);
4339 SDValue N1 = Op.getOperand(1);
4340 SDValue N2 = Op.getOperand(2);
4342 if (EVT.getSizeInBits() == 16) {
4343 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4344 // as its second argument.
4345 if (N1.getValueType() != MVT::i32)
4346 N1 = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, N1);
4347 if (N2.getValueType() != MVT::i32)
4348 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4349 return DAG.getNode(X86ISD::PINSRW, VT, N0, N1, N2);
4355 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4356 if (Op.getValueType() == MVT::v2f32)
4357 return DAG.getNode(ISD::BIT_CONVERT, MVT::v2f32,
4358 DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2i32,
4359 DAG.getNode(ISD::BIT_CONVERT, MVT::i32,
4360 Op.getOperand(0))));
4362 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, MVT::i32, Op.getOperand(0));
4363 MVT VT = MVT::v2i32;
4364 switch (Op.getValueType().getSimpleVT()) {
4371 return DAG.getNode(ISD::BIT_CONVERT, Op.getValueType(),
4372 DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, AnyExt));
4375 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4376 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4377 // one of the above mentioned nodes. It has to be wrapped because otherwise
4378 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4379 // be used to form addressing mode. These wrapped nodes will be selected
4382 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4383 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4384 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(),
4386 CP->getAlignment());
4387 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4388 // With PIC, the address is actually $g + Offset.
4389 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4390 !Subtarget->isPICStyleRIPRel()) {
4391 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4392 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4400 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV,
4402 SelectionDAG &DAG) const {
4403 bool IsPic = getTargetMachine().getRelocationModel() == Reloc::PIC_;
4404 bool ExtraLoadRequired =
4405 Subtarget->GVRequiresExtraLoad(GV, getTargetMachine(), false);
4407 // Create the TargetGlobalAddress node, folding in the constant
4408 // offset if it is legal.
4410 if (!IsPic && !ExtraLoadRequired && isInt32(Offset)) {
4411 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4414 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0);
4415 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4417 // With PIC, the address is actually $g + Offset.
4418 if (IsPic && !Subtarget->isPICStyleRIPRel()) {
4419 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4420 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4424 // For Darwin & Mingw32, external and weak symbols are indirect, so we want to
4425 // load the value at address GV, not the value of GV itself. This means that
4426 // the GlobalAddress must be in the base or index register of the address, not
4427 // the GV offset field. Platform check is inside GVRequiresExtraLoad() call
4428 // The same applies for external symbols during PIC codegen
4429 if (ExtraLoadRequired)
4430 Result = DAG.getLoad(getPointerTy(), DAG.getEntryNode(), Result,
4431 PseudoSourceValue::getGOT(), 0);
4433 // If there was a non-zero offset that we didn't fold, create an explicit
4436 Result = DAG.getNode(ISD::ADD, getPointerTy(), Result,
4437 DAG.getConstant(Offset, getPointerTy()));
4443 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4444 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4445 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4446 return LowerGlobalAddress(GV, Offset, DAG);
4449 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4451 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4454 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), X86::EBX,
4455 DAG.getNode(X86ISD::GlobalBaseReg,
4457 InFlag = Chain.getValue(1);
4459 // emit leal symbol@TLSGD(,%ebx,1), %eax
4460 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4461 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4462 GA->getValueType(0),
4464 SDValue Ops[] = { Chain, TGA, InFlag };
4465 SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 3);
4466 InFlag = Result.getValue(2);
4467 Chain = Result.getValue(1);
4469 // call ___tls_get_addr. This function receives its argument in
4470 // the register EAX.
4471 Chain = DAG.getCopyToReg(Chain, X86::EAX, Result, InFlag);
4472 InFlag = Chain.getValue(1);
4474 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4475 SDValue Ops1[] = { Chain,
4476 DAG.getTargetExternalSymbol("___tls_get_addr",
4478 DAG.getRegister(X86::EAX, PtrVT),
4479 DAG.getRegister(X86::EBX, PtrVT),
4481 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 5);
4482 InFlag = Chain.getValue(1);
4484 return DAG.getCopyFromReg(Chain, X86::EAX, PtrVT, InFlag);
4487 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4489 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4491 SDValue InFlag, Chain;
4493 // emit leaq symbol@TLSGD(%rip), %rdi
4494 SDVTList NodeTys = DAG.getVTList(PtrVT, MVT::Other, MVT::Flag);
4495 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4496 GA->getValueType(0),
4498 SDValue Ops[] = { DAG.getEntryNode(), TGA};
4499 SDValue Result = DAG.getNode(X86ISD::TLSADDR, NodeTys, Ops, 2);
4500 Chain = Result.getValue(1);
4501 InFlag = Result.getValue(2);
4503 // call __tls_get_addr. This function receives its argument in
4504 // the register RDI.
4505 Chain = DAG.getCopyToReg(Chain, X86::RDI, Result, InFlag);
4506 InFlag = Chain.getValue(1);
4508 NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4509 SDValue Ops1[] = { Chain,
4510 DAG.getTargetExternalSymbol("__tls_get_addr",
4512 DAG.getRegister(X86::RDI, PtrVT),
4514 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops1, 4);
4515 InFlag = Chain.getValue(1);
4517 return DAG.getCopyFromReg(Chain, X86::RAX, PtrVT, InFlag);
4520 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4521 // "local exec" model.
4522 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4524 // Get the Thread Pointer
4525 SDValue ThreadPointer = DAG.getNode(X86ISD::THREAD_POINTER, PtrVT);
4526 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4528 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4529 GA->getValueType(0),
4531 SDValue Offset = DAG.getNode(X86ISD::Wrapper, PtrVT, TGA);
4533 if (GA->getGlobal()->isDeclaration()) // initial exec TLS model
4534 Offset = DAG.getLoad(PtrVT, DAG.getEntryNode(), Offset,
4535 PseudoSourceValue::getGOT(), 0);
4537 // The address of the thread local variable is the add of the thread
4538 // pointer with the offset of the variable.
4539 return DAG.getNode(ISD::ADD, PtrVT, ThreadPointer, Offset);
4543 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4544 // TODO: implement the "local dynamic" model
4545 // TODO: implement the "initial exec"model for pic executables
4546 assert(Subtarget->isTargetELF() &&
4547 "TLS not implemented for non-ELF targets");
4548 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4549 // If the relocation model is PIC, use the "General Dynamic" TLS Model,
4550 // otherwise use the "Local Exec"TLS Model
4551 if (Subtarget->is64Bit()) {
4552 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4554 if (getTargetMachine().getRelocationModel() == Reloc::PIC_)
4555 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4557 return LowerToTLSExecModel(GA, DAG, getPointerTy());
4562 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4563 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4564 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy());
4565 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4566 // With PIC, the address is actually $g + Offset.
4567 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4568 !Subtarget->isPICStyleRIPRel()) {
4569 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4570 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4577 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4578 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4579 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy());
4580 Result = DAG.getNode(X86ISD::Wrapper, getPointerTy(), Result);
4581 // With PIC, the address is actually $g + Offset.
4582 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4583 !Subtarget->isPICStyleRIPRel()) {
4584 Result = DAG.getNode(ISD::ADD, getPointerTy(),
4585 DAG.getNode(X86ISD::GlobalBaseReg, getPointerTy()),
4592 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4593 /// take a 2 x i32 value to shift plus a shift amount.
4594 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4595 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4596 MVT VT = Op.getValueType();
4597 unsigned VTBits = VT.getSizeInBits();
4598 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4599 SDValue ShOpLo = Op.getOperand(0);
4600 SDValue ShOpHi = Op.getOperand(1);
4601 SDValue ShAmt = Op.getOperand(2);
4602 SDValue Tmp1 = isSRA ?
4603 DAG.getNode(ISD::SRA, VT, ShOpHi, DAG.getConstant(VTBits - 1, MVT::i8)) :
4604 DAG.getConstant(0, VT);
4607 if (Op.getOpcode() == ISD::SHL_PARTS) {
4608 Tmp2 = DAG.getNode(X86ISD::SHLD, VT, ShOpHi, ShOpLo, ShAmt);
4609 Tmp3 = DAG.getNode(ISD::SHL, VT, ShOpLo, ShAmt);
4611 Tmp2 = DAG.getNode(X86ISD::SHRD, VT, ShOpLo, ShOpHi, ShAmt);
4612 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, VT, ShOpHi, ShAmt);
4615 SDValue AndNode = DAG.getNode(ISD::AND, MVT::i8, ShAmt,
4616 DAG.getConstant(VTBits, MVT::i8));
4617 SDValue Cond = DAG.getNode(X86ISD::CMP, VT,
4618 AndNode, DAG.getConstant(0, MVT::i8));
4621 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4622 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4623 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4625 if (Op.getOpcode() == ISD::SHL_PARTS) {
4626 Hi = DAG.getNode(X86ISD::CMOV, VT, Ops0, 4);
4627 Lo = DAG.getNode(X86ISD::CMOV, VT, Ops1, 4);
4629 Lo = DAG.getNode(X86ISD::CMOV, VT, Ops0, 4);
4630 Hi = DAG.getNode(X86ISD::CMOV, VT, Ops1, 4);
4633 SDValue Ops[2] = { Lo, Hi };
4634 return DAG.getMergeValues(Ops, 2);
4637 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4638 MVT SrcVT = Op.getOperand(0).getValueType();
4639 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4640 "Unknown SINT_TO_FP to lower!");
4642 // These are really Legal; caller falls through into that case.
4643 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4645 if (SrcVT == MVT::i64 && Op.getValueType() != MVT::f80 &&
4646 Subtarget->is64Bit())
4649 unsigned Size = SrcVT.getSizeInBits()/8;
4650 MachineFunction &MF = DAG.getMachineFunction();
4651 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4652 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4653 SDValue Chain = DAG.getStore(DAG.getEntryNode(), Op.getOperand(0),
4655 PseudoSourceValue::getFixedStack(SSFI), 0);
4659 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4661 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4663 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4664 SmallVector<SDValue, 8> Ops;
4665 Ops.push_back(Chain);
4666 Ops.push_back(StackSlot);
4667 Ops.push_back(DAG.getValueType(SrcVT));
4668 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD,
4669 Tys, &Ops[0], Ops.size());
4672 Chain = Result.getValue(1);
4673 SDValue InFlag = Result.getValue(2);
4675 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
4676 // shouldn't be necessary except that RFP cannot be live across
4677 // multiple blocks. When stackifier is fixed, they can be uncoupled.
4678 MachineFunction &MF = DAG.getMachineFunction();
4679 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
4680 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4681 Tys = DAG.getVTList(MVT::Other);
4682 SmallVector<SDValue, 8> Ops;
4683 Ops.push_back(Chain);
4684 Ops.push_back(Result);
4685 Ops.push_back(StackSlot);
4686 Ops.push_back(DAG.getValueType(Op.getValueType()));
4687 Ops.push_back(InFlag);
4688 Chain = DAG.getNode(X86ISD::FST, Tys, &Ops[0], Ops.size());
4689 Result = DAG.getLoad(Op.getValueType(), Chain, StackSlot,
4690 PseudoSourceValue::getFixedStack(SSFI), 0);
4696 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4697 MVT SrcVT = Op.getOperand(0).getValueType();
4698 assert(SrcVT.getSimpleVT() == MVT::i64 && "Unknown UINT_TO_FP to lower!");
4700 // We only handle SSE2 f64 target here; caller can handle the rest.
4701 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
4704 // This algorithm is not obvious. Here it is in C code, more or less:
4706 double uint64_to_double( uint32_t hi, uint32_t lo )
4708 static const __m128i exp = { 0x4330000045300000ULL, 0 };
4709 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
4711 // copy ints to xmm registers
4712 __m128i xh = _mm_cvtsi32_si128( hi );
4713 __m128i xl = _mm_cvtsi32_si128( lo );
4715 // combine into low half of a single xmm register
4716 __m128i x = _mm_unpacklo_epi32( xh, xl );
4720 // merge in appropriate exponents to give the integer bits the
4722 x = _mm_unpacklo_epi32( x, exp );
4724 // subtract away the biases to deal with the IEEE-754 double precision
4726 d = _mm_sub_pd( (__m128d) x, bias );
4728 // All conversions up to here are exact. The correctly rounded result is
4729 // calculated using the
4730 // current rounding mode using the following horizontal add.
4731 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
4732 _mm_store_sd( &sd, d ); //since we are returning doubles in XMM, this
4733 // store doesn't really need to be here (except maybe to zero the other
4739 // Build some magic constants.
4740 std::vector<Constant*>CV0;
4741 CV0.push_back(ConstantInt::get(APInt(32, 0x45300000)));
4742 CV0.push_back(ConstantInt::get(APInt(32, 0x43300000)));
4743 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4744 CV0.push_back(ConstantInt::get(APInt(32, 0)));
4745 Constant *C0 = ConstantVector::get(CV0);
4746 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 4);
4748 std::vector<Constant*>CV1;
4749 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4530000000000000ULL))));
4750 CV1.push_back(ConstantFP::get(APFloat(APInt(64, 0x4330000000000000ULL))));
4751 Constant *C1 = ConstantVector::get(CV1);
4752 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 4);
4754 SmallVector<SDValue, 4> MaskVec;
4755 MaskVec.push_back(DAG.getConstant(0, MVT::i32));
4756 MaskVec.push_back(DAG.getConstant(4, MVT::i32));
4757 MaskVec.push_back(DAG.getConstant(1, MVT::i32));
4758 MaskVec.push_back(DAG.getConstant(5, MVT::i32));
4759 SDValue UnpcklMask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v4i32, &MaskVec[0],
4761 SmallVector<SDValue, 4> MaskVec2;
4762 MaskVec2.push_back(DAG.getConstant(1, MVT::i32));
4763 MaskVec2.push_back(DAG.getConstant(0, MVT::i32));
4764 SDValue ShufMask = DAG.getNode(ISD::BUILD_VECTOR, MVT::v2i32, &MaskVec2[0],
4767 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v4i32,
4768 DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
4770 DAG.getIntPtrConstant(1)));
4771 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v4i32,
4772 DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
4774 DAG.getIntPtrConstant(0)));
4775 SDValue Unpck1 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32,
4776 XR1, XR2, UnpcklMask);
4777 SDValue CLod0 = DAG.getLoad(MVT::v4i32, DAG.getEntryNode(), CPIdx0,
4778 PseudoSourceValue::getConstantPool(), 0, false, 16);
4779 SDValue Unpck2 = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v4i32,
4780 Unpck1, CLod0, UnpcklMask);
4781 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, MVT::v2f64, Unpck2);
4782 SDValue CLod1 = DAG.getLoad(MVT::v2f64, CLod0.getValue(1), CPIdx1,
4783 PseudoSourceValue::getConstantPool(), 0, false, 16);
4784 SDValue Sub = DAG.getNode(ISD::FSUB, MVT::v2f64, XR2F, CLod1);
4785 // Add the halves; easiest way is to swap them into another reg first.
4786 SDValue Shuf = DAG.getNode(ISD::VECTOR_SHUFFLE, MVT::v2f64,
4787 Sub, Sub, ShufMask);
4788 SDValue Add = DAG.getNode(ISD::FADD, MVT::v2f64, Shuf, Sub);
4789 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f64, Add,
4790 DAG.getIntPtrConstant(0));
4793 std::pair<SDValue,SDValue> X86TargetLowering::
4794 FP_TO_SINTHelper(SDValue Op, SelectionDAG &DAG) {
4795 assert(Op.getValueType().getSimpleVT() <= MVT::i64 &&
4796 Op.getValueType().getSimpleVT() >= MVT::i16 &&
4797 "Unknown FP_TO_SINT to lower!");
4799 // These are really Legal.
4800 if (Op.getValueType() == MVT::i32 &&
4801 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
4802 return std::make_pair(SDValue(), SDValue());
4803 if (Subtarget->is64Bit() &&
4804 Op.getValueType() == MVT::i64 &&
4805 Op.getOperand(0).getValueType() != MVT::f80)
4806 return std::make_pair(SDValue(), SDValue());
4808 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
4810 MachineFunction &MF = DAG.getMachineFunction();
4811 unsigned MemSize = Op.getValueType().getSizeInBits()/8;
4812 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4813 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4815 switch (Op.getValueType().getSimpleVT()) {
4816 default: assert(0 && "Invalid FP_TO_SINT to lower!");
4817 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
4818 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
4819 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
4822 SDValue Chain = DAG.getEntryNode();
4823 SDValue Value = Op.getOperand(0);
4824 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
4825 assert(Op.getValueType() == MVT::i64 && "Invalid FP_TO_SINT to lower!");
4826 Chain = DAG.getStore(Chain, Value, StackSlot,
4827 PseudoSourceValue::getFixedStack(SSFI), 0);
4828 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
4830 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
4832 Value = DAG.getNode(X86ISD::FLD, Tys, Ops, 3);
4833 Chain = Value.getValue(1);
4834 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
4835 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4838 // Build the FP_TO_INT*_IN_MEM
4839 SDValue Ops[] = { Chain, Value, StackSlot };
4840 SDValue FIST = DAG.getNode(Opc, MVT::Other, Ops, 3);
4842 return std::make_pair(FIST, StackSlot);
4845 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
4846 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(Op, DAG);
4847 SDValue FIST = Vals.first, StackSlot = Vals.second;
4848 if (FIST.getNode() == 0) return SDValue();
4851 return DAG.getLoad(Op.getValueType(), FIST, StackSlot, NULL, 0);
4854 SDNode *X86TargetLowering::ExpandFP_TO_SINT(SDNode *N, SelectionDAG &DAG) {
4855 std::pair<SDValue,SDValue> Vals = FP_TO_SINTHelper(SDValue(N, 0), DAG);
4856 SDValue FIST = Vals.first, StackSlot = Vals.second;
4857 if (FIST.getNode() == 0) return 0;
4859 MVT VT = N->getValueType(0);
4861 // Return a load from the stack slot.
4862 SDValue Res = DAG.getLoad(VT, FIST, StackSlot, NULL, 0);
4864 // Use MERGE_VALUES to drop the chain result value and get a node with one
4865 // result. This requires turning off getMergeValues simplification, since
4866 // otherwise it will give us Res back.
4867 return DAG.getMergeValues(&Res, 1, false).getNode();
4870 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
4871 MVT VT = Op.getValueType();
4874 EltVT = VT.getVectorElementType();
4875 std::vector<Constant*> CV;
4876 if (EltVT == MVT::f64) {
4877 Constant *C = ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63))));
4881 Constant *C = ConstantFP::get(APFloat(APInt(32, ~(1U << 31))));
4887 Constant *C = ConstantVector::get(CV);
4888 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4889 SDValue Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4890 PseudoSourceValue::getConstantPool(), 0,
4892 return DAG.getNode(X86ISD::FAND, VT, Op.getOperand(0), Mask);
4895 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
4896 MVT VT = Op.getValueType();
4898 unsigned EltNum = 1;
4899 if (VT.isVector()) {
4900 EltVT = VT.getVectorElementType();
4901 EltNum = VT.getVectorNumElements();
4903 std::vector<Constant*> CV;
4904 if (EltVT == MVT::f64) {
4905 Constant *C = ConstantFP::get(APFloat(APInt(64, 1ULL << 63)));
4909 Constant *C = ConstantFP::get(APFloat(APInt(32, 1U << 31)));
4915 Constant *C = ConstantVector::get(CV);
4916 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4917 SDValue Mask = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4918 PseudoSourceValue::getConstantPool(), 0,
4920 if (VT.isVector()) {
4921 return DAG.getNode(ISD::BIT_CONVERT, VT,
4922 DAG.getNode(ISD::XOR, MVT::v2i64,
4923 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Op.getOperand(0)),
4924 DAG.getNode(ISD::BIT_CONVERT, MVT::v2i64, Mask)));
4926 return DAG.getNode(X86ISD::FXOR, VT, Op.getOperand(0), Mask);
4930 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
4931 SDValue Op0 = Op.getOperand(0);
4932 SDValue Op1 = Op.getOperand(1);
4933 MVT VT = Op.getValueType();
4934 MVT SrcVT = Op1.getValueType();
4936 // If second operand is smaller, extend it first.
4937 if (SrcVT.bitsLT(VT)) {
4938 Op1 = DAG.getNode(ISD::FP_EXTEND, VT, Op1);
4941 // And if it is bigger, shrink it first.
4942 if (SrcVT.bitsGT(VT)) {
4943 Op1 = DAG.getNode(ISD::FP_ROUND, VT, Op1, DAG.getIntPtrConstant(1));
4947 // At this point the operands and the result should have the same
4948 // type, and that won't be f80 since that is not custom lowered.
4950 // First get the sign bit of second operand.
4951 std::vector<Constant*> CV;
4952 if (SrcVT == MVT::f64) {
4953 CV.push_back(ConstantFP::get(APFloat(APInt(64, 1ULL << 63))));
4954 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4956 CV.push_back(ConstantFP::get(APFloat(APInt(32, 1U << 31))));
4957 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4958 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4959 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4961 Constant *C = ConstantVector::get(CV);
4962 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4963 SDValue Mask1 = DAG.getLoad(SrcVT, DAG.getEntryNode(), CPIdx,
4964 PseudoSourceValue::getConstantPool(), 0,
4966 SDValue SignBit = DAG.getNode(X86ISD::FAND, SrcVT, Op1, Mask1);
4968 // Shift sign bit right or left if the two operands have different types.
4969 if (SrcVT.bitsGT(VT)) {
4970 // Op0 is MVT::f32, Op1 is MVT::f64.
4971 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, MVT::v2f64, SignBit);
4972 SignBit = DAG.getNode(X86ISD::FSRL, MVT::v2f64, SignBit,
4973 DAG.getConstant(32, MVT::i32));
4974 SignBit = DAG.getNode(ISD::BIT_CONVERT, MVT::v4f32, SignBit);
4975 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, MVT::f32, SignBit,
4976 DAG.getIntPtrConstant(0));
4979 // Clear first operand sign bit.
4981 if (VT == MVT::f64) {
4982 CV.push_back(ConstantFP::get(APFloat(APInt(64, ~(1ULL << 63)))));
4983 CV.push_back(ConstantFP::get(APFloat(APInt(64, 0))));
4985 CV.push_back(ConstantFP::get(APFloat(APInt(32, ~(1U << 31)))));
4986 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4987 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4988 CV.push_back(ConstantFP::get(APFloat(APInt(32, 0))));
4990 C = ConstantVector::get(CV);
4991 CPIdx = DAG.getConstantPool(C, getPointerTy(), 4);
4992 SDValue Mask2 = DAG.getLoad(VT, DAG.getEntryNode(), CPIdx,
4993 PseudoSourceValue::getConstantPool(), 0,
4995 SDValue Val = DAG.getNode(X86ISD::FAND, VT, Op0, Mask2);
4997 // Or the value with the sign bit.
4998 return DAG.getNode(X86ISD::FOR, VT, Val, SignBit);
5001 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5002 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5004 SDValue Op0 = Op.getOperand(0);
5005 SDValue Op1 = Op.getOperand(1);
5006 SDValue CC = Op.getOperand(2);
5007 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5010 if (translateX86CC(cast<CondCodeSDNode>(CC)->get(), isFP, X86CC,
5012 Cond = DAG.getNode(X86ISD::CMP, MVT::i32, Op0, Op1);
5013 return DAG.getNode(X86ISD::SETCC, MVT::i8,
5014 DAG.getConstant(X86CC, MVT::i8), Cond);
5017 assert(0 && "Illegal SetCC!");
5021 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5023 SDValue Op0 = Op.getOperand(0);
5024 SDValue Op1 = Op.getOperand(1);
5025 SDValue CC = Op.getOperand(2);
5026 MVT VT = Op.getValueType();
5027 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5028 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5032 MVT VT0 = Op0.getValueType();
5033 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5034 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5037 switch (SetCCOpcode) {
5040 case ISD::SETEQ: SSECC = 0; break;
5042 case ISD::SETGT: Swap = true; // Fallthrough
5044 case ISD::SETOLT: SSECC = 1; break;
5046 case ISD::SETGE: Swap = true; // Fallthrough
5048 case ISD::SETOLE: SSECC = 2; break;
5049 case ISD::SETUO: SSECC = 3; break;
5051 case ISD::SETNE: SSECC = 4; break;
5052 case ISD::SETULE: Swap = true;
5053 case ISD::SETUGE: SSECC = 5; break;
5054 case ISD::SETULT: Swap = true;
5055 case ISD::SETUGT: SSECC = 6; break;
5056 case ISD::SETO: SSECC = 7; break;
5059 std::swap(Op0, Op1);
5061 // In the two special cases we can't handle, emit two comparisons.
5063 if (SetCCOpcode == ISD::SETUEQ) {
5065 UNORD = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5066 EQ = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5067 return DAG.getNode(ISD::OR, VT, UNORD, EQ);
5069 else if (SetCCOpcode == ISD::SETONE) {
5071 ORD = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5072 NEQ = DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5073 return DAG.getNode(ISD::AND, VT, ORD, NEQ);
5075 assert(0 && "Illegal FP comparison");
5077 // Handle all other FP comparisons here.
5078 return DAG.getNode(Opc, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5081 // We are handling one of the integer comparisons here. Since SSE only has
5082 // GT and EQ comparisons for integer, swapping operands and multiple
5083 // operations may be required for some comparisons.
5084 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5085 bool Swap = false, Invert = false, FlipSigns = false;
5087 switch (VT.getSimpleVT()) {
5089 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5090 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5091 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5092 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5095 switch (SetCCOpcode) {
5097 case ISD::SETNE: Invert = true;
5098 case ISD::SETEQ: Opc = EQOpc; break;
5099 case ISD::SETLT: Swap = true;
5100 case ISD::SETGT: Opc = GTOpc; break;
5101 case ISD::SETGE: Swap = true;
5102 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
5103 case ISD::SETULT: Swap = true;
5104 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5105 case ISD::SETUGE: Swap = true;
5106 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5109 std::swap(Op0, Op1);
5111 // Since SSE has no unsigned integer comparisons, we need to flip the sign
5112 // bits of the inputs before performing those operations.
5114 MVT EltVT = VT.getVectorElementType();
5115 SDValue SignBit = DAG.getConstant(EltVT.getIntegerVTSignBit(), EltVT);
5116 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5117 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, VT, &SignBits[0],
5119 Op0 = DAG.getNode(ISD::XOR, VT, Op0, SignVec);
5120 Op1 = DAG.getNode(ISD::XOR, VT, Op1, SignVec);
5123 SDValue Result = DAG.getNode(Opc, VT, Op0, Op1);
5125 // If the logical-not of the result is required, perform that now.
5127 MVT EltVT = VT.getVectorElementType();
5128 SDValue NegOne = DAG.getConstant(EltVT.getIntegerVTBitMask(), EltVT);
5129 std::vector<SDValue> NegOnes(VT.getVectorNumElements(), NegOne);
5130 SDValue NegOneV = DAG.getNode(ISD::BUILD_VECTOR, VT, &NegOnes[0],
5132 Result = DAG.getNode(ISD::XOR, VT, Result, NegOneV);
5137 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5138 bool addTest = true;
5139 SDValue Cond = Op.getOperand(0);
5142 if (Cond.getOpcode() == ISD::SETCC)
5143 Cond = LowerSETCC(Cond, DAG);
5145 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5146 // setting operand in place of the X86ISD::SETCC.
5147 if (Cond.getOpcode() == X86ISD::SETCC) {
5148 CC = Cond.getOperand(0);
5150 SDValue Cmp = Cond.getOperand(1);
5151 unsigned Opc = Cmp.getOpcode();
5152 MVT VT = Op.getValueType();
5154 bool IllegalFPCMov = false;
5155 if (VT.isFloatingPoint() && !VT.isVector() &&
5156 !isScalarFPTypeInSSEReg(VT)) // FPStack?
5157 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
5159 if ((Opc == X86ISD::CMP ||
5160 Opc == X86ISD::COMI ||
5161 Opc == X86ISD::UCOMI) && !IllegalFPCMov) {
5168 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5169 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
5172 const MVT *VTs = DAG.getNodeValueTypes(Op.getValueType(),
5174 SmallVector<SDValue, 4> Ops;
5175 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
5176 // condition is true.
5177 Ops.push_back(Op.getOperand(2));
5178 Ops.push_back(Op.getOperand(1));
5180 Ops.push_back(Cond);
5181 return DAG.getNode(X86ISD::CMOV, VTs, 2, &Ops[0], Ops.size());
5184 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
5185 bool addTest = true;
5186 SDValue Chain = Op.getOperand(0);
5187 SDValue Cond = Op.getOperand(1);
5188 SDValue Dest = Op.getOperand(2);
5191 if (Cond.getOpcode() == ISD::SETCC)
5192 Cond = LowerSETCC(Cond, DAG);
5194 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5195 // setting operand in place of the X86ISD::SETCC.
5196 if (Cond.getOpcode() == X86ISD::SETCC) {
5197 CC = Cond.getOperand(0);
5199 SDValue Cmp = Cond.getOperand(1);
5200 unsigned Opc = Cmp.getOpcode();
5201 if (Opc == X86ISD::CMP ||
5202 Opc == X86ISD::COMI ||
5203 Opc == X86ISD::UCOMI) {
5207 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
5208 // two branches instead of an explicit OR instruction with a
5210 } else if (Cond.getOpcode() == ISD::OR &&
5212 Cond.getOperand(0).getOpcode() == X86ISD::SETCC &&
5213 Cond.getOperand(0).hasOneUse() &&
5214 Cond.getOperand(1).getOpcode() == X86ISD::SETCC &&
5215 Cond.getOperand(1).hasOneUse()) {
5216 SDValue Cmp = Cond.getOperand(0).getOperand(1);
5217 unsigned Opc = Cmp.getOpcode();
5218 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5219 (Opc == X86ISD::CMP ||
5220 Opc == X86ISD::COMI ||
5221 Opc == X86ISD::UCOMI)) {
5222 CC = Cond.getOperand(0).getOperand(0);
5223 Chain = DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
5224 Chain, Dest, CC, Cmp);
5225 CC = Cond.getOperand(1).getOperand(0);
5229 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
5230 // two branches instead of an explicit AND instruction with a
5231 // separate test. However, we only do this if this block doesn't
5232 // have a fall-through edge, because this requires an explicit
5233 // jmp when the condition is false.
5234 } else if (Cond.getOpcode() == ISD::AND &&
5236 Cond.getOperand(0).getOpcode() == X86ISD::SETCC &&
5237 Cond.getOperand(0).hasOneUse() &&
5238 Cond.getOperand(1).getOpcode() == X86ISD::SETCC &&
5239 Cond.getOperand(1).hasOneUse()) {
5240 SDValue Cmp = Cond.getOperand(0).getOperand(1);
5241 unsigned Opc = Cmp.getOpcode();
5242 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5243 (Opc == X86ISD::CMP ||
5244 Opc == X86ISD::COMI ||
5245 Opc == X86ISD::UCOMI) &&
5246 Op.getNode()->hasOneUse()) {
5247 X86::CondCode CCode =
5248 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5249 CCode = X86::GetOppositeBranchCondition(CCode);
5250 CC = DAG.getConstant(CCode, MVT::i8);
5251 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
5252 // Look for an unconditional branch following this conditional branch.
5253 // We need this because we need to reverse the successors in order
5254 // to implement FCMP_OEQ.
5255 if (User.getOpcode() == ISD::BR) {
5256 SDValue FalseBB = User.getOperand(1);
5258 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
5259 assert(NewBR == User);
5262 Chain = DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
5263 Chain, Dest, CC, Cmp);
5264 X86::CondCode CCode =
5265 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
5266 CCode = X86::GetOppositeBranchCondition(CCode);
5267 CC = DAG.getConstant(CCode, MVT::i8);
5275 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5276 Cond= DAG.getNode(X86ISD::CMP, MVT::i32, Cond, DAG.getConstant(0, MVT::i8));
5278 return DAG.getNode(X86ISD::BRCOND, Op.getValueType(),
5279 Chain, Dest, CC, Cond);
5283 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
5284 // Calls to _alloca is needed to probe the stack when allocating more than 4k
5285 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
5286 // that the guard pages used by the OS virtual memory manager are allocated in
5287 // correct sequence.
5289 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5290 SelectionDAG &DAG) {
5291 assert(Subtarget->isTargetCygMing() &&
5292 "This should be used only on Cygwin/Mingw targets");
5295 SDValue Chain = Op.getOperand(0);
5296 SDValue Size = Op.getOperand(1);
5297 // FIXME: Ensure alignment here
5301 MVT IntPtr = getPointerTy();
5302 MVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
5304 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
5306 Chain = DAG.getCopyToReg(Chain, X86::EAX, Size, Flag);
5307 Flag = Chain.getValue(1);
5309 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5310 SDValue Ops[] = { Chain,
5311 DAG.getTargetExternalSymbol("_alloca", IntPtr),
5312 DAG.getRegister(X86::EAX, IntPtr),
5313 DAG.getRegister(X86StackPtr, SPTy),
5315 Chain = DAG.getNode(X86ISD::CALL, NodeTys, Ops, 5);
5316 Flag = Chain.getValue(1);
5318 Chain = DAG.getCALLSEQ_END(Chain,
5319 DAG.getIntPtrConstant(0, true),
5320 DAG.getIntPtrConstant(0, true),
5323 Chain = DAG.getCopyFromReg(Chain, X86StackPtr, SPTy).getValue(1);
5325 SDValue Ops1[2] = { Chain.getValue(0), Chain };
5326 return DAG.getMergeValues(Ops1, 2);
5330 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG,
5332 SDValue Dst, SDValue Src,
5333 SDValue Size, unsigned Align,
5335 uint64_t DstSVOff) {
5336 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5338 // If not DWORD aligned or size is more than the threshold, call the library.
5339 // The libc version is likely to be faster for these cases. It can use the
5340 // address value and run time information about the CPU.
5341 if ((Align & 3) != 0 ||
5343 ConstantSize->getZExtValue() >
5344 getSubtarget()->getMaxInlineSizeThreshold()) {
5345 SDValue InFlag(0, 0);
5347 // Check to see if there is a specialized entry-point for memory zeroing.
5348 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
5350 if (const char *bzeroEntry = V &&
5351 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
5352 MVT IntPtr = getPointerTy();
5353 const Type *IntPtrTy = TD->getIntPtrType();
5354 TargetLowering::ArgListTy Args;
5355 TargetLowering::ArgListEntry Entry;
5357 Entry.Ty = IntPtrTy;
5358 Args.push_back(Entry);
5360 Args.push_back(Entry);
5361 std::pair<SDValue,SDValue> CallResult =
5362 LowerCallTo(Chain, Type::VoidTy, false, false, false, false,
5363 CallingConv::C, false,
5364 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG);
5365 return CallResult.second;
5368 // Otherwise have the target-independent code call memset.
5372 uint64_t SizeVal = ConstantSize->getZExtValue();
5373 SDValue InFlag(0, 0);
5376 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
5377 unsigned BytesLeft = 0;
5378 bool TwoRepStos = false;
5381 uint64_t Val = ValC->getZExtValue() & 255;
5383 // If the value is a constant, then we can potentially use larger sets.
5384 switch (Align & 3) {
5385 case 2: // WORD aligned
5388 Val = (Val << 8) | Val;
5390 case 0: // DWORD aligned
5393 Val = (Val << 8) | Val;
5394 Val = (Val << 16) | Val;
5395 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
5398 Val = (Val << 32) | Val;
5401 default: // Byte aligned
5404 Count = DAG.getIntPtrConstant(SizeVal);
5408 if (AVT.bitsGT(MVT::i8)) {
5409 unsigned UBytes = AVT.getSizeInBits() / 8;
5410 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
5411 BytesLeft = SizeVal % UBytes;
5414 Chain = DAG.getCopyToReg(Chain, ValReg, DAG.getConstant(Val, AVT),
5416 InFlag = Chain.getValue(1);
5419 Count = DAG.getIntPtrConstant(SizeVal);
5420 Chain = DAG.getCopyToReg(Chain, X86::AL, Src, InFlag);
5421 InFlag = Chain.getValue(1);
5424 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
5426 InFlag = Chain.getValue(1);
5427 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
5429 InFlag = Chain.getValue(1);
5431 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5432 SmallVector<SDValue, 8> Ops;
5433 Ops.push_back(Chain);
5434 Ops.push_back(DAG.getValueType(AVT));
5435 Ops.push_back(InFlag);
5436 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
5439 InFlag = Chain.getValue(1);
5441 MVT CVT = Count.getValueType();
5442 SDValue Left = DAG.getNode(ISD::AND, CVT, Count,
5443 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
5444 Chain = DAG.getCopyToReg(Chain, (CVT == MVT::i64) ? X86::RCX : X86::ECX,
5446 InFlag = Chain.getValue(1);
5447 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5449 Ops.push_back(Chain);
5450 Ops.push_back(DAG.getValueType(MVT::i8));
5451 Ops.push_back(InFlag);
5452 Chain = DAG.getNode(X86ISD::REP_STOS, Tys, &Ops[0], Ops.size());
5453 } else if (BytesLeft) {
5454 // Handle the last 1 - 7 bytes.
5455 unsigned Offset = SizeVal - BytesLeft;
5456 MVT AddrVT = Dst.getValueType();
5457 MVT SizeVT = Size.getValueType();
5459 Chain = DAG.getMemset(Chain,
5460 DAG.getNode(ISD::ADD, AddrVT, Dst,
5461 DAG.getConstant(Offset, AddrVT)),
5463 DAG.getConstant(BytesLeft, SizeVT),
5464 Align, DstSV, DstSVOff + Offset);
5467 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
5472 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG,
5473 SDValue Chain, SDValue Dst, SDValue Src,
5474 SDValue Size, unsigned Align,
5476 const Value *DstSV, uint64_t DstSVOff,
5477 const Value *SrcSV, uint64_t SrcSVOff) {
5478 // This requires the copy size to be a constant, preferrably
5479 // within a subtarget-specific limit.
5480 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
5483 uint64_t SizeVal = ConstantSize->getZExtValue();
5484 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
5487 /// If not DWORD aligned, call the library.
5488 if ((Align & 3) != 0)
5493 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
5496 unsigned UBytes = AVT.getSizeInBits() / 8;
5497 unsigned CountVal = SizeVal / UBytes;
5498 SDValue Count = DAG.getIntPtrConstant(CountVal);
5499 unsigned BytesLeft = SizeVal % UBytes;
5501 SDValue InFlag(0, 0);
5502 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RCX : X86::ECX,
5504 InFlag = Chain.getValue(1);
5505 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RDI : X86::EDI,
5507 InFlag = Chain.getValue(1);
5508 Chain = DAG.getCopyToReg(Chain, Subtarget->is64Bit() ? X86::RSI : X86::ESI,
5510 InFlag = Chain.getValue(1);
5512 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5513 SmallVector<SDValue, 8> Ops;
5514 Ops.push_back(Chain);
5515 Ops.push_back(DAG.getValueType(AVT));
5516 Ops.push_back(InFlag);
5517 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, Tys, &Ops[0], Ops.size());
5519 SmallVector<SDValue, 4> Results;
5520 Results.push_back(RepMovs);
5522 // Handle the last 1 - 7 bytes.
5523 unsigned Offset = SizeVal - BytesLeft;
5524 MVT DstVT = Dst.getValueType();
5525 MVT SrcVT = Src.getValueType();
5526 MVT SizeVT = Size.getValueType();
5527 Results.push_back(DAG.getMemcpy(Chain,
5528 DAG.getNode(ISD::ADD, DstVT, Dst,
5529 DAG.getConstant(Offset, DstVT)),
5530 DAG.getNode(ISD::ADD, SrcVT, Src,
5531 DAG.getConstant(Offset, SrcVT)),
5532 DAG.getConstant(BytesLeft, SizeVT),
5533 Align, AlwaysInline,
5534 DstSV, DstSVOff + Offset,
5535 SrcSV, SrcSVOff + Offset));
5538 return DAG.getNode(ISD::TokenFactor, MVT::Other, &Results[0], Results.size());
5541 /// Expand the result of: i64,outchain = READCYCLECOUNTER inchain
5542 SDNode *X86TargetLowering::ExpandREADCYCLECOUNTER(SDNode *N, SelectionDAG &DAG){
5543 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
5544 SDValue TheChain = N->getOperand(0);
5545 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, Tys, &TheChain, 1);
5546 if (Subtarget->is64Bit()) {
5547 SDValue rax = DAG.getCopyFromReg(rd, X86::RAX, MVT::i64, rd.getValue(1));
5548 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), X86::RDX,
5549 MVT::i64, rax.getValue(2));
5550 SDValue Tmp = DAG.getNode(ISD::SHL, MVT::i64, rdx,
5551 DAG.getConstant(32, MVT::i8));
5553 DAG.getNode(ISD::OR, MVT::i64, rax, Tmp), rdx.getValue(1)
5556 return DAG.getMergeValues(Ops, 2).getNode();
5559 SDValue eax = DAG.getCopyFromReg(rd, X86::EAX, MVT::i32, rd.getValue(1));
5560 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), X86::EDX,
5561 MVT::i32, eax.getValue(2));
5562 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
5563 SDValue Ops[] = { eax, edx };
5564 Ops[0] = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Ops, 2);
5566 // Use a MERGE_VALUES to return the value and chain.
5567 Ops[1] = edx.getValue(1);
5568 return DAG.getMergeValues(Ops, 2).getNode();
5571 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
5572 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
5574 if (!Subtarget->is64Bit()) {
5575 // vastart just stores the address of the VarArgsFrameIndex slot into the
5576 // memory location argument.
5577 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5578 return DAG.getStore(Op.getOperand(0), FR,Op.getOperand(1), SV, 0);
5582 // gp_offset (0 - 6 * 8)
5583 // fp_offset (48 - 48 + 8 * 16)
5584 // overflow_arg_area (point to parameters coming in memory).
5586 SmallVector<SDValue, 8> MemOps;
5587 SDValue FIN = Op.getOperand(1);
5589 SDValue Store = DAG.getStore(Op.getOperand(0),
5590 DAG.getConstant(VarArgsGPOffset, MVT::i32),
5592 MemOps.push_back(Store);
5595 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
5596 Store = DAG.getStore(Op.getOperand(0),
5597 DAG.getConstant(VarArgsFPOffset, MVT::i32),
5599 MemOps.push_back(Store);
5601 // Store ptr to overflow_arg_area
5602 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(4));
5603 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
5604 Store = DAG.getStore(Op.getOperand(0), OVFIN, FIN, SV, 0);
5605 MemOps.push_back(Store);
5607 // Store ptr to reg_save_area.
5608 FIN = DAG.getNode(ISD::ADD, getPointerTy(), FIN, DAG.getIntPtrConstant(8));
5609 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
5610 Store = DAG.getStore(Op.getOperand(0), RSFIN, FIN, SV, 0);
5611 MemOps.push_back(Store);
5612 return DAG.getNode(ISD::TokenFactor, MVT::Other, &MemOps[0], MemOps.size());
5615 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
5616 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5617 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
5618 SDValue Chain = Op.getOperand(0);
5619 SDValue SrcPtr = Op.getOperand(1);
5620 SDValue SrcSV = Op.getOperand(2);
5622 assert(0 && "VAArgInst is not yet implemented for x86-64!");
5627 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
5628 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
5629 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
5630 SDValue Chain = Op.getOperand(0);
5631 SDValue DstPtr = Op.getOperand(1);
5632 SDValue SrcPtr = Op.getOperand(2);
5633 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
5634 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5636 return DAG.getMemcpy(Chain, DstPtr, SrcPtr,
5637 DAG.getIntPtrConstant(24), 8, false,
5638 DstSV, 0, SrcSV, 0);
5642 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
5643 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5645 default: return SDValue(); // Don't custom lower most intrinsics.
5646 // Comparison intrinsics.
5647 case Intrinsic::x86_sse_comieq_ss:
5648 case Intrinsic::x86_sse_comilt_ss:
5649 case Intrinsic::x86_sse_comile_ss:
5650 case Intrinsic::x86_sse_comigt_ss:
5651 case Intrinsic::x86_sse_comige_ss:
5652 case Intrinsic::x86_sse_comineq_ss:
5653 case Intrinsic::x86_sse_ucomieq_ss:
5654 case Intrinsic::x86_sse_ucomilt_ss:
5655 case Intrinsic::x86_sse_ucomile_ss:
5656 case Intrinsic::x86_sse_ucomigt_ss:
5657 case Intrinsic::x86_sse_ucomige_ss:
5658 case Intrinsic::x86_sse_ucomineq_ss:
5659 case Intrinsic::x86_sse2_comieq_sd:
5660 case Intrinsic::x86_sse2_comilt_sd:
5661 case Intrinsic::x86_sse2_comile_sd:
5662 case Intrinsic::x86_sse2_comigt_sd:
5663 case Intrinsic::x86_sse2_comige_sd:
5664 case Intrinsic::x86_sse2_comineq_sd:
5665 case Intrinsic::x86_sse2_ucomieq_sd:
5666 case Intrinsic::x86_sse2_ucomilt_sd:
5667 case Intrinsic::x86_sse2_ucomile_sd:
5668 case Intrinsic::x86_sse2_ucomigt_sd:
5669 case Intrinsic::x86_sse2_ucomige_sd:
5670 case Intrinsic::x86_sse2_ucomineq_sd: {
5672 ISD::CondCode CC = ISD::SETCC_INVALID;
5675 case Intrinsic::x86_sse_comieq_ss:
5676 case Intrinsic::x86_sse2_comieq_sd:
5680 case Intrinsic::x86_sse_comilt_ss:
5681 case Intrinsic::x86_sse2_comilt_sd:
5685 case Intrinsic::x86_sse_comile_ss:
5686 case Intrinsic::x86_sse2_comile_sd:
5690 case Intrinsic::x86_sse_comigt_ss:
5691 case Intrinsic::x86_sse2_comigt_sd:
5695 case Intrinsic::x86_sse_comige_ss:
5696 case Intrinsic::x86_sse2_comige_sd:
5700 case Intrinsic::x86_sse_comineq_ss:
5701 case Intrinsic::x86_sse2_comineq_sd:
5705 case Intrinsic::x86_sse_ucomieq_ss:
5706 case Intrinsic::x86_sse2_ucomieq_sd:
5707 Opc = X86ISD::UCOMI;
5710 case Intrinsic::x86_sse_ucomilt_ss:
5711 case Intrinsic::x86_sse2_ucomilt_sd:
5712 Opc = X86ISD::UCOMI;
5715 case Intrinsic::x86_sse_ucomile_ss:
5716 case Intrinsic::x86_sse2_ucomile_sd:
5717 Opc = X86ISD::UCOMI;
5720 case Intrinsic::x86_sse_ucomigt_ss:
5721 case Intrinsic::x86_sse2_ucomigt_sd:
5722 Opc = X86ISD::UCOMI;
5725 case Intrinsic::x86_sse_ucomige_ss:
5726 case Intrinsic::x86_sse2_ucomige_sd:
5727 Opc = X86ISD::UCOMI;
5730 case Intrinsic::x86_sse_ucomineq_ss:
5731 case Intrinsic::x86_sse2_ucomineq_sd:
5732 Opc = X86ISD::UCOMI;
5738 SDValue LHS = Op.getOperand(1);
5739 SDValue RHS = Op.getOperand(2);
5740 translateX86CC(CC, true, X86CC, LHS, RHS, DAG);
5742 SDValue Cond = DAG.getNode(Opc, MVT::i32, LHS, RHS);
5743 SDValue SetCC = DAG.getNode(X86ISD::SETCC, MVT::i8,
5744 DAG.getConstant(X86CC, MVT::i8), Cond);
5745 return DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, SetCC);
5748 // Fix vector shift instructions where the last operand is a non-immediate
5750 case Intrinsic::x86_sse2_pslli_w:
5751 case Intrinsic::x86_sse2_pslli_d:
5752 case Intrinsic::x86_sse2_pslli_q:
5753 case Intrinsic::x86_sse2_psrli_w:
5754 case Intrinsic::x86_sse2_psrli_d:
5755 case Intrinsic::x86_sse2_psrli_q:
5756 case Intrinsic::x86_sse2_psrai_w:
5757 case Intrinsic::x86_sse2_psrai_d:
5758 case Intrinsic::x86_mmx_pslli_w:
5759 case Intrinsic::x86_mmx_pslli_d:
5760 case Intrinsic::x86_mmx_pslli_q:
5761 case Intrinsic::x86_mmx_psrli_w:
5762 case Intrinsic::x86_mmx_psrli_d:
5763 case Intrinsic::x86_mmx_psrli_q:
5764 case Intrinsic::x86_mmx_psrai_w:
5765 case Intrinsic::x86_mmx_psrai_d: {
5766 SDValue ShAmt = Op.getOperand(2);
5767 if (isa<ConstantSDNode>(ShAmt))
5770 unsigned NewIntNo = 0;
5771 MVT ShAmtVT = MVT::v4i32;
5773 case Intrinsic::x86_sse2_pslli_w:
5774 NewIntNo = Intrinsic::x86_sse2_psll_w;
5776 case Intrinsic::x86_sse2_pslli_d:
5777 NewIntNo = Intrinsic::x86_sse2_psll_d;
5779 case Intrinsic::x86_sse2_pslli_q:
5780 NewIntNo = Intrinsic::x86_sse2_psll_q;
5782 case Intrinsic::x86_sse2_psrli_w:
5783 NewIntNo = Intrinsic::x86_sse2_psrl_w;
5785 case Intrinsic::x86_sse2_psrli_d:
5786 NewIntNo = Intrinsic::x86_sse2_psrl_d;
5788 case Intrinsic::x86_sse2_psrli_q:
5789 NewIntNo = Intrinsic::x86_sse2_psrl_q;
5791 case Intrinsic::x86_sse2_psrai_w:
5792 NewIntNo = Intrinsic::x86_sse2_psra_w;
5794 case Intrinsic::x86_sse2_psrai_d:
5795 NewIntNo = Intrinsic::x86_sse2_psra_d;
5798 ShAmtVT = MVT::v2i32;
5800 case Intrinsic::x86_mmx_pslli_w:
5801 NewIntNo = Intrinsic::x86_mmx_psll_w;
5803 case Intrinsic::x86_mmx_pslli_d:
5804 NewIntNo = Intrinsic::x86_mmx_psll_d;
5806 case Intrinsic::x86_mmx_pslli_q:
5807 NewIntNo = Intrinsic::x86_mmx_psll_q;
5809 case Intrinsic::x86_mmx_psrli_w:
5810 NewIntNo = Intrinsic::x86_mmx_psrl_w;
5812 case Intrinsic::x86_mmx_psrli_d:
5813 NewIntNo = Intrinsic::x86_mmx_psrl_d;
5815 case Intrinsic::x86_mmx_psrli_q:
5816 NewIntNo = Intrinsic::x86_mmx_psrl_q;
5818 case Intrinsic::x86_mmx_psrai_w:
5819 NewIntNo = Intrinsic::x86_mmx_psra_w;
5821 case Intrinsic::x86_mmx_psrai_d:
5822 NewIntNo = Intrinsic::x86_mmx_psra_d;
5824 default: abort(); // Can't reach here.
5829 MVT VT = Op.getValueType();
5830 ShAmt = DAG.getNode(ISD::BIT_CONVERT, VT,
5831 DAG.getNode(ISD::SCALAR_TO_VECTOR, ShAmtVT, ShAmt));
5832 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VT,
5833 DAG.getConstant(NewIntNo, MVT::i32),
5834 Op.getOperand(1), ShAmt);
5839 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
5840 // Depths > 0 not supported yet!
5841 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() > 0)
5844 // Just load the return address
5845 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
5846 return DAG.getLoad(getPointerTy(), DAG.getEntryNode(), RetAddrFI, NULL, 0);
5849 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
5850 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5851 MFI->setFrameAddressIsTaken(true);
5852 MVT VT = Op.getValueType();
5853 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5854 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
5855 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), FrameReg, VT);
5857 FrameAddr = DAG.getLoad(VT, DAG.getEntryNode(), FrameAddr, NULL, 0);
5861 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
5862 SelectionDAG &DAG) {
5863 return DAG.getIntPtrConstant(2*TD->getPointerSize());
5866 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
5868 MachineFunction &MF = DAG.getMachineFunction();
5869 SDValue Chain = Op.getOperand(0);
5870 SDValue Offset = Op.getOperand(1);
5871 SDValue Handler = Op.getOperand(2);
5873 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
5875 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
5877 SDValue StoreAddr = DAG.getNode(ISD::SUB, getPointerTy(), Frame,
5878 DAG.getIntPtrConstant(-TD->getPointerSize()));
5879 StoreAddr = DAG.getNode(ISD::ADD, getPointerTy(), StoreAddr, Offset);
5880 Chain = DAG.getStore(Chain, Handler, StoreAddr, NULL, 0);
5881 Chain = DAG.getCopyToReg(Chain, StoreAddrReg, StoreAddr);
5882 MF.getRegInfo().addLiveOut(StoreAddrReg);
5884 return DAG.getNode(X86ISD::EH_RETURN,
5886 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
5889 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
5890 SelectionDAG &DAG) {
5891 SDValue Root = Op.getOperand(0);
5892 SDValue Trmp = Op.getOperand(1); // trampoline
5893 SDValue FPtr = Op.getOperand(2); // nested function
5894 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
5896 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
5898 const X86InstrInfo *TII =
5899 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
5901 if (Subtarget->is64Bit()) {
5902 SDValue OutChains[6];
5904 // Large code-model.
5906 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
5907 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
5909 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
5910 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
5912 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
5914 // Load the pointer to the nested function into R11.
5915 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
5916 SDValue Addr = Trmp;
5917 OutChains[0] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5920 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(2, MVT::i64));
5921 OutChains[1] = DAG.getStore(Root, FPtr, Addr, TrmpAddr, 2, false, 2);
5923 // Load the 'nest' parameter value into R10.
5924 // R10 is specified in X86CallingConv.td
5925 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
5926 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(10, MVT::i64));
5927 OutChains[2] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5930 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(12, MVT::i64));
5931 OutChains[3] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 12, false, 2);
5933 // Jump to the nested function.
5934 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
5935 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(20, MVT::i64));
5936 OutChains[4] = DAG.getStore(Root, DAG.getConstant(OpCode, MVT::i16), Addr,
5939 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
5940 Addr = DAG.getNode(ISD::ADD, MVT::i64, Trmp, DAG.getConstant(22, MVT::i64));
5941 OutChains[5] = DAG.getStore(Root, DAG.getConstant(ModRM, MVT::i8), Addr,
5945 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 6) };
5946 return DAG.getMergeValues(Ops, 2);
5948 const Function *Func =
5949 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
5950 unsigned CC = Func->getCallingConv();
5955 assert(0 && "Unsupported calling convention");
5956 case CallingConv::C:
5957 case CallingConv::X86_StdCall: {
5958 // Pass 'nest' parameter in ECX.
5959 // Must be kept in sync with X86CallingConv.td
5962 // Check that ECX wasn't needed by an 'inreg' parameter.
5963 const FunctionType *FTy = Func->getFunctionType();
5964 const AttrListPtr &Attrs = Func->getAttributes();
5966 if (!Attrs.isEmpty() && !Func->isVarArg()) {
5967 unsigned InRegCount = 0;
5970 for (FunctionType::param_iterator I = FTy->param_begin(),
5971 E = FTy->param_end(); I != E; ++I, ++Idx)
5972 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
5973 // FIXME: should only count parameters that are lowered to integers.
5974 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
5976 if (InRegCount > 2) {
5977 cerr << "Nest register in use - reduce number of inreg parameters!\n";
5983 case CallingConv::X86_FastCall:
5984 case CallingConv::Fast:
5985 // Pass 'nest' parameter in EAX.
5986 // Must be kept in sync with X86CallingConv.td
5991 SDValue OutChains[4];
5994 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(10, MVT::i32));
5995 Disp = DAG.getNode(ISD::SUB, MVT::i32, FPtr, Addr);
5997 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
5998 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
5999 OutChains[0] = DAG.getStore(Root, DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
6002 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(1, MVT::i32));
6003 OutChains[1] = DAG.getStore(Root, Nest, Addr, TrmpAddr, 1, false, 1);
6005 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
6006 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(5, MVT::i32));
6007 OutChains[2] = DAG.getStore(Root, DAG.getConstant(JMP, MVT::i8), Addr,
6008 TrmpAddr, 5, false, 1);
6010 Addr = DAG.getNode(ISD::ADD, MVT::i32, Trmp, DAG.getConstant(6, MVT::i32));
6011 OutChains[3] = DAG.getStore(Root, Disp, Addr, TrmpAddr, 6, false, 1);
6014 { Trmp, DAG.getNode(ISD::TokenFactor, MVT::Other, OutChains, 4) };
6015 return DAG.getMergeValues(Ops, 2);
6019 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
6021 The rounding mode is in bits 11:10 of FPSR, and has the following
6028 FLT_ROUNDS, on the other hand, expects the following:
6035 To perform the conversion, we do:
6036 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
6039 MachineFunction &MF = DAG.getMachineFunction();
6040 const TargetMachine &TM = MF.getTarget();
6041 const TargetFrameInfo &TFI = *TM.getFrameInfo();
6042 unsigned StackAlignment = TFI.getStackAlignment();
6043 MVT VT = Op.getValueType();
6045 // Save FP Control Word to stack slot
6046 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
6047 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6049 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, MVT::Other,
6050 DAG.getEntryNode(), StackSlot);
6052 // Load FP Control Word from stack slot
6053 SDValue CWD = DAG.getLoad(MVT::i16, Chain, StackSlot, NULL, 0);
6055 // Transform as necessary
6057 DAG.getNode(ISD::SRL, MVT::i16,
6058 DAG.getNode(ISD::AND, MVT::i16,
6059 CWD, DAG.getConstant(0x800, MVT::i16)),
6060 DAG.getConstant(11, MVT::i8));
6062 DAG.getNode(ISD::SRL, MVT::i16,
6063 DAG.getNode(ISD::AND, MVT::i16,
6064 CWD, DAG.getConstant(0x400, MVT::i16)),
6065 DAG.getConstant(9, MVT::i8));
6068 DAG.getNode(ISD::AND, MVT::i16,
6069 DAG.getNode(ISD::ADD, MVT::i16,
6070 DAG.getNode(ISD::OR, MVT::i16, CWD1, CWD2),
6071 DAG.getConstant(1, MVT::i16)),
6072 DAG.getConstant(3, MVT::i16));
6075 return DAG.getNode((VT.getSizeInBits() < 16 ?
6076 ISD::TRUNCATE : ISD::ZERO_EXTEND), VT, RetVal);
6079 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
6080 MVT VT = Op.getValueType();
6082 unsigned NumBits = VT.getSizeInBits();
6084 Op = Op.getOperand(0);
6085 if (VT == MVT::i8) {
6086 // Zero extend to i32 since there is not an i8 bsr.
6088 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
6091 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
6092 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6093 Op = DAG.getNode(X86ISD::BSR, VTs, Op);
6095 // If src is zero (i.e. bsr sets ZF), returns NumBits.
6096 SmallVector<SDValue, 4> Ops;
6098 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
6099 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6100 Ops.push_back(Op.getValue(1));
6101 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
6103 // Finally xor with NumBits-1.
6104 Op = DAG.getNode(ISD::XOR, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
6107 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
6111 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
6112 MVT VT = Op.getValueType();
6114 unsigned NumBits = VT.getSizeInBits();
6116 Op = Op.getOperand(0);
6117 if (VT == MVT::i8) {
6119 Op = DAG.getNode(ISD::ZERO_EXTEND, OpVT, Op);
6122 // Issue a bsf (scan bits forward) which also sets EFLAGS.
6123 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6124 Op = DAG.getNode(X86ISD::BSF, VTs, Op);
6126 // If src is zero (i.e. bsf sets ZF), returns NumBits.
6127 SmallVector<SDValue, 4> Ops;
6129 Ops.push_back(DAG.getConstant(NumBits, OpVT));
6130 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6131 Ops.push_back(Op.getValue(1));
6132 Op = DAG.getNode(X86ISD::CMOV, OpVT, &Ops[0], 4);
6135 Op = DAG.getNode(ISD::TRUNCATE, MVT::i8, Op);
6139 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
6140 MVT T = Op.getValueType();
6143 switch(T.getSimpleVT()) {
6145 assert(false && "Invalid value type!");
6146 case MVT::i8: Reg = X86::AL; size = 1; break;
6147 case MVT::i16: Reg = X86::AX; size = 2; break;
6148 case MVT::i32: Reg = X86::EAX; size = 4; break;
6150 if (Subtarget->is64Bit()) {
6151 Reg = X86::RAX; size = 8;
6152 } else //Should go away when LegalizeType stuff lands
6153 return SDValue(ExpandATOMIC_CMP_SWAP(Op.getNode(), DAG), 0);
6156 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), Reg,
6157 Op.getOperand(2), SDValue());
6158 SDValue Ops[] = { cpIn.getValue(0),
6161 DAG.getTargetConstant(size, MVT::i8),
6163 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6164 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, Tys, Ops, 5);
6166 DAG.getCopyFromReg(Result.getValue(0), Reg, T, Result.getValue(1));
6170 SDNode* X86TargetLowering::ExpandATOMIC_CMP_SWAP(SDNode* Op,
6171 SelectionDAG &DAG) {
6172 MVT T = Op->getValueType(0);
6173 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
6174 SDValue cpInL, cpInH;
6175 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
6176 DAG.getConstant(0, MVT::i32));
6177 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(2),
6178 DAG.getConstant(1, MVT::i32));
6179 cpInL = DAG.getCopyToReg(Op->getOperand(0), X86::EAX,
6181 cpInH = DAG.getCopyToReg(cpInL.getValue(0), X86::EDX,
6182 cpInH, cpInL.getValue(1));
6183 SDValue swapInL, swapInH;
6184 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
6185 DAG.getConstant(0, MVT::i32));
6186 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op->getOperand(3),
6187 DAG.getConstant(1, MVT::i32));
6188 swapInL = DAG.getCopyToReg(cpInH.getValue(0), X86::EBX,
6189 swapInL, cpInH.getValue(1));
6190 swapInH = DAG.getCopyToReg(swapInL.getValue(0), X86::ECX,
6191 swapInH, swapInL.getValue(1));
6192 SDValue Ops[] = { swapInH.getValue(0),
6194 swapInH.getValue(1) };
6195 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6196 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, Tys, Ops, 3);
6197 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), X86::EAX, MVT::i32,
6198 Result.getValue(1));
6199 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), X86::EDX, MVT::i32,
6200 cpOutL.getValue(2));
6201 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
6202 SDValue ResultVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2);
6203 SDValue Vals[2] = { ResultVal, cpOutH.getValue(1) };
6204 return DAG.getMergeValues(Vals, 2).getNode();
6207 SDValue X86TargetLowering::LowerATOMIC_BINARY_64(SDValue Op,
6210 SDNode *Node = Op.getNode();
6211 MVT T = Node->getValueType(0);
6212 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
6214 SDValue Chain = Node->getOperand(0);
6215 SDValue In1 = Node->getOperand(1);
6216 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
6217 Node->getOperand(2), DAG.getIntPtrConstant(0));
6218 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
6219 Node->getOperand(2), DAG.getIntPtrConstant(1));
6220 // This is a generalized SDNode, not an AtomicSDNode, so it doesn't
6221 // have a MemOperand. Pass the info through as a normal operand.
6222 SDValue LSI = DAG.getMemOperand(cast<MemSDNode>(Node)->getMemOperand());
6223 SDValue Ops[] = { Chain, In1, In2L, In2H, LSI };
6224 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
6225 SDValue Result = DAG.getNode(NewOp, Tys, Ops, 5);
6226 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
6227 SDValue ResultVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OpsF, 2);
6228 SDValue Vals[2] = { ResultVal, Result.getValue(2) };
6229 return SDValue(DAG.getMergeValues(Vals, 2).getNode(), 0);
6232 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
6233 SDNode *Node = Op.getNode();
6234 MVT T = Node->getValueType(0);
6235 SDValue negOp = DAG.getNode(ISD::SUB, T,
6236 DAG.getConstant(0, T), Node->getOperand(2));
6237 return DAG.getAtomic((Op.getOpcode()==ISD::ATOMIC_LOAD_SUB_8 ?
6238 ISD::ATOMIC_LOAD_ADD_8 :
6239 Op.getOpcode()==ISD::ATOMIC_LOAD_SUB_16 ?
6240 ISD::ATOMIC_LOAD_ADD_16 :
6241 Op.getOpcode()==ISD::ATOMIC_LOAD_SUB_32 ?
6242 ISD::ATOMIC_LOAD_ADD_32 :
6243 ISD::ATOMIC_LOAD_ADD_64),
6244 Node->getOperand(0),
6245 Node->getOperand(1), negOp,
6246 cast<AtomicSDNode>(Node)->getSrcValue(),
6247 cast<AtomicSDNode>(Node)->getAlignment());
6250 /// LowerOperation - Provide custom lowering hooks for some operations.
6252 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
6253 switch (Op.getOpcode()) {
6254 default: assert(0 && "Should not custom lower this!");
6255 case ISD::ATOMIC_CMP_SWAP_8:
6256 case ISD::ATOMIC_CMP_SWAP_16:
6257 case ISD::ATOMIC_CMP_SWAP_32:
6258 case ISD::ATOMIC_CMP_SWAP_64: return LowerCMP_SWAP(Op,DAG);
6259 case ISD::ATOMIC_LOAD_SUB_8:
6260 case ISD::ATOMIC_LOAD_SUB_16:
6261 case ISD::ATOMIC_LOAD_SUB_32: return LowerLOAD_SUB(Op,DAG);
6262 case ISD::ATOMIC_LOAD_SUB_64: return (Subtarget->is64Bit()) ?
6263 LowerLOAD_SUB(Op,DAG) :
6264 LowerATOMIC_BINARY_64(Op,DAG,
6265 X86ISD::ATOMSUB64_DAG);
6266 case ISD::ATOMIC_LOAD_AND_64: return LowerATOMIC_BINARY_64(Op,DAG,
6267 X86ISD::ATOMAND64_DAG);
6268 case ISD::ATOMIC_LOAD_OR_64: return LowerATOMIC_BINARY_64(Op, DAG,
6269 X86ISD::ATOMOR64_DAG);
6270 case ISD::ATOMIC_LOAD_XOR_64: return LowerATOMIC_BINARY_64(Op,DAG,
6271 X86ISD::ATOMXOR64_DAG);
6272 case ISD::ATOMIC_LOAD_NAND_64:return LowerATOMIC_BINARY_64(Op,DAG,
6273 X86ISD::ATOMNAND64_DAG);
6274 case ISD::ATOMIC_LOAD_ADD_64: return LowerATOMIC_BINARY_64(Op,DAG,
6275 X86ISD::ATOMADD64_DAG);
6276 case ISD::ATOMIC_SWAP_64: return LowerATOMIC_BINARY_64(Op,DAG,
6277 X86ISD::ATOMSWAP64_DAG);
6278 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
6279 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
6280 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
6281 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
6282 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
6283 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
6284 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
6285 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
6286 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
6287 case ISD::SHL_PARTS:
6288 case ISD::SRA_PARTS:
6289 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
6290 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
6291 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
6292 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
6293 case ISD::FABS: return LowerFABS(Op, DAG);
6294 case ISD::FNEG: return LowerFNEG(Op, DAG);
6295 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
6296 case ISD::SETCC: return LowerSETCC(Op, DAG);
6297 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
6298 case ISD::SELECT: return LowerSELECT(Op, DAG);
6299 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
6300 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
6301 case ISD::CALL: return LowerCALL(Op, DAG);
6302 case ISD::RET: return LowerRET(Op, DAG);
6303 case ISD::FORMAL_ARGUMENTS: return LowerFORMAL_ARGUMENTS(Op, DAG);
6304 case ISD::VASTART: return LowerVASTART(Op, DAG);
6305 case ISD::VAARG: return LowerVAARG(Op, DAG);
6306 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
6307 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
6308 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
6309 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
6310 case ISD::FRAME_TO_ARGS_OFFSET:
6311 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
6312 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
6313 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
6314 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
6315 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
6316 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
6317 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
6319 // FIXME: REMOVE THIS WHEN LegalizeDAGTypes lands.
6320 case ISD::READCYCLECOUNTER:
6321 return SDValue(ExpandREADCYCLECOUNTER(Op.getNode(), DAG), 0);
6325 /// ReplaceNodeResults - Replace a node with an illegal result type
6326 /// with a new node built out of custom code.
6327 SDNode *X86TargetLowering::ReplaceNodeResults(SDNode *N, SelectionDAG &DAG) {
6328 switch (N->getOpcode()) {
6330 return X86TargetLowering::LowerOperation(SDValue (N, 0), DAG).getNode();
6331 case ISD::FP_TO_SINT: return ExpandFP_TO_SINT(N, DAG);
6332 case ISD::READCYCLECOUNTER: return ExpandREADCYCLECOUNTER(N, DAG);
6333 case ISD::ATOMIC_CMP_SWAP_64: return ExpandATOMIC_CMP_SWAP(N, DAG);
6337 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
6339 default: return NULL;
6340 case X86ISD::BSF: return "X86ISD::BSF";
6341 case X86ISD::BSR: return "X86ISD::BSR";
6342 case X86ISD::SHLD: return "X86ISD::SHLD";
6343 case X86ISD::SHRD: return "X86ISD::SHRD";
6344 case X86ISD::FAND: return "X86ISD::FAND";
6345 case X86ISD::FOR: return "X86ISD::FOR";
6346 case X86ISD::FXOR: return "X86ISD::FXOR";
6347 case X86ISD::FSRL: return "X86ISD::FSRL";
6348 case X86ISD::FILD: return "X86ISD::FILD";
6349 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
6350 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
6351 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
6352 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
6353 case X86ISD::FLD: return "X86ISD::FLD";
6354 case X86ISD::FST: return "X86ISD::FST";
6355 case X86ISD::CALL: return "X86ISD::CALL";
6356 case X86ISD::TAILCALL: return "X86ISD::TAILCALL";
6357 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
6358 case X86ISD::CMP: return "X86ISD::CMP";
6359 case X86ISD::COMI: return "X86ISD::COMI";
6360 case X86ISD::UCOMI: return "X86ISD::UCOMI";
6361 case X86ISD::SETCC: return "X86ISD::SETCC";
6362 case X86ISD::CMOV: return "X86ISD::CMOV";
6363 case X86ISD::BRCOND: return "X86ISD::BRCOND";
6364 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
6365 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
6366 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
6367 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
6368 case X86ISD::Wrapper: return "X86ISD::Wrapper";
6369 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
6370 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
6371 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
6372 case X86ISD::PINSRB: return "X86ISD::PINSRB";
6373 case X86ISD::PINSRW: return "X86ISD::PINSRW";
6374 case X86ISD::FMAX: return "X86ISD::FMAX";
6375 case X86ISD::FMIN: return "X86ISD::FMIN";
6376 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
6377 case X86ISD::FRCP: return "X86ISD::FRCP";
6378 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
6379 case X86ISD::THREAD_POINTER: return "X86ISD::THREAD_POINTER";
6380 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
6381 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
6382 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
6383 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
6384 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
6385 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
6386 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
6387 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
6388 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
6389 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
6390 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
6391 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
6392 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
6393 case X86ISD::VSHL: return "X86ISD::VSHL";
6394 case X86ISD::VSRL: return "X86ISD::VSRL";
6395 case X86ISD::CMPPD: return "X86ISD::CMPPD";
6396 case X86ISD::CMPPS: return "X86ISD::CMPPS";
6397 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
6398 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
6399 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
6400 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
6401 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
6402 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
6403 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
6404 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
6408 // isLegalAddressingMode - Return true if the addressing mode represented
6409 // by AM is legal for this target, for a load/store of the specified type.
6410 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
6411 const Type *Ty) const {
6412 // X86 supports extremely general addressing modes.
6414 // X86 allows a sign-extended 32-bit immediate field as a displacement.
6415 if (AM.BaseOffs <= -(1LL << 32) || AM.BaseOffs >= (1LL << 32)-1)
6419 // We can only fold this if we don't need an extra load.
6420 if (Subtarget->GVRequiresExtraLoad(AM.BaseGV, getTargetMachine(), false))
6423 // X86-64 only supports addr of globals in small code model.
6424 if (Subtarget->is64Bit()) {
6425 if (getTargetMachine().getCodeModel() != CodeModel::Small)
6427 // If lower 4G is not available, then we must use rip-relative addressing.
6428 if (AM.BaseOffs || AM.Scale > 1)
6439 // These scales always work.
6444 // These scales are formed with basereg+scalereg. Only accept if there is
6449 default: // Other stuff never works.
6457 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
6458 if (!Ty1->isInteger() || !Ty2->isInteger())
6460 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6461 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6462 if (NumBits1 <= NumBits2)
6464 return Subtarget->is64Bit() || NumBits1 < 64;
6467 bool X86TargetLowering::isTruncateFree(MVT VT1, MVT VT2) const {
6468 if (!VT1.isInteger() || !VT2.isInteger())
6470 unsigned NumBits1 = VT1.getSizeInBits();
6471 unsigned NumBits2 = VT2.getSizeInBits();
6472 if (NumBits1 <= NumBits2)
6474 return Subtarget->is64Bit() || NumBits1 < 64;
6477 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6478 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6479 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6480 /// are assumed to be legal.
6482 X86TargetLowering::isShuffleMaskLegal(SDValue Mask, MVT VT) const {
6483 // Only do shuffles on 128-bit vector types for now.
6484 if (VT.getSizeInBits() == 64) return false;
6485 return (Mask.getNode()->getNumOperands() <= 4 ||
6486 isIdentityMask(Mask.getNode()) ||
6487 isIdentityMask(Mask.getNode(), true) ||
6488 isSplatMask(Mask.getNode()) ||
6489 isPSHUFHW_PSHUFLWMask(Mask.getNode()) ||
6490 X86::isUNPCKLMask(Mask.getNode()) ||
6491 X86::isUNPCKHMask(Mask.getNode()) ||
6492 X86::isUNPCKL_v_undef_Mask(Mask.getNode()) ||
6493 X86::isUNPCKH_v_undef_Mask(Mask.getNode()));
6497 X86TargetLowering::isVectorClearMaskLegal(const std::vector<SDValue> &BVOps,
6498 MVT EVT, SelectionDAG &DAG) const {
6499 unsigned NumElts = BVOps.size();
6500 // Only do shuffles on 128-bit vector types for now.
6501 if (EVT.getSizeInBits() * NumElts == 64) return false;
6502 if (NumElts == 2) return true;
6504 return (isMOVLMask(&BVOps[0], 4) ||
6505 isCommutedMOVL(&BVOps[0], 4, true) ||
6506 isSHUFPMask(&BVOps[0], 4) ||
6507 isCommutedSHUFP(&BVOps[0], 4));
6512 //===----------------------------------------------------------------------===//
6513 // X86 Scheduler Hooks
6514 //===----------------------------------------------------------------------===//
6516 // private utility function
6518 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
6519 MachineBasicBlock *MBB,
6527 TargetRegisterClass *RC,
6529 // For the atomic bitwise operator, we generate
6532 // ld t1 = [bitinstr.addr]
6533 // op t2 = t1, [bitinstr.val]
6535 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
6537 // fallthrough -->nextMBB
6538 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6539 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6540 MachineFunction::iterator MBBIter = MBB;
6543 /// First build the CFG
6544 MachineFunction *F = MBB->getParent();
6545 MachineBasicBlock *thisMBB = MBB;
6546 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6547 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6548 F->insert(MBBIter, newMBB);
6549 F->insert(MBBIter, nextMBB);
6551 // Move all successors to thisMBB to nextMBB
6552 nextMBB->transferSuccessors(thisMBB);
6554 // Update thisMBB to fall through to newMBB
6555 thisMBB->addSuccessor(newMBB);
6557 // newMBB jumps to itself and fall through to nextMBB
6558 newMBB->addSuccessor(nextMBB);
6559 newMBB->addSuccessor(newMBB);
6561 // Insert instructions into newMBB based on incoming instruction
6562 assert(bInstr->getNumOperands() < 8 && "unexpected number of operands");
6563 MachineOperand& destOper = bInstr->getOperand(0);
6564 MachineOperand* argOpers[6];
6565 int numArgs = bInstr->getNumOperands() - 1;
6566 for (int i=0; i < numArgs; ++i)
6567 argOpers[i] = &bInstr->getOperand(i+1);
6569 // x86 address has 4 operands: base, index, scale, and displacement
6570 int lastAddrIndx = 3; // [0,3]
6573 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
6574 MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(LoadOpc), t1);
6575 for (int i=0; i <= lastAddrIndx; ++i)
6576 (*MIB).addOperand(*argOpers[i]);
6578 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
6580 MIB = BuildMI(newMBB, TII->get(notOpc), tt).addReg(t1);
6585 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
6586 assert((argOpers[valArgIndx]->isReg() ||
6587 argOpers[valArgIndx]->isImm()) &&
6589 if (argOpers[valArgIndx]->isReg())
6590 MIB = BuildMI(newMBB, TII->get(regOpc), t2);
6592 MIB = BuildMI(newMBB, TII->get(immOpc), t2);
6594 (*MIB).addOperand(*argOpers[valArgIndx]);
6596 MIB = BuildMI(newMBB, TII->get(copyOpc), EAXreg);
6599 MIB = BuildMI(newMBB, TII->get(CXchgOpc));
6600 for (int i=0; i <= lastAddrIndx; ++i)
6601 (*MIB).addOperand(*argOpers[i]);
6603 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
6604 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
6606 MIB = BuildMI(newMBB, TII->get(copyOpc), destOper.getReg());
6610 BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
6612 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
6616 // private utility function: 64 bit atomics on 32 bit host.
6618 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
6619 MachineBasicBlock *MBB,
6625 // For the atomic bitwise operator, we generate
6626 // thisMBB (instructions are in pairs, except cmpxchg8b)
6627 // ld t1,t2 = [bitinstr.addr]
6629 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
6630 // op t5, t6 <- out1, out2, [bitinstr.val]
6631 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
6632 // mov ECX, EBX <- t5, t6
6633 // mov EAX, EDX <- t1, t2
6634 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
6635 // mov t3, t4 <- EAX, EDX
6637 // result in out1, out2
6638 // fallthrough -->nextMBB
6640 const TargetRegisterClass *RC = X86::GR32RegisterClass;
6641 const unsigned LoadOpc = X86::MOV32rm;
6642 const unsigned copyOpc = X86::MOV32rr;
6643 const unsigned NotOpc = X86::NOT32r;
6644 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6645 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6646 MachineFunction::iterator MBBIter = MBB;
6649 /// First build the CFG
6650 MachineFunction *F = MBB->getParent();
6651 MachineBasicBlock *thisMBB = MBB;
6652 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6653 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6654 F->insert(MBBIter, newMBB);
6655 F->insert(MBBIter, nextMBB);
6657 // Move all successors to thisMBB to nextMBB
6658 nextMBB->transferSuccessors(thisMBB);
6660 // Update thisMBB to fall through to newMBB
6661 thisMBB->addSuccessor(newMBB);
6663 // newMBB jumps to itself and fall through to nextMBB
6664 newMBB->addSuccessor(nextMBB);
6665 newMBB->addSuccessor(newMBB);
6667 // Insert instructions into newMBB based on incoming instruction
6668 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
6669 assert(bInstr->getNumOperands() < 18 && "unexpected number of operands");
6670 MachineOperand& dest1Oper = bInstr->getOperand(0);
6671 MachineOperand& dest2Oper = bInstr->getOperand(1);
6672 MachineOperand* argOpers[6];
6673 for (int i=0; i < 6; ++i)
6674 argOpers[i] = &bInstr->getOperand(i+2);
6676 // x86 address has 4 operands: base, index, scale, and displacement
6677 int lastAddrIndx = 3; // [0,3]
6679 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
6680 MachineInstrBuilder MIB = BuildMI(thisMBB, TII->get(LoadOpc), t1);
6681 for (int i=0; i <= lastAddrIndx; ++i)
6682 (*MIB).addOperand(*argOpers[i]);
6683 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
6684 MIB = BuildMI(thisMBB, TII->get(LoadOpc), t2);
6685 // add 4 to displacement.
6686 for (int i=0; i <= lastAddrIndx-1; ++i)
6687 (*MIB).addOperand(*argOpers[i]);
6688 MachineOperand newOp3 = *(argOpers[3]);
6690 newOp3.setImm(newOp3.getImm()+4);
6692 newOp3.setOffset(newOp3.getOffset()+4);
6693 (*MIB).addOperand(newOp3);
6695 // t3/4 are defined later, at the bottom of the loop
6696 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
6697 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
6698 BuildMI(newMBB, TII->get(X86::PHI), dest1Oper.getReg())
6699 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
6700 BuildMI(newMBB, TII->get(X86::PHI), dest2Oper.getReg())
6701 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
6703 unsigned tt1 = F->getRegInfo().createVirtualRegister(RC);
6704 unsigned tt2 = F->getRegInfo().createVirtualRegister(RC);
6706 MIB = BuildMI(newMBB, TII->get(NotOpc), tt1).addReg(t1);
6707 MIB = BuildMI(newMBB, TII->get(NotOpc), tt2).addReg(t2);
6713 assert((argOpers[4]->isReg() || argOpers[4]->isImm()) &&
6715 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
6716 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
6717 if (argOpers[4]->isReg())
6718 MIB = BuildMI(newMBB, TII->get(regOpcL), t5);
6720 MIB = BuildMI(newMBB, TII->get(immOpcL), t5);
6721 if (regOpcL != X86::MOV32rr)
6723 (*MIB).addOperand(*argOpers[4]);
6724 assert(argOpers[5]->isReg() == argOpers[4]->isReg());
6725 assert(argOpers[5]->isImm() == argOpers[4]->isImm());
6726 if (argOpers[5]->isReg())
6727 MIB = BuildMI(newMBB, TII->get(regOpcH), t6);
6729 MIB = BuildMI(newMBB, TII->get(immOpcH), t6);
6730 if (regOpcH != X86::MOV32rr)
6732 (*MIB).addOperand(*argOpers[5]);
6734 MIB = BuildMI(newMBB, TII->get(copyOpc), X86::EAX);
6736 MIB = BuildMI(newMBB, TII->get(copyOpc), X86::EDX);
6739 MIB = BuildMI(newMBB, TII->get(copyOpc), X86::EBX);
6741 MIB = BuildMI(newMBB, TII->get(copyOpc), X86::ECX);
6744 MIB = BuildMI(newMBB, TII->get(X86::LCMPXCHG8B));
6745 for (int i=0; i <= lastAddrIndx; ++i)
6746 (*MIB).addOperand(*argOpers[i]);
6748 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
6749 (*MIB).addMemOperand(*F, *bInstr->memoperands_begin());
6751 MIB = BuildMI(newMBB, TII->get(copyOpc), t3);
6752 MIB.addReg(X86::EAX);
6753 MIB = BuildMI(newMBB, TII->get(copyOpc), t4);
6754 MIB.addReg(X86::EDX);
6757 BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
6759 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
6763 // private utility function
6765 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
6766 MachineBasicBlock *MBB,
6768 // For the atomic min/max operator, we generate
6771 // ld t1 = [min/max.addr]
6772 // mov t2 = [min/max.val]
6774 // cmov[cond] t2 = t1
6776 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
6778 // fallthrough -->nextMBB
6780 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6781 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
6782 MachineFunction::iterator MBBIter = MBB;
6785 /// First build the CFG
6786 MachineFunction *F = MBB->getParent();
6787 MachineBasicBlock *thisMBB = MBB;
6788 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
6789 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
6790 F->insert(MBBIter, newMBB);
6791 F->insert(MBBIter, nextMBB);
6793 // Move all successors to thisMBB to nextMBB
6794 nextMBB->transferSuccessors(thisMBB);
6796 // Update thisMBB to fall through to newMBB
6797 thisMBB->addSuccessor(newMBB);
6799 // newMBB jumps to newMBB and fall through to nextMBB
6800 newMBB->addSuccessor(nextMBB);
6801 newMBB->addSuccessor(newMBB);
6803 // Insert instructions into newMBB based on incoming instruction
6804 assert(mInstr->getNumOperands() < 8 && "unexpected number of operands");
6805 MachineOperand& destOper = mInstr->getOperand(0);
6806 MachineOperand* argOpers[6];
6807 int numArgs = mInstr->getNumOperands() - 1;
6808 for (int i=0; i < numArgs; ++i)
6809 argOpers[i] = &mInstr->getOperand(i+1);
6811 // x86 address has 4 operands: base, index, scale, and displacement
6812 int lastAddrIndx = 3; // [0,3]
6815 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6816 MachineInstrBuilder MIB = BuildMI(newMBB, TII->get(X86::MOV32rm), t1);
6817 for (int i=0; i <= lastAddrIndx; ++i)
6818 (*MIB).addOperand(*argOpers[i]);
6820 // We only support register and immediate values
6821 assert((argOpers[valArgIndx]->isReg() ||
6822 argOpers[valArgIndx]->isImm()) &&
6825 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6826 if (argOpers[valArgIndx]->isReg())
6827 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
6829 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), t2);
6830 (*MIB).addOperand(*argOpers[valArgIndx]);
6832 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), X86::EAX);
6835 MIB = BuildMI(newMBB, TII->get(X86::CMP32rr));
6840 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
6841 MIB = BuildMI(newMBB, TII->get(cmovOpc),t3);
6845 // Cmp and exchange if none has modified the memory location
6846 MIB = BuildMI(newMBB, TII->get(X86::LCMPXCHG32));
6847 for (int i=0; i <= lastAddrIndx; ++i)
6848 (*MIB).addOperand(*argOpers[i]);
6850 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
6851 (*MIB).addMemOperand(*F, *mInstr->memoperands_begin());
6853 MIB = BuildMI(newMBB, TII->get(X86::MOV32rr), destOper.getReg());
6854 MIB.addReg(X86::EAX);
6857 BuildMI(newMBB, TII->get(X86::JNE)).addMBB(newMBB);
6859 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
6865 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
6866 MachineBasicBlock *BB) {
6867 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
6868 switch (MI->getOpcode()) {
6869 default: assert(false && "Unexpected instr type to insert");
6870 case X86::CMOV_FR32:
6871 case X86::CMOV_FR64:
6872 case X86::CMOV_V4F32:
6873 case X86::CMOV_V2F64:
6874 case X86::CMOV_V2I64: {
6875 // To "insert" a SELECT_CC instruction, we actually have to insert the
6876 // diamond control-flow pattern. The incoming instruction knows the
6877 // destination vreg to set, the condition code register to branch on, the
6878 // true/false values to select between, and a branch opcode to use.
6879 const BasicBlock *LLVM_BB = BB->getBasicBlock();
6880 MachineFunction::iterator It = BB;
6886 // cmpTY ccX, r1, r2
6888 // fallthrough --> copy0MBB
6889 MachineBasicBlock *thisMBB = BB;
6890 MachineFunction *F = BB->getParent();
6891 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
6892 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
6894 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
6895 BuildMI(BB, TII->get(Opc)).addMBB(sinkMBB);
6896 F->insert(It, copy0MBB);
6897 F->insert(It, sinkMBB);
6898 // Update machine-CFG edges by transferring all successors of the current
6899 // block to the new block which will contain the Phi node for the select.
6900 sinkMBB->transferSuccessors(BB);
6902 // Add the true and fallthrough blocks as its successors.
6903 BB->addSuccessor(copy0MBB);
6904 BB->addSuccessor(sinkMBB);
6907 // %FalseValue = ...
6908 // # fallthrough to sinkMBB
6911 // Update machine-CFG edges
6912 BB->addSuccessor(sinkMBB);
6915 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
6918 BuildMI(BB, TII->get(X86::PHI), MI->getOperand(0).getReg())
6919 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
6920 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
6922 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
6926 case X86::FP32_TO_INT16_IN_MEM:
6927 case X86::FP32_TO_INT32_IN_MEM:
6928 case X86::FP32_TO_INT64_IN_MEM:
6929 case X86::FP64_TO_INT16_IN_MEM:
6930 case X86::FP64_TO_INT32_IN_MEM:
6931 case X86::FP64_TO_INT64_IN_MEM:
6932 case X86::FP80_TO_INT16_IN_MEM:
6933 case X86::FP80_TO_INT32_IN_MEM:
6934 case X86::FP80_TO_INT64_IN_MEM: {
6935 // Change the floating point control register to use "round towards zero"
6936 // mode when truncating to an integer value.
6937 MachineFunction *F = BB->getParent();
6938 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
6939 addFrameReference(BuildMI(BB, TII->get(X86::FNSTCW16m)), CWFrameIdx);
6941 // Load the old value of the high byte of the control word...
6943 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
6944 addFrameReference(BuildMI(BB, TII->get(X86::MOV16rm), OldCW), CWFrameIdx);
6946 // Set the high part to be round to zero...
6947 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mi)), CWFrameIdx)
6950 // Reload the modified control word now...
6951 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
6953 // Restore the memory image of control word to original value
6954 addFrameReference(BuildMI(BB, TII->get(X86::MOV16mr)), CWFrameIdx)
6957 // Get the X86 opcode to use.
6959 switch (MI->getOpcode()) {
6960 default: assert(0 && "illegal opcode!");
6961 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
6962 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
6963 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
6964 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
6965 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
6966 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
6967 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
6968 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
6969 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
6973 MachineOperand &Op = MI->getOperand(0);
6975 AM.BaseType = X86AddressMode::RegBase;
6976 AM.Base.Reg = Op.getReg();
6978 AM.BaseType = X86AddressMode::FrameIndexBase;
6979 AM.Base.FrameIndex = Op.getIndex();
6981 Op = MI->getOperand(1);
6983 AM.Scale = Op.getImm();
6984 Op = MI->getOperand(2);
6986 AM.IndexReg = Op.getImm();
6987 Op = MI->getOperand(3);
6988 if (Op.isGlobal()) {
6989 AM.GV = Op.getGlobal();
6991 AM.Disp = Op.getImm();
6993 addFullAddress(BuildMI(BB, TII->get(Opc)), AM)
6994 .addReg(MI->getOperand(4).getReg());
6996 // Reload the original control word now.
6997 addFrameReference(BuildMI(BB, TII->get(X86::FLDCW16m)), CWFrameIdx);
6999 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7002 case X86::ATOMAND32:
7003 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7004 X86::AND32ri, X86::MOV32rm,
7005 X86::LCMPXCHG32, X86::MOV32rr,
7006 X86::NOT32r, X86::EAX,
7007 X86::GR32RegisterClass);
7009 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
7010 X86::OR32ri, X86::MOV32rm,
7011 X86::LCMPXCHG32, X86::MOV32rr,
7012 X86::NOT32r, X86::EAX,
7013 X86::GR32RegisterClass);
7014 case X86::ATOMXOR32:
7015 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
7016 X86::XOR32ri, X86::MOV32rm,
7017 X86::LCMPXCHG32, X86::MOV32rr,
7018 X86::NOT32r, X86::EAX,
7019 X86::GR32RegisterClass);
7020 case X86::ATOMNAND32:
7021 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
7022 X86::AND32ri, X86::MOV32rm,
7023 X86::LCMPXCHG32, X86::MOV32rr,
7024 X86::NOT32r, X86::EAX,
7025 X86::GR32RegisterClass, true);
7026 case X86::ATOMMIN32:
7027 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
7028 case X86::ATOMMAX32:
7029 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
7030 case X86::ATOMUMIN32:
7031 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
7032 case X86::ATOMUMAX32:
7033 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
7035 case X86::ATOMAND16:
7036 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7037 X86::AND16ri, X86::MOV16rm,
7038 X86::LCMPXCHG16, X86::MOV16rr,
7039 X86::NOT16r, X86::AX,
7040 X86::GR16RegisterClass);
7042 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
7043 X86::OR16ri, X86::MOV16rm,
7044 X86::LCMPXCHG16, X86::MOV16rr,
7045 X86::NOT16r, X86::AX,
7046 X86::GR16RegisterClass);
7047 case X86::ATOMXOR16:
7048 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
7049 X86::XOR16ri, X86::MOV16rm,
7050 X86::LCMPXCHG16, X86::MOV16rr,
7051 X86::NOT16r, X86::AX,
7052 X86::GR16RegisterClass);
7053 case X86::ATOMNAND16:
7054 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
7055 X86::AND16ri, X86::MOV16rm,
7056 X86::LCMPXCHG16, X86::MOV16rr,
7057 X86::NOT16r, X86::AX,
7058 X86::GR16RegisterClass, true);
7059 case X86::ATOMMIN16:
7060 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
7061 case X86::ATOMMAX16:
7062 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
7063 case X86::ATOMUMIN16:
7064 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
7065 case X86::ATOMUMAX16:
7066 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
7069 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7070 X86::AND8ri, X86::MOV8rm,
7071 X86::LCMPXCHG8, X86::MOV8rr,
7072 X86::NOT8r, X86::AL,
7073 X86::GR8RegisterClass);
7075 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
7076 X86::OR8ri, X86::MOV8rm,
7077 X86::LCMPXCHG8, X86::MOV8rr,
7078 X86::NOT8r, X86::AL,
7079 X86::GR8RegisterClass);
7081 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
7082 X86::XOR8ri, X86::MOV8rm,
7083 X86::LCMPXCHG8, X86::MOV8rr,
7084 X86::NOT8r, X86::AL,
7085 X86::GR8RegisterClass);
7086 case X86::ATOMNAND8:
7087 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
7088 X86::AND8ri, X86::MOV8rm,
7089 X86::LCMPXCHG8, X86::MOV8rr,
7090 X86::NOT8r, X86::AL,
7091 X86::GR8RegisterClass, true);
7092 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
7093 // This group is for 64-bit host.
7094 case X86::ATOMAND64:
7095 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7096 X86::AND64ri32, X86::MOV64rm,
7097 X86::LCMPXCHG64, X86::MOV64rr,
7098 X86::NOT64r, X86::RAX,
7099 X86::GR64RegisterClass);
7101 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
7102 X86::OR64ri32, X86::MOV64rm,
7103 X86::LCMPXCHG64, X86::MOV64rr,
7104 X86::NOT64r, X86::RAX,
7105 X86::GR64RegisterClass);
7106 case X86::ATOMXOR64:
7107 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
7108 X86::XOR64ri32, X86::MOV64rm,
7109 X86::LCMPXCHG64, X86::MOV64rr,
7110 X86::NOT64r, X86::RAX,
7111 X86::GR64RegisterClass);
7112 case X86::ATOMNAND64:
7113 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
7114 X86::AND64ri32, X86::MOV64rm,
7115 X86::LCMPXCHG64, X86::MOV64rr,
7116 X86::NOT64r, X86::RAX,
7117 X86::GR64RegisterClass, true);
7118 case X86::ATOMMIN64:
7119 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
7120 case X86::ATOMMAX64:
7121 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
7122 case X86::ATOMUMIN64:
7123 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
7124 case X86::ATOMUMAX64:
7125 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
7127 // This group does 64-bit operations on a 32-bit host.
7128 case X86::ATOMAND6432:
7129 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7130 X86::AND32rr, X86::AND32rr,
7131 X86::AND32ri, X86::AND32ri,
7133 case X86::ATOMOR6432:
7134 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7135 X86::OR32rr, X86::OR32rr,
7136 X86::OR32ri, X86::OR32ri,
7138 case X86::ATOMXOR6432:
7139 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7140 X86::XOR32rr, X86::XOR32rr,
7141 X86::XOR32ri, X86::XOR32ri,
7143 case X86::ATOMNAND6432:
7144 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7145 X86::AND32rr, X86::AND32rr,
7146 X86::AND32ri, X86::AND32ri,
7148 case X86::ATOMADD6432:
7149 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7150 X86::ADD32rr, X86::ADC32rr,
7151 X86::ADD32ri, X86::ADC32ri,
7153 case X86::ATOMSUB6432:
7154 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7155 X86::SUB32rr, X86::SBB32rr,
7156 X86::SUB32ri, X86::SBB32ri,
7158 case X86::ATOMSWAP6432:
7159 return EmitAtomicBit6432WithCustomInserter(MI, BB,
7160 X86::MOV32rr, X86::MOV32rr,
7161 X86::MOV32ri, X86::MOV32ri,
7166 //===----------------------------------------------------------------------===//
7167 // X86 Optimization Hooks
7168 //===----------------------------------------------------------------------===//
7170 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
7174 const SelectionDAG &DAG,
7175 unsigned Depth) const {
7176 unsigned Opc = Op.getOpcode();
7177 assert((Opc >= ISD::BUILTIN_OP_END ||
7178 Opc == ISD::INTRINSIC_WO_CHAIN ||
7179 Opc == ISD::INTRINSIC_W_CHAIN ||
7180 Opc == ISD::INTRINSIC_VOID) &&
7181 "Should use MaskedValueIsZero if you don't know whether Op"
7182 " is a target node!");
7184 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
7188 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
7189 Mask.getBitWidth() - 1);
7194 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
7195 /// node is a GlobalAddress + offset.
7196 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
7197 GlobalValue* &GA, int64_t &Offset) const{
7198 if (N->getOpcode() == X86ISD::Wrapper) {
7199 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
7200 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
7201 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
7205 return TargetLowering::isGAPlusOffset(N, GA, Offset);
7208 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
7209 const TargetLowering &TLI) {
7212 if (TLI.isGAPlusOffset(Base, GV, Offset))
7213 return (GV->getAlignment() >= N && (Offset % N) == 0);
7214 // DAG combine handles the stack object case.
7218 static bool EltsFromConsecutiveLoads(SDNode *N, SDValue PermMask,
7219 unsigned NumElems, MVT EVT,
7221 SelectionDAG &DAG, MachineFrameInfo *MFI,
7222 const TargetLowering &TLI) {
7224 for (unsigned i = 0; i < NumElems; ++i) {
7225 SDValue Idx = PermMask.getOperand(i);
7226 if (Idx.getOpcode() == ISD::UNDEF) {
7232 SDValue Elt = DAG.getShuffleScalarElt(N, i);
7233 if (!Elt.getNode() ||
7234 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
7237 Base = Elt.getNode();
7238 if (Base->getOpcode() == ISD::UNDEF)
7242 if (Elt.getOpcode() == ISD::UNDEF)
7245 if (!TLI.isConsecutiveLoad(Elt.getNode(), Base,
7246 EVT.getSizeInBits()/8, i, MFI))
7252 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
7253 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
7254 /// if the load addresses are consecutive, non-overlapping, and in the right
7256 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
7257 const TargetLowering &TLI) {
7258 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7259 MVT VT = N->getValueType(0);
7260 MVT EVT = VT.getVectorElementType();
7261 SDValue PermMask = N->getOperand(2);
7262 unsigned NumElems = PermMask.getNumOperands();
7263 SDNode *Base = NULL;
7264 if (!EltsFromConsecutiveLoads(N, PermMask, NumElems, EVT, Base,
7268 LoadSDNode *LD = cast<LoadSDNode>(Base);
7269 if (isBaseAlignmentOfN(16, Base->getOperand(1).getNode(), TLI))
7270 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
7271 LD->getSrcValueOffset(), LD->isVolatile());
7272 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(), LD->getSrcValue(),
7273 LD->getSrcValueOffset(), LD->isVolatile(),
7274 LD->getAlignment());
7277 /// PerformBuildVectorCombine - build_vector 0,(load i64 / f64) -> movq / movsd.
7278 static SDValue PerformBuildVectorCombine(SDNode *N, SelectionDAG &DAG,
7279 const X86Subtarget *Subtarget,
7280 const TargetLowering &TLI) {
7281 unsigned NumOps = N->getNumOperands();
7283 // Ignore single operand BUILD_VECTOR.
7287 MVT VT = N->getValueType(0);
7288 MVT EVT = VT.getVectorElementType();
7289 if ((EVT != MVT::i64 && EVT != MVT::f64) || Subtarget->is64Bit())
7290 // We are looking for load i64 and zero extend. We want to transform
7291 // it before legalizer has a chance to expand it. Also look for i64
7292 // BUILD_PAIR bit casted to f64.
7294 // This must be an insertion into a zero vector.
7295 SDValue HighElt = N->getOperand(1);
7296 if (!isZeroNode(HighElt))
7299 // Value must be a load.
7300 SDNode *Base = N->getOperand(0).getNode();
7301 if (!isa<LoadSDNode>(Base)) {
7302 if (Base->getOpcode() != ISD::BIT_CONVERT)
7304 Base = Base->getOperand(0).getNode();
7305 if (!isa<LoadSDNode>(Base))
7309 // Transform it into VZEXT_LOAD addr.
7310 LoadSDNode *LD = cast<LoadSDNode>(Base);
7312 // Load must not be an extload.
7313 if (LD->getExtensionType() != ISD::NON_EXTLOAD)
7316 SDVTList Tys = DAG.getVTList(VT, MVT::Other);
7317 SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
7318 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, Tys, Ops, 2);
7319 DAG.ReplaceAllUsesOfValueWith(SDValue(Base, 1), ResNode.getValue(1));
7323 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
7324 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
7325 const X86Subtarget *Subtarget) {
7326 SDValue Cond = N->getOperand(0);
7328 // If we have SSE[12] support, try to form min/max nodes.
7329 if (Subtarget->hasSSE2() &&
7330 (N->getValueType(0) == MVT::f32 || N->getValueType(0) == MVT::f64)) {
7331 if (Cond.getOpcode() == ISD::SETCC) {
7332 // Get the LHS/RHS of the select.
7333 SDValue LHS = N->getOperand(1);
7334 SDValue RHS = N->getOperand(2);
7335 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
7337 unsigned Opcode = 0;
7338 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
7341 case ISD::SETOLE: // (X <= Y) ? X : Y -> min
7344 if (!UnsafeFPMath) break;
7346 case ISD::SETOLT: // (X olt/lt Y) ? X : Y -> min
7348 Opcode = X86ISD::FMIN;
7351 case ISD::SETOGT: // (X > Y) ? X : Y -> max
7354 if (!UnsafeFPMath) break;
7356 case ISD::SETUGE: // (X uge/ge Y) ? X : Y -> max
7358 Opcode = X86ISD::FMAX;
7361 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
7364 case ISD::SETOGT: // (X > Y) ? Y : X -> min
7367 if (!UnsafeFPMath) break;
7369 case ISD::SETUGE: // (X uge/ge Y) ? Y : X -> min
7371 Opcode = X86ISD::FMIN;
7374 case ISD::SETOLE: // (X <= Y) ? Y : X -> max
7377 if (!UnsafeFPMath) break;
7379 case ISD::SETOLT: // (X olt/lt Y) ? Y : X -> max
7381 Opcode = X86ISD::FMAX;
7387 return DAG.getNode(Opcode, N->getValueType(0), LHS, RHS);
7395 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
7396 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
7397 const X86Subtarget *Subtarget) {
7398 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
7399 // the FP state in cases where an emms may be missing.
7400 // A preferable solution to the general problem is to figure out the right
7401 // places to insert EMMS. This qualifies as a quick hack.
7402 StoreSDNode *St = cast<StoreSDNode>(N);
7403 if (St->getValue().getValueType().isVector() &&
7404 St->getValue().getValueType().getSizeInBits() == 64 &&
7405 isa<LoadSDNode>(St->getValue()) &&
7406 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
7407 St->getChain().hasOneUse() && !St->isVolatile()) {
7408 SDNode* LdVal = St->getValue().getNode();
7410 int TokenFactorIndex = -1;
7411 SmallVector<SDValue, 8> Ops;
7412 SDNode* ChainVal = St->getChain().getNode();
7413 // Must be a store of a load. We currently handle two cases: the load
7414 // is a direct child, and it's under an intervening TokenFactor. It is
7415 // possible to dig deeper under nested TokenFactors.
7416 if (ChainVal == LdVal)
7417 Ld = cast<LoadSDNode>(St->getChain());
7418 else if (St->getValue().hasOneUse() &&
7419 ChainVal->getOpcode() == ISD::TokenFactor) {
7420 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
7421 if (ChainVal->getOperand(i).getNode() == LdVal) {
7422 TokenFactorIndex = i;
7423 Ld = cast<LoadSDNode>(St->getValue());
7425 Ops.push_back(ChainVal->getOperand(i));
7429 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
7430 if (Subtarget->is64Bit()) {
7431 SDValue NewLd = DAG.getLoad(MVT::i64, Ld->getChain(),
7432 Ld->getBasePtr(), Ld->getSrcValue(),
7433 Ld->getSrcValueOffset(), Ld->isVolatile(),
7434 Ld->getAlignment());
7435 SDValue NewChain = NewLd.getValue(1);
7436 if (TokenFactorIndex != -1) {
7437 Ops.push_back(NewChain);
7438 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
7441 return DAG.getStore(NewChain, NewLd, St->getBasePtr(),
7442 St->getSrcValue(), St->getSrcValueOffset(),
7443 St->isVolatile(), St->getAlignment());
7446 // Otherwise, lower to two 32-bit copies.
7447 SDValue LoAddr = Ld->getBasePtr();
7448 SDValue HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
7449 DAG.getConstant(4, MVT::i32));
7451 SDValue LoLd = DAG.getLoad(MVT::i32, Ld->getChain(), LoAddr,
7452 Ld->getSrcValue(), Ld->getSrcValueOffset(),
7453 Ld->isVolatile(), Ld->getAlignment());
7454 SDValue HiLd = DAG.getLoad(MVT::i32, Ld->getChain(), HiAddr,
7455 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
7457 MinAlign(Ld->getAlignment(), 4));
7459 SDValue NewChain = LoLd.getValue(1);
7460 if (TokenFactorIndex != -1) {
7461 Ops.push_back(LoLd);
7462 Ops.push_back(HiLd);
7463 NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0],
7467 LoAddr = St->getBasePtr();
7468 HiAddr = DAG.getNode(ISD::ADD, MVT::i32, LoAddr,
7469 DAG.getConstant(4, MVT::i32));
7471 SDValue LoSt = DAG.getStore(NewChain, LoLd, LoAddr,
7472 St->getSrcValue(), St->getSrcValueOffset(),
7473 St->isVolatile(), St->getAlignment());
7474 SDValue HiSt = DAG.getStore(NewChain, HiLd, HiAddr,
7476 St->getSrcValueOffset() + 4,
7478 MinAlign(St->getAlignment(), 4));
7479 return DAG.getNode(ISD::TokenFactor, MVT::Other, LoSt, HiSt);
7485 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
7486 /// X86ISD::FXOR nodes.
7487 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
7488 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
7489 // F[X]OR(0.0, x) -> x
7490 // F[X]OR(x, 0.0) -> x
7491 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
7492 if (C->getValueAPF().isPosZero())
7493 return N->getOperand(1);
7494 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
7495 if (C->getValueAPF().isPosZero())
7496 return N->getOperand(0);
7500 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
7501 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
7502 // FAND(0.0, x) -> 0.0
7503 // FAND(x, 0.0) -> 0.0
7504 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
7505 if (C->getValueAPF().isPosZero())
7506 return N->getOperand(0);
7507 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
7508 if (C->getValueAPF().isPosZero())
7509 return N->getOperand(1);
7514 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
7515 DAGCombinerInfo &DCI) const {
7516 SelectionDAG &DAG = DCI.DAG;
7517 switch (N->getOpcode()) {
7519 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
7520 case ISD::BUILD_VECTOR:
7521 return PerformBuildVectorCombine(N, DAG, Subtarget, *this);
7522 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
7523 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
7525 case X86ISD::FOR: return PerformFORCombine(N, DAG);
7526 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
7532 //===----------------------------------------------------------------------===//
7533 // X86 Inline Assembly Support
7534 //===----------------------------------------------------------------------===//
7536 /// getConstraintType - Given a constraint letter, return the type of
7537 /// constraint it is for this target.
7538 X86TargetLowering::ConstraintType
7539 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
7540 if (Constraint.size() == 1) {
7541 switch (Constraint[0]) {
7552 return C_RegisterClass;
7557 return TargetLowering::getConstraintType(Constraint);
7560 /// LowerXConstraint - try to replace an X constraint, which matches anything,
7561 /// with another that has more specific requirements based on the type of the
7562 /// corresponding operand.
7563 const char *X86TargetLowering::
7564 LowerXConstraint(MVT ConstraintVT) const {
7565 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
7566 // 'f' like normal targets.
7567 if (ConstraintVT.isFloatingPoint()) {
7568 if (Subtarget->hasSSE2())
7570 if (Subtarget->hasSSE1())
7574 return TargetLowering::LowerXConstraint(ConstraintVT);
7577 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
7578 /// vector. If it is invalid, don't add anything to Ops.
7579 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
7582 std::vector<SDValue>&Ops,
7583 SelectionDAG &DAG) const {
7584 SDValue Result(0, 0);
7586 switch (Constraint) {
7589 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
7590 if (C->getZExtValue() <= 31) {
7591 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
7597 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
7598 if (C->getZExtValue() <= 63) {
7599 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
7605 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
7606 if (C->getZExtValue() <= 255) {
7607 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
7613 // Literal immediates are always ok.
7614 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
7615 Result = DAG.getTargetConstant(CST->getZExtValue(), Op.getValueType());
7619 // If we are in non-pic codegen mode, we allow the address of a global (with
7620 // an optional displacement) to be used with 'i'.
7621 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
7624 // Match either (GA) or (GA+C)
7626 Offset = GA->getOffset();
7627 } else if (Op.getOpcode() == ISD::ADD) {
7628 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7629 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
7631 Offset = GA->getOffset()+C->getZExtValue();
7633 C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7634 GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
7636 Offset = GA->getOffset()+C->getZExtValue();
7644 Op = LowerGlobalAddress(GA->getGlobal(), Offset, DAG);
7646 Op = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
7652 // Otherwise, not valid for this mode.
7657 if (Result.getNode()) {
7658 Ops.push_back(Result);
7661 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
7665 std::vector<unsigned> X86TargetLowering::
7666 getRegClassForInlineAsmConstraint(const std::string &Constraint,
7668 if (Constraint.size() == 1) {
7669 // FIXME: not handling fp-stack yet!
7670 switch (Constraint[0]) { // GCC X86 Constraint Letters
7671 default: break; // Unknown constraint letter
7672 case 'A': // EAX/EDX
7673 if (VT == MVT::i32 || VT == MVT::i64)
7674 return make_vector<unsigned>(X86::EAX, X86::EDX, 0);
7676 case 'q': // Q_REGS (GENERAL_REGS in 64-bit mode)
7679 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
7680 else if (VT == MVT::i16)
7681 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
7682 else if (VT == MVT::i8)
7683 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
7684 else if (VT == MVT::i64)
7685 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
7690 return std::vector<unsigned>();
7693 std::pair<unsigned, const TargetRegisterClass*>
7694 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
7696 // First, see if this is a constraint that directly corresponds to an LLVM
7698 if (Constraint.size() == 1) {
7699 // GCC Constraint Letters
7700 switch (Constraint[0]) {
7702 case 'r': // GENERAL_REGS
7703 case 'R': // LEGACY_REGS
7704 case 'l': // INDEX_REGS
7706 return std::make_pair(0U, X86::GR8RegisterClass);
7708 return std::make_pair(0U, X86::GR16RegisterClass);
7709 if (VT == MVT::i32 || !Subtarget->is64Bit())
7710 return std::make_pair(0U, X86::GR32RegisterClass);
7711 return std::make_pair(0U, X86::GR64RegisterClass);
7712 case 'f': // FP Stack registers.
7713 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
7714 // value to the correct fpstack register class.
7715 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
7716 return std::make_pair(0U, X86::RFP32RegisterClass);
7717 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
7718 return std::make_pair(0U, X86::RFP64RegisterClass);
7719 return std::make_pair(0U, X86::RFP80RegisterClass);
7720 case 'y': // MMX_REGS if MMX allowed.
7721 if (!Subtarget->hasMMX()) break;
7722 return std::make_pair(0U, X86::VR64RegisterClass);
7723 case 'Y': // SSE_REGS if SSE2 allowed
7724 if (!Subtarget->hasSSE2()) break;
7726 case 'x': // SSE_REGS if SSE1 allowed
7727 if (!Subtarget->hasSSE1()) break;
7729 switch (VT.getSimpleVT()) {
7731 // Scalar SSE types.
7734 return std::make_pair(0U, X86::FR32RegisterClass);
7737 return std::make_pair(0U, X86::FR64RegisterClass);
7745 return std::make_pair(0U, X86::VR128RegisterClass);
7751 // Use the default implementation in TargetLowering to convert the register
7752 // constraint into a member of a register class.
7753 std::pair<unsigned, const TargetRegisterClass*> Res;
7754 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
7756 // Not found as a standard register?
7757 if (Res.second == 0) {
7758 // GCC calls "st(0)" just plain "st".
7759 if (StringsEqualNoCase("{st}", Constraint)) {
7760 Res.first = X86::ST0;
7761 Res.second = X86::RFP80RegisterClass;
7767 // Otherwise, check to see if this is a register class of the wrong value
7768 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
7769 // turn into {ax},{dx}.
7770 if (Res.second->hasType(VT))
7771 return Res; // Correct type already, nothing to do.
7773 // All of the single-register GCC register classes map their values onto
7774 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
7775 // really want an 8-bit or 32-bit register, map to the appropriate register
7776 // class and return the appropriate register.
7777 if (Res.second == X86::GR16RegisterClass) {
7778 if (VT == MVT::i8) {
7779 unsigned DestReg = 0;
7780 switch (Res.first) {
7782 case X86::AX: DestReg = X86::AL; break;
7783 case X86::DX: DestReg = X86::DL; break;
7784 case X86::CX: DestReg = X86::CL; break;
7785 case X86::BX: DestReg = X86::BL; break;
7788 Res.first = DestReg;
7789 Res.second = Res.second = X86::GR8RegisterClass;
7791 } else if (VT == MVT::i32) {
7792 unsigned DestReg = 0;
7793 switch (Res.first) {
7795 case X86::AX: DestReg = X86::EAX; break;
7796 case X86::DX: DestReg = X86::EDX; break;
7797 case X86::CX: DestReg = X86::ECX; break;
7798 case X86::BX: DestReg = X86::EBX; break;
7799 case X86::SI: DestReg = X86::ESI; break;
7800 case X86::DI: DestReg = X86::EDI; break;
7801 case X86::BP: DestReg = X86::EBP; break;
7802 case X86::SP: DestReg = X86::ESP; break;
7805 Res.first = DestReg;
7806 Res.second = Res.second = X86::GR32RegisterClass;
7808 } else if (VT == MVT::i64) {
7809 unsigned DestReg = 0;
7810 switch (Res.first) {
7812 case X86::AX: DestReg = X86::RAX; break;
7813 case X86::DX: DestReg = X86::RDX; break;
7814 case X86::CX: DestReg = X86::RCX; break;
7815 case X86::BX: DestReg = X86::RBX; break;
7816 case X86::SI: DestReg = X86::RSI; break;
7817 case X86::DI: DestReg = X86::RDI; break;
7818 case X86::BP: DestReg = X86::RBP; break;
7819 case X86::SP: DestReg = X86::RSP; break;
7822 Res.first = DestReg;
7823 Res.second = Res.second = X86::GR64RegisterClass;
7826 } else if (Res.second == X86::FR32RegisterClass ||
7827 Res.second == X86::FR64RegisterClass ||
7828 Res.second == X86::VR128RegisterClass) {
7829 // Handle references to XMM physical registers that got mapped into the
7830 // wrong class. This can happen with constraints like {xmm0} where the
7831 // target independent register mapper will just pick the first match it can
7832 // find, ignoring the required type.
7834 Res.second = X86::FR32RegisterClass;
7835 else if (VT == MVT::f64)
7836 Res.second = X86::FR64RegisterClass;
7837 else if (X86::VR128RegisterClass->hasType(VT))
7838 Res.second = X86::VR128RegisterClass;
7844 //===----------------------------------------------------------------------===//
7845 // X86 Widen vector type
7846 //===----------------------------------------------------------------------===//
7848 /// getWidenVectorType: given a vector type, returns the type to widen
7849 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
7850 /// If there is no vector type that we want to widen to, returns MVT::Other
7851 /// When and were to widen is target dependent based on the cost of
7852 /// scalarizing vs using the wider vector type.
7854 MVT X86TargetLowering::getWidenVectorType(MVT VT) {
7855 assert(VT.isVector());
7856 if (isTypeLegal(VT))
7859 // TODO: In computeRegisterProperty, we can compute the list of legal vector
7860 // type based on element type. This would speed up our search (though
7861 // it may not be worth it since the size of the list is relatively
7863 MVT EltVT = VT.getVectorElementType();
7864 unsigned NElts = VT.getVectorNumElements();
7866 // On X86, it make sense to widen any vector wider than 1
7870 for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
7871 nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
7872 MVT SVT = (MVT::SimpleValueType)nVT;
7874 if (isTypeLegal(SVT) &&
7875 SVT.getVectorElementType() == EltVT &&
7876 SVT.getVectorNumElements() > NElts)