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 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "x86-isel"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86ShuffleDecode.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/CallingConv.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/GlobalAlias.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Function.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/LLVMContext.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/PseudoSourceValue.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCExpr.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/ADT/BitVector.h"
43 #include "llvm/ADT/SmallSet.h"
44 #include "llvm/ADT/Statistic.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/ADT/VectorExtras.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/Dwarf.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/raw_ostream.h"
54 using namespace dwarf;
56 STATISTIC(NumTailCalls, "Number of tail calls");
59 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
61 // Forward declarations.
62 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
65 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
67 bool is64Bit = TM.getSubtarget<X86Subtarget>().is64Bit();
69 if (TM.getSubtarget<X86Subtarget>().isTargetDarwin()) {
70 if (is64Bit) return new X8664_MachoTargetObjectFile();
71 return new TargetLoweringObjectFileMachO();
72 } else if (TM.getSubtarget<X86Subtarget>().isTargetELF() ){
73 if (is64Bit) return new X8664_ELFTargetObjectFile(TM);
74 return new X8632_ELFTargetObjectFile(TM);
75 } else if (TM.getSubtarget<X86Subtarget>().isTargetCOFF()) {
76 return new TargetLoweringObjectFileCOFF();
78 llvm_unreachable("unknown subtarget type");
81 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
82 : TargetLowering(TM, createTLOF(TM)) {
83 Subtarget = &TM.getSubtarget<X86Subtarget>();
84 X86ScalarSSEf64 = Subtarget->hasSSE2();
85 X86ScalarSSEf32 = Subtarget->hasSSE1();
86 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
88 RegInfo = TM.getRegisterInfo();
91 // Set up the TargetLowering object.
93 // X86 is weird, it always uses i8 for shift amounts and setcc results.
94 setShiftAmountType(MVT::i8);
95 setBooleanContents(ZeroOrOneBooleanContent);
96 setSchedulingPreference(Sched::RegPressure);
97 setStackPointerRegisterToSaveRestore(X86StackPtr);
99 if (Subtarget->isTargetDarwin()) {
100 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
101 setUseUnderscoreSetJmp(false);
102 setUseUnderscoreLongJmp(false);
103 } else if (Subtarget->isTargetMingw()) {
104 // MS runtime is weird: it exports _setjmp, but longjmp!
105 setUseUnderscoreSetJmp(true);
106 setUseUnderscoreLongJmp(false);
108 setUseUnderscoreSetJmp(true);
109 setUseUnderscoreLongJmp(true);
112 // Set up the register classes.
113 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
114 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
115 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
116 if (Subtarget->is64Bit())
117 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
119 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
121 // We don't accept any truncstore of integer registers.
122 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
123 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
124 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
125 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
126 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
127 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
129 // SETOEQ and SETUNE require checking two conditions.
130 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
131 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
132 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
133 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
134 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
135 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
137 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
139 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
140 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
141 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
143 if (Subtarget->is64Bit()) {
144 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
145 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
146 } else if (!UseSoftFloat) {
147 // We have an algorithm for SSE2->double, and we turn this into a
148 // 64-bit FILD followed by conditional FADD for other targets.
149 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
150 // We have an algorithm for SSE2, and we turn this into a 64-bit
151 // FILD for other targets.
152 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
155 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
157 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
158 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
161 // SSE has no i16 to fp conversion, only i32
162 if (X86ScalarSSEf32) {
163 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
164 // f32 and f64 cases are Legal, f80 case is not
165 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
167 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
168 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
171 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
172 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
175 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
176 // are Legal, f80 is custom lowered.
177 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
178 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
180 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
182 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
183 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
185 if (X86ScalarSSEf32) {
186 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
187 // f32 and f64 cases are Legal, f80 case is not
188 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
190 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
191 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
194 // Handle FP_TO_UINT by promoting the destination to a larger signed
196 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
197 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
198 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
200 if (Subtarget->is64Bit()) {
201 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
202 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
203 } else if (!UseSoftFloat) {
204 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
205 // Expand FP_TO_UINT into a select.
206 // FIXME: We would like to use a Custom expander here eventually to do
207 // the optimal thing for SSE vs. the default expansion in the legalizer.
208 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
210 // With SSE3 we can use fisttpll to convert to a signed i64; without
211 // SSE, we're stuck with a fistpll.
212 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
215 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
216 if (!X86ScalarSSEf64) {
217 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
218 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
219 if (Subtarget->is64Bit()) {
220 setOperationAction(ISD::BIT_CONVERT , MVT::f64 , Expand);
221 // Without SSE, i64->f64 goes through memory; i64->MMX is Legal.
222 if (Subtarget->hasMMX() && !DisableMMX)
223 setOperationAction(ISD::BIT_CONVERT , MVT::i64 , Custom);
225 setOperationAction(ISD::BIT_CONVERT , MVT::i64 , Expand);
229 // Scalar integer divide and remainder are lowered to use operations that
230 // produce two results, to match the available instructions. This exposes
231 // the two-result form to trivial CSE, which is able to combine x/y and x%y
232 // into a single instruction.
234 // Scalar integer multiply-high is also lowered to use two-result
235 // operations, to match the available instructions. However, plain multiply
236 // (low) operations are left as Legal, as there are single-result
237 // instructions for this in x86. Using the two-result multiply instructions
238 // when both high and low results are needed must be arranged by dagcombine.
239 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
240 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
241 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
242 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
243 setOperationAction(ISD::SREM , MVT::i8 , Expand);
244 setOperationAction(ISD::UREM , MVT::i8 , Expand);
245 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
246 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
247 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
248 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
249 setOperationAction(ISD::SREM , MVT::i16 , Expand);
250 setOperationAction(ISD::UREM , MVT::i16 , Expand);
251 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
252 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
253 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
254 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
255 setOperationAction(ISD::SREM , MVT::i32 , Expand);
256 setOperationAction(ISD::UREM , MVT::i32 , Expand);
257 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
258 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
259 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
260 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
261 setOperationAction(ISD::SREM , MVT::i64 , Expand);
262 setOperationAction(ISD::UREM , MVT::i64 , Expand);
264 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
265 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
266 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
267 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
268 if (Subtarget->is64Bit())
269 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
270 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
271 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
272 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
273 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
274 setOperationAction(ISD::FREM , MVT::f32 , Expand);
275 setOperationAction(ISD::FREM , MVT::f64 , Expand);
276 setOperationAction(ISD::FREM , MVT::f80 , Expand);
277 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
279 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
280 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
281 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
282 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
283 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
284 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
285 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
286 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
287 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
288 if (Subtarget->is64Bit()) {
289 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
290 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
291 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
294 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
295 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
297 // These should be promoted to a larger select which is supported.
298 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
299 // X86 wants to expand cmov itself.
300 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
301 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
302 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
303 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
304 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
305 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
306 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
307 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
308 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
309 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
310 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
311 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
312 if (Subtarget->is64Bit()) {
313 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
314 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
316 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
319 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
320 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
321 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
322 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
323 if (Subtarget->is64Bit())
324 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
325 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
326 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
327 if (Subtarget->is64Bit()) {
328 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
329 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
330 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
331 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
332 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
334 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
335 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
336 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
337 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
338 if (Subtarget->is64Bit()) {
339 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
340 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
341 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
344 if (Subtarget->hasSSE1())
345 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
347 // We may not have a libcall for MEMBARRIER so we should lower this.
348 setOperationAction(ISD::MEMBARRIER , MVT::Other, Custom);
350 // On X86 and X86-64, atomic operations are lowered to locked instructions.
351 // Locked instructions, in turn, have implicit fence semantics (all memory
352 // operations are flushed before issuing the locked instruction, and they
353 // are not buffered), so we can fold away the common pattern of
354 // fence-atomic-fence.
355 setShouldFoldAtomicFences(true);
357 // Expand certain atomics
358 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
359 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
360 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
361 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
363 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
364 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
365 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
366 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
368 if (!Subtarget->is64Bit()) {
369 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
370 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
371 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
372 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
373 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
374 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
375 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
378 // FIXME - use subtarget debug flags
379 if (!Subtarget->isTargetDarwin() &&
380 !Subtarget->isTargetELF() &&
381 !Subtarget->isTargetCygMing()) {
382 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
385 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
386 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
387 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
388 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
389 if (Subtarget->is64Bit()) {
390 setExceptionPointerRegister(X86::RAX);
391 setExceptionSelectorRegister(X86::RDX);
393 setExceptionPointerRegister(X86::EAX);
394 setExceptionSelectorRegister(X86::EDX);
396 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
397 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
399 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
401 setOperationAction(ISD::TRAP, MVT::Other, Legal);
403 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
404 setOperationAction(ISD::VASTART , MVT::Other, Custom);
405 setOperationAction(ISD::VAEND , MVT::Other, Expand);
406 if (Subtarget->is64Bit()) {
407 setOperationAction(ISD::VAARG , MVT::Other, Custom);
408 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
410 setOperationAction(ISD::VAARG , MVT::Other, Expand);
411 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
414 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
415 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
416 if (Subtarget->is64Bit())
417 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
418 if (Subtarget->isTargetCygMing())
419 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
421 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
423 if (!UseSoftFloat && X86ScalarSSEf64) {
424 // f32 and f64 use SSE.
425 // Set up the FP register classes.
426 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
427 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
429 // Use ANDPD to simulate FABS.
430 setOperationAction(ISD::FABS , MVT::f64, Custom);
431 setOperationAction(ISD::FABS , MVT::f32, Custom);
433 // Use XORP to simulate FNEG.
434 setOperationAction(ISD::FNEG , MVT::f64, Custom);
435 setOperationAction(ISD::FNEG , MVT::f32, Custom);
437 // Use ANDPD and ORPD to simulate FCOPYSIGN.
438 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
439 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
441 // We don't support sin/cos/fmod
442 setOperationAction(ISD::FSIN , MVT::f64, Expand);
443 setOperationAction(ISD::FCOS , MVT::f64, Expand);
444 setOperationAction(ISD::FSIN , MVT::f32, Expand);
445 setOperationAction(ISD::FCOS , MVT::f32, Expand);
447 // Expand FP immediates into loads from the stack, except for the special
449 addLegalFPImmediate(APFloat(+0.0)); // xorpd
450 addLegalFPImmediate(APFloat(+0.0f)); // xorps
451 } else if (!UseSoftFloat && X86ScalarSSEf32) {
452 // Use SSE for f32, x87 for f64.
453 // Set up the FP register classes.
454 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
455 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
457 // Use ANDPS to simulate FABS.
458 setOperationAction(ISD::FABS , MVT::f32, Custom);
460 // Use XORP to simulate FNEG.
461 setOperationAction(ISD::FNEG , MVT::f32, Custom);
463 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
465 // Use ANDPS and ORPS to simulate FCOPYSIGN.
466 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
467 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
469 // We don't support sin/cos/fmod
470 setOperationAction(ISD::FSIN , MVT::f32, Expand);
471 setOperationAction(ISD::FCOS , MVT::f32, Expand);
473 // Special cases we handle for FP constants.
474 addLegalFPImmediate(APFloat(+0.0f)); // xorps
475 addLegalFPImmediate(APFloat(+0.0)); // FLD0
476 addLegalFPImmediate(APFloat(+1.0)); // FLD1
477 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
478 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
481 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
482 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
484 } else if (!UseSoftFloat) {
485 // f32 and f64 in x87.
486 // Set up the FP register classes.
487 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
488 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
490 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
491 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
492 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
493 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
496 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
497 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
499 addLegalFPImmediate(APFloat(+0.0)); // FLD0
500 addLegalFPImmediate(APFloat(+1.0)); // FLD1
501 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
502 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
503 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
504 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
505 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
506 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
509 // Long double always uses X87.
511 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
512 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
513 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
516 APFloat TmpFlt(+0.0);
517 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
519 addLegalFPImmediate(TmpFlt); // FLD0
521 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
522 APFloat TmpFlt2(+1.0);
523 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
525 addLegalFPImmediate(TmpFlt2); // FLD1
526 TmpFlt2.changeSign();
527 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
531 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
532 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
536 // Always use a library call for pow.
537 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
538 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
539 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
541 setOperationAction(ISD::FLOG, MVT::f80, Expand);
542 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
543 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
544 setOperationAction(ISD::FEXP, MVT::f80, Expand);
545 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
547 // First set operation action for all vector types to either promote
548 // (for widening) or expand (for scalarization). Then we will selectively
549 // turn on ones that can be effectively codegen'd.
550 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
551 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
552 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
553 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
554 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
555 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
556 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
557 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
558 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
559 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
560 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
561 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
562 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
563 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
564 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
565 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
566 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
567 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
568 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
569 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
570 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
571 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
572 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
573 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
574 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
575 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
576 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
577 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
578 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
579 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
580 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
581 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
582 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
583 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
584 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
585 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
586 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
587 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
588 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
589 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
590 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
591 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
592 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
593 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
594 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
595 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
596 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
597 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
598 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
599 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
600 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
601 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
602 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
603 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
604 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
605 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
606 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
607 setTruncStoreAction((MVT::SimpleValueType)VT,
608 (MVT::SimpleValueType)InnerVT, Expand);
609 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
610 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
611 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
614 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
615 // with -msoft-float, disable use of MMX as well.
616 if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
617 addRegisterClass(MVT::x86mmx, X86::VR64RegisterClass, false);
619 // FIXME: Remove the rest of this stuff.
620 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass, false);
621 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass, false);
622 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass, false);
624 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass, false);
626 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
627 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
628 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
629 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
631 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
632 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
633 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
634 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
636 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
637 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
639 setOperationAction(ISD::AND, MVT::v8i8, Promote);
640 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
641 setOperationAction(ISD::AND, MVT::v4i16, Promote);
642 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
643 setOperationAction(ISD::AND, MVT::v2i32, Promote);
644 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
645 setOperationAction(ISD::AND, MVT::v1i64, Legal);
647 setOperationAction(ISD::OR, MVT::v8i8, Promote);
648 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
649 setOperationAction(ISD::OR, MVT::v4i16, Promote);
650 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
651 setOperationAction(ISD::OR, MVT::v2i32, Promote);
652 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
653 setOperationAction(ISD::OR, MVT::v1i64, Legal);
655 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
656 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
657 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
658 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
659 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
660 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
661 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
663 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
664 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
665 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
666 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
667 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
668 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
669 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
671 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
672 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
673 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
674 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
676 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
677 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
678 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
679 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
681 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
682 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
683 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
685 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
687 setOperationAction(ISD::SELECT, MVT::v8i8, Promote);
688 setOperationAction(ISD::SELECT, MVT::v4i16, Promote);
689 setOperationAction(ISD::SELECT, MVT::v2i32, Promote);
690 setOperationAction(ISD::SELECT, MVT::v1i64, Custom);
691 setOperationAction(ISD::VSETCC, MVT::v8i8, Custom);
692 setOperationAction(ISD::VSETCC, MVT::v4i16, Custom);
693 setOperationAction(ISD::VSETCC, MVT::v2i32, Custom);
695 if (!X86ScalarSSEf64 && Subtarget->is64Bit()) {
696 setOperationAction(ISD::BIT_CONVERT, MVT::v8i8, Custom);
697 setOperationAction(ISD::BIT_CONVERT, MVT::v4i16, Custom);
698 setOperationAction(ISD::BIT_CONVERT, MVT::v2i32, Custom);
699 setOperationAction(ISD::BIT_CONVERT, MVT::v1i64, Custom);
703 if (!UseSoftFloat && Subtarget->hasSSE1()) {
704 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
706 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
707 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
708 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
709 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
710 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
711 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
712 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
713 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
714 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
715 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
716 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
717 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
720 if (!UseSoftFloat && Subtarget->hasSSE2()) {
721 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
723 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
724 // registers cannot be used even for integer operations.
725 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
726 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
727 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
728 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
730 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
731 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
732 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
733 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
734 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
735 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
736 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
737 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
738 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
739 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
740 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
741 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
742 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
743 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
744 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
745 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
747 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
748 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
749 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
750 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
752 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
753 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
754 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
755 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
756 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
758 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
759 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
760 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
761 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
762 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
764 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
765 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
766 EVT VT = (MVT::SimpleValueType)i;
767 // Do not attempt to custom lower non-power-of-2 vectors
768 if (!isPowerOf2_32(VT.getVectorNumElements()))
770 // Do not attempt to custom lower non-128-bit vectors
771 if (!VT.is128BitVector())
773 setOperationAction(ISD::BUILD_VECTOR,
774 VT.getSimpleVT().SimpleTy, Custom);
775 setOperationAction(ISD::VECTOR_SHUFFLE,
776 VT.getSimpleVT().SimpleTy, Custom);
777 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
778 VT.getSimpleVT().SimpleTy, Custom);
781 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
782 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
783 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
784 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
785 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
786 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
788 if (Subtarget->is64Bit()) {
789 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
790 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
793 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
794 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
795 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
798 // Do not attempt to promote non-128-bit vectors
799 if (!VT.is128BitVector())
802 setOperationAction(ISD::AND, SVT, Promote);
803 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
804 setOperationAction(ISD::OR, SVT, Promote);
805 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
806 setOperationAction(ISD::XOR, SVT, Promote);
807 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
808 setOperationAction(ISD::LOAD, SVT, Promote);
809 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
810 setOperationAction(ISD::SELECT, SVT, Promote);
811 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
814 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
816 // Custom lower v2i64 and v2f64 selects.
817 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
818 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
819 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
820 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
822 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
823 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
824 if (!DisableMMX && Subtarget->hasMMX()) {
825 setOperationAction(ISD::FP_TO_SINT, MVT::v2i32, Custom);
826 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
830 if (Subtarget->hasSSE41()) {
831 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
832 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
833 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
834 setOperationAction(ISD::FRINT, MVT::f32, Legal);
835 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
836 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
837 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
838 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
839 setOperationAction(ISD::FRINT, MVT::f64, Legal);
840 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
842 // FIXME: Do we need to handle scalar-to-vector here?
843 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
845 // Can turn SHL into an integer multiply.
846 setOperationAction(ISD::SHL, MVT::v4i32, Custom);
847 setOperationAction(ISD::SHL, MVT::v16i8, Custom);
849 // i8 and i16 vectors are custom , because the source register and source
850 // source memory operand types are not the same width. f32 vectors are
851 // custom since the immediate controlling the insert encodes additional
853 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
854 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
855 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
856 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
858 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
859 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
860 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
861 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
863 if (Subtarget->is64Bit()) {
864 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
865 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
869 if (Subtarget->hasSSE42()) {
870 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
873 if (!UseSoftFloat && Subtarget->hasAVX()) {
874 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
875 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
876 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
877 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
878 addRegisterClass(MVT::v32i8, X86::VR256RegisterClass);
880 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
881 setOperationAction(ISD::LOAD, MVT::v8i32, Legal);
882 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
883 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
884 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
885 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
886 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
887 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
888 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
889 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
890 setOperationAction(ISD::BUILD_VECTOR, MVT::v8f32, Custom);
891 //setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Custom);
892 //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
893 //setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
894 //setOperationAction(ISD::VSETCC, MVT::v8f32, Custom);
896 // Operations to consider commented out -v16i16 v32i8
897 //setOperationAction(ISD::ADD, MVT::v16i16, Legal);
898 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
899 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
900 //setOperationAction(ISD::SUB, MVT::v32i8, Legal);
901 //setOperationAction(ISD::SUB, MVT::v16i16, Legal);
902 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
903 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
904 //setOperationAction(ISD::MUL, MVT::v16i16, Legal);
905 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
906 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
907 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
908 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
909 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
910 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
912 setOperationAction(ISD::VSETCC, MVT::v4f64, Custom);
913 // setOperationAction(ISD::VSETCC, MVT::v32i8, Custom);
914 // setOperationAction(ISD::VSETCC, MVT::v16i16, Custom);
915 setOperationAction(ISD::VSETCC, MVT::v8i32, Custom);
917 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v32i8, Custom);
918 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i16, Custom);
919 // setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i16, Custom);
920 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i32, Custom);
921 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8f32, Custom);
923 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
924 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i64, Custom);
925 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f64, Custom);
926 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i64, Custom);
927 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f64, Custom);
928 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
931 // Not sure we want to do this since there are no 256-bit integer
934 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
935 // This includes 256-bit vectors
936 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
937 EVT VT = (MVT::SimpleValueType)i;
939 // Do not attempt to custom lower non-power-of-2 vectors
940 if (!isPowerOf2_32(VT.getVectorNumElements()))
943 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
944 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
945 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
948 if (Subtarget->is64Bit()) {
949 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i64, Custom);
950 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
955 // Not sure we want to do this since there are no 256-bit integer
958 // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
959 // Including 256-bit vectors
960 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
961 EVT VT = (MVT::SimpleValueType)i;
963 if (!VT.is256BitVector()) {
966 setOperationAction(ISD::AND, VT, Promote);
967 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
968 setOperationAction(ISD::OR, VT, Promote);
969 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
970 setOperationAction(ISD::XOR, VT, Promote);
971 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
972 setOperationAction(ISD::LOAD, VT, Promote);
973 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
974 setOperationAction(ISD::SELECT, VT, Promote);
975 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
978 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
982 // We want to custom lower some of our intrinsics.
983 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
985 // Add/Sub/Mul with overflow operations are custom lowered.
986 setOperationAction(ISD::SADDO, MVT::i32, Custom);
987 setOperationAction(ISD::UADDO, MVT::i32, Custom);
988 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
989 setOperationAction(ISD::USUBO, MVT::i32, Custom);
990 setOperationAction(ISD::SMULO, MVT::i32, Custom);
992 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
993 // handle type legalization for these operations here.
995 // FIXME: We really should do custom legalization for addition and
996 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
997 // than generic legalization for 64-bit multiplication-with-overflow, though.
998 if (Subtarget->is64Bit()) {
999 setOperationAction(ISD::SADDO, MVT::i64, Custom);
1000 setOperationAction(ISD::UADDO, MVT::i64, Custom);
1001 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
1002 setOperationAction(ISD::USUBO, MVT::i64, Custom);
1003 setOperationAction(ISD::SMULO, MVT::i64, Custom);
1006 if (!Subtarget->is64Bit()) {
1007 // These libcalls are not available in 32-bit.
1008 setLibcallName(RTLIB::SHL_I128, 0);
1009 setLibcallName(RTLIB::SRL_I128, 0);
1010 setLibcallName(RTLIB::SRA_I128, 0);
1013 // We have target-specific dag combine patterns for the following nodes:
1014 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1015 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1016 setTargetDAGCombine(ISD::BUILD_VECTOR);
1017 setTargetDAGCombine(ISD::SELECT);
1018 setTargetDAGCombine(ISD::SHL);
1019 setTargetDAGCombine(ISD::SRA);
1020 setTargetDAGCombine(ISD::SRL);
1021 setTargetDAGCombine(ISD::OR);
1022 setTargetDAGCombine(ISD::STORE);
1023 setTargetDAGCombine(ISD::ZERO_EXTEND);
1024 if (Subtarget->is64Bit())
1025 setTargetDAGCombine(ISD::MUL);
1027 computeRegisterProperties();
1029 // FIXME: These should be based on subtarget info. Plus, the values should
1030 // be smaller when we are in optimizing for size mode.
1031 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1032 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1033 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
1034 setPrefLoopAlignment(16);
1035 benefitFromCodePlacementOpt = true;
1039 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1044 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1045 /// the desired ByVal argument alignment.
1046 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1049 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1050 if (VTy->getBitWidth() == 128)
1052 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1053 unsigned EltAlign = 0;
1054 getMaxByValAlign(ATy->getElementType(), EltAlign);
1055 if (EltAlign > MaxAlign)
1056 MaxAlign = EltAlign;
1057 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1058 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1059 unsigned EltAlign = 0;
1060 getMaxByValAlign(STy->getElementType(i), EltAlign);
1061 if (EltAlign > MaxAlign)
1062 MaxAlign = EltAlign;
1070 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1071 /// function arguments in the caller parameter area. For X86, aggregates
1072 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1073 /// are at 4-byte boundaries.
1074 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1075 if (Subtarget->is64Bit()) {
1076 // Max of 8 and alignment of type.
1077 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1084 if (Subtarget->hasSSE1())
1085 getMaxByValAlign(Ty, Align);
1089 /// getOptimalMemOpType - Returns the target specific optimal type for load
1090 /// and store operations as a result of memset, memcpy, and memmove
1091 /// lowering. If DstAlign is zero that means it's safe to destination
1092 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1093 /// means there isn't a need to check it against alignment requirement,
1094 /// probably because the source does not need to be loaded. If
1095 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1096 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1097 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1098 /// constant so it does not need to be loaded.
1099 /// It returns EVT::Other if the type should be determined using generic
1100 /// target-independent logic.
1102 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1103 unsigned DstAlign, unsigned SrcAlign,
1104 bool NonScalarIntSafe,
1106 MachineFunction &MF) const {
1107 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1108 // linux. This is because the stack realignment code can't handle certain
1109 // cases like PR2962. This should be removed when PR2962 is fixed.
1110 const Function *F = MF.getFunction();
1111 if (NonScalarIntSafe &&
1112 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1114 (Subtarget->isUnalignedMemAccessFast() ||
1115 ((DstAlign == 0 || DstAlign >= 16) &&
1116 (SrcAlign == 0 || SrcAlign >= 16))) &&
1117 Subtarget->getStackAlignment() >= 16) {
1118 if (Subtarget->hasSSE2())
1120 if (Subtarget->hasSSE1())
1122 } else if (!MemcpyStrSrc && Size >= 8 &&
1123 !Subtarget->is64Bit() &&
1124 Subtarget->getStackAlignment() >= 8 &&
1125 Subtarget->hasSSE2()) {
1126 // Do not use f64 to lower memcpy if source is string constant. It's
1127 // better to use i32 to avoid the loads.
1131 if (Subtarget->is64Bit() && Size >= 8)
1136 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1137 /// current function. The returned value is a member of the
1138 /// MachineJumpTableInfo::JTEntryKind enum.
1139 unsigned X86TargetLowering::getJumpTableEncoding() const {
1140 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1142 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1143 Subtarget->isPICStyleGOT())
1144 return MachineJumpTableInfo::EK_Custom32;
1146 // Otherwise, use the normal jump table encoding heuristics.
1147 return TargetLowering::getJumpTableEncoding();
1150 /// getPICBaseSymbol - Return the X86-32 PIC base.
1152 X86TargetLowering::getPICBaseSymbol(const MachineFunction *MF,
1153 MCContext &Ctx) const {
1154 const MCAsmInfo &MAI = *getTargetMachine().getMCAsmInfo();
1155 return Ctx.GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix())+
1156 Twine(MF->getFunctionNumber())+"$pb");
1161 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1162 const MachineBasicBlock *MBB,
1163 unsigned uid,MCContext &Ctx) const{
1164 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1165 Subtarget->isPICStyleGOT());
1166 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1168 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1169 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1172 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1174 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1175 SelectionDAG &DAG) const {
1176 if (!Subtarget->is64Bit())
1177 // This doesn't have DebugLoc associated with it, but is not really the
1178 // same as a Register.
1179 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1183 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1184 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1186 const MCExpr *X86TargetLowering::
1187 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1188 MCContext &Ctx) const {
1189 // X86-64 uses RIP relative addressing based on the jump table label.
1190 if (Subtarget->isPICStyleRIPRel())
1191 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1193 // Otherwise, the reference is relative to the PIC base.
1194 return MCSymbolRefExpr::Create(getPICBaseSymbol(MF, Ctx), Ctx);
1197 /// getFunctionAlignment - Return the Log2 alignment of this function.
1198 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1199 return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1202 std::pair<const TargetRegisterClass*, uint8_t>
1203 X86TargetLowering::findRepresentativeClass(EVT VT) const{
1204 const TargetRegisterClass *RRC = 0;
1206 switch (VT.getSimpleVT().SimpleTy) {
1208 return TargetLowering::findRepresentativeClass(VT);
1209 case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1210 RRC = (Subtarget->is64Bit()
1211 ? X86::GR64RegisterClass : X86::GR32RegisterClass);
1213 case MVT::v8i8: case MVT::v4i16:
1214 case MVT::v2i32: case MVT::v1i64:
1215 RRC = X86::VR64RegisterClass;
1217 case MVT::f32: case MVT::f64:
1218 case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1219 case MVT::v4f32: case MVT::v2f64:
1220 case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1222 RRC = X86::VR128RegisterClass;
1225 return std::make_pair(RRC, Cost);
1229 X86TargetLowering::getRegPressureLimit(const TargetRegisterClass *RC,
1230 MachineFunction &MF) const {
1231 unsigned FPDiff = RegInfo->hasFP(MF) ? 1 : 0;
1232 switch (RC->getID()) {
1235 case X86::GR32RegClassID:
1237 case X86::GR64RegClassID:
1239 case X86::VR128RegClassID:
1240 return Subtarget->is64Bit() ? 10 : 4;
1241 case X86::VR64RegClassID:
1246 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1247 unsigned &Offset) const {
1248 if (!Subtarget->isTargetLinux())
1251 if (Subtarget->is64Bit()) {
1252 // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1254 if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1267 //===----------------------------------------------------------------------===//
1268 // Return Value Calling Convention Implementation
1269 //===----------------------------------------------------------------------===//
1271 #include "X86GenCallingConv.inc"
1274 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1275 const SmallVectorImpl<ISD::OutputArg> &Outs,
1276 LLVMContext &Context) const {
1277 SmallVector<CCValAssign, 16> RVLocs;
1278 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1280 return CCInfo.CheckReturn(Outs, RetCC_X86);
1284 X86TargetLowering::LowerReturn(SDValue Chain,
1285 CallingConv::ID CallConv, bool isVarArg,
1286 const SmallVectorImpl<ISD::OutputArg> &Outs,
1287 const SmallVectorImpl<SDValue> &OutVals,
1288 DebugLoc dl, SelectionDAG &DAG) const {
1289 MachineFunction &MF = DAG.getMachineFunction();
1290 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1292 SmallVector<CCValAssign, 16> RVLocs;
1293 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1294 RVLocs, *DAG.getContext());
1295 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1297 // Add the regs to the liveout set for the function.
1298 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1299 for (unsigned i = 0; i != RVLocs.size(); ++i)
1300 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1301 MRI.addLiveOut(RVLocs[i].getLocReg());
1305 SmallVector<SDValue, 6> RetOps;
1306 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1307 // Operand #1 = Bytes To Pop
1308 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1311 // Copy the result values into the output registers.
1312 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1313 CCValAssign &VA = RVLocs[i];
1314 assert(VA.isRegLoc() && "Can only return in registers!");
1315 SDValue ValToCopy = OutVals[i];
1316 EVT ValVT = ValToCopy.getValueType();
1318 // If this is x86-64, and we disabled SSE, we can't return FP values
1319 if ((ValVT == MVT::f32 || ValVT == MVT::f64) &&
1320 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1321 report_fatal_error("SSE register return with SSE disabled");
1323 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1324 // llvm-gcc has never done it right and no one has noticed, so this
1325 // should be OK for now.
1326 if (ValVT == MVT::f64 &&
1327 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1328 report_fatal_error("SSE2 register return with SSE2 disabled");
1330 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1331 // the RET instruction and handled by the FP Stackifier.
1332 if (VA.getLocReg() == X86::ST0 ||
1333 VA.getLocReg() == X86::ST1) {
1334 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1335 // change the value to the FP stack register class.
1336 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1337 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1338 RetOps.push_back(ValToCopy);
1339 // Don't emit a copytoreg.
1343 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1344 // which is returned in RAX / RDX.
1345 if (Subtarget->is64Bit()) {
1346 if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1347 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1348 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1349 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1352 // If we don't have SSE2 available, convert to v4f32 so the generated
1353 // register is legal.
1354 if (!Subtarget->hasSSE2())
1355 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32,ValToCopy);
1360 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1361 Flag = Chain.getValue(1);
1364 // The x86-64 ABI for returning structs by value requires that we copy
1365 // the sret argument into %rax for the return. We saved the argument into
1366 // a virtual register in the entry block, so now we copy the value out
1368 if (Subtarget->is64Bit() &&
1369 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1370 MachineFunction &MF = DAG.getMachineFunction();
1371 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1372 unsigned Reg = FuncInfo->getSRetReturnReg();
1374 "SRetReturnReg should have been set in LowerFormalArguments().");
1375 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1377 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1378 Flag = Chain.getValue(1);
1380 // RAX now acts like a return value.
1381 MRI.addLiveOut(X86::RAX);
1384 RetOps[0] = Chain; // Update chain.
1386 // Add the flag if we have it.
1388 RetOps.push_back(Flag);
1390 return DAG.getNode(X86ISD::RET_FLAG, dl,
1391 MVT::Other, &RetOps[0], RetOps.size());
1394 /// LowerCallResult - Lower the result values of a call into the
1395 /// appropriate copies out of appropriate physical registers.
1398 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1399 CallingConv::ID CallConv, bool isVarArg,
1400 const SmallVectorImpl<ISD::InputArg> &Ins,
1401 DebugLoc dl, SelectionDAG &DAG,
1402 SmallVectorImpl<SDValue> &InVals) const {
1404 // Assign locations to each value returned by this call.
1405 SmallVector<CCValAssign, 16> RVLocs;
1406 bool Is64Bit = Subtarget->is64Bit();
1407 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1408 RVLocs, *DAG.getContext());
1409 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1411 // Copy all of the result registers out of their specified physreg.
1412 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1413 CCValAssign &VA = RVLocs[i];
1414 EVT CopyVT = VA.getValVT();
1416 // If this is x86-64, and we disabled SSE, we can't return FP values
1417 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1418 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1419 report_fatal_error("SSE register return with SSE disabled");
1424 // If this is a call to a function that returns an fp value on the floating
1425 // point stack, we must guarantee the the value is popped from the stack, so
1426 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1427 // if the return value is not used. We use the FpGET_ST0 instructions
1429 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1430 // If we prefer to use the value in xmm registers, copy it out as f80 and
1431 // use a truncate to move it from fp stack reg to xmm reg.
1432 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1433 bool isST0 = VA.getLocReg() == X86::ST0;
1435 if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1436 if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1437 if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1438 SDValue Ops[] = { Chain, InFlag };
1439 Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Flag,
1441 Val = Chain.getValue(0);
1443 // Round the f80 to the right size, which also moves it to the appropriate
1445 if (CopyVT != VA.getValVT())
1446 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1447 // This truncation won't change the value.
1448 DAG.getIntPtrConstant(1));
1449 } else if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1450 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1451 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1452 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1453 MVT::v2i64, InFlag).getValue(1);
1454 Val = Chain.getValue(0);
1455 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1456 Val, DAG.getConstant(0, MVT::i64));
1458 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1459 MVT::i64, InFlag).getValue(1);
1460 Val = Chain.getValue(0);
1462 Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1464 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1465 CopyVT, InFlag).getValue(1);
1466 Val = Chain.getValue(0);
1468 InFlag = Chain.getValue(2);
1469 InVals.push_back(Val);
1476 //===----------------------------------------------------------------------===//
1477 // C & StdCall & Fast Calling Convention implementation
1478 //===----------------------------------------------------------------------===//
1479 // StdCall calling convention seems to be standard for many Windows' API
1480 // routines and around. It differs from C calling convention just a little:
1481 // callee should clean up the stack, not caller. Symbols should be also
1482 // decorated in some fancy way :) It doesn't support any vector arguments.
1483 // For info on fast calling convention see Fast Calling Convention (tail call)
1484 // implementation LowerX86_32FastCCCallTo.
1486 /// CallIsStructReturn - Determines whether a call uses struct return
1488 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1492 return Outs[0].Flags.isSRet();
1495 /// ArgsAreStructReturn - Determines whether a function uses struct
1496 /// return semantics.
1498 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1502 return Ins[0].Flags.isSRet();
1505 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1506 /// given CallingConvention value.
1507 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1508 if (Subtarget->is64Bit()) {
1509 if (CC == CallingConv::GHC)
1510 return CC_X86_64_GHC;
1511 else if (Subtarget->isTargetWin64())
1512 return CC_X86_Win64_C;
1517 if (CC == CallingConv::X86_FastCall)
1518 return CC_X86_32_FastCall;
1519 else if (CC == CallingConv::X86_ThisCall)
1520 return CC_X86_32_ThisCall;
1521 else if (CC == CallingConv::Fast)
1522 return CC_X86_32_FastCC;
1523 else if (CC == CallingConv::GHC)
1524 return CC_X86_32_GHC;
1529 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1530 /// by "Src" to address "Dst" with size and alignment information specified by
1531 /// the specific parameter attribute. The copy will be passed as a byval
1532 /// function parameter.
1534 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1535 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1537 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1538 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1539 /*isVolatile*/false, /*AlwaysInline=*/true,
1543 /// IsTailCallConvention - Return true if the calling convention is one that
1544 /// supports tail call optimization.
1545 static bool IsTailCallConvention(CallingConv::ID CC) {
1546 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1549 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1550 /// a tailcall target by changing its ABI.
1551 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1552 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1556 X86TargetLowering::LowerMemArgument(SDValue Chain,
1557 CallingConv::ID CallConv,
1558 const SmallVectorImpl<ISD::InputArg> &Ins,
1559 DebugLoc dl, SelectionDAG &DAG,
1560 const CCValAssign &VA,
1561 MachineFrameInfo *MFI,
1563 // Create the nodes corresponding to a load from this parameter slot.
1564 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1565 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1566 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1569 // If value is passed by pointer we have address passed instead of the value
1571 if (VA.getLocInfo() == CCValAssign::Indirect)
1572 ValVT = VA.getLocVT();
1574 ValVT = VA.getValVT();
1576 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1577 // changed with more analysis.
1578 // In case of tail call optimization mark all arguments mutable. Since they
1579 // could be overwritten by lowering of arguments in case of a tail call.
1580 if (Flags.isByVal()) {
1581 int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1582 VA.getLocMemOffset(), isImmutable);
1583 return DAG.getFrameIndex(FI, getPointerTy());
1585 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1586 VA.getLocMemOffset(), isImmutable);
1587 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1588 return DAG.getLoad(ValVT, dl, Chain, FIN,
1589 PseudoSourceValue::getFixedStack(FI), 0,
1595 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1596 CallingConv::ID CallConv,
1598 const SmallVectorImpl<ISD::InputArg> &Ins,
1601 SmallVectorImpl<SDValue> &InVals)
1603 MachineFunction &MF = DAG.getMachineFunction();
1604 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1606 const Function* Fn = MF.getFunction();
1607 if (Fn->hasExternalLinkage() &&
1608 Subtarget->isTargetCygMing() &&
1609 Fn->getName() == "main")
1610 FuncInfo->setForceFramePointer(true);
1612 MachineFrameInfo *MFI = MF.getFrameInfo();
1613 bool Is64Bit = Subtarget->is64Bit();
1614 bool IsWin64 = Subtarget->isTargetWin64();
1616 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1617 "Var args not supported with calling convention fastcc or ghc");
1619 // Assign locations to all of the incoming arguments.
1620 SmallVector<CCValAssign, 16> ArgLocs;
1621 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1622 ArgLocs, *DAG.getContext());
1623 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1625 unsigned LastVal = ~0U;
1627 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1628 CCValAssign &VA = ArgLocs[i];
1629 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1631 assert(VA.getValNo() != LastVal &&
1632 "Don't support value assigned to multiple locs yet");
1633 LastVal = VA.getValNo();
1635 if (VA.isRegLoc()) {
1636 EVT RegVT = VA.getLocVT();
1637 TargetRegisterClass *RC = NULL;
1638 if (RegVT == MVT::i32)
1639 RC = X86::GR32RegisterClass;
1640 else if (Is64Bit && RegVT == MVT::i64)
1641 RC = X86::GR64RegisterClass;
1642 else if (RegVT == MVT::f32)
1643 RC = X86::FR32RegisterClass;
1644 else if (RegVT == MVT::f64)
1645 RC = X86::FR64RegisterClass;
1646 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1647 RC = X86::VR256RegisterClass;
1648 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1649 RC = X86::VR128RegisterClass;
1650 else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1651 RC = X86::VR64RegisterClass;
1653 llvm_unreachable("Unknown argument type!");
1655 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1656 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1658 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1659 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1661 if (VA.getLocInfo() == CCValAssign::SExt)
1662 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1663 DAG.getValueType(VA.getValVT()));
1664 else if (VA.getLocInfo() == CCValAssign::ZExt)
1665 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1666 DAG.getValueType(VA.getValVT()));
1667 else if (VA.getLocInfo() == CCValAssign::BCvt)
1668 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1670 if (VA.isExtInLoc()) {
1671 // Handle MMX values passed in XMM regs.
1672 if (RegVT.isVector()) {
1673 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1674 ArgValue, DAG.getConstant(0, MVT::i64));
1675 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1677 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1680 assert(VA.isMemLoc());
1681 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1684 // If value is passed via pointer - do a load.
1685 if (VA.getLocInfo() == CCValAssign::Indirect)
1686 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0,
1689 InVals.push_back(ArgValue);
1692 // The x86-64 ABI for returning structs by value requires that we copy
1693 // the sret argument into %rax for the return. Save the argument into
1694 // a virtual register so that we can access it from the return points.
1695 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1696 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1697 unsigned Reg = FuncInfo->getSRetReturnReg();
1699 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1700 FuncInfo->setSRetReturnReg(Reg);
1702 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1703 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1706 unsigned StackSize = CCInfo.getNextStackOffset();
1707 // Align stack specially for tail calls.
1708 if (FuncIsMadeTailCallSafe(CallConv))
1709 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1711 // If the function takes variable number of arguments, make a frame index for
1712 // the start of the first vararg value... for expansion of llvm.va_start.
1714 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1715 CallConv != CallingConv::X86_ThisCall)) {
1716 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1719 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1721 // FIXME: We should really autogenerate these arrays
1722 static const unsigned GPR64ArgRegsWin64[] = {
1723 X86::RCX, X86::RDX, X86::R8, X86::R9
1725 static const unsigned XMMArgRegsWin64[] = {
1726 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1728 static const unsigned GPR64ArgRegs64Bit[] = {
1729 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1731 static const unsigned XMMArgRegs64Bit[] = {
1732 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1733 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1735 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1738 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1739 GPR64ArgRegs = GPR64ArgRegsWin64;
1740 XMMArgRegs = XMMArgRegsWin64;
1742 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1743 GPR64ArgRegs = GPR64ArgRegs64Bit;
1744 XMMArgRegs = XMMArgRegs64Bit;
1746 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1748 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1751 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1752 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1753 "SSE register cannot be used when SSE is disabled!");
1754 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1755 "SSE register cannot be used when SSE is disabled!");
1756 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1757 // Kernel mode asks for SSE to be disabled, so don't push them
1759 TotalNumXMMRegs = 0;
1761 // For X86-64, if there are vararg parameters that are passed via
1762 // registers, then we must store them to their spots on the stack so they
1763 // may be loaded by deferencing the result of va_next.
1764 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1765 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1766 FuncInfo->setRegSaveFrameIndex(
1767 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1770 // Store the integer parameter registers.
1771 SmallVector<SDValue, 8> MemOps;
1772 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1774 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1775 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1776 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1777 DAG.getIntPtrConstant(Offset));
1778 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1779 X86::GR64RegisterClass);
1780 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1782 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1783 PseudoSourceValue::getFixedStack(
1784 FuncInfo->getRegSaveFrameIndex()),
1785 Offset, false, false, 0);
1786 MemOps.push_back(Store);
1790 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1791 // Now store the XMM (fp + vector) parameter registers.
1792 SmallVector<SDValue, 11> SaveXMMOps;
1793 SaveXMMOps.push_back(Chain);
1795 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1796 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1797 SaveXMMOps.push_back(ALVal);
1799 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1800 FuncInfo->getRegSaveFrameIndex()));
1801 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1802 FuncInfo->getVarArgsFPOffset()));
1804 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1805 unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1806 X86::VR128RegisterClass);
1807 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1808 SaveXMMOps.push_back(Val);
1810 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1812 &SaveXMMOps[0], SaveXMMOps.size()));
1815 if (!MemOps.empty())
1816 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1817 &MemOps[0], MemOps.size());
1821 // Some CCs need callee pop.
1822 if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1823 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1825 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1826 // If this is an sret function, the return should pop the hidden pointer.
1827 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1828 FuncInfo->setBytesToPopOnReturn(4);
1832 // RegSaveFrameIndex is X86-64 only.
1833 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1834 if (CallConv == CallingConv::X86_FastCall ||
1835 CallConv == CallingConv::X86_ThisCall)
1836 // fastcc functions can't have varargs.
1837 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1844 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1845 SDValue StackPtr, SDValue Arg,
1846 DebugLoc dl, SelectionDAG &DAG,
1847 const CCValAssign &VA,
1848 ISD::ArgFlagsTy Flags) const {
1849 const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1850 unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1851 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1852 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1853 if (Flags.isByVal()) {
1854 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1856 return DAG.getStore(Chain, dl, Arg, PtrOff,
1857 PseudoSourceValue::getStack(), LocMemOffset,
1861 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1862 /// optimization is performed and it is required.
1864 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1865 SDValue &OutRetAddr, SDValue Chain,
1866 bool IsTailCall, bool Is64Bit,
1867 int FPDiff, DebugLoc dl) const {
1868 // Adjust the Return address stack slot.
1869 EVT VT = getPointerTy();
1870 OutRetAddr = getReturnAddressFrameIndex(DAG);
1872 // Load the "old" Return address.
1873 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0, false, false, 0);
1874 return SDValue(OutRetAddr.getNode(), 1);
1877 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1878 /// optimization is performed and it is required (FPDiff!=0).
1880 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1881 SDValue Chain, SDValue RetAddrFrIdx,
1882 bool Is64Bit, int FPDiff, DebugLoc dl) {
1883 // Store the return address to the appropriate stack slot.
1884 if (!FPDiff) return Chain;
1885 // Calculate the new stack slot for the return address.
1886 int SlotSize = Is64Bit ? 8 : 4;
1887 int NewReturnAddrFI =
1888 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1889 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1890 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1891 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1892 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0,
1898 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1899 CallingConv::ID CallConv, bool isVarArg,
1901 const SmallVectorImpl<ISD::OutputArg> &Outs,
1902 const SmallVectorImpl<SDValue> &OutVals,
1903 const SmallVectorImpl<ISD::InputArg> &Ins,
1904 DebugLoc dl, SelectionDAG &DAG,
1905 SmallVectorImpl<SDValue> &InVals) const {
1906 MachineFunction &MF = DAG.getMachineFunction();
1907 bool Is64Bit = Subtarget->is64Bit();
1908 bool IsStructRet = CallIsStructReturn(Outs);
1909 bool IsSibcall = false;
1912 // Check if it's really possible to do a tail call.
1913 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1914 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1915 Outs, OutVals, Ins, DAG);
1917 // Sibcalls are automatically detected tailcalls which do not require
1919 if (!GuaranteedTailCallOpt && isTailCall)
1926 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1927 "Var args not supported with calling convention fastcc or ghc");
1929 // Analyze operands of the call, assigning locations to each operand.
1930 SmallVector<CCValAssign, 16> ArgLocs;
1931 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1932 ArgLocs, *DAG.getContext());
1933 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1935 // Get a count of how many bytes are to be pushed on the stack.
1936 unsigned NumBytes = CCInfo.getNextStackOffset();
1938 // This is a sibcall. The memory operands are available in caller's
1939 // own caller's stack.
1941 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1942 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1945 if (isTailCall && !IsSibcall) {
1946 // Lower arguments at fp - stackoffset + fpdiff.
1947 unsigned NumBytesCallerPushed =
1948 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1949 FPDiff = NumBytesCallerPushed - NumBytes;
1951 // Set the delta of movement of the returnaddr stackslot.
1952 // But only set if delta is greater than previous delta.
1953 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1954 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1958 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1960 SDValue RetAddrFrIdx;
1961 // Load return adress for tail calls.
1962 if (isTailCall && FPDiff)
1963 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1964 Is64Bit, FPDiff, dl);
1966 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1967 SmallVector<SDValue, 8> MemOpChains;
1970 // Walk the register/memloc assignments, inserting copies/loads. In the case
1971 // of tail call optimization arguments are handle later.
1972 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1973 CCValAssign &VA = ArgLocs[i];
1974 EVT RegVT = VA.getLocVT();
1975 SDValue Arg = OutVals[i];
1976 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1977 bool isByVal = Flags.isByVal();
1979 // Promote the value if needed.
1980 switch (VA.getLocInfo()) {
1981 default: llvm_unreachable("Unknown loc info!");
1982 case CCValAssign::Full: break;
1983 case CCValAssign::SExt:
1984 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1986 case CCValAssign::ZExt:
1987 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1989 case CCValAssign::AExt:
1990 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1991 // Special case: passing MMX values in XMM registers.
1992 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1993 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1994 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1996 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1998 case CCValAssign::BCvt:
1999 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
2001 case CCValAssign::Indirect: {
2002 // Store the argument.
2003 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2004 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2005 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2006 PseudoSourceValue::getFixedStack(FI), 0,
2013 if (VA.isRegLoc()) {
2014 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2015 if (isVarArg && Subtarget->isTargetWin64()) {
2016 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2017 // shadow reg if callee is a varargs function.
2018 unsigned ShadowReg = 0;
2019 switch (VA.getLocReg()) {
2020 case X86::XMM0: ShadowReg = X86::RCX; break;
2021 case X86::XMM1: ShadowReg = X86::RDX; break;
2022 case X86::XMM2: ShadowReg = X86::R8; break;
2023 case X86::XMM3: ShadowReg = X86::R9; break;
2026 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2028 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2029 assert(VA.isMemLoc());
2030 if (StackPtr.getNode() == 0)
2031 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2032 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2033 dl, DAG, VA, Flags));
2037 if (!MemOpChains.empty())
2038 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2039 &MemOpChains[0], MemOpChains.size());
2041 // Build a sequence of copy-to-reg nodes chained together with token chain
2042 // and flag operands which copy the outgoing args into registers.
2044 // Tail call byval lowering might overwrite argument registers so in case of
2045 // tail call optimization the copies to registers are lowered later.
2047 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2048 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2049 RegsToPass[i].second, InFlag);
2050 InFlag = Chain.getValue(1);
2053 if (Subtarget->isPICStyleGOT()) {
2054 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2057 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2058 DAG.getNode(X86ISD::GlobalBaseReg,
2059 DebugLoc(), getPointerTy()),
2061 InFlag = Chain.getValue(1);
2063 // If we are tail calling and generating PIC/GOT style code load the
2064 // address of the callee into ECX. The value in ecx is used as target of
2065 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2066 // for tail calls on PIC/GOT architectures. Normally we would just put the
2067 // address of GOT into ebx and then call target@PLT. But for tail calls
2068 // ebx would be restored (since ebx is callee saved) before jumping to the
2071 // Note: The actual moving to ECX is done further down.
2072 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2073 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2074 !G->getGlobal()->hasProtectedVisibility())
2075 Callee = LowerGlobalAddress(Callee, DAG);
2076 else if (isa<ExternalSymbolSDNode>(Callee))
2077 Callee = LowerExternalSymbol(Callee, DAG);
2081 if (Is64Bit && isVarArg && !Subtarget->isTargetWin64()) {
2082 // From AMD64 ABI document:
2083 // For calls that may call functions that use varargs or stdargs
2084 // (prototype-less calls or calls to functions containing ellipsis (...) in
2085 // the declaration) %al is used as hidden argument to specify the number
2086 // of SSE registers used. The contents of %al do not need to match exactly
2087 // the number of registers, but must be an ubound on the number of SSE
2088 // registers used and is in the range 0 - 8 inclusive.
2090 // Count the number of XMM registers allocated.
2091 static const unsigned XMMArgRegs[] = {
2092 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2093 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2095 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2096 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2097 && "SSE registers cannot be used when SSE is disabled");
2099 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2100 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2101 InFlag = Chain.getValue(1);
2105 // For tail calls lower the arguments to the 'real' stack slot.
2107 // Force all the incoming stack arguments to be loaded from the stack
2108 // before any new outgoing arguments are stored to the stack, because the
2109 // outgoing stack slots may alias the incoming argument stack slots, and
2110 // the alias isn't otherwise explicit. This is slightly more conservative
2111 // than necessary, because it means that each store effectively depends
2112 // on every argument instead of just those arguments it would clobber.
2113 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2115 SmallVector<SDValue, 8> MemOpChains2;
2118 // Do not flag preceeding copytoreg stuff together with the following stuff.
2120 if (GuaranteedTailCallOpt) {
2121 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2122 CCValAssign &VA = ArgLocs[i];
2125 assert(VA.isMemLoc());
2126 SDValue Arg = OutVals[i];
2127 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2128 // Create frame index.
2129 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2130 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2131 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2132 FIN = DAG.getFrameIndex(FI, getPointerTy());
2134 if (Flags.isByVal()) {
2135 // Copy relative to framepointer.
2136 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2137 if (StackPtr.getNode() == 0)
2138 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2140 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2142 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2146 // Store relative to framepointer.
2147 MemOpChains2.push_back(
2148 DAG.getStore(ArgChain, dl, Arg, FIN,
2149 PseudoSourceValue::getFixedStack(FI), 0,
2155 if (!MemOpChains2.empty())
2156 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2157 &MemOpChains2[0], MemOpChains2.size());
2159 // Copy arguments to their registers.
2160 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2161 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2162 RegsToPass[i].second, InFlag);
2163 InFlag = Chain.getValue(1);
2167 // Store the return address to the appropriate stack slot.
2168 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2172 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2173 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2174 // In the 64-bit large code model, we have to make all calls
2175 // through a register, since the call instruction's 32-bit
2176 // pc-relative offset may not be large enough to hold the whole
2178 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2179 // If the callee is a GlobalAddress node (quite common, every direct call
2180 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2183 // We should use extra load for direct calls to dllimported functions in
2185 const GlobalValue *GV = G->getGlobal();
2186 if (!GV->hasDLLImportLinkage()) {
2187 unsigned char OpFlags = 0;
2189 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2190 // external symbols most go through the PLT in PIC mode. If the symbol
2191 // has hidden or protected visibility, or if it is static or local, then
2192 // we don't need to use the PLT - we can directly call it.
2193 if (Subtarget->isTargetELF() &&
2194 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2195 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2196 OpFlags = X86II::MO_PLT;
2197 } else if (Subtarget->isPICStyleStubAny() &&
2198 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2199 Subtarget->getDarwinVers() < 9) {
2200 // PC-relative references to external symbols should go through $stub,
2201 // unless we're building with the leopard linker or later, which
2202 // automatically synthesizes these stubs.
2203 OpFlags = X86II::MO_DARWIN_STUB;
2206 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2207 G->getOffset(), OpFlags);
2209 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2210 unsigned char OpFlags = 0;
2212 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2213 // symbols should go through the PLT.
2214 if (Subtarget->isTargetELF() &&
2215 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2216 OpFlags = X86II::MO_PLT;
2217 } else if (Subtarget->isPICStyleStubAny() &&
2218 Subtarget->getDarwinVers() < 9) {
2219 // PC-relative references to external symbols should go through $stub,
2220 // unless we're building with the leopard linker or later, which
2221 // automatically synthesizes these stubs.
2222 OpFlags = X86II::MO_DARWIN_STUB;
2225 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2229 // Returns a chain & a flag for retval copy to use.
2230 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2231 SmallVector<SDValue, 8> Ops;
2233 if (!IsSibcall && isTailCall) {
2234 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2235 DAG.getIntPtrConstant(0, true), InFlag);
2236 InFlag = Chain.getValue(1);
2239 Ops.push_back(Chain);
2240 Ops.push_back(Callee);
2243 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2245 // Add argument registers to the end of the list so that they are known live
2247 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2248 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2249 RegsToPass[i].second.getValueType()));
2251 // Add an implicit use GOT pointer in EBX.
2252 if (!isTailCall && Subtarget->isPICStyleGOT())
2253 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2255 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2256 if (Is64Bit && isVarArg && !Subtarget->isTargetWin64())
2257 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2259 if (InFlag.getNode())
2260 Ops.push_back(InFlag);
2264 //// If this is the first return lowered for this function, add the regs
2265 //// to the liveout set for the function.
2266 // This isn't right, although it's probably harmless on x86; liveouts
2267 // should be computed from returns not tail calls. Consider a void
2268 // function making a tail call to a function returning int.
2269 return DAG.getNode(X86ISD::TC_RETURN, dl,
2270 NodeTys, &Ops[0], Ops.size());
2273 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2274 InFlag = Chain.getValue(1);
2276 // Create the CALLSEQ_END node.
2277 unsigned NumBytesForCalleeToPush;
2278 if (Subtarget->IsCalleePop(isVarArg, CallConv))
2279 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2280 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2281 // If this is a call to a struct-return function, the callee
2282 // pops the hidden struct pointer, so we have to push it back.
2283 // This is common for Darwin/X86, Linux & Mingw32 targets.
2284 NumBytesForCalleeToPush = 4;
2286 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2288 // Returns a flag for retval copy to use.
2290 Chain = DAG.getCALLSEQ_END(Chain,
2291 DAG.getIntPtrConstant(NumBytes, true),
2292 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2295 InFlag = Chain.getValue(1);
2298 // Handle result values, copying them out of physregs into vregs that we
2300 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2301 Ins, dl, DAG, InVals);
2305 //===----------------------------------------------------------------------===//
2306 // Fast Calling Convention (tail call) implementation
2307 //===----------------------------------------------------------------------===//
2309 // Like std call, callee cleans arguments, convention except that ECX is
2310 // reserved for storing the tail called function address. Only 2 registers are
2311 // free for argument passing (inreg). Tail call optimization is performed
2313 // * tailcallopt is enabled
2314 // * caller/callee are fastcc
2315 // On X86_64 architecture with GOT-style position independent code only local
2316 // (within module) calls are supported at the moment.
2317 // To keep the stack aligned according to platform abi the function
2318 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2319 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2320 // If a tail called function callee has more arguments than the caller the
2321 // caller needs to make sure that there is room to move the RETADDR to. This is
2322 // achieved by reserving an area the size of the argument delta right after the
2323 // original REtADDR, but before the saved framepointer or the spilled registers
2324 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2336 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2337 /// for a 16 byte align requirement.
2339 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2340 SelectionDAG& DAG) const {
2341 MachineFunction &MF = DAG.getMachineFunction();
2342 const TargetMachine &TM = MF.getTarget();
2343 const TargetFrameInfo &TFI = *TM.getFrameInfo();
2344 unsigned StackAlignment = TFI.getStackAlignment();
2345 uint64_t AlignMask = StackAlignment - 1;
2346 int64_t Offset = StackSize;
2347 uint64_t SlotSize = TD->getPointerSize();
2348 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2349 // Number smaller than 12 so just add the difference.
2350 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2352 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2353 Offset = ((~AlignMask) & Offset) + StackAlignment +
2354 (StackAlignment-SlotSize);
2359 /// MatchingStackOffset - Return true if the given stack call argument is
2360 /// already available in the same position (relatively) of the caller's
2361 /// incoming argument stack.
2363 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2364 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2365 const X86InstrInfo *TII) {
2366 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2368 if (Arg.getOpcode() == ISD::CopyFromReg) {
2369 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2370 if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2372 MachineInstr *Def = MRI->getVRegDef(VR);
2375 if (!Flags.isByVal()) {
2376 if (!TII->isLoadFromStackSlot(Def, FI))
2379 unsigned Opcode = Def->getOpcode();
2380 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2381 Def->getOperand(1).isFI()) {
2382 FI = Def->getOperand(1).getIndex();
2383 Bytes = Flags.getByValSize();
2387 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2388 if (Flags.isByVal())
2389 // ByVal argument is passed in as a pointer but it's now being
2390 // dereferenced. e.g.
2391 // define @foo(%struct.X* %A) {
2392 // tail call @bar(%struct.X* byval %A)
2395 SDValue Ptr = Ld->getBasePtr();
2396 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2399 FI = FINode->getIndex();
2403 assert(FI != INT_MAX);
2404 if (!MFI->isFixedObjectIndex(FI))
2406 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2409 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2410 /// for tail call optimization. Targets which want to do tail call
2411 /// optimization should implement this function.
2413 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2414 CallingConv::ID CalleeCC,
2416 bool isCalleeStructRet,
2417 bool isCallerStructRet,
2418 const SmallVectorImpl<ISD::OutputArg> &Outs,
2419 const SmallVectorImpl<SDValue> &OutVals,
2420 const SmallVectorImpl<ISD::InputArg> &Ins,
2421 SelectionDAG& DAG) const {
2422 if (!IsTailCallConvention(CalleeCC) &&
2423 CalleeCC != CallingConv::C)
2426 // If -tailcallopt is specified, make fastcc functions tail-callable.
2427 const MachineFunction &MF = DAG.getMachineFunction();
2428 const Function *CallerF = DAG.getMachineFunction().getFunction();
2429 CallingConv::ID CallerCC = CallerF->getCallingConv();
2430 bool CCMatch = CallerCC == CalleeCC;
2432 if (GuaranteedTailCallOpt) {
2433 if (IsTailCallConvention(CalleeCC) && CCMatch)
2438 // Look for obvious safe cases to perform tail call optimization that do not
2439 // require ABI changes. This is what gcc calls sibcall.
2441 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2442 // emit a special epilogue.
2443 if (RegInfo->needsStackRealignment(MF))
2446 // Do not sibcall optimize vararg calls unless the call site is not passing
2448 if (isVarArg && !Outs.empty())
2451 // Also avoid sibcall optimization if either caller or callee uses struct
2452 // return semantics.
2453 if (isCalleeStructRet || isCallerStructRet)
2456 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2457 // Therefore if it's not used by the call it is not safe to optimize this into
2459 bool Unused = false;
2460 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2467 SmallVector<CCValAssign, 16> RVLocs;
2468 CCState CCInfo(CalleeCC, false, getTargetMachine(),
2469 RVLocs, *DAG.getContext());
2470 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2471 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2472 CCValAssign &VA = RVLocs[i];
2473 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2478 // If the calling conventions do not match, then we'd better make sure the
2479 // results are returned in the same way as what the caller expects.
2481 SmallVector<CCValAssign, 16> RVLocs1;
2482 CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2483 RVLocs1, *DAG.getContext());
2484 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2486 SmallVector<CCValAssign, 16> RVLocs2;
2487 CCState CCInfo2(CallerCC, false, getTargetMachine(),
2488 RVLocs2, *DAG.getContext());
2489 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2491 if (RVLocs1.size() != RVLocs2.size())
2493 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2494 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2496 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2498 if (RVLocs1[i].isRegLoc()) {
2499 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2502 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2508 // If the callee takes no arguments then go on to check the results of the
2510 if (!Outs.empty()) {
2511 // Check if stack adjustment is needed. For now, do not do this if any
2512 // argument is passed on the stack.
2513 SmallVector<CCValAssign, 16> ArgLocs;
2514 CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2515 ArgLocs, *DAG.getContext());
2516 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
2517 if (CCInfo.getNextStackOffset()) {
2518 MachineFunction &MF = DAG.getMachineFunction();
2519 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2521 if (Subtarget->isTargetWin64())
2522 // Win64 ABI has additional complications.
2525 // Check if the arguments are already laid out in the right way as
2526 // the caller's fixed stack objects.
2527 MachineFrameInfo *MFI = MF.getFrameInfo();
2528 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2529 const X86InstrInfo *TII =
2530 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2531 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2532 CCValAssign &VA = ArgLocs[i];
2533 SDValue Arg = OutVals[i];
2534 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2535 if (VA.getLocInfo() == CCValAssign::Indirect)
2537 if (!VA.isRegLoc()) {
2538 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2545 // If the tailcall address may be in a register, then make sure it's
2546 // possible to register allocate for it. In 32-bit, the call address can
2547 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2548 // callee-saved registers are restored. These happen to be the same
2549 // registers used to pass 'inreg' arguments so watch out for those.
2550 if (!Subtarget->is64Bit() &&
2551 !isa<GlobalAddressSDNode>(Callee) &&
2552 !isa<ExternalSymbolSDNode>(Callee)) {
2553 unsigned NumInRegs = 0;
2554 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2555 CCValAssign &VA = ArgLocs[i];
2558 unsigned Reg = VA.getLocReg();
2561 case X86::EAX: case X86::EDX: case X86::ECX:
2562 if (++NumInRegs == 3)
2574 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2575 return X86::createFastISel(funcInfo);
2579 //===----------------------------------------------------------------------===//
2580 // Other Lowering Hooks
2581 //===----------------------------------------------------------------------===//
2583 static bool MayFoldLoad(SDValue Op) {
2584 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2587 static bool MayFoldIntoStore(SDValue Op) {
2588 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2591 static bool isTargetShuffle(unsigned Opcode) {
2593 default: return false;
2594 case X86ISD::PSHUFD:
2595 case X86ISD::PSHUFHW:
2596 case X86ISD::PSHUFLW:
2597 case X86ISD::SHUFPD:
2598 case X86ISD::PALIGN:
2599 case X86ISD::SHUFPS:
2600 case X86ISD::MOVLHPS:
2601 case X86ISD::MOVLHPD:
2602 case X86ISD::MOVHLPS:
2603 case X86ISD::MOVLPS:
2604 case X86ISD::MOVLPD:
2605 case X86ISD::MOVSHDUP:
2606 case X86ISD::MOVSLDUP:
2607 case X86ISD::MOVDDUP:
2610 case X86ISD::UNPCKLPS:
2611 case X86ISD::UNPCKLPD:
2612 case X86ISD::PUNPCKLWD:
2613 case X86ISD::PUNPCKLBW:
2614 case X86ISD::PUNPCKLDQ:
2615 case X86ISD::PUNPCKLQDQ:
2616 case X86ISD::UNPCKHPS:
2617 case X86ISD::UNPCKHPD:
2618 case X86ISD::PUNPCKHWD:
2619 case X86ISD::PUNPCKHBW:
2620 case X86ISD::PUNPCKHDQ:
2621 case X86ISD::PUNPCKHQDQ:
2627 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2628 SDValue V1, SelectionDAG &DAG) {
2630 default: llvm_unreachable("Unknown x86 shuffle node");
2631 case X86ISD::MOVSHDUP:
2632 case X86ISD::MOVSLDUP:
2633 case X86ISD::MOVDDUP:
2634 return DAG.getNode(Opc, dl, VT, V1);
2640 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2641 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2643 default: llvm_unreachable("Unknown x86 shuffle node");
2644 case X86ISD::PSHUFD:
2645 case X86ISD::PSHUFHW:
2646 case X86ISD::PSHUFLW:
2647 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2653 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2654 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2656 default: llvm_unreachable("Unknown x86 shuffle node");
2657 case X86ISD::PALIGN:
2658 case X86ISD::SHUFPD:
2659 case X86ISD::SHUFPS:
2660 return DAG.getNode(Opc, dl, VT, V1, V2,
2661 DAG.getConstant(TargetMask, MVT::i8));
2666 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2667 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2669 default: llvm_unreachable("Unknown x86 shuffle node");
2670 case X86ISD::MOVLHPS:
2671 case X86ISD::MOVLHPD:
2672 case X86ISD::MOVHLPS:
2673 case X86ISD::MOVLPS:
2674 case X86ISD::MOVLPD:
2677 case X86ISD::UNPCKLPS:
2678 case X86ISD::UNPCKLPD:
2679 case X86ISD::PUNPCKLWD:
2680 case X86ISD::PUNPCKLBW:
2681 case X86ISD::PUNPCKLDQ:
2682 case X86ISD::PUNPCKLQDQ:
2683 case X86ISD::UNPCKHPS:
2684 case X86ISD::UNPCKHPD:
2685 case X86ISD::PUNPCKHWD:
2686 case X86ISD::PUNPCKHBW:
2687 case X86ISD::PUNPCKHDQ:
2688 case X86ISD::PUNPCKHQDQ:
2689 return DAG.getNode(Opc, dl, VT, V1, V2);
2694 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2695 MachineFunction &MF = DAG.getMachineFunction();
2696 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2697 int ReturnAddrIndex = FuncInfo->getRAIndex();
2699 if (ReturnAddrIndex == 0) {
2700 // Set up a frame object for the return address.
2701 uint64_t SlotSize = TD->getPointerSize();
2702 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2704 FuncInfo->setRAIndex(ReturnAddrIndex);
2707 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2711 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2712 bool hasSymbolicDisplacement) {
2713 // Offset should fit into 32 bit immediate field.
2714 if (!isInt<32>(Offset))
2717 // If we don't have a symbolic displacement - we don't have any extra
2719 if (!hasSymbolicDisplacement)
2722 // FIXME: Some tweaks might be needed for medium code model.
2723 if (M != CodeModel::Small && M != CodeModel::Kernel)
2726 // For small code model we assume that latest object is 16MB before end of 31
2727 // bits boundary. We may also accept pretty large negative constants knowing
2728 // that all objects are in the positive half of address space.
2729 if (M == CodeModel::Small && Offset < 16*1024*1024)
2732 // For kernel code model we know that all object resist in the negative half
2733 // of 32bits address space. We may not accept negative offsets, since they may
2734 // be just off and we may accept pretty large positive ones.
2735 if (M == CodeModel::Kernel && Offset > 0)
2741 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2742 /// specific condition code, returning the condition code and the LHS/RHS of the
2743 /// comparison to make.
2744 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2745 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2747 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2748 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2749 // X > -1 -> X == 0, jump !sign.
2750 RHS = DAG.getConstant(0, RHS.getValueType());
2751 return X86::COND_NS;
2752 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2753 // X < 0 -> X == 0, jump on sign.
2755 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2757 RHS = DAG.getConstant(0, RHS.getValueType());
2758 return X86::COND_LE;
2762 switch (SetCCOpcode) {
2763 default: llvm_unreachable("Invalid integer condition!");
2764 case ISD::SETEQ: return X86::COND_E;
2765 case ISD::SETGT: return X86::COND_G;
2766 case ISD::SETGE: return X86::COND_GE;
2767 case ISD::SETLT: return X86::COND_L;
2768 case ISD::SETLE: return X86::COND_LE;
2769 case ISD::SETNE: return X86::COND_NE;
2770 case ISD::SETULT: return X86::COND_B;
2771 case ISD::SETUGT: return X86::COND_A;
2772 case ISD::SETULE: return X86::COND_BE;
2773 case ISD::SETUGE: return X86::COND_AE;
2777 // First determine if it is required or is profitable to flip the operands.
2779 // If LHS is a foldable load, but RHS is not, flip the condition.
2780 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2781 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2782 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2783 std::swap(LHS, RHS);
2786 switch (SetCCOpcode) {
2792 std::swap(LHS, RHS);
2796 // On a floating point condition, the flags are set as follows:
2798 // 0 | 0 | 0 | X > Y
2799 // 0 | 0 | 1 | X < Y
2800 // 1 | 0 | 0 | X == Y
2801 // 1 | 1 | 1 | unordered
2802 switch (SetCCOpcode) {
2803 default: llvm_unreachable("Condcode should be pre-legalized away");
2805 case ISD::SETEQ: return X86::COND_E;
2806 case ISD::SETOLT: // flipped
2808 case ISD::SETGT: return X86::COND_A;
2809 case ISD::SETOLE: // flipped
2811 case ISD::SETGE: return X86::COND_AE;
2812 case ISD::SETUGT: // flipped
2814 case ISD::SETLT: return X86::COND_B;
2815 case ISD::SETUGE: // flipped
2817 case ISD::SETLE: return X86::COND_BE;
2819 case ISD::SETNE: return X86::COND_NE;
2820 case ISD::SETUO: return X86::COND_P;
2821 case ISD::SETO: return X86::COND_NP;
2823 case ISD::SETUNE: return X86::COND_INVALID;
2827 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2828 /// code. Current x86 isa includes the following FP cmov instructions:
2829 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2830 static bool hasFPCMov(unsigned X86CC) {
2846 /// isFPImmLegal - Returns true if the target can instruction select the
2847 /// specified FP immediate natively. If false, the legalizer will
2848 /// materialize the FP immediate as a load from a constant pool.
2849 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2850 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2851 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2857 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2858 /// the specified range (L, H].
2859 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2860 return (Val < 0) || (Val >= Low && Val < Hi);
2863 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2864 /// specified value.
2865 static bool isUndefOrEqual(int Val, int CmpVal) {
2866 if (Val < 0 || Val == CmpVal)
2871 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2872 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2873 /// the second operand.
2874 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2875 if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2876 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2877 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2878 return (Mask[0] < 2 && Mask[1] < 2);
2882 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2883 SmallVector<int, 8> M;
2885 return ::isPSHUFDMask(M, N->getValueType(0));
2888 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2889 /// is suitable for input to PSHUFHW.
2890 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2891 if (VT != MVT::v8i16)
2894 // Lower quadword copied in order or undef.
2895 for (int i = 0; i != 4; ++i)
2896 if (Mask[i] >= 0 && Mask[i] != i)
2899 // Upper quadword shuffled.
2900 for (int i = 4; i != 8; ++i)
2901 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2907 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2908 SmallVector<int, 8> M;
2910 return ::isPSHUFHWMask(M, N->getValueType(0));
2913 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2914 /// is suitable for input to PSHUFLW.
2915 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2916 if (VT != MVT::v8i16)
2919 // Upper quadword copied in order.
2920 for (int i = 4; i != 8; ++i)
2921 if (Mask[i] >= 0 && Mask[i] != i)
2924 // Lower quadword shuffled.
2925 for (int i = 0; i != 4; ++i)
2932 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2933 SmallVector<int, 8> M;
2935 return ::isPSHUFLWMask(M, N->getValueType(0));
2938 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2939 /// is suitable for input to PALIGNR.
2940 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2942 int i, e = VT.getVectorNumElements();
2944 // Do not handle v2i64 / v2f64 shuffles with palignr.
2945 if (e < 4 || !hasSSSE3)
2948 for (i = 0; i != e; ++i)
2952 // All undef, not a palignr.
2956 // Determine if it's ok to perform a palignr with only the LHS, since we
2957 // don't have access to the actual shuffle elements to see if RHS is undef.
2958 bool Unary = Mask[i] < (int)e;
2959 bool NeedsUnary = false;
2961 int s = Mask[i] - i;
2963 // Check the rest of the elements to see if they are consecutive.
2964 for (++i; i != e; ++i) {
2969 Unary = Unary && (m < (int)e);
2970 NeedsUnary = NeedsUnary || (m < s);
2972 if (NeedsUnary && !Unary)
2974 if (Unary && m != ((s+i) & (e-1)))
2976 if (!Unary && m != (s+i))
2982 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2983 SmallVector<int, 8> M;
2985 return ::isPALIGNRMask(M, N->getValueType(0), true);
2988 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2989 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2990 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2991 int NumElems = VT.getVectorNumElements();
2992 if (NumElems != 2 && NumElems != 4)
2995 int Half = NumElems / 2;
2996 for (int i = 0; i < Half; ++i)
2997 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2999 for (int i = Half; i < NumElems; ++i)
3000 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3006 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3007 SmallVector<int, 8> M;
3009 return ::isSHUFPMask(M, N->getValueType(0));
3012 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3013 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3014 /// half elements to come from vector 1 (which would equal the dest.) and
3015 /// the upper half to come from vector 2.
3016 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3017 int NumElems = VT.getVectorNumElements();
3019 if (NumElems != 2 && NumElems != 4)
3022 int Half = NumElems / 2;
3023 for (int i = 0; i < Half; ++i)
3024 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3026 for (int i = Half; i < NumElems; ++i)
3027 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3032 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3033 SmallVector<int, 8> M;
3035 return isCommutedSHUFPMask(M, N->getValueType(0));
3038 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3039 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3040 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3041 if (N->getValueType(0).getVectorNumElements() != 4)
3044 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3045 return isUndefOrEqual(N->getMaskElt(0), 6) &&
3046 isUndefOrEqual(N->getMaskElt(1), 7) &&
3047 isUndefOrEqual(N->getMaskElt(2), 2) &&
3048 isUndefOrEqual(N->getMaskElt(3), 3);
3051 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3052 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3054 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3055 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3060 return isUndefOrEqual(N->getMaskElt(0), 2) &&
3061 isUndefOrEqual(N->getMaskElt(1), 3) &&
3062 isUndefOrEqual(N->getMaskElt(2), 2) &&
3063 isUndefOrEqual(N->getMaskElt(3), 3);
3066 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3067 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3068 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3069 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3071 if (NumElems != 2 && NumElems != 4)
3074 for (unsigned i = 0; i < NumElems/2; ++i)
3075 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3078 for (unsigned i = NumElems/2; i < NumElems; ++i)
3079 if (!isUndefOrEqual(N->getMaskElt(i), i))
3085 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3086 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3087 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3088 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3090 if (NumElems != 2 && NumElems != 4)
3093 for (unsigned i = 0; i < NumElems/2; ++i)
3094 if (!isUndefOrEqual(N->getMaskElt(i), i))
3097 for (unsigned i = 0; i < NumElems/2; ++i)
3098 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3104 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3105 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3106 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3107 bool V2IsSplat = false) {
3108 int NumElts = VT.getVectorNumElements();
3109 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3112 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3114 int BitI1 = Mask[i+1];
3115 if (!isUndefOrEqual(BitI, j))
3118 if (!isUndefOrEqual(BitI1, NumElts))
3121 if (!isUndefOrEqual(BitI1, j + NumElts))
3128 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3129 SmallVector<int, 8> M;
3131 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3134 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3135 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3136 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3137 bool V2IsSplat = false) {
3138 int NumElts = VT.getVectorNumElements();
3139 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3142 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3144 int BitI1 = Mask[i+1];
3145 if (!isUndefOrEqual(BitI, j + NumElts/2))
3148 if (isUndefOrEqual(BitI1, NumElts))
3151 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3158 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3159 SmallVector<int, 8> M;
3161 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3164 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3165 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3167 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3168 int NumElems = VT.getVectorNumElements();
3169 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3172 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
3174 int BitI1 = Mask[i+1];
3175 if (!isUndefOrEqual(BitI, j))
3177 if (!isUndefOrEqual(BitI1, j))
3183 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3184 SmallVector<int, 8> M;
3186 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3189 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3190 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3192 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3193 int NumElems = VT.getVectorNumElements();
3194 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3197 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3199 int BitI1 = Mask[i+1];
3200 if (!isUndefOrEqual(BitI, j))
3202 if (!isUndefOrEqual(BitI1, j))
3208 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3209 SmallVector<int, 8> M;
3211 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3214 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3215 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3216 /// MOVSD, and MOVD, i.e. setting the lowest element.
3217 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3218 if (VT.getVectorElementType().getSizeInBits() < 32)
3221 int NumElts = VT.getVectorNumElements();
3223 if (!isUndefOrEqual(Mask[0], NumElts))
3226 for (int i = 1; i < NumElts; ++i)
3227 if (!isUndefOrEqual(Mask[i], i))
3233 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3234 SmallVector<int, 8> M;
3236 return ::isMOVLMask(M, N->getValueType(0));
3239 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3240 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3241 /// element of vector 2 and the other elements to come from vector 1 in order.
3242 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3243 bool V2IsSplat = false, bool V2IsUndef = false) {
3244 int NumOps = VT.getVectorNumElements();
3245 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3248 if (!isUndefOrEqual(Mask[0], 0))
3251 for (int i = 1; i < NumOps; ++i)
3252 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3253 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3254 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3260 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3261 bool V2IsUndef = false) {
3262 SmallVector<int, 8> M;
3264 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3267 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3268 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3269 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3270 if (N->getValueType(0).getVectorNumElements() != 4)
3273 // Expect 1, 1, 3, 3
3274 for (unsigned i = 0; i < 2; ++i) {
3275 int Elt = N->getMaskElt(i);
3276 if (Elt >= 0 && Elt != 1)
3281 for (unsigned i = 2; i < 4; ++i) {
3282 int Elt = N->getMaskElt(i);
3283 if (Elt >= 0 && Elt != 3)
3288 // Don't use movshdup if it can be done with a shufps.
3289 // FIXME: verify that matching u, u, 3, 3 is what we want.
3293 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3294 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3295 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3296 if (N->getValueType(0).getVectorNumElements() != 4)
3299 // Expect 0, 0, 2, 2
3300 for (unsigned i = 0; i < 2; ++i)
3301 if (N->getMaskElt(i) > 0)
3305 for (unsigned i = 2; i < 4; ++i) {
3306 int Elt = N->getMaskElt(i);
3307 if (Elt >= 0 && Elt != 2)
3312 // Don't use movsldup if it can be done with a shufps.
3316 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3317 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3318 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3319 int e = N->getValueType(0).getVectorNumElements() / 2;
3321 for (int i = 0; i < e; ++i)
3322 if (!isUndefOrEqual(N->getMaskElt(i), i))
3324 for (int i = 0; i < e; ++i)
3325 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3330 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3331 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3332 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3333 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3334 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3336 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3338 for (int i = 0; i < NumOperands; ++i) {
3339 int Val = SVOp->getMaskElt(NumOperands-i-1);
3340 if (Val < 0) Val = 0;
3341 if (Val >= NumOperands) Val -= NumOperands;
3343 if (i != NumOperands - 1)
3349 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3350 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3351 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3352 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3354 // 8 nodes, but we only care about the last 4.
3355 for (unsigned i = 7; i >= 4; --i) {
3356 int Val = SVOp->getMaskElt(i);
3365 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3366 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3367 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3368 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3370 // 8 nodes, but we only care about the first 4.
3371 for (int i = 3; i >= 0; --i) {
3372 int Val = SVOp->getMaskElt(i);
3381 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3382 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3383 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3384 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3385 EVT VVT = N->getValueType(0);
3386 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3390 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3391 Val = SVOp->getMaskElt(i);
3395 return (Val - i) * EltSize;
3398 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3400 bool X86::isZeroNode(SDValue Elt) {
3401 return ((isa<ConstantSDNode>(Elt) &&
3402 cast<ConstantSDNode>(Elt)->isNullValue()) ||
3403 (isa<ConstantFPSDNode>(Elt) &&
3404 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3407 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3408 /// their permute mask.
3409 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3410 SelectionDAG &DAG) {
3411 EVT VT = SVOp->getValueType(0);
3412 unsigned NumElems = VT.getVectorNumElements();
3413 SmallVector<int, 8> MaskVec;
3415 for (unsigned i = 0; i != NumElems; ++i) {
3416 int idx = SVOp->getMaskElt(i);
3418 MaskVec.push_back(idx);
3419 else if (idx < (int)NumElems)
3420 MaskVec.push_back(idx + NumElems);
3422 MaskVec.push_back(idx - NumElems);
3424 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3425 SVOp->getOperand(0), &MaskVec[0]);
3428 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3429 /// the two vector operands have swapped position.
3430 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3431 unsigned NumElems = VT.getVectorNumElements();
3432 for (unsigned i = 0; i != NumElems; ++i) {
3436 else if (idx < (int)NumElems)
3437 Mask[i] = idx + NumElems;
3439 Mask[i] = idx - NumElems;
3443 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3444 /// match movhlps. The lower half elements should come from upper half of
3445 /// V1 (and in order), and the upper half elements should come from the upper
3446 /// half of V2 (and in order).
3447 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3448 if (Op->getValueType(0).getVectorNumElements() != 4)
3450 for (unsigned i = 0, e = 2; i != e; ++i)
3451 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3453 for (unsigned i = 2; i != 4; ++i)
3454 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3459 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3460 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3462 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3463 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3465 N = N->getOperand(0).getNode();
3466 if (!ISD::isNON_EXTLoad(N))
3469 *LD = cast<LoadSDNode>(N);
3473 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3474 /// match movlp{s|d}. The lower half elements should come from lower half of
3475 /// V1 (and in order), and the upper half elements should come from the upper
3476 /// half of V2 (and in order). And since V1 will become the source of the
3477 /// MOVLP, it must be either a vector load or a scalar load to vector.
3478 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3479 ShuffleVectorSDNode *Op) {
3480 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3482 // Is V2 is a vector load, don't do this transformation. We will try to use
3483 // load folding shufps op.
3484 if (ISD::isNON_EXTLoad(V2))
3487 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3489 if (NumElems != 2 && NumElems != 4)
3491 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3492 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3494 for (unsigned i = NumElems/2; i != NumElems; ++i)
3495 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3500 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3502 static bool isSplatVector(SDNode *N) {
3503 if (N->getOpcode() != ISD::BUILD_VECTOR)
3506 SDValue SplatValue = N->getOperand(0);
3507 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3508 if (N->getOperand(i) != SplatValue)
3513 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3514 /// to an zero vector.
3515 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3516 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3517 SDValue V1 = N->getOperand(0);
3518 SDValue V2 = N->getOperand(1);
3519 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3520 for (unsigned i = 0; i != NumElems; ++i) {
3521 int Idx = N->getMaskElt(i);
3522 if (Idx >= (int)NumElems) {
3523 unsigned Opc = V2.getOpcode();
3524 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3526 if (Opc != ISD::BUILD_VECTOR ||
3527 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3529 } else if (Idx >= 0) {
3530 unsigned Opc = V1.getOpcode();
3531 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3533 if (Opc != ISD::BUILD_VECTOR ||
3534 !X86::isZeroNode(V1.getOperand(Idx)))
3541 /// getZeroVector - Returns a vector of specified type with all zero elements.
3543 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3545 assert(VT.isVector() && "Expected a vector type");
3547 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted
3548 // to their dest type. This ensures they get CSE'd.
3550 if (VT.getSizeInBits() == 64) { // MMX
3551 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3552 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3553 } else if (VT.getSizeInBits() == 128) {
3554 if (HasSSE2) { // SSE2
3555 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3556 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3558 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3559 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3561 } else if (VT.getSizeInBits() == 256) { // AVX
3562 // 256-bit logic and arithmetic instructions in AVX are
3563 // all floating-point, no support for integer ops. Default
3564 // to emitting fp zeroed vectors then.
3565 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3566 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3567 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3569 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3572 /// getOnesVector - Returns a vector of specified type with all bits set.
3574 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3575 assert(VT.isVector() && "Expected a vector type");
3577 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3578 // type. This ensures they get CSE'd.
3579 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3581 if (VT.getSizeInBits() == 64) // MMX
3582 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3584 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3585 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3589 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3590 /// that point to V2 points to its first element.
3591 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3592 EVT VT = SVOp->getValueType(0);
3593 unsigned NumElems = VT.getVectorNumElements();
3595 bool Changed = false;
3596 SmallVector<int, 8> MaskVec;
3597 SVOp->getMask(MaskVec);
3599 for (unsigned i = 0; i != NumElems; ++i) {
3600 if (MaskVec[i] > (int)NumElems) {
3601 MaskVec[i] = NumElems;
3606 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3607 SVOp->getOperand(1), &MaskVec[0]);
3608 return SDValue(SVOp, 0);
3611 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3612 /// operation of specified width.
3613 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3615 unsigned NumElems = VT.getVectorNumElements();
3616 SmallVector<int, 8> Mask;
3617 Mask.push_back(NumElems);
3618 for (unsigned i = 1; i != NumElems; ++i)
3620 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3623 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3624 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3626 unsigned NumElems = VT.getVectorNumElements();
3627 SmallVector<int, 8> Mask;
3628 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3630 Mask.push_back(i + NumElems);
3632 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3635 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3636 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3638 unsigned NumElems = VT.getVectorNumElements();
3639 unsigned Half = NumElems/2;
3640 SmallVector<int, 8> Mask;
3641 for (unsigned i = 0; i != Half; ++i) {
3642 Mask.push_back(i + Half);
3643 Mask.push_back(i + NumElems + Half);
3645 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3648 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3649 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3650 EVT PVT = MVT::v4f32;
3651 EVT VT = SV->getValueType(0);
3652 DebugLoc dl = SV->getDebugLoc();
3653 SDValue V1 = SV->getOperand(0);
3654 int NumElems = VT.getVectorNumElements();
3655 int EltNo = SV->getSplatIndex();
3657 // unpack elements to the correct location
3658 while (NumElems > 4) {
3659 if (EltNo < NumElems/2) {
3660 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3662 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3663 EltNo -= NumElems/2;
3668 // Perform the splat.
3669 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3670 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3671 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3672 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3675 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3676 /// vector of zero or undef vector. This produces a shuffle where the low
3677 /// element of V2 is swizzled into the zero/undef vector, landing at element
3678 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3679 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3680 bool isZero, bool HasSSE2,
3681 SelectionDAG &DAG) {
3682 EVT VT = V2.getValueType();
3684 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3685 unsigned NumElems = VT.getVectorNumElements();
3686 SmallVector<int, 16> MaskVec;
3687 for (unsigned i = 0; i != NumElems; ++i)
3688 // If this is the insertion idx, put the low elt of V2 here.
3689 MaskVec.push_back(i == Idx ? NumElems : i);
3690 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3693 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3694 /// element of the result of the vector shuffle.
3695 SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3698 return SDValue(); // Limit search depth.
3700 SDValue V = SDValue(N, 0);
3701 EVT VT = V.getValueType();
3702 unsigned Opcode = V.getOpcode();
3704 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3705 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3706 Index = SV->getMaskElt(Index);
3709 return DAG.getUNDEF(VT.getVectorElementType());
3711 int NumElems = VT.getVectorNumElements();
3712 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3713 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3716 // Recurse into target specific vector shuffles to find scalars.
3717 if (isTargetShuffle(Opcode)) {
3718 int NumElems = VT.getVectorNumElements();
3719 SmallVector<unsigned, 16> ShuffleMask;
3723 case X86ISD::SHUFPS:
3724 case X86ISD::SHUFPD:
3725 ImmN = N->getOperand(N->getNumOperands()-1);
3726 DecodeSHUFPSMask(NumElems,
3727 cast<ConstantSDNode>(ImmN)->getZExtValue(),
3730 case X86ISD::PUNPCKHBW:
3731 case X86ISD::PUNPCKHWD:
3732 case X86ISD::PUNPCKHDQ:
3733 case X86ISD::PUNPCKHQDQ:
3734 DecodePUNPCKHMask(NumElems, ShuffleMask);
3736 case X86ISD::UNPCKHPS:
3737 case X86ISD::UNPCKHPD:
3738 DecodeUNPCKHPMask(NumElems, ShuffleMask);
3740 case X86ISD::PUNPCKLBW:
3741 case X86ISD::PUNPCKLWD:
3742 case X86ISD::PUNPCKLDQ:
3743 case X86ISD::PUNPCKLQDQ:
3744 DecodePUNPCKLMask(NumElems, ShuffleMask);
3746 case X86ISD::UNPCKLPS:
3747 case X86ISD::UNPCKLPD:
3748 DecodeUNPCKLPMask(NumElems, ShuffleMask);
3750 case X86ISD::MOVHLPS:
3751 DecodeMOVHLPSMask(NumElems, ShuffleMask);
3753 case X86ISD::MOVLHPS:
3754 DecodeMOVLHPSMask(NumElems, ShuffleMask);
3756 case X86ISD::PSHUFD:
3757 ImmN = N->getOperand(N->getNumOperands()-1);
3758 DecodePSHUFMask(NumElems,
3759 cast<ConstantSDNode>(ImmN)->getZExtValue(),
3762 case X86ISD::PSHUFHW:
3763 ImmN = N->getOperand(N->getNumOperands()-1);
3764 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3767 case X86ISD::PSHUFLW:
3768 ImmN = N->getOperand(N->getNumOperands()-1);
3769 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3773 case X86ISD::MOVSD: {
3774 // The index 0 always comes from the first element of the second source,
3775 // this is why MOVSS and MOVSD are used in the first place. The other
3776 // elements come from the other positions of the first source vector.
3777 unsigned OpNum = (Index == 0) ? 1 : 0;
3778 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
3782 assert("not implemented for target shuffle node");
3786 Index = ShuffleMask[Index];
3788 return DAG.getUNDEF(VT.getVectorElementType());
3790 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
3791 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
3795 // Actual nodes that may contain scalar elements
3796 if (Opcode == ISD::BIT_CONVERT) {
3797 V = V.getOperand(0);
3798 EVT SrcVT = V.getValueType();
3799 unsigned NumElems = VT.getVectorNumElements();
3801 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
3805 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
3806 return (Index == 0) ? V.getOperand(0)
3807 : DAG.getUNDEF(VT.getVectorElementType());
3809 if (V.getOpcode() == ISD::BUILD_VECTOR)
3810 return V.getOperand(Index);
3815 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
3816 /// shuffle operation which come from a consecutively from a zero. The
3817 /// search can start in two diferent directions, from left or right.
3819 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
3820 bool ZerosFromLeft, SelectionDAG &DAG) {
3823 while (i < NumElems) {
3824 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
3825 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
3826 if (!(Elt.getNode() &&
3827 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
3835 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
3836 /// MaskE correspond consecutively to elements from one of the vector operands,
3837 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
3839 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
3840 int OpIdx, int NumElems, unsigned &OpNum) {
3841 bool SeenV1 = false;
3842 bool SeenV2 = false;
3844 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
3845 int Idx = SVOp->getMaskElt(i);
3846 // Ignore undef indicies
3855 // Only accept consecutive elements from the same vector
3856 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
3860 OpNum = SeenV1 ? 0 : 1;
3864 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
3865 /// logical left shift of a vector.
3866 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3867 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3868 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3869 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3870 false /* check zeros from right */, DAG);
3876 // Considering the elements in the mask that are not consecutive zeros,
3877 // check if they consecutively come from only one of the source vectors.
3879 // V1 = {X, A, B, C} 0
3881 // vector_shuffle V1, V2 <1, 2, 3, X>
3883 if (!isShuffleMaskConsecutive(SVOp,
3884 0, // Mask Start Index
3885 NumElems-NumZeros-1, // Mask End Index
3886 NumZeros, // Where to start looking in the src vector
3887 NumElems, // Number of elements in vector
3888 OpSrc)) // Which source operand ?
3893 ShVal = SVOp->getOperand(OpSrc);
3897 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
3898 /// logical left shift of a vector.
3899 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3900 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3901 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3902 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3903 true /* check zeros from left */, DAG);
3909 // Considering the elements in the mask that are not consecutive zeros,
3910 // check if they consecutively come from only one of the source vectors.
3912 // 0 { A, B, X, X } = V2
3914 // vector_shuffle V1, V2 <X, X, 4, 5>
3916 if (!isShuffleMaskConsecutive(SVOp,
3917 NumZeros, // Mask Start Index
3918 NumElems-1, // Mask End Index
3919 0, // Where to start looking in the src vector
3920 NumElems, // Number of elements in vector
3921 OpSrc)) // Which source operand ?
3926 ShVal = SVOp->getOperand(OpSrc);
3930 /// isVectorShift - Returns true if the shuffle can be implemented as a
3931 /// logical left or right shift of a vector.
3932 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3933 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3934 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
3935 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
3941 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3943 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3944 unsigned NumNonZero, unsigned NumZero,
3946 const TargetLowering &TLI) {
3950 DebugLoc dl = Op.getDebugLoc();
3953 for (unsigned i = 0; i < 16; ++i) {
3954 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3955 if (ThisIsNonZero && First) {
3957 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3959 V = DAG.getUNDEF(MVT::v8i16);
3964 SDValue ThisElt(0, 0), LastElt(0, 0);
3965 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3966 if (LastIsNonZero) {
3967 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3968 MVT::i16, Op.getOperand(i-1));
3970 if (ThisIsNonZero) {
3971 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3972 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3973 ThisElt, DAG.getConstant(8, MVT::i8));
3975 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3979 if (ThisElt.getNode())
3980 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3981 DAG.getIntPtrConstant(i/2));
3985 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3988 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3990 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3991 unsigned NumNonZero, unsigned NumZero,
3993 const TargetLowering &TLI) {
3997 DebugLoc dl = Op.getDebugLoc();
4000 for (unsigned i = 0; i < 8; ++i) {
4001 bool isNonZero = (NonZeros & (1 << i)) != 0;
4005 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4007 V = DAG.getUNDEF(MVT::v8i16);
4010 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4011 MVT::v8i16, V, Op.getOperand(i),
4012 DAG.getIntPtrConstant(i));
4019 /// getVShift - Return a vector logical shift node.
4021 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4022 unsigned NumBits, SelectionDAG &DAG,
4023 const TargetLowering &TLI, DebugLoc dl) {
4024 bool isMMX = VT.getSizeInBits() == 64;
4025 EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
4026 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4027 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
4028 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4029 DAG.getNode(Opc, dl, ShVT, SrcOp,
4030 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
4034 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4035 SelectionDAG &DAG) const {
4037 // Check if the scalar load can be widened into a vector load. And if
4038 // the address is "base + cst" see if the cst can be "absorbed" into
4039 // the shuffle mask.
4040 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4041 SDValue Ptr = LD->getBasePtr();
4042 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4044 EVT PVT = LD->getValueType(0);
4045 if (PVT != MVT::i32 && PVT != MVT::f32)
4050 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4051 FI = FINode->getIndex();
4053 } else if (Ptr.getOpcode() == ISD::ADD &&
4054 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
4055 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4056 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4057 Offset = Ptr.getConstantOperandVal(1);
4058 Ptr = Ptr.getOperand(0);
4063 SDValue Chain = LD->getChain();
4064 // Make sure the stack object alignment is at least 16.
4065 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4066 if (DAG.InferPtrAlignment(Ptr) < 16) {
4067 if (MFI->isFixedObjectIndex(FI)) {
4068 // Can't change the alignment. FIXME: It's possible to compute
4069 // the exact stack offset and reference FI + adjust offset instead.
4070 // If someone *really* cares about this. That's the way to implement it.
4073 MFI->setObjectAlignment(FI, 16);
4077 // (Offset % 16) must be multiple of 4. Then address is then
4078 // Ptr + (Offset & ~15).
4081 if ((Offset % 16) & 3)
4083 int64_t StartOffset = Offset & ~15;
4085 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4086 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4088 int EltNo = (Offset - StartOffset) >> 2;
4089 int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4090 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4091 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,LD->getSrcValue(),0,
4093 // Canonicalize it to a v4i32 shuffle.
4094 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
4095 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4096 DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4097 DAG.getUNDEF(MVT::v4i32), &Mask[0]));
4103 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4104 /// vector of type 'VT', see if the elements can be replaced by a single large
4105 /// load which has the same value as a build_vector whose operands are 'elts'.
4107 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4109 /// FIXME: we'd also like to handle the case where the last elements are zero
4110 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4111 /// There's even a handy isZeroNode for that purpose.
4112 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4113 DebugLoc &dl, SelectionDAG &DAG) {
4114 EVT EltVT = VT.getVectorElementType();
4115 unsigned NumElems = Elts.size();
4117 LoadSDNode *LDBase = NULL;
4118 unsigned LastLoadedElt = -1U;
4120 // For each element in the initializer, see if we've found a load or an undef.
4121 // If we don't find an initial load element, or later load elements are
4122 // non-consecutive, bail out.
4123 for (unsigned i = 0; i < NumElems; ++i) {
4124 SDValue Elt = Elts[i];
4126 if (!Elt.getNode() ||
4127 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4130 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4132 LDBase = cast<LoadSDNode>(Elt.getNode());
4136 if (Elt.getOpcode() == ISD::UNDEF)
4139 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4140 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4145 // If we have found an entire vector of loads and undefs, then return a large
4146 // load of the entire vector width starting at the base pointer. If we found
4147 // consecutive loads for the low half, generate a vzext_load node.
4148 if (LastLoadedElt == NumElems - 1) {
4149 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4150 return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
4151 LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
4152 LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4153 return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
4154 LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
4155 LDBase->isVolatile(), LDBase->isNonTemporal(),
4156 LDBase->getAlignment());
4157 } else if (NumElems == 4 && LastLoadedElt == 1) {
4158 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4159 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4160 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
4161 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
4167 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4168 DebugLoc dl = Op.getDebugLoc();
4169 // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4170 // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4171 // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4172 // is present, so AllOnes is ignored.
4173 if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4174 (Op.getValueType().getSizeInBits() != 256 &&
4175 ISD::isBuildVectorAllOnes(Op.getNode()))) {
4176 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
4177 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4178 // eliminated on x86-32 hosts.
4179 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
4182 if (ISD::isBuildVectorAllOnes(Op.getNode()))
4183 return getOnesVector(Op.getValueType(), DAG, dl);
4184 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4187 EVT VT = Op.getValueType();
4188 EVT ExtVT = VT.getVectorElementType();
4189 unsigned EVTBits = ExtVT.getSizeInBits();
4191 unsigned NumElems = Op.getNumOperands();
4192 unsigned NumZero = 0;
4193 unsigned NumNonZero = 0;
4194 unsigned NonZeros = 0;
4195 bool IsAllConstants = true;
4196 SmallSet<SDValue, 8> Values;
4197 for (unsigned i = 0; i < NumElems; ++i) {
4198 SDValue Elt = Op.getOperand(i);
4199 if (Elt.getOpcode() == ISD::UNDEF)
4202 if (Elt.getOpcode() != ISD::Constant &&
4203 Elt.getOpcode() != ISD::ConstantFP)
4204 IsAllConstants = false;
4205 if (X86::isZeroNode(Elt))
4208 NonZeros |= (1 << i);
4213 // All undef vector. Return an UNDEF. All zero vectors were handled above.
4214 if (NumNonZero == 0)
4215 return DAG.getUNDEF(VT);
4217 // Special case for single non-zero, non-undef, element.
4218 if (NumNonZero == 1) {
4219 unsigned Idx = CountTrailingZeros_32(NonZeros);
4220 SDValue Item = Op.getOperand(Idx);
4222 // If this is an insertion of an i64 value on x86-32, and if the top bits of
4223 // the value are obviously zero, truncate the value to i32 and do the
4224 // insertion that way. Only do this if the value is non-constant or if the
4225 // value is a constant being inserted into element 0. It is cheaper to do
4226 // a constant pool load than it is to do a movd + shuffle.
4227 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4228 (!IsAllConstants || Idx == 0)) {
4229 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4230 // Handle MMX and SSE both.
4231 EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
4232 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
4234 // Truncate the value (which may itself be a constant) to i32, and
4235 // convert it to a vector with movd (S2V+shuffle to zero extend).
4236 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4237 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4238 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4239 Subtarget->hasSSE2(), DAG);
4241 // Now we have our 32-bit value zero extended in the low element of
4242 // a vector. If Idx != 0, swizzle it into place.
4244 SmallVector<int, 4> Mask;
4245 Mask.push_back(Idx);
4246 for (unsigned i = 1; i != VecElts; ++i)
4248 Item = DAG.getVectorShuffle(VecVT, dl, Item,
4249 DAG.getUNDEF(Item.getValueType()),
4252 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
4256 // If we have a constant or non-constant insertion into the low element of
4257 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4258 // the rest of the elements. This will be matched as movd/movq/movss/movsd
4259 // depending on what the source datatype is.
4262 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4263 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4264 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4265 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4266 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4267 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4269 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4270 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4271 EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
4272 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4273 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4274 Subtarget->hasSSE2(), DAG);
4275 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
4279 // Is it a vector logical left shift?
4280 if (NumElems == 2 && Idx == 1 &&
4281 X86::isZeroNode(Op.getOperand(0)) &&
4282 !X86::isZeroNode(Op.getOperand(1))) {
4283 unsigned NumBits = VT.getSizeInBits();
4284 return getVShift(true, VT,
4285 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4286 VT, Op.getOperand(1)),
4287 NumBits/2, DAG, *this, dl);
4290 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4293 // Otherwise, if this is a vector with i32 or f32 elements, and the element
4294 // is a non-constant being inserted into an element other than the low one,
4295 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
4296 // movd/movss) to move this into the low element, then shuffle it into
4298 if (EVTBits == 32) {
4299 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4301 // Turn it into a shuffle of zero and zero-extended scalar to vector.
4302 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4303 Subtarget->hasSSE2(), DAG);
4304 SmallVector<int, 8> MaskVec;
4305 for (unsigned i = 0; i < NumElems; i++)
4306 MaskVec.push_back(i == Idx ? 0 : 1);
4307 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4311 // Splat is obviously ok. Let legalizer expand it to a shuffle.
4312 if (Values.size() == 1) {
4313 if (EVTBits == 32) {
4314 // Instead of a shuffle like this:
4315 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4316 // Check if it's possible to issue this instead.
4317 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4318 unsigned Idx = CountTrailingZeros_32(NonZeros);
4319 SDValue Item = Op.getOperand(Idx);
4320 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4321 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4326 // A vector full of immediates; various special cases are already
4327 // handled, so this is best done with a single constant-pool load.
4331 // Let legalizer expand 2-wide build_vectors.
4332 if (EVTBits == 64) {
4333 if (NumNonZero == 1) {
4334 // One half is zero or undef.
4335 unsigned Idx = CountTrailingZeros_32(NonZeros);
4336 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4337 Op.getOperand(Idx));
4338 return getShuffleVectorZeroOrUndef(V2, Idx, true,
4339 Subtarget->hasSSE2(), DAG);
4344 // If element VT is < 32 bits, convert it to inserts into a zero vector.
4345 if (EVTBits == 8 && NumElems == 16) {
4346 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4348 if (V.getNode()) return V;
4351 if (EVTBits == 16 && NumElems == 8) {
4352 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4354 if (V.getNode()) return V;
4357 // If element VT is == 32 bits, turn it into a number of shuffles.
4358 SmallVector<SDValue, 8> V;
4360 if (NumElems == 4 && NumZero > 0) {
4361 for (unsigned i = 0; i < 4; ++i) {
4362 bool isZero = !(NonZeros & (1 << i));
4364 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4366 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4369 for (unsigned i = 0; i < 2; ++i) {
4370 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4373 V[i] = V[i*2]; // Must be a zero vector.
4376 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4379 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4382 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4387 SmallVector<int, 8> MaskVec;
4388 bool Reverse = (NonZeros & 0x3) == 2;
4389 for (unsigned i = 0; i < 2; ++i)
4390 MaskVec.push_back(Reverse ? 1-i : i);
4391 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4392 for (unsigned i = 0; i < 2; ++i)
4393 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4394 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4397 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4398 // Check for a build vector of consecutive loads.
4399 for (unsigned i = 0; i < NumElems; ++i)
4400 V[i] = Op.getOperand(i);
4402 // Check for elements which are consecutive loads.
4403 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4407 // For SSE 4.1, use insertps to put the high elements into the low element.
4408 if (getSubtarget()->hasSSE41()) {
4410 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4411 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4413 Result = DAG.getUNDEF(VT);
4415 for (unsigned i = 1; i < NumElems; ++i) {
4416 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4417 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4418 Op.getOperand(i), DAG.getIntPtrConstant(i));
4423 // Otherwise, expand into a number of unpckl*, start by extending each of
4424 // our (non-undef) elements to the full vector width with the element in the
4425 // bottom slot of the vector (which generates no code for SSE).
4426 for (unsigned i = 0; i < NumElems; ++i) {
4427 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4428 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4430 V[i] = DAG.getUNDEF(VT);
4433 // Next, we iteratively mix elements, e.g. for v4f32:
4434 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4435 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4436 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
4437 unsigned EltStride = NumElems >> 1;
4438 while (EltStride != 0) {
4439 for (unsigned i = 0; i < EltStride; ++i) {
4440 // If V[i+EltStride] is undef and this is the first round of mixing,
4441 // then it is safe to just drop this shuffle: V[i] is already in the
4442 // right place, the one element (since it's the first round) being
4443 // inserted as undef can be dropped. This isn't safe for successive
4444 // rounds because they will permute elements within both vectors.
4445 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4446 EltStride == NumElems/2)
4449 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4459 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4460 // We support concatenate two MMX registers and place them in a MMX
4461 // register. This is better than doing a stack convert.
4462 DebugLoc dl = Op.getDebugLoc();
4463 EVT ResVT = Op.getValueType();
4464 assert(Op.getNumOperands() == 2);
4465 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4466 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4468 SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
4469 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4470 InVec = Op.getOperand(1);
4471 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4472 unsigned NumElts = ResVT.getVectorNumElements();
4473 VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4474 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4475 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4477 InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
4478 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4479 Mask[0] = 0; Mask[1] = 2;
4480 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4482 return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4485 // v8i16 shuffles - Prefer shuffles in the following order:
4486 // 1. [all] pshuflw, pshufhw, optional move
4487 // 2. [ssse3] 1 x pshufb
4488 // 3. [ssse3] 2 x pshufb + 1 x por
4489 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4491 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4492 SelectionDAG &DAG) const {
4493 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4494 SDValue V1 = SVOp->getOperand(0);
4495 SDValue V2 = SVOp->getOperand(1);
4496 DebugLoc dl = SVOp->getDebugLoc();
4497 SmallVector<int, 8> MaskVals;
4499 // Determine if more than 1 of the words in each of the low and high quadwords
4500 // of the result come from the same quadword of one of the two inputs. Undef
4501 // mask values count as coming from any quadword, for better codegen.
4502 SmallVector<unsigned, 4> LoQuad(4);
4503 SmallVector<unsigned, 4> HiQuad(4);
4504 BitVector InputQuads(4);
4505 for (unsigned i = 0; i < 8; ++i) {
4506 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4507 int EltIdx = SVOp->getMaskElt(i);
4508 MaskVals.push_back(EltIdx);
4517 InputQuads.set(EltIdx / 4);
4520 int BestLoQuad = -1;
4521 unsigned MaxQuad = 1;
4522 for (unsigned i = 0; i < 4; ++i) {
4523 if (LoQuad[i] > MaxQuad) {
4525 MaxQuad = LoQuad[i];
4529 int BestHiQuad = -1;
4531 for (unsigned i = 0; i < 4; ++i) {
4532 if (HiQuad[i] > MaxQuad) {
4534 MaxQuad = HiQuad[i];
4538 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4539 // of the two input vectors, shuffle them into one input vector so only a
4540 // single pshufb instruction is necessary. If There are more than 2 input
4541 // quads, disable the next transformation since it does not help SSSE3.
4542 bool V1Used = InputQuads[0] || InputQuads[1];
4543 bool V2Used = InputQuads[2] || InputQuads[3];
4544 if (Subtarget->hasSSSE3()) {
4545 if (InputQuads.count() == 2 && V1Used && V2Used) {
4546 BestLoQuad = InputQuads.find_first();
4547 BestHiQuad = InputQuads.find_next(BestLoQuad);
4549 if (InputQuads.count() > 2) {
4555 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4556 // the shuffle mask. If a quad is scored as -1, that means that it contains
4557 // words from all 4 input quadwords.
4559 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4560 SmallVector<int, 8> MaskV;
4561 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4562 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4563 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4564 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
4565 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
4566 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
4568 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4569 // source words for the shuffle, to aid later transformations.
4570 bool AllWordsInNewV = true;
4571 bool InOrder[2] = { true, true };
4572 for (unsigned i = 0; i != 8; ++i) {
4573 int idx = MaskVals[i];
4575 InOrder[i/4] = false;
4576 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4578 AllWordsInNewV = false;
4582 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4583 if (AllWordsInNewV) {
4584 for (int i = 0; i != 8; ++i) {
4585 int idx = MaskVals[i];
4588 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4589 if ((idx != i) && idx < 4)
4591 if ((idx != i) && idx > 3)
4600 // If we've eliminated the use of V2, and the new mask is a pshuflw or
4601 // pshufhw, that's as cheap as it gets. Return the new shuffle.
4602 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4603 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4604 unsigned TargetMask = 0;
4605 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4606 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4607 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4608 X86::getShufflePSHUFLWImmediate(NewV.getNode());
4609 V1 = NewV.getOperand(0);
4610 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4614 // If we have SSSE3, and all words of the result are from 1 input vector,
4615 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
4616 // is present, fall back to case 4.
4617 if (Subtarget->hasSSSE3()) {
4618 SmallVector<SDValue,16> pshufbMask;
4620 // If we have elements from both input vectors, set the high bit of the
4621 // shuffle mask element to zero out elements that come from V2 in the V1
4622 // mask, and elements that come from V1 in the V2 mask, so that the two
4623 // results can be OR'd together.
4624 bool TwoInputs = V1Used && V2Used;
4625 for (unsigned i = 0; i != 8; ++i) {
4626 int EltIdx = MaskVals[i] * 2;
4627 if (TwoInputs && (EltIdx >= 16)) {
4628 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4629 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4632 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4633 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4635 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
4636 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4637 DAG.getNode(ISD::BUILD_VECTOR, dl,
4638 MVT::v16i8, &pshufbMask[0], 16));
4640 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4642 // Calculate the shuffle mask for the second input, shuffle it, and
4643 // OR it with the first shuffled input.
4645 for (unsigned i = 0; i != 8; ++i) {
4646 int EltIdx = MaskVals[i] * 2;
4648 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4649 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4652 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4653 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4655 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
4656 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4657 DAG.getNode(ISD::BUILD_VECTOR, dl,
4658 MVT::v16i8, &pshufbMask[0], 16));
4659 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4660 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4663 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4664 // and update MaskVals with new element order.
4665 BitVector InOrder(8);
4666 if (BestLoQuad >= 0) {
4667 SmallVector<int, 8> MaskV;
4668 for (int i = 0; i != 4; ++i) {
4669 int idx = MaskVals[i];
4671 MaskV.push_back(-1);
4673 } else if ((idx / 4) == BestLoQuad) {
4674 MaskV.push_back(idx & 3);
4677 MaskV.push_back(-1);
4680 for (unsigned i = 4; i != 8; ++i)
4682 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4685 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4686 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4688 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4692 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4693 // and update MaskVals with the new element order.
4694 if (BestHiQuad >= 0) {
4695 SmallVector<int, 8> MaskV;
4696 for (unsigned i = 0; i != 4; ++i)
4698 for (unsigned i = 4; i != 8; ++i) {
4699 int idx = MaskVals[i];
4701 MaskV.push_back(-1);
4703 } else if ((idx / 4) == BestHiQuad) {
4704 MaskV.push_back((idx & 3) + 4);
4707 MaskV.push_back(-1);
4710 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4713 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4714 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
4716 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
4720 // In case BestHi & BestLo were both -1, which means each quadword has a word
4721 // from each of the four input quadwords, calculate the InOrder bitvector now
4722 // before falling through to the insert/extract cleanup.
4723 if (BestLoQuad == -1 && BestHiQuad == -1) {
4725 for (int i = 0; i != 8; ++i)
4726 if (MaskVals[i] < 0 || MaskVals[i] == i)
4730 // The other elements are put in the right place using pextrw and pinsrw.
4731 for (unsigned i = 0; i != 8; ++i) {
4734 int EltIdx = MaskVals[i];
4737 SDValue ExtOp = (EltIdx < 8)
4738 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4739 DAG.getIntPtrConstant(EltIdx))
4740 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4741 DAG.getIntPtrConstant(EltIdx - 8));
4742 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4743 DAG.getIntPtrConstant(i));
4748 // v16i8 shuffles - Prefer shuffles in the following order:
4749 // 1. [ssse3] 1 x pshufb
4750 // 2. [ssse3] 2 x pshufb + 1 x por
4751 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
4753 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4755 const X86TargetLowering &TLI) {
4756 SDValue V1 = SVOp->getOperand(0);
4757 SDValue V2 = SVOp->getOperand(1);
4758 DebugLoc dl = SVOp->getDebugLoc();
4759 SmallVector<int, 16> MaskVals;
4760 SVOp->getMask(MaskVals);
4762 // If we have SSSE3, case 1 is generated when all result bytes come from
4763 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
4764 // present, fall back to case 3.
4765 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4768 for (unsigned i = 0; i < 16; ++i) {
4769 int EltIdx = MaskVals[i];
4778 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4779 if (TLI.getSubtarget()->hasSSSE3()) {
4780 SmallVector<SDValue,16> pshufbMask;
4782 // If all result elements are from one input vector, then only translate
4783 // undef mask values to 0x80 (zero out result) in the pshufb mask.
4785 // Otherwise, we have elements from both input vectors, and must zero out
4786 // elements that come from V2 in the first mask, and V1 in the second mask
4787 // so that we can OR them together.
4788 bool TwoInputs = !(V1Only || V2Only);
4789 for (unsigned i = 0; i != 16; ++i) {
4790 int EltIdx = MaskVals[i];
4791 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4792 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4795 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4797 // If all the elements are from V2, assign it to V1 and return after
4798 // building the first pshufb.
4801 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4802 DAG.getNode(ISD::BUILD_VECTOR, dl,
4803 MVT::v16i8, &pshufbMask[0], 16));
4807 // Calculate the shuffle mask for the second input, shuffle it, and
4808 // OR it with the first shuffled input.
4810 for (unsigned i = 0; i != 16; ++i) {
4811 int EltIdx = MaskVals[i];
4813 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4816 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4818 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4819 DAG.getNode(ISD::BUILD_VECTOR, dl,
4820 MVT::v16i8, &pshufbMask[0], 16));
4821 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4824 // No SSSE3 - Calculate in place words and then fix all out of place words
4825 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
4826 // the 16 different words that comprise the two doublequadword input vectors.
4827 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4828 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4829 SDValue NewV = V2Only ? V2 : V1;
4830 for (int i = 0; i != 8; ++i) {
4831 int Elt0 = MaskVals[i*2];
4832 int Elt1 = MaskVals[i*2+1];
4834 // This word of the result is all undef, skip it.
4835 if (Elt0 < 0 && Elt1 < 0)
4838 // This word of the result is already in the correct place, skip it.
4839 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4841 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4844 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4845 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4848 // If Elt0 and Elt1 are defined, are consecutive, and can be load
4849 // using a single extract together, load it and store it.
4850 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4851 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4852 DAG.getIntPtrConstant(Elt1 / 2));
4853 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4854 DAG.getIntPtrConstant(i));
4858 // If Elt1 is defined, extract it from the appropriate source. If the
4859 // source byte is not also odd, shift the extracted word left 8 bits
4860 // otherwise clear the bottom 8 bits if we need to do an or.
4862 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4863 DAG.getIntPtrConstant(Elt1 / 2));
4864 if ((Elt1 & 1) == 0)
4865 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4866 DAG.getConstant(8, TLI.getShiftAmountTy()));
4868 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4869 DAG.getConstant(0xFF00, MVT::i16));
4871 // If Elt0 is defined, extract it from the appropriate source. If the
4872 // source byte is not also even, shift the extracted word right 8 bits. If
4873 // Elt1 was also defined, OR the extracted values together before
4874 // inserting them in the result.
4876 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4877 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4878 if ((Elt0 & 1) != 0)
4879 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4880 DAG.getConstant(8, TLI.getShiftAmountTy()));
4882 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4883 DAG.getConstant(0x00FF, MVT::i16));
4884 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4887 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4888 DAG.getIntPtrConstant(i));
4890 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4893 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4894 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
4895 /// done when every pair / quad of shuffle mask elements point to elements in
4896 /// the right sequence. e.g.
4897 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
4899 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4900 SelectionDAG &DAG, DebugLoc dl) {
4901 EVT VT = SVOp->getValueType(0);
4902 SDValue V1 = SVOp->getOperand(0);
4903 SDValue V2 = SVOp->getOperand(1);
4904 unsigned NumElems = VT.getVectorNumElements();
4905 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4907 switch (VT.getSimpleVT().SimpleTy) {
4908 default: assert(false && "Unexpected!");
4909 case MVT::v4f32: NewVT = MVT::v2f64; break;
4910 case MVT::v4i32: NewVT = MVT::v2i64; break;
4911 case MVT::v8i16: NewVT = MVT::v4i32; break;
4912 case MVT::v16i8: NewVT = MVT::v4i32; break;
4915 int Scale = NumElems / NewWidth;
4916 SmallVector<int, 8> MaskVec;
4917 for (unsigned i = 0; i < NumElems; i += Scale) {
4919 for (int j = 0; j < Scale; ++j) {
4920 int EltIdx = SVOp->getMaskElt(i+j);
4924 StartIdx = EltIdx - (EltIdx % Scale);
4925 if (EltIdx != StartIdx + j)
4929 MaskVec.push_back(-1);
4931 MaskVec.push_back(StartIdx / Scale);
4934 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4935 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4936 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4939 /// getVZextMovL - Return a zero-extending vector move low node.
4941 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4942 SDValue SrcOp, SelectionDAG &DAG,
4943 const X86Subtarget *Subtarget, DebugLoc dl) {
4944 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4945 LoadSDNode *LD = NULL;
4946 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4947 LD = dyn_cast<LoadSDNode>(SrcOp);
4949 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4951 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4952 if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4953 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4954 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4955 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4957 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4958 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4959 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4960 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4968 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4969 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4970 DAG.getNode(ISD::BIT_CONVERT, dl,
4974 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4977 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4978 SDValue V1 = SVOp->getOperand(0);
4979 SDValue V2 = SVOp->getOperand(1);
4980 DebugLoc dl = SVOp->getDebugLoc();
4981 EVT VT = SVOp->getValueType(0);
4983 SmallVector<std::pair<int, int>, 8> Locs;
4985 SmallVector<int, 8> Mask1(4U, -1);
4986 SmallVector<int, 8> PermMask;
4987 SVOp->getMask(PermMask);
4991 for (unsigned i = 0; i != 4; ++i) {
4992 int Idx = PermMask[i];
4994 Locs[i] = std::make_pair(-1, -1);
4996 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4998 Locs[i] = std::make_pair(0, NumLo);
5002 Locs[i] = std::make_pair(1, NumHi);
5004 Mask1[2+NumHi] = Idx;
5010 if (NumLo <= 2 && NumHi <= 2) {
5011 // If no more than two elements come from either vector. This can be
5012 // implemented with two shuffles. First shuffle gather the elements.
5013 // The second shuffle, which takes the first shuffle as both of its
5014 // vector operands, put the elements into the right order.
5015 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5017 SmallVector<int, 8> Mask2(4U, -1);
5019 for (unsigned i = 0; i != 4; ++i) {
5020 if (Locs[i].first == -1)
5023 unsigned Idx = (i < 2) ? 0 : 4;
5024 Idx += Locs[i].first * 2 + Locs[i].second;
5029 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5030 } else if (NumLo == 3 || NumHi == 3) {
5031 // Otherwise, we must have three elements from one vector, call it X, and
5032 // one element from the other, call it Y. First, use a shufps to build an
5033 // intermediate vector with the one element from Y and the element from X
5034 // that will be in the same half in the final destination (the indexes don't
5035 // matter). Then, use a shufps to build the final vector, taking the half
5036 // containing the element from Y from the intermediate, and the other half
5039 // Normalize it so the 3 elements come from V1.
5040 CommuteVectorShuffleMask(PermMask, VT);
5044 // Find the element from V2.
5046 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5047 int Val = PermMask[HiIndex];
5054 Mask1[0] = PermMask[HiIndex];
5056 Mask1[2] = PermMask[HiIndex^1];
5058 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5061 Mask1[0] = PermMask[0];
5062 Mask1[1] = PermMask[1];
5063 Mask1[2] = HiIndex & 1 ? 6 : 4;
5064 Mask1[3] = HiIndex & 1 ? 4 : 6;
5065 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5067 Mask1[0] = HiIndex & 1 ? 2 : 0;
5068 Mask1[1] = HiIndex & 1 ? 0 : 2;
5069 Mask1[2] = PermMask[2];
5070 Mask1[3] = PermMask[3];
5075 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5079 // Break it into (shuffle shuffle_hi, shuffle_lo).
5081 SmallVector<int,8> LoMask(4U, -1);
5082 SmallVector<int,8> HiMask(4U, -1);
5084 SmallVector<int,8> *MaskPtr = &LoMask;
5085 unsigned MaskIdx = 0;
5088 for (unsigned i = 0; i != 4; ++i) {
5095 int Idx = PermMask[i];
5097 Locs[i] = std::make_pair(-1, -1);
5098 } else if (Idx < 4) {
5099 Locs[i] = std::make_pair(MaskIdx, LoIdx);
5100 (*MaskPtr)[LoIdx] = Idx;
5103 Locs[i] = std::make_pair(MaskIdx, HiIdx);
5104 (*MaskPtr)[HiIdx] = Idx;
5109 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5110 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5111 SmallVector<int, 8> MaskOps;
5112 for (unsigned i = 0; i != 4; ++i) {
5113 if (Locs[i].first == -1) {
5114 MaskOps.push_back(-1);
5116 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5117 MaskOps.push_back(Idx);
5120 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5123 static bool MayFoldVectorLoad(SDValue V) {
5124 if (V.hasOneUse() && V.getOpcode() == ISD::BIT_CONVERT)
5125 V = V.getOperand(0);
5126 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5127 V = V.getOperand(0);
5133 // FIXME: the version above should always be used. Since there's
5134 // a bug where several vector shuffles can't be folded because the
5135 // DAG is not updated during lowering and a node claims to have two
5136 // uses while it only has one, use this version, and let isel match
5137 // another instruction if the load really happens to have more than
5138 // one use. Remove this version after this bug get fixed.
5139 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5140 if (V.hasOneUse() && V.getOpcode() == ISD::BIT_CONVERT)
5141 V = V.getOperand(0);
5142 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5143 V = V.getOperand(0);
5144 if (ISD::isNormalLoad(V.getNode()))
5149 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5150 /// a vector extract, and if both can be later optimized into a single load.
5151 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5152 /// here because otherwise a target specific shuffle node is going to be
5153 /// emitted for this shuffle, and the optimization not done.
5154 /// FIXME: This is probably not the best approach, but fix the problem
5155 /// until the right path is decided.
5157 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5158 const TargetLowering &TLI) {
5159 EVT VT = V.getValueType();
5160 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5162 // Be sure that the vector shuffle is present in a pattern like this:
5163 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5167 SDNode *N = *V.getNode()->use_begin();
5168 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5171 SDValue EltNo = N->getOperand(1);
5172 if (!isa<ConstantSDNode>(EltNo))
5175 // If the bit convert changed the number of elements, it is unsafe
5176 // to examine the mask.
5177 bool HasShuffleIntoBitcast = false;
5178 if (V.getOpcode() == ISD::BIT_CONVERT) {
5179 EVT SrcVT = V.getOperand(0).getValueType();
5180 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5182 V = V.getOperand(0);
5183 HasShuffleIntoBitcast = true;
5186 // Select the input vector, guarding against out of range extract vector.
5187 unsigned NumElems = VT.getVectorNumElements();
5188 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5189 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5190 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5192 // Skip one more bit_convert if necessary
5193 if (V.getOpcode() == ISD::BIT_CONVERT)
5194 V = V.getOperand(0);
5196 if (ISD::isNormalLoad(V.getNode())) {
5197 // Is the original load suitable?
5198 LoadSDNode *LN0 = cast<LoadSDNode>(V);
5200 // FIXME: avoid the multi-use bug that is preventing lots of
5201 // of foldings to be detected, this is still wrong of course, but
5202 // give the temporary desired behavior, and if it happens that
5203 // the load has real more uses, during isel it will not fold, and
5204 // will generate poor code.
5205 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5208 if (!HasShuffleIntoBitcast)
5211 // If there's a bitcast before the shuffle, check if the load type and
5212 // alignment is valid.
5213 unsigned Align = LN0->getAlignment();
5215 TLI.getTargetData()->getABITypeAlignment(
5216 VT.getTypeForEVT(*DAG.getContext()));
5218 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5226 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5228 SDValue V1 = Op.getOperand(0);
5229 SDValue V2 = Op.getOperand(1);
5230 EVT VT = Op.getValueType();
5232 assert(VT != MVT::v2i64 && "unsupported shuffle type");
5234 if (HasSSE2 && VT == MVT::v2f64)
5235 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5238 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5242 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5243 SDValue V1 = Op.getOperand(0);
5244 SDValue V2 = Op.getOperand(1);
5245 EVT VT = Op.getValueType();
5247 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5248 "unsupported shuffle type");
5250 if (V2.getOpcode() == ISD::UNDEF)
5254 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5258 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5259 SDValue V1 = Op.getOperand(0);
5260 SDValue V2 = Op.getOperand(1);
5261 EVT VT = Op.getValueType();
5262 unsigned NumElems = VT.getVectorNumElements();
5264 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5265 // operand of these instructions is only memory, so check if there's a
5266 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5268 bool CanFoldLoad = false;
5270 // Trivial case, when V2 comes from a load.
5271 if (MayFoldVectorLoad(V2))
5274 // When V1 is a load, it can be folded later into a store in isel, example:
5275 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5277 // (MOVLPSmr addr:$src1, VR128:$src2)
5278 // So, recognize this potential and also use MOVLPS or MOVLPD
5279 if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5283 if (HasSSE2 && NumElems == 2)
5284 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5287 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5290 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5291 // movl and movlp will both match v2i64, but v2i64 is never matched by
5292 // movl earlier because we make it strict to avoid messing with the movlp load
5293 // folding logic (see the code above getMOVLP call). Match it here then,
5294 // this is horrible, but will stay like this until we move all shuffle
5295 // matching to x86 specific nodes. Note that for the 1st condition all
5296 // types are matched with movsd.
5297 if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5298 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5300 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5303 assert(VT != MVT::v4i32 && "unsupported shuffle type");
5305 // Invert the operand order and use SHUFPS to match it.
5306 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5307 X86::getShuffleSHUFImmediate(SVOp), DAG);
5310 static inline unsigned getUNPCKLOpcode(EVT VT) {
5311 switch(VT.getSimpleVT().SimpleTy) {
5312 case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5313 case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5314 case MVT::v4f32: return X86ISD::UNPCKLPS;
5315 case MVT::v2f64: return X86ISD::UNPCKLPD;
5316 case MVT::v16i8: return X86ISD::PUNPCKLBW;
5317 case MVT::v8i16: return X86ISD::PUNPCKLWD;
5319 llvm_unreachable("Unknow type for unpckl");
5324 static inline unsigned getUNPCKHOpcode(EVT VT) {
5325 switch(VT.getSimpleVT().SimpleTy) {
5326 case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5327 case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5328 case MVT::v4f32: return X86ISD::UNPCKHPS;
5329 case MVT::v2f64: return X86ISD::UNPCKHPD;
5330 case MVT::v16i8: return X86ISD::PUNPCKHBW;
5331 case MVT::v8i16: return X86ISD::PUNPCKHWD;
5333 llvm_unreachable("Unknow type for unpckh");
5339 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5340 const TargetLowering &TLI,
5341 const X86Subtarget *Subtarget) {
5342 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5343 EVT VT = Op.getValueType();
5344 DebugLoc dl = Op.getDebugLoc();
5345 SDValue V1 = Op.getOperand(0);
5346 SDValue V2 = Op.getOperand(1);
5348 if (isZeroShuffle(SVOp))
5349 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5351 // Handle splat operations
5352 if (SVOp->isSplat()) {
5353 // Special case, this is the only place now where it's
5354 // allowed to return a vector_shuffle operation without
5355 // using a target specific node, because *hopefully* it
5356 // will be optimized away by the dag combiner.
5357 if (VT.getVectorNumElements() <= 4 &&
5358 CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5361 // Handle splats by matching through known masks
5362 if (VT.getVectorNumElements() <= 4)
5365 // Canonize all of the remaining to v4f32.
5366 return PromoteSplat(SVOp, DAG);
5369 // If the shuffle can be profitably rewritten as a narrower shuffle, then
5371 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5372 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5373 if (NewOp.getNode())
5374 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, NewOp);
5375 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5376 // FIXME: Figure out a cleaner way to do this.
5377 // Try to make use of movq to zero out the top part.
5378 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5379 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5380 if (NewOp.getNode()) {
5381 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5382 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5383 DAG, Subtarget, dl);
5385 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5386 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5387 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5388 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5389 DAG, Subtarget, dl);
5396 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5397 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5398 SDValue V1 = Op.getOperand(0);
5399 SDValue V2 = Op.getOperand(1);
5400 EVT VT = Op.getValueType();
5401 DebugLoc dl = Op.getDebugLoc();
5402 unsigned NumElems = VT.getVectorNumElements();
5403 bool isMMX = VT.getSizeInBits() == 64;
5404 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5405 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5406 bool V1IsSplat = false;
5407 bool V2IsSplat = false;
5408 bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5409 bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5410 bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5411 MachineFunction &MF = DAG.getMachineFunction();
5412 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5414 // FIXME: this is somehow handled during isel by MMX pattern fragments. Remove
5415 // the check or come up with another solution when all MMX move to intrinsics,
5416 // but don't allow this to be considered legal, we don't want vector_shuffle
5417 // operations to be matched during isel anymore.
5418 if (isMMX && SVOp->isSplat())
5421 // Vector shuffle lowering takes 3 steps:
5423 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5424 // narrowing and commutation of operands should be handled.
5425 // 2) Matching of shuffles with known shuffle masks to x86 target specific
5427 // 3) Rewriting of unmatched masks into new generic shuffle operations,
5428 // so the shuffle can be broken into other shuffles and the legalizer can
5429 // try the lowering again.
5431 // The general ideia is that no vector_shuffle operation should be left to
5432 // be matched during isel, all of them must be converted to a target specific
5435 // Normalize the input vectors. Here splats, zeroed vectors, profitable
5436 // narrowing and commutation of operands should be handled. The actual code
5437 // doesn't include all of those, work in progress...
5438 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5439 if (NewOp.getNode())
5442 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5443 // unpckh_undef). Only use pshufd if speed is more important than size.
5444 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5445 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5446 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5447 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5448 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5449 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5451 if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5452 RelaxedMayFoldVectorLoad(V1) && !isMMX)
5453 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
5455 if (!isMMX && X86::isMOVHLPS_v_undef_Mask(SVOp))
5456 return getMOVHighToLow(Op, dl, DAG);
5458 // Use to match splats
5459 if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5460 (VT == MVT::v2f64 || VT == MVT::v2i64))
5461 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5463 if (X86::isPSHUFDMask(SVOp)) {
5464 // The actual implementation will match the mask in the if above and then
5465 // during isel it can match several different instructions, not only pshufd
5466 // as its name says, sad but true, emulate the behavior for now...
5467 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5468 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5470 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5472 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5473 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5475 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5476 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5479 if (VT == MVT::v4f32)
5480 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5484 // Check if this can be converted into a logical shift.
5485 bool isLeft = false;
5488 bool isShift = getSubtarget()->hasSSE2() &&
5489 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5490 if (isShift && ShVal.hasOneUse()) {
5491 // If the shifted value has multiple uses, it may be cheaper to use
5492 // v_set0 + movlhps or movhlps, etc.
5493 EVT EltVT = VT.getVectorElementType();
5494 ShAmt *= EltVT.getSizeInBits();
5495 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5498 if (X86::isMOVLMask(SVOp)) {
5501 if (ISD::isBuildVectorAllZeros(V1.getNode()))
5502 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5503 if (!isMMX && !X86::isMOVLPMask(SVOp)) {
5504 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5505 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5507 if (VT == MVT::v4i32 || VT == MVT::v4f32)
5508 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5512 // FIXME: fold these into legal mask.
5514 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5515 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5517 if (X86::isMOVHLPSMask(SVOp))
5518 return getMOVHighToLow(Op, dl, DAG);
5520 if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5521 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5523 if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5524 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5526 if (X86::isMOVLPMask(SVOp))
5527 return getMOVLP(Op, dl, DAG, HasSSE2);
5530 if (ShouldXformToMOVHLPS(SVOp) ||
5531 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5532 return CommuteVectorShuffle(SVOp, DAG);
5535 // No better options. Use a vshl / vsrl.
5536 EVT EltVT = VT.getVectorElementType();
5537 ShAmt *= EltVT.getSizeInBits();
5538 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5541 bool Commuted = false;
5542 // FIXME: This should also accept a bitcast of a splat? Be careful, not
5543 // 1,1,1,1 -> v8i16 though.
5544 V1IsSplat = isSplatVector(V1.getNode());
5545 V2IsSplat = isSplatVector(V2.getNode());
5547 // Canonicalize the splat or undef, if present, to be on the RHS.
5548 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5549 Op = CommuteVectorShuffle(SVOp, DAG);
5550 SVOp = cast<ShuffleVectorSDNode>(Op);
5551 V1 = SVOp->getOperand(0);
5552 V2 = SVOp->getOperand(1);
5553 std::swap(V1IsSplat, V2IsSplat);
5554 std::swap(V1IsUndef, V2IsUndef);
5558 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5559 // Shuffling low element of v1 into undef, just return v1.
5562 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5563 // the instruction selector will not match, so get a canonical MOVL with
5564 // swapped operands to undo the commute.
5565 return getMOVL(DAG, dl, VT, V2, V1);
5568 if (X86::isUNPCKLMask(SVOp))
5570 Op : getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
5572 if (X86::isUNPCKHMask(SVOp))
5574 Op : getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5577 // Normalize mask so all entries that point to V2 points to its first
5578 // element then try to match unpck{h|l} again. If match, return a
5579 // new vector_shuffle with the corrected mask.
5580 SDValue NewMask = NormalizeMask(SVOp, DAG);
5581 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5582 if (NSVOp != SVOp) {
5583 if (X86::isUNPCKLMask(NSVOp, true)) {
5585 } else if (X86::isUNPCKHMask(NSVOp, true)) {
5592 // Commute is back and try unpck* again.
5593 // FIXME: this seems wrong.
5594 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5595 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5597 if (X86::isUNPCKLMask(NewSVOp))
5599 NewOp : getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
5601 if (X86::isUNPCKHMask(NewSVOp))
5603 NewOp : getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5606 // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
5608 // Normalize the node to match x86 shuffle ops if needed
5609 if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5610 return CommuteVectorShuffle(SVOp, DAG);
5612 // The checks below are all present in isShuffleMaskLegal, but they are
5613 // inlined here right now to enable us to directly emit target specific
5614 // nodes, and remove one by one until they don't return Op anymore.
5615 SmallVector<int, 16> M;
5618 if (isPALIGNRMask(M, VT, HasSSSE3))
5619 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5620 X86::getShufflePALIGNRImmediate(SVOp),
5623 // Only a few shuffle masks are handled for 64-bit vectors (MMX), and
5624 // 64-bit vectors which made to this point can't be handled, they are
5629 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5630 SVOp->getSplatIndex() == 0 && V2IsUndef) {
5631 if (VT == MVT::v2f64)
5632 return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
5633 if (VT == MVT::v2i64)
5634 return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5637 if (isPSHUFHWMask(M, VT))
5638 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5639 X86::getShufflePSHUFHWImmediate(SVOp),
5642 if (isPSHUFLWMask(M, VT))
5643 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5644 X86::getShufflePSHUFLWImmediate(SVOp),
5647 if (isSHUFPMask(M, VT)) {
5648 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5649 if (VT == MVT::v4f32 || VT == MVT::v4i32)
5650 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5652 if (VT == MVT::v2f64 || VT == MVT::v2i64)
5653 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5657 if (X86::isUNPCKL_v_undef_Mask(SVOp))
5658 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5659 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5660 if (X86::isUNPCKH_v_undef_Mask(SVOp))
5661 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5662 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5664 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5665 if (VT == MVT::v8i16) {
5666 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5667 if (NewOp.getNode())
5671 if (VT == MVT::v16i8) {
5672 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5673 if (NewOp.getNode())
5677 // Handle all 4 wide cases with a number of shuffles except for MMX.
5678 if (NumElems == 4 && !isMMX)
5679 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5685 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5686 SelectionDAG &DAG) const {
5687 EVT VT = Op.getValueType();
5688 DebugLoc dl = Op.getDebugLoc();
5689 if (VT.getSizeInBits() == 8) {
5690 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5691 Op.getOperand(0), Op.getOperand(1));
5692 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5693 DAG.getValueType(VT));
5694 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5695 } else if (VT.getSizeInBits() == 16) {
5696 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5697 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
5699 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5700 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5701 DAG.getNode(ISD::BIT_CONVERT, dl,
5705 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
5706 Op.getOperand(0), Op.getOperand(1));
5707 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5708 DAG.getValueType(VT));
5709 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5710 } else if (VT == MVT::f32) {
5711 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
5712 // the result back to FR32 register. It's only worth matching if the
5713 // result has a single use which is a store or a bitcast to i32. And in
5714 // the case of a store, it's not worth it if the index is a constant 0,
5715 // because a MOVSSmr can be used instead, which is smaller and faster.
5716 if (!Op.hasOneUse())
5718 SDNode *User = *Op.getNode()->use_begin();
5719 if ((User->getOpcode() != ISD::STORE ||
5720 (isa<ConstantSDNode>(Op.getOperand(1)) &&
5721 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
5722 (User->getOpcode() != ISD::BIT_CONVERT ||
5723 User->getValueType(0) != MVT::i32))
5725 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5726 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
5729 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
5730 } else if (VT == MVT::i32) {
5731 // ExtractPS works with constant index.
5732 if (isa<ConstantSDNode>(Op.getOperand(1)))
5740 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5741 SelectionDAG &DAG) const {
5742 if (!isa<ConstantSDNode>(Op.getOperand(1)))
5745 if (Subtarget->hasSSE41()) {
5746 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
5751 EVT VT = Op.getValueType();
5752 DebugLoc dl = Op.getDebugLoc();
5753 // TODO: handle v16i8.
5754 if (VT.getSizeInBits() == 16) {
5755 SDValue Vec = Op.getOperand(0);
5756 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5758 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5759 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5760 DAG.getNode(ISD::BIT_CONVERT, dl,
5763 // Transform it so it match pextrw which produces a 32-bit result.
5764 EVT EltVT = MVT::i32;
5765 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
5766 Op.getOperand(0), Op.getOperand(1));
5767 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
5768 DAG.getValueType(VT));
5769 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5770 } else if (VT.getSizeInBits() == 32) {
5771 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5775 // SHUFPS the element to the lowest double word, then movss.
5776 int Mask[4] = { Idx, -1, -1, -1 };
5777 EVT VVT = Op.getOperand(0).getValueType();
5778 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5779 DAG.getUNDEF(VVT), Mask);
5780 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5781 DAG.getIntPtrConstant(0));
5782 } else if (VT.getSizeInBits() == 64) {
5783 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
5784 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
5785 // to match extract_elt for f64.
5786 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5790 // UNPCKHPD the element to the lowest double word, then movsd.
5791 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
5792 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
5793 int Mask[2] = { 1, -1 };
5794 EVT VVT = Op.getOperand(0).getValueType();
5795 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5796 DAG.getUNDEF(VVT), Mask);
5797 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5798 DAG.getIntPtrConstant(0));
5805 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
5806 SelectionDAG &DAG) const {
5807 EVT VT = Op.getValueType();
5808 EVT EltVT = VT.getVectorElementType();
5809 DebugLoc dl = Op.getDebugLoc();
5811 SDValue N0 = Op.getOperand(0);
5812 SDValue N1 = Op.getOperand(1);
5813 SDValue N2 = Op.getOperand(2);
5815 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
5816 isa<ConstantSDNode>(N2)) {
5818 if (VT == MVT::v8i16)
5819 Opc = X86ISD::PINSRW;
5820 else if (VT == MVT::v4i16)
5821 Opc = X86ISD::MMX_PINSRW;
5822 else if (VT == MVT::v16i8)
5823 Opc = X86ISD::PINSRB;
5825 Opc = X86ISD::PINSRB;
5827 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
5829 if (N1.getValueType() != MVT::i32)
5830 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5831 if (N2.getValueType() != MVT::i32)
5832 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5833 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
5834 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
5835 // Bits [7:6] of the constant are the source select. This will always be
5836 // zero here. The DAG Combiner may combine an extract_elt index into these
5837 // bits. For example (insert (extract, 3), 2) could be matched by putting
5838 // the '3' into bits [7:6] of X86ISD::INSERTPS.
5839 // Bits [5:4] of the constant are the destination select. This is the
5840 // value of the incoming immediate.
5841 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
5842 // combine either bitwise AND or insert of float 0.0 to set these bits.
5843 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
5844 // Create this as a scalar to vector..
5845 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
5846 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
5847 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
5848 // PINSR* works with constant index.
5855 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
5856 EVT VT = Op.getValueType();
5857 EVT EltVT = VT.getVectorElementType();
5859 if (Subtarget->hasSSE41())
5860 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
5862 if (EltVT == MVT::i8)
5865 DebugLoc dl = Op.getDebugLoc();
5866 SDValue N0 = Op.getOperand(0);
5867 SDValue N1 = Op.getOperand(1);
5868 SDValue N2 = Op.getOperand(2);
5870 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
5871 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
5872 // as its second argument.
5873 if (N1.getValueType() != MVT::i32)
5874 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5875 if (N2.getValueType() != MVT::i32)
5876 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5877 return DAG.getNode(VT == MVT::v8i16 ? X86ISD::PINSRW : X86ISD::MMX_PINSRW,
5878 dl, VT, N0, N1, N2);
5884 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5885 DebugLoc dl = Op.getDebugLoc();
5887 if (Op.getValueType() == MVT::v1i64 &&
5888 Op.getOperand(0).getValueType() == MVT::i64)
5889 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5891 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5892 EVT VT = MVT::v2i32;
5893 switch (Op.getValueType().getSimpleVT().SimpleTy) {
5900 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
5901 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
5904 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5905 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5906 // one of the above mentioned nodes. It has to be wrapped because otherwise
5907 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5908 // be used to form addressing mode. These wrapped nodes will be selected
5911 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
5912 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5914 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5916 unsigned char OpFlag = 0;
5917 unsigned WrapperKind = X86ISD::Wrapper;
5918 CodeModel::Model M = getTargetMachine().getCodeModel();
5920 if (Subtarget->isPICStyleRIPRel() &&
5921 (M == CodeModel::Small || M == CodeModel::Kernel))
5922 WrapperKind = X86ISD::WrapperRIP;
5923 else if (Subtarget->isPICStyleGOT())
5924 OpFlag = X86II::MO_GOTOFF;
5925 else if (Subtarget->isPICStyleStubPIC())
5926 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5928 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5930 CP->getOffset(), OpFlag);
5931 DebugLoc DL = CP->getDebugLoc();
5932 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5933 // With PIC, the address is actually $g + Offset.
5935 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5936 DAG.getNode(X86ISD::GlobalBaseReg,
5937 DebugLoc(), getPointerTy()),
5944 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
5945 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5947 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5949 unsigned char OpFlag = 0;
5950 unsigned WrapperKind = X86ISD::Wrapper;
5951 CodeModel::Model M = getTargetMachine().getCodeModel();
5953 if (Subtarget->isPICStyleRIPRel() &&
5954 (M == CodeModel::Small || M == CodeModel::Kernel))
5955 WrapperKind = X86ISD::WrapperRIP;
5956 else if (Subtarget->isPICStyleGOT())
5957 OpFlag = X86II::MO_GOTOFF;
5958 else if (Subtarget->isPICStyleStubPIC())
5959 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5961 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5963 DebugLoc DL = JT->getDebugLoc();
5964 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5966 // With PIC, the address is actually $g + Offset.
5968 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5969 DAG.getNode(X86ISD::GlobalBaseReg,
5970 DebugLoc(), getPointerTy()),
5978 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
5979 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5981 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5983 unsigned char OpFlag = 0;
5984 unsigned WrapperKind = X86ISD::Wrapper;
5985 CodeModel::Model M = getTargetMachine().getCodeModel();
5987 if (Subtarget->isPICStyleRIPRel() &&
5988 (M == CodeModel::Small || M == CodeModel::Kernel))
5989 WrapperKind = X86ISD::WrapperRIP;
5990 else if (Subtarget->isPICStyleGOT())
5991 OpFlag = X86II::MO_GOTOFF;
5992 else if (Subtarget->isPICStyleStubPIC())
5993 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5995 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5997 DebugLoc DL = Op.getDebugLoc();
5998 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6001 // With PIC, the address is actually $g + Offset.
6002 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6003 !Subtarget->is64Bit()) {
6004 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6005 DAG.getNode(X86ISD::GlobalBaseReg,
6006 DebugLoc(), getPointerTy()),
6014 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6015 // Create the TargetBlockAddressAddress node.
6016 unsigned char OpFlags =
6017 Subtarget->ClassifyBlockAddressReference();
6018 CodeModel::Model M = getTargetMachine().getCodeModel();
6019 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6020 DebugLoc dl = Op.getDebugLoc();
6021 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6022 /*isTarget=*/true, OpFlags);
6024 if (Subtarget->isPICStyleRIPRel() &&
6025 (M == CodeModel::Small || M == CodeModel::Kernel))
6026 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6028 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6030 // With PIC, the address is actually $g + Offset.
6031 if (isGlobalRelativeToPICBase(OpFlags)) {
6032 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6033 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6041 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6043 SelectionDAG &DAG) const {
6044 // Create the TargetGlobalAddress node, folding in the constant
6045 // offset if it is legal.
6046 unsigned char OpFlags =
6047 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6048 CodeModel::Model M = getTargetMachine().getCodeModel();
6050 if (OpFlags == X86II::MO_NO_FLAG &&
6051 X86::isOffsetSuitableForCodeModel(Offset, M)) {
6052 // A direct static reference to a global.
6053 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6056 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6059 if (Subtarget->isPICStyleRIPRel() &&
6060 (M == CodeModel::Small || M == CodeModel::Kernel))
6061 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6063 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6065 // With PIC, the address is actually $g + Offset.
6066 if (isGlobalRelativeToPICBase(OpFlags)) {
6067 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6068 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6072 // For globals that require a load from a stub to get the address, emit the
6074 if (isGlobalStubReference(OpFlags))
6075 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6076 PseudoSourceValue::getGOT(), 0, false, false, 0);
6078 // If there was a non-zero offset that we didn't fold, create an explicit
6081 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6082 DAG.getConstant(Offset, getPointerTy()));
6088 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6089 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6090 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6091 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6095 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6096 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6097 unsigned char OperandFlags) {
6098 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6099 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6100 DebugLoc dl = GA->getDebugLoc();
6101 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6102 GA->getValueType(0),
6106 SDValue Ops[] = { Chain, TGA, *InFlag };
6107 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6109 SDValue Ops[] = { Chain, TGA };
6110 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6113 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6114 MFI->setAdjustsStack(true);
6116 SDValue Flag = Chain.getValue(1);
6117 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6120 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6122 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6125 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
6126 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6127 DAG.getNode(X86ISD::GlobalBaseReg,
6128 DebugLoc(), PtrVT), InFlag);
6129 InFlag = Chain.getValue(1);
6131 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6134 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6136 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6138 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6139 X86::RAX, X86II::MO_TLSGD);
6142 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6143 // "local exec" model.
6144 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6145 const EVT PtrVT, TLSModel::Model model,
6147 DebugLoc dl = GA->getDebugLoc();
6148 // Get the Thread Pointer
6149 SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
6151 DAG.getRegister(is64Bit? X86::FS : X86::GS,
6154 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
6155 NULL, 0, false, false, 0);
6157 unsigned char OperandFlags = 0;
6158 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
6160 unsigned WrapperKind = X86ISD::Wrapper;
6161 if (model == TLSModel::LocalExec) {
6162 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6163 } else if (is64Bit) {
6164 assert(model == TLSModel::InitialExec);
6165 OperandFlags = X86II::MO_GOTTPOFF;
6166 WrapperKind = X86ISD::WrapperRIP;
6168 assert(model == TLSModel::InitialExec);
6169 OperandFlags = X86II::MO_INDNTPOFF;
6172 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6174 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6175 GA->getValueType(0),
6176 GA->getOffset(), OperandFlags);
6177 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6179 if (model == TLSModel::InitialExec)
6180 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6181 PseudoSourceValue::getGOT(), 0, false, false, 0);
6183 // The address of the thread local variable is the add of the thread
6184 // pointer with the offset of the variable.
6185 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6189 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6191 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6192 const GlobalValue *GV = GA->getGlobal();
6194 if (Subtarget->isTargetELF()) {
6195 // TODO: implement the "local dynamic" model
6196 // TODO: implement the "initial exec"model for pic executables
6198 // If GV is an alias then use the aliasee for determining
6199 // thread-localness.
6200 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6201 GV = GA->resolveAliasedGlobal(false);
6203 TLSModel::Model model
6204 = getTLSModel(GV, getTargetMachine().getRelocationModel());
6207 case TLSModel::GeneralDynamic:
6208 case TLSModel::LocalDynamic: // not implemented
6209 if (Subtarget->is64Bit())
6210 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6211 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6213 case TLSModel::InitialExec:
6214 case TLSModel::LocalExec:
6215 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6216 Subtarget->is64Bit());
6218 } else if (Subtarget->isTargetDarwin()) {
6219 // Darwin only has one model of TLS. Lower to that.
6220 unsigned char OpFlag = 0;
6221 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6222 X86ISD::WrapperRIP : X86ISD::Wrapper;
6224 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6226 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6227 !Subtarget->is64Bit();
6229 OpFlag = X86II::MO_TLVP_PIC_BASE;
6231 OpFlag = X86II::MO_TLVP;
6232 DebugLoc DL = Op.getDebugLoc();
6233 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6235 GA->getOffset(), OpFlag);
6236 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6238 // With PIC32, the address is actually $g + Offset.
6240 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6241 DAG.getNode(X86ISD::GlobalBaseReg,
6242 DebugLoc(), getPointerTy()),
6245 // Lowering the machine isd will make sure everything is in the right
6247 SDValue Args[] = { Offset };
6248 SDValue Chain = DAG.getNode(X86ISD::TLSCALL, DL, MVT::Other, Args, 1);
6250 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6251 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6252 MFI->setAdjustsStack(true);
6254 // And our return value (tls address) is in the standard call return value
6256 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6257 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6261 "TLS not implemented for this target.");
6263 llvm_unreachable("Unreachable");
6268 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
6269 /// take a 2 x i32 value to shift plus a shift amount.
6270 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
6271 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6272 EVT VT = Op.getValueType();
6273 unsigned VTBits = VT.getSizeInBits();
6274 DebugLoc dl = Op.getDebugLoc();
6275 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6276 SDValue ShOpLo = Op.getOperand(0);
6277 SDValue ShOpHi = Op.getOperand(1);
6278 SDValue ShAmt = Op.getOperand(2);
6279 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6280 DAG.getConstant(VTBits - 1, MVT::i8))
6281 : DAG.getConstant(0, VT);
6284 if (Op.getOpcode() == ISD::SHL_PARTS) {
6285 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6286 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6288 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6289 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6292 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6293 DAG.getConstant(VTBits, MVT::i8));
6294 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6295 AndNode, DAG.getConstant(0, MVT::i8));
6298 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6299 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6300 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6302 if (Op.getOpcode() == ISD::SHL_PARTS) {
6303 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6304 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6306 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6307 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6310 SDValue Ops[2] = { Lo, Hi };
6311 return DAG.getMergeValues(Ops, 2, dl);
6314 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6315 SelectionDAG &DAG) const {
6316 EVT SrcVT = Op.getOperand(0).getValueType();
6318 if (SrcVT.isVector()) {
6319 if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
6325 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6326 "Unknown SINT_TO_FP to lower!");
6328 // These are really Legal; return the operand so the caller accepts it as
6330 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6332 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6333 Subtarget->is64Bit()) {
6337 DebugLoc dl = Op.getDebugLoc();
6338 unsigned Size = SrcVT.getSizeInBits()/8;
6339 MachineFunction &MF = DAG.getMachineFunction();
6340 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6341 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6342 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6344 PseudoSourceValue::getFixedStack(SSFI), 0,
6346 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6349 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6351 SelectionDAG &DAG) const {
6353 DebugLoc dl = Op.getDebugLoc();
6355 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6357 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
6359 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6360 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6361 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
6362 Tys, Ops, array_lengthof(Ops));
6365 Chain = Result.getValue(1);
6366 SDValue InFlag = Result.getValue(2);
6368 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6369 // shouldn't be necessary except that RFP cannot be live across
6370 // multiple blocks. When stackifier is fixed, they can be uncoupled.
6371 MachineFunction &MF = DAG.getMachineFunction();
6372 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
6373 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6374 Tys = DAG.getVTList(MVT::Other);
6376 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6378 Chain = DAG.getNode(X86ISD::FST, dl, Tys, Ops, array_lengthof(Ops));
6379 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
6380 PseudoSourceValue::getFixedStack(SSFI), 0,
6387 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6388 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6389 SelectionDAG &DAG) const {
6390 // This algorithm is not obvious. Here it is in C code, more or less:
6392 double uint64_to_double( uint32_t hi, uint32_t lo ) {
6393 static const __m128i exp = { 0x4330000045300000ULL, 0 };
6394 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6396 // Copy ints to xmm registers.
6397 __m128i xh = _mm_cvtsi32_si128( hi );
6398 __m128i xl = _mm_cvtsi32_si128( lo );
6400 // Combine into low half of a single xmm register.
6401 __m128i x = _mm_unpacklo_epi32( xh, xl );
6405 // Merge in appropriate exponents to give the integer bits the right
6407 x = _mm_unpacklo_epi32( x, exp );
6409 // Subtract away the biases to deal with the IEEE-754 double precision
6411 d = _mm_sub_pd( (__m128d) x, bias );
6413 // All conversions up to here are exact. The correctly rounded result is
6414 // calculated using the current rounding mode using the following
6416 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6417 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
6418 // store doesn't really need to be here (except
6419 // maybe to zero the other double)
6424 DebugLoc dl = Op.getDebugLoc();
6425 LLVMContext *Context = DAG.getContext();
6427 // Build some magic constants.
6428 std::vector<Constant*> CV0;
6429 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6430 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6431 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6432 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6433 Constant *C0 = ConstantVector::get(CV0);
6434 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6436 std::vector<Constant*> CV1;
6438 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6440 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6441 Constant *C1 = ConstantVector::get(CV1);
6442 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6444 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6445 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6447 DAG.getIntPtrConstant(1)));
6448 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6449 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6451 DAG.getIntPtrConstant(0)));
6452 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6453 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6454 PseudoSourceValue::getConstantPool(), 0,
6456 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6457 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
6458 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6459 PseudoSourceValue::getConstantPool(), 0,
6461 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6463 // Add the halves; easiest way is to swap them into another reg first.
6464 int ShufMask[2] = { 1, -1 };
6465 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6466 DAG.getUNDEF(MVT::v2f64), ShufMask);
6467 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6468 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6469 DAG.getIntPtrConstant(0));
6472 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6473 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6474 SelectionDAG &DAG) const {
6475 DebugLoc dl = Op.getDebugLoc();
6476 // FP constant to bias correct the final result.
6477 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6480 // Load the 32-bit value into an XMM register.
6481 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6482 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6484 DAG.getIntPtrConstant(0)));
6486 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6487 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
6488 DAG.getIntPtrConstant(0));
6490 // Or the load with the bias.
6491 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6492 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
6493 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6495 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
6496 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6497 MVT::v2f64, Bias)));
6498 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6499 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
6500 DAG.getIntPtrConstant(0));
6502 // Subtract the bias.
6503 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6505 // Handle final rounding.
6506 EVT DestVT = Op.getValueType();
6508 if (DestVT.bitsLT(MVT::f64)) {
6509 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6510 DAG.getIntPtrConstant(0));
6511 } else if (DestVT.bitsGT(MVT::f64)) {
6512 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6515 // Handle final rounding.
6519 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6520 SelectionDAG &DAG) const {
6521 SDValue N0 = Op.getOperand(0);
6522 DebugLoc dl = Op.getDebugLoc();
6524 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6525 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6526 // the optimization here.
6527 if (DAG.SignBitIsZero(N0))
6528 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6530 EVT SrcVT = N0.getValueType();
6531 EVT DstVT = Op.getValueType();
6532 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6533 return LowerUINT_TO_FP_i64(Op, DAG);
6534 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6535 return LowerUINT_TO_FP_i32(Op, DAG);
6537 // Make a 64-bit buffer, and use it to build an FILD.
6538 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6539 if (SrcVT == MVT::i32) {
6540 SDValue WordOff = DAG.getConstant(4, getPointerTy());
6541 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6542 getPointerTy(), StackSlot, WordOff);
6543 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6544 StackSlot, NULL, 0, false, false, 0);
6545 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6546 OffsetSlot, NULL, 0, false, false, 0);
6547 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6551 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6552 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6553 StackSlot, NULL, 0, false, false, 0);
6554 // For i64 source, we need to add the appropriate power of 2 if the input
6555 // was negative. This is the same as the optimization in
6556 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6557 // we must be careful to do the computation in x87 extended precision, not
6558 // in SSE. (The generic code can't know it's OK to do this, or how to.)
6559 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6560 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6561 SDValue Fild = DAG.getNode(X86ISD::FILD, dl, Tys, Ops, 3);
6563 APInt FF(32, 0x5F800000ULL);
6565 // Check whether the sign bit is set.
6566 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6567 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6570 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6571 SDValue FudgePtr = DAG.getConstantPool(
6572 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6575 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6576 SDValue Zero = DAG.getIntPtrConstant(0);
6577 SDValue Four = DAG.getIntPtrConstant(4);
6578 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6580 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6582 // Load the value out, extending it from f32 to f80.
6583 // FIXME: Avoid the extend by constructing the right constant pool?
6584 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, MVT::f80, dl, DAG.getEntryNode(),
6585 FudgePtr, PseudoSourceValue::getConstantPool(),
6586 0, MVT::f32, false, false, 4);
6587 // Extend everything to 80 bits to force it to be done on x87.
6588 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6589 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6592 std::pair<SDValue,SDValue> X86TargetLowering::
6593 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6594 DebugLoc dl = Op.getDebugLoc();
6596 EVT DstTy = Op.getValueType();
6599 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
6603 assert(DstTy.getSimpleVT() <= MVT::i64 &&
6604 DstTy.getSimpleVT() >= MVT::i16 &&
6605 "Unknown FP_TO_SINT to lower!");
6607 // These are really Legal.
6608 if (DstTy == MVT::i32 &&
6609 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6610 return std::make_pair(SDValue(), SDValue());
6611 if (Subtarget->is64Bit() &&
6612 DstTy == MVT::i64 &&
6613 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6614 return std::make_pair(SDValue(), SDValue());
6616 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
6618 MachineFunction &MF = DAG.getMachineFunction();
6619 unsigned MemSize = DstTy.getSizeInBits()/8;
6620 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6621 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6624 switch (DstTy.getSimpleVT().SimpleTy) {
6625 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
6626 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
6627 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
6628 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
6631 SDValue Chain = DAG.getEntryNode();
6632 SDValue Value = Op.getOperand(0);
6633 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
6634 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
6635 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
6636 PseudoSourceValue::getFixedStack(SSFI), 0,
6638 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
6640 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
6642 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
6643 Chain = Value.getValue(1);
6644 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6645 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6648 // Build the FP_TO_INT*_IN_MEM
6649 SDValue Ops[] = { Chain, Value, StackSlot };
6650 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
6652 return std::make_pair(FIST, StackSlot);
6655 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
6656 SelectionDAG &DAG) const {
6657 if (Op.getValueType().isVector()) {
6658 if (Op.getValueType() == MVT::v2i32 &&
6659 Op.getOperand(0).getValueType() == MVT::v2f64) {
6665 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
6666 SDValue FIST = Vals.first, StackSlot = Vals.second;
6667 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
6668 if (FIST.getNode() == 0) return Op;
6671 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6672 FIST, StackSlot, NULL, 0, false, false, 0);
6675 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
6676 SelectionDAG &DAG) const {
6677 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
6678 SDValue FIST = Vals.first, StackSlot = Vals.second;
6679 assert(FIST.getNode() && "Unexpected failure");
6682 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6683 FIST, StackSlot, NULL, 0, false, false, 0);
6686 SDValue X86TargetLowering::LowerFABS(SDValue Op,
6687 SelectionDAG &DAG) const {
6688 LLVMContext *Context = DAG.getContext();
6689 DebugLoc dl = Op.getDebugLoc();
6690 EVT VT = Op.getValueType();
6693 EltVT = VT.getVectorElementType();
6694 std::vector<Constant*> CV;
6695 if (EltVT == MVT::f64) {
6696 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
6700 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
6706 Constant *C = ConstantVector::get(CV);
6707 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6708 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6709 PseudoSourceValue::getConstantPool(), 0,
6711 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
6714 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
6715 LLVMContext *Context = DAG.getContext();
6716 DebugLoc dl = Op.getDebugLoc();
6717 EVT VT = Op.getValueType();
6720 EltVT = VT.getVectorElementType();
6721 std::vector<Constant*> CV;
6722 if (EltVT == MVT::f64) {
6723 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
6727 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
6733 Constant *C = ConstantVector::get(CV);
6734 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6735 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6736 PseudoSourceValue::getConstantPool(), 0,
6738 if (VT.isVector()) {
6739 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
6740 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
6741 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
6743 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
6745 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
6749 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
6750 LLVMContext *Context = DAG.getContext();
6751 SDValue Op0 = Op.getOperand(0);
6752 SDValue Op1 = Op.getOperand(1);
6753 DebugLoc dl = Op.getDebugLoc();
6754 EVT VT = Op.getValueType();
6755 EVT SrcVT = Op1.getValueType();
6757 // If second operand is smaller, extend it first.
6758 if (SrcVT.bitsLT(VT)) {
6759 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
6762 // And if it is bigger, shrink it first.
6763 if (SrcVT.bitsGT(VT)) {
6764 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
6768 // At this point the operands and the result should have the same
6769 // type, and that won't be f80 since that is not custom lowered.
6771 // First get the sign bit of second operand.
6772 std::vector<Constant*> CV;
6773 if (SrcVT == MVT::f64) {
6774 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
6775 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6777 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
6778 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6779 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6780 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6782 Constant *C = ConstantVector::get(CV);
6783 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6784 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
6785 PseudoSourceValue::getConstantPool(), 0,
6787 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
6789 // Shift sign bit right or left if the two operands have different types.
6790 if (SrcVT.bitsGT(VT)) {
6791 // Op0 is MVT::f32, Op1 is MVT::f64.
6792 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
6793 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
6794 DAG.getConstant(32, MVT::i32));
6795 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
6796 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
6797 DAG.getIntPtrConstant(0));
6800 // Clear first operand sign bit.
6802 if (VT == MVT::f64) {
6803 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
6804 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6806 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
6807 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6808 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6809 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6811 C = ConstantVector::get(CV);
6812 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6813 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6814 PseudoSourceValue::getConstantPool(), 0,
6816 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
6818 // Or the value with the sign bit.
6819 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
6822 /// Emit nodes that will be selected as "test Op0,Op0", or something
6824 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
6825 SelectionDAG &DAG) const {
6826 DebugLoc dl = Op.getDebugLoc();
6828 // CF and OF aren't always set the way we want. Determine which
6829 // of these we need.
6830 bool NeedCF = false;
6831 bool NeedOF = false;
6834 case X86::COND_A: case X86::COND_AE:
6835 case X86::COND_B: case X86::COND_BE:
6838 case X86::COND_G: case X86::COND_GE:
6839 case X86::COND_L: case X86::COND_LE:
6840 case X86::COND_O: case X86::COND_NO:
6845 // See if we can use the EFLAGS value from the operand instead of
6846 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
6847 // we prove that the arithmetic won't overflow, we can't use OF or CF.
6848 if (Op.getResNo() != 0 || NeedOF || NeedCF)
6849 // Emit a CMP with 0, which is the TEST pattern.
6850 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6851 DAG.getConstant(0, Op.getValueType()));
6853 unsigned Opcode = 0;
6854 unsigned NumOperands = 0;
6855 switch (Op.getNode()->getOpcode()) {
6857 // Due to an isel shortcoming, be conservative if this add is likely to be
6858 // selected as part of a load-modify-store instruction. When the root node
6859 // in a match is a store, isel doesn't know how to remap non-chain non-flag
6860 // uses of other nodes in the match, such as the ADD in this case. This
6861 // leads to the ADD being left around and reselected, with the result being
6862 // two adds in the output. Alas, even if none our users are stores, that
6863 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
6864 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
6865 // climbing the DAG back to the root, and it doesn't seem to be worth the
6867 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6868 UE = Op.getNode()->use_end(); UI != UE; ++UI)
6869 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
6872 if (ConstantSDNode *C =
6873 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
6874 // An add of one will be selected as an INC.
6875 if (C->getAPIntValue() == 1) {
6876 Opcode = X86ISD::INC;
6881 // An add of negative one (subtract of one) will be selected as a DEC.
6882 if (C->getAPIntValue().isAllOnesValue()) {
6883 Opcode = X86ISD::DEC;
6889 // Otherwise use a regular EFLAGS-setting add.
6890 Opcode = X86ISD::ADD;
6894 // If the primary and result isn't used, don't bother using X86ISD::AND,
6895 // because a TEST instruction will be better.
6896 bool NonFlagUse = false;
6897 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6898 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
6900 unsigned UOpNo = UI.getOperandNo();
6901 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
6902 // Look pass truncate.
6903 UOpNo = User->use_begin().getOperandNo();
6904 User = *User->use_begin();
6907 if (User->getOpcode() != ISD::BRCOND &&
6908 User->getOpcode() != ISD::SETCC &&
6909 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
6922 // Due to the ISEL shortcoming noted above, be conservative if this op is
6923 // likely to be selected as part of a load-modify-store instruction.
6924 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6925 UE = Op.getNode()->use_end(); UI != UE; ++UI)
6926 if (UI->getOpcode() == ISD::STORE)
6929 // Otherwise use a regular EFLAGS-setting instruction.
6930 switch (Op.getNode()->getOpcode()) {
6931 default: llvm_unreachable("unexpected operator!");
6932 case ISD::SUB: Opcode = X86ISD::SUB; break;
6933 case ISD::OR: Opcode = X86ISD::OR; break;
6934 case ISD::XOR: Opcode = X86ISD::XOR; break;
6935 case ISD::AND: Opcode = X86ISD::AND; break;
6947 return SDValue(Op.getNode(), 1);
6954 // Emit a CMP with 0, which is the TEST pattern.
6955 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6956 DAG.getConstant(0, Op.getValueType()));
6958 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
6959 SmallVector<SDValue, 4> Ops;
6960 for (unsigned i = 0; i != NumOperands; ++i)
6961 Ops.push_back(Op.getOperand(i));
6963 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
6964 DAG.ReplaceAllUsesWith(Op, New);
6965 return SDValue(New.getNode(), 1);
6968 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
6970 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
6971 SelectionDAG &DAG) const {
6972 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
6973 if (C->getAPIntValue() == 0)
6974 return EmitTest(Op0, X86CC, DAG);
6976 DebugLoc dl = Op0.getDebugLoc();
6977 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
6980 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
6981 /// if it's possible.
6982 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
6983 DebugLoc dl, SelectionDAG &DAG) const {
6984 SDValue Op0 = And.getOperand(0);
6985 SDValue Op1 = And.getOperand(1);
6986 if (Op0.getOpcode() == ISD::TRUNCATE)
6987 Op0 = Op0.getOperand(0);
6988 if (Op1.getOpcode() == ISD::TRUNCATE)
6989 Op1 = Op1.getOperand(0);
6992 if (Op1.getOpcode() == ISD::SHL)
6993 std::swap(Op0, Op1);
6994 if (Op0.getOpcode() == ISD::SHL) {
6995 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
6996 if (And00C->getZExtValue() == 1) {
6997 // If we looked past a truncate, check that it's only truncating away
6999 unsigned BitWidth = Op0.getValueSizeInBits();
7000 unsigned AndBitWidth = And.getValueSizeInBits();
7001 if (BitWidth > AndBitWidth) {
7002 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7003 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7004 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7008 RHS = Op0.getOperand(1);
7010 } else if (Op1.getOpcode() == ISD::Constant) {
7011 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7012 SDValue AndLHS = Op0;
7013 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7014 LHS = AndLHS.getOperand(0);
7015 RHS = AndLHS.getOperand(1);
7019 if (LHS.getNode()) {
7020 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
7021 // instruction. Since the shift amount is in-range-or-undefined, we know
7022 // that doing a bittest on the i32 value is ok. We extend to i32 because
7023 // the encoding for the i16 version is larger than the i32 version.
7024 // Also promote i16 to i32 for performance / code size reason.
7025 if (LHS.getValueType() == MVT::i8 ||
7026 LHS.getValueType() == MVT::i16)
7027 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7029 // If the operand types disagree, extend the shift amount to match. Since
7030 // BT ignores high bits (like shifts) we can use anyextend.
7031 if (LHS.getValueType() != RHS.getValueType())
7032 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7034 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7035 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7036 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7037 DAG.getConstant(Cond, MVT::i8), BT);
7043 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7044 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7045 SDValue Op0 = Op.getOperand(0);
7046 SDValue Op1 = Op.getOperand(1);
7047 DebugLoc dl = Op.getDebugLoc();
7048 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7050 // Optimize to BT if possible.
7051 // Lower (X & (1 << N)) == 0 to BT(X, N).
7052 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7053 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7054 if (Op0.getOpcode() == ISD::AND &&
7056 Op1.getOpcode() == ISD::Constant &&
7057 cast<ConstantSDNode>(Op1)->isNullValue() &&
7058 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7059 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7060 if (NewSetCC.getNode())
7064 // Look for "(setcc) == / != 1" to avoid unncessary setcc.
7065 if (Op0.getOpcode() == X86ISD::SETCC &&
7066 Op1.getOpcode() == ISD::Constant &&
7067 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7068 cast<ConstantSDNode>(Op1)->isNullValue()) &&
7069 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7070 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7071 bool Invert = (CC == ISD::SETNE) ^
7072 cast<ConstantSDNode>(Op1)->isNullValue();
7074 CCode = X86::GetOppositeBranchCondition(CCode);
7075 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7076 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7079 bool isFP = Op1.getValueType().isFloatingPoint();
7080 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7081 if (X86CC == X86::COND_INVALID)
7084 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
7086 // Use sbb x, x to materialize carry bit into a GPR.
7087 if (X86CC == X86::COND_B)
7088 return DAG.getNode(ISD::AND, dl, MVT::i8,
7089 DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
7090 DAG.getConstant(X86CC, MVT::i8), Cond),
7091 DAG.getConstant(1, MVT::i8));
7093 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7094 DAG.getConstant(X86CC, MVT::i8), Cond);
7097 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7099 SDValue Op0 = Op.getOperand(0);
7100 SDValue Op1 = Op.getOperand(1);
7101 SDValue CC = Op.getOperand(2);
7102 EVT VT = Op.getValueType();
7103 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7104 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7105 DebugLoc dl = Op.getDebugLoc();
7109 EVT VT0 = Op0.getValueType();
7110 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7111 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7114 switch (SetCCOpcode) {
7117 case ISD::SETEQ: SSECC = 0; break;
7119 case ISD::SETGT: Swap = true; // Fallthrough
7121 case ISD::SETOLT: SSECC = 1; break;
7123 case ISD::SETGE: Swap = true; // Fallthrough
7125 case ISD::SETOLE: SSECC = 2; break;
7126 case ISD::SETUO: SSECC = 3; break;
7128 case ISD::SETNE: SSECC = 4; break;
7129 case ISD::SETULE: Swap = true;
7130 case ISD::SETUGE: SSECC = 5; break;
7131 case ISD::SETULT: Swap = true;
7132 case ISD::SETUGT: SSECC = 6; break;
7133 case ISD::SETO: SSECC = 7; break;
7136 std::swap(Op0, Op1);
7138 // In the two special cases we can't handle, emit two comparisons.
7140 if (SetCCOpcode == ISD::SETUEQ) {
7142 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7143 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7144 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7146 else if (SetCCOpcode == ISD::SETONE) {
7148 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7149 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7150 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7152 llvm_unreachable("Illegal FP comparison");
7154 // Handle all other FP comparisons here.
7155 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7158 // We are handling one of the integer comparisons here. Since SSE only has
7159 // GT and EQ comparisons for integer, swapping operands and multiple
7160 // operations may be required for some comparisons.
7161 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7162 bool Swap = false, Invert = false, FlipSigns = false;
7164 switch (VT.getSimpleVT().SimpleTy) {
7167 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7169 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7171 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7172 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7175 switch (SetCCOpcode) {
7177 case ISD::SETNE: Invert = true;
7178 case ISD::SETEQ: Opc = EQOpc; break;
7179 case ISD::SETLT: Swap = true;
7180 case ISD::SETGT: Opc = GTOpc; break;
7181 case ISD::SETGE: Swap = true;
7182 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
7183 case ISD::SETULT: Swap = true;
7184 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7185 case ISD::SETUGE: Swap = true;
7186 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7189 std::swap(Op0, Op1);
7191 // Since SSE has no unsigned integer comparisons, we need to flip the sign
7192 // bits of the inputs before performing those operations.
7194 EVT EltVT = VT.getVectorElementType();
7195 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7197 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7198 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7200 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7201 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7204 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7206 // If the logical-not of the result is required, perform that now.
7208 Result = DAG.getNOT(dl, Result, VT);
7213 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7214 static bool isX86LogicalCmp(SDValue Op) {
7215 unsigned Opc = Op.getNode()->getOpcode();
7216 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7218 if (Op.getResNo() == 1 &&
7219 (Opc == X86ISD::ADD ||
7220 Opc == X86ISD::SUB ||
7221 Opc == X86ISD::SMUL ||
7222 Opc == X86ISD::UMUL ||
7223 Opc == X86ISD::INC ||
7224 Opc == X86ISD::DEC ||
7225 Opc == X86ISD::OR ||
7226 Opc == X86ISD::XOR ||
7227 Opc == X86ISD::AND))
7233 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7234 bool addTest = true;
7235 SDValue Cond = Op.getOperand(0);
7236 DebugLoc dl = Op.getDebugLoc();
7239 if (Cond.getOpcode() == ISD::SETCC) {
7240 SDValue NewCond = LowerSETCC(Cond, DAG);
7241 if (NewCond.getNode())
7245 // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
7246 SDValue Op1 = Op.getOperand(1);
7247 SDValue Op2 = Op.getOperand(2);
7248 if (Cond.getOpcode() == X86ISD::SETCC &&
7249 cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
7250 SDValue Cmp = Cond.getOperand(1);
7251 if (Cmp.getOpcode() == X86ISD::CMP) {
7252 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
7253 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7254 ConstantSDNode *RHSC =
7255 dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
7256 if (N1C && N1C->isAllOnesValue() &&
7257 N2C && N2C->isNullValue() &&
7258 RHSC && RHSC->isNullValue()) {
7259 SDValue CmpOp0 = Cmp.getOperand(0);
7260 Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7261 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7262 return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
7263 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7268 // Look pass (and (setcc_carry (cmp ...)), 1).
7269 if (Cond.getOpcode() == ISD::AND &&
7270 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7271 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7272 if (C && C->getAPIntValue() == 1)
7273 Cond = Cond.getOperand(0);
7276 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7277 // setting operand in place of the X86ISD::SETCC.
7278 if (Cond.getOpcode() == X86ISD::SETCC ||
7279 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7280 CC = Cond.getOperand(0);
7282 SDValue Cmp = Cond.getOperand(1);
7283 unsigned Opc = Cmp.getOpcode();
7284 EVT VT = Op.getValueType();
7286 bool IllegalFPCMov = false;
7287 if (VT.isFloatingPoint() && !VT.isVector() &&
7288 !isScalarFPTypeInSSEReg(VT)) // FPStack?
7289 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7291 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7292 Opc == X86ISD::BT) { // FIXME
7299 // Look pass the truncate.
7300 if (Cond.getOpcode() == ISD::TRUNCATE)
7301 Cond = Cond.getOperand(0);
7303 // We know the result of AND is compared against zero. Try to match
7305 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7306 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7307 if (NewSetCC.getNode()) {
7308 CC = NewSetCC.getOperand(0);
7309 Cond = NewSetCC.getOperand(1);
7316 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7317 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7320 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7321 // condition is true.
7322 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
7323 SDValue Ops[] = { Op2, Op1, CC, Cond };
7324 return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
7327 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7328 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7329 // from the AND / OR.
7330 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7331 Opc = Op.getOpcode();
7332 if (Opc != ISD::OR && Opc != ISD::AND)
7334 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7335 Op.getOperand(0).hasOneUse() &&
7336 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7337 Op.getOperand(1).hasOneUse());
7340 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7341 // 1 and that the SETCC node has a single use.
7342 static bool isXor1OfSetCC(SDValue Op) {
7343 if (Op.getOpcode() != ISD::XOR)
7345 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7346 if (N1C && N1C->getAPIntValue() == 1) {
7347 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7348 Op.getOperand(0).hasOneUse();
7353 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7354 bool addTest = true;
7355 SDValue Chain = Op.getOperand(0);
7356 SDValue Cond = Op.getOperand(1);
7357 SDValue Dest = Op.getOperand(2);
7358 DebugLoc dl = Op.getDebugLoc();
7361 if (Cond.getOpcode() == ISD::SETCC) {
7362 SDValue NewCond = LowerSETCC(Cond, DAG);
7363 if (NewCond.getNode())
7367 // FIXME: LowerXALUO doesn't handle these!!
7368 else if (Cond.getOpcode() == X86ISD::ADD ||
7369 Cond.getOpcode() == X86ISD::SUB ||
7370 Cond.getOpcode() == X86ISD::SMUL ||
7371 Cond.getOpcode() == X86ISD::UMUL)
7372 Cond = LowerXALUO(Cond, DAG);
7375 // Look pass (and (setcc_carry (cmp ...)), 1).
7376 if (Cond.getOpcode() == ISD::AND &&
7377 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7378 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7379 if (C && C->getAPIntValue() == 1)
7380 Cond = Cond.getOperand(0);
7383 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7384 // setting operand in place of the X86ISD::SETCC.
7385 if (Cond.getOpcode() == X86ISD::SETCC ||
7386 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7387 CC = Cond.getOperand(0);
7389 SDValue Cmp = Cond.getOperand(1);
7390 unsigned Opc = Cmp.getOpcode();
7391 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7392 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7396 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7400 // These can only come from an arithmetic instruction with overflow,
7401 // e.g. SADDO, UADDO.
7402 Cond = Cond.getNode()->getOperand(1);
7409 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7410 SDValue Cmp = Cond.getOperand(0).getOperand(1);
7411 if (CondOpc == ISD::OR) {
7412 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7413 // two branches instead of an explicit OR instruction with a
7415 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7416 isX86LogicalCmp(Cmp)) {
7417 CC = Cond.getOperand(0).getOperand(0);
7418 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7419 Chain, Dest, CC, Cmp);
7420 CC = Cond.getOperand(1).getOperand(0);
7424 } else { // ISD::AND
7425 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7426 // two branches instead of an explicit AND instruction with a
7427 // separate test. However, we only do this if this block doesn't
7428 // have a fall-through edge, because this requires an explicit
7429 // jmp when the condition is false.
7430 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7431 isX86LogicalCmp(Cmp) &&
7432 Op.getNode()->hasOneUse()) {
7433 X86::CondCode CCode =
7434 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7435 CCode = X86::GetOppositeBranchCondition(CCode);
7436 CC = DAG.getConstant(CCode, MVT::i8);
7437 SDNode *User = *Op.getNode()->use_begin();
7438 // Look for an unconditional branch following this conditional branch.
7439 // We need this because we need to reverse the successors in order
7440 // to implement FCMP_OEQ.
7441 if (User->getOpcode() == ISD::BR) {
7442 SDValue FalseBB = User->getOperand(1);
7444 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7445 assert(NewBR == User);
7449 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7450 Chain, Dest, CC, Cmp);
7451 X86::CondCode CCode =
7452 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7453 CCode = X86::GetOppositeBranchCondition(CCode);
7454 CC = DAG.getConstant(CCode, MVT::i8);
7460 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7461 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7462 // It should be transformed during dag combiner except when the condition
7463 // is set by a arithmetics with overflow node.
7464 X86::CondCode CCode =
7465 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7466 CCode = X86::GetOppositeBranchCondition(CCode);
7467 CC = DAG.getConstant(CCode, MVT::i8);
7468 Cond = Cond.getOperand(0).getOperand(1);
7474 // Look pass the truncate.
7475 if (Cond.getOpcode() == ISD::TRUNCATE)
7476 Cond = Cond.getOperand(0);
7478 // We know the result of AND is compared against zero. Try to match
7480 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7481 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7482 if (NewSetCC.getNode()) {
7483 CC = NewSetCC.getOperand(0);
7484 Cond = NewSetCC.getOperand(1);
7491 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7492 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7494 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7495 Chain, Dest, CC, Cond);
7499 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7500 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7501 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7502 // that the guard pages used by the OS virtual memory manager are allocated in
7503 // correct sequence.
7505 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7506 SelectionDAG &DAG) const {
7507 assert(Subtarget->isTargetCygMing() &&
7508 "This should be used only on Cygwin/Mingw targets");
7509 DebugLoc dl = Op.getDebugLoc();
7512 SDValue Chain = Op.getOperand(0);
7513 SDValue Size = Op.getOperand(1);
7514 // FIXME: Ensure alignment here
7518 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7520 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
7521 Flag = Chain.getValue(1);
7523 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
7525 Chain = DAG.getNode(X86ISD::MINGW_ALLOCA, dl, NodeTys, Chain, Flag);
7526 Flag = Chain.getValue(1);
7528 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
7530 SDValue Ops1[2] = { Chain.getValue(0), Chain };
7531 return DAG.getMergeValues(Ops1, 2, dl);
7534 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
7535 MachineFunction &MF = DAG.getMachineFunction();
7536 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
7538 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7539 DebugLoc dl = Op.getDebugLoc();
7541 if (!Subtarget->is64Bit()) {
7542 // vastart just stores the address of the VarArgsFrameIndex slot into the
7543 // memory location argument.
7544 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7546 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0,
7551 // gp_offset (0 - 6 * 8)
7552 // fp_offset (48 - 48 + 8 * 16)
7553 // overflow_arg_area (point to parameters coming in memory).
7555 SmallVector<SDValue, 8> MemOps;
7556 SDValue FIN = Op.getOperand(1);
7558 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
7559 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
7561 FIN, SV, 0, false, false, 0);
7562 MemOps.push_back(Store);
7565 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7566 FIN, DAG.getIntPtrConstant(4));
7567 Store = DAG.getStore(Op.getOperand(0), dl,
7568 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
7570 FIN, SV, 4, false, false, 0);
7571 MemOps.push_back(Store);
7573 // Store ptr to overflow_arg_area
7574 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7575 FIN, DAG.getIntPtrConstant(4));
7576 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7578 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 8,
7580 MemOps.push_back(Store);
7582 // Store ptr to reg_save_area.
7583 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
7584 FIN, DAG.getIntPtrConstant(8));
7585 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
7587 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 16,
7589 MemOps.push_back(Store);
7590 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
7591 &MemOps[0], MemOps.size());
7594 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
7595 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
7596 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
7598 report_fatal_error("VAArgInst is not yet implemented for x86-64!");
7602 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
7603 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
7604 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
7605 SDValue Chain = Op.getOperand(0);
7606 SDValue DstPtr = Op.getOperand(1);
7607 SDValue SrcPtr = Op.getOperand(2);
7608 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
7609 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7610 DebugLoc dl = Op.getDebugLoc();
7612 return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
7613 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
7614 false, DstSV, 0, SrcSV, 0);
7618 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
7619 DebugLoc dl = Op.getDebugLoc();
7620 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7622 default: return SDValue(); // Don't custom lower most intrinsics.
7623 // Comparison intrinsics.
7624 case Intrinsic::x86_sse_comieq_ss:
7625 case Intrinsic::x86_sse_comilt_ss:
7626 case Intrinsic::x86_sse_comile_ss:
7627 case Intrinsic::x86_sse_comigt_ss:
7628 case Intrinsic::x86_sse_comige_ss:
7629 case Intrinsic::x86_sse_comineq_ss:
7630 case Intrinsic::x86_sse_ucomieq_ss:
7631 case Intrinsic::x86_sse_ucomilt_ss:
7632 case Intrinsic::x86_sse_ucomile_ss:
7633 case Intrinsic::x86_sse_ucomigt_ss:
7634 case Intrinsic::x86_sse_ucomige_ss:
7635 case Intrinsic::x86_sse_ucomineq_ss:
7636 case Intrinsic::x86_sse2_comieq_sd:
7637 case Intrinsic::x86_sse2_comilt_sd:
7638 case Intrinsic::x86_sse2_comile_sd:
7639 case Intrinsic::x86_sse2_comigt_sd:
7640 case Intrinsic::x86_sse2_comige_sd:
7641 case Intrinsic::x86_sse2_comineq_sd:
7642 case Intrinsic::x86_sse2_ucomieq_sd:
7643 case Intrinsic::x86_sse2_ucomilt_sd:
7644 case Intrinsic::x86_sse2_ucomile_sd:
7645 case Intrinsic::x86_sse2_ucomigt_sd:
7646 case Intrinsic::x86_sse2_ucomige_sd:
7647 case Intrinsic::x86_sse2_ucomineq_sd: {
7649 ISD::CondCode CC = ISD::SETCC_INVALID;
7652 case Intrinsic::x86_sse_comieq_ss:
7653 case Intrinsic::x86_sse2_comieq_sd:
7657 case Intrinsic::x86_sse_comilt_ss:
7658 case Intrinsic::x86_sse2_comilt_sd:
7662 case Intrinsic::x86_sse_comile_ss:
7663 case Intrinsic::x86_sse2_comile_sd:
7667 case Intrinsic::x86_sse_comigt_ss:
7668 case Intrinsic::x86_sse2_comigt_sd:
7672 case Intrinsic::x86_sse_comige_ss:
7673 case Intrinsic::x86_sse2_comige_sd:
7677 case Intrinsic::x86_sse_comineq_ss:
7678 case Intrinsic::x86_sse2_comineq_sd:
7682 case Intrinsic::x86_sse_ucomieq_ss:
7683 case Intrinsic::x86_sse2_ucomieq_sd:
7684 Opc = X86ISD::UCOMI;
7687 case Intrinsic::x86_sse_ucomilt_ss:
7688 case Intrinsic::x86_sse2_ucomilt_sd:
7689 Opc = X86ISD::UCOMI;
7692 case Intrinsic::x86_sse_ucomile_ss:
7693 case Intrinsic::x86_sse2_ucomile_sd:
7694 Opc = X86ISD::UCOMI;
7697 case Intrinsic::x86_sse_ucomigt_ss:
7698 case Intrinsic::x86_sse2_ucomigt_sd:
7699 Opc = X86ISD::UCOMI;
7702 case Intrinsic::x86_sse_ucomige_ss:
7703 case Intrinsic::x86_sse2_ucomige_sd:
7704 Opc = X86ISD::UCOMI;
7707 case Intrinsic::x86_sse_ucomineq_ss:
7708 case Intrinsic::x86_sse2_ucomineq_sd:
7709 Opc = X86ISD::UCOMI;
7714 SDValue LHS = Op.getOperand(1);
7715 SDValue RHS = Op.getOperand(2);
7716 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
7717 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
7718 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
7719 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7720 DAG.getConstant(X86CC, MVT::i8), Cond);
7721 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7723 // ptest and testp intrinsics. The intrinsic these come from are designed to
7724 // return an integer value, not just an instruction so lower it to the ptest
7725 // or testp pattern and a setcc for the result.
7726 case Intrinsic::x86_sse41_ptestz:
7727 case Intrinsic::x86_sse41_ptestc:
7728 case Intrinsic::x86_sse41_ptestnzc:
7729 case Intrinsic::x86_avx_ptestz_256:
7730 case Intrinsic::x86_avx_ptestc_256:
7731 case Intrinsic::x86_avx_ptestnzc_256:
7732 case Intrinsic::x86_avx_vtestz_ps:
7733 case Intrinsic::x86_avx_vtestc_ps:
7734 case Intrinsic::x86_avx_vtestnzc_ps:
7735 case Intrinsic::x86_avx_vtestz_pd:
7736 case Intrinsic::x86_avx_vtestc_pd:
7737 case Intrinsic::x86_avx_vtestnzc_pd:
7738 case Intrinsic::x86_avx_vtestz_ps_256:
7739 case Intrinsic::x86_avx_vtestc_ps_256:
7740 case Intrinsic::x86_avx_vtestnzc_ps_256:
7741 case Intrinsic::x86_avx_vtestz_pd_256:
7742 case Intrinsic::x86_avx_vtestc_pd_256:
7743 case Intrinsic::x86_avx_vtestnzc_pd_256: {
7744 bool IsTestPacked = false;
7747 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
7748 case Intrinsic::x86_avx_vtestz_ps:
7749 case Intrinsic::x86_avx_vtestz_pd:
7750 case Intrinsic::x86_avx_vtestz_ps_256:
7751 case Intrinsic::x86_avx_vtestz_pd_256:
7752 IsTestPacked = true; // Fallthrough
7753 case Intrinsic::x86_sse41_ptestz:
7754 case Intrinsic::x86_avx_ptestz_256:
7756 X86CC = X86::COND_E;
7758 case Intrinsic::x86_avx_vtestc_ps:
7759 case Intrinsic::x86_avx_vtestc_pd:
7760 case Intrinsic::x86_avx_vtestc_ps_256:
7761 case Intrinsic::x86_avx_vtestc_pd_256:
7762 IsTestPacked = true; // Fallthrough
7763 case Intrinsic::x86_sse41_ptestc:
7764 case Intrinsic::x86_avx_ptestc_256:
7766 X86CC = X86::COND_B;
7768 case Intrinsic::x86_avx_vtestnzc_ps:
7769 case Intrinsic::x86_avx_vtestnzc_pd:
7770 case Intrinsic::x86_avx_vtestnzc_ps_256:
7771 case Intrinsic::x86_avx_vtestnzc_pd_256:
7772 IsTestPacked = true; // Fallthrough
7773 case Intrinsic::x86_sse41_ptestnzc:
7774 case Intrinsic::x86_avx_ptestnzc_256:
7776 X86CC = X86::COND_A;
7780 SDValue LHS = Op.getOperand(1);
7781 SDValue RHS = Op.getOperand(2);
7782 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
7783 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
7784 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
7785 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
7786 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7789 // Fix vector shift instructions where the last operand is a non-immediate
7791 case Intrinsic::x86_sse2_pslli_w:
7792 case Intrinsic::x86_sse2_pslli_d:
7793 case Intrinsic::x86_sse2_pslli_q:
7794 case Intrinsic::x86_sse2_psrli_w:
7795 case Intrinsic::x86_sse2_psrli_d:
7796 case Intrinsic::x86_sse2_psrli_q:
7797 case Intrinsic::x86_sse2_psrai_w:
7798 case Intrinsic::x86_sse2_psrai_d:
7799 case Intrinsic::x86_mmx_pslli_w:
7800 case Intrinsic::x86_mmx_pslli_d:
7801 case Intrinsic::x86_mmx_pslli_q:
7802 case Intrinsic::x86_mmx_psrli_w:
7803 case Intrinsic::x86_mmx_psrli_d:
7804 case Intrinsic::x86_mmx_psrli_q:
7805 case Intrinsic::x86_mmx_psrai_w:
7806 case Intrinsic::x86_mmx_psrai_d: {
7807 SDValue ShAmt = Op.getOperand(2);
7808 if (isa<ConstantSDNode>(ShAmt))
7811 unsigned NewIntNo = 0;
7812 EVT ShAmtVT = MVT::v4i32;
7814 case Intrinsic::x86_sse2_pslli_w:
7815 NewIntNo = Intrinsic::x86_sse2_psll_w;
7817 case Intrinsic::x86_sse2_pslli_d:
7818 NewIntNo = Intrinsic::x86_sse2_psll_d;
7820 case Intrinsic::x86_sse2_pslli_q:
7821 NewIntNo = Intrinsic::x86_sse2_psll_q;
7823 case Intrinsic::x86_sse2_psrli_w:
7824 NewIntNo = Intrinsic::x86_sse2_psrl_w;
7826 case Intrinsic::x86_sse2_psrli_d:
7827 NewIntNo = Intrinsic::x86_sse2_psrl_d;
7829 case Intrinsic::x86_sse2_psrli_q:
7830 NewIntNo = Intrinsic::x86_sse2_psrl_q;
7832 case Intrinsic::x86_sse2_psrai_w:
7833 NewIntNo = Intrinsic::x86_sse2_psra_w;
7835 case Intrinsic::x86_sse2_psrai_d:
7836 NewIntNo = Intrinsic::x86_sse2_psra_d;
7839 ShAmtVT = MVT::v2i32;
7841 case Intrinsic::x86_mmx_pslli_w:
7842 NewIntNo = Intrinsic::x86_mmx_psll_w;
7844 case Intrinsic::x86_mmx_pslli_d:
7845 NewIntNo = Intrinsic::x86_mmx_psll_d;
7847 case Intrinsic::x86_mmx_pslli_q:
7848 NewIntNo = Intrinsic::x86_mmx_psll_q;
7850 case Intrinsic::x86_mmx_psrli_w:
7851 NewIntNo = Intrinsic::x86_mmx_psrl_w;
7853 case Intrinsic::x86_mmx_psrli_d:
7854 NewIntNo = Intrinsic::x86_mmx_psrl_d;
7856 case Intrinsic::x86_mmx_psrli_q:
7857 NewIntNo = Intrinsic::x86_mmx_psrl_q;
7859 case Intrinsic::x86_mmx_psrai_w:
7860 NewIntNo = Intrinsic::x86_mmx_psra_w;
7862 case Intrinsic::x86_mmx_psrai_d:
7863 NewIntNo = Intrinsic::x86_mmx_psra_d;
7865 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7871 // The vector shift intrinsics with scalars uses 32b shift amounts but
7872 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
7876 ShOps[1] = DAG.getConstant(0, MVT::i32);
7877 if (ShAmtVT == MVT::v4i32) {
7878 ShOps[2] = DAG.getUNDEF(MVT::i32);
7879 ShOps[3] = DAG.getUNDEF(MVT::i32);
7880 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
7882 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
7885 EVT VT = Op.getValueType();
7886 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
7887 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7888 DAG.getConstant(NewIntNo, MVT::i32),
7889 Op.getOperand(1), ShAmt);
7894 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
7895 SelectionDAG &DAG) const {
7896 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7897 MFI->setReturnAddressIsTaken(true);
7899 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7900 DebugLoc dl = Op.getDebugLoc();
7903 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7905 DAG.getConstant(TD->getPointerSize(),
7906 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
7907 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7908 DAG.getNode(ISD::ADD, dl, getPointerTy(),
7910 NULL, 0, false, false, 0);
7913 // Just load the return address.
7914 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
7915 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7916 RetAddrFI, NULL, 0, false, false, 0);
7919 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
7920 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7921 MFI->setFrameAddressIsTaken(true);
7923 EVT VT = Op.getValueType();
7924 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
7925 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7926 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
7927 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
7929 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0,
7934 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
7935 SelectionDAG &DAG) const {
7936 return DAG.getIntPtrConstant(2*TD->getPointerSize());
7939 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
7940 MachineFunction &MF = DAG.getMachineFunction();
7941 SDValue Chain = Op.getOperand(0);
7942 SDValue Offset = Op.getOperand(1);
7943 SDValue Handler = Op.getOperand(2);
7944 DebugLoc dl = Op.getDebugLoc();
7946 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
7947 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
7949 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
7951 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
7952 DAG.getIntPtrConstant(TD->getPointerSize()));
7953 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
7954 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0, false, false, 0);
7955 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
7956 MF.getRegInfo().addLiveOut(StoreAddrReg);
7958 return DAG.getNode(X86ISD::EH_RETURN, dl,
7960 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
7963 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
7964 SelectionDAG &DAG) const {
7965 SDValue Root = Op.getOperand(0);
7966 SDValue Trmp = Op.getOperand(1); // trampoline
7967 SDValue FPtr = Op.getOperand(2); // nested function
7968 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
7969 DebugLoc dl = Op.getDebugLoc();
7971 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7973 if (Subtarget->is64Bit()) {
7974 SDValue OutChains[6];
7976 // Large code-model.
7977 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
7978 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
7980 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
7981 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
7983 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
7985 // Load the pointer to the nested function into R11.
7986 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
7987 SDValue Addr = Trmp;
7988 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7989 Addr, TrmpAddr, 0, false, false, 0);
7991 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7992 DAG.getConstant(2, MVT::i64));
7993 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2,
7996 // Load the 'nest' parameter value into R10.
7997 // R10 is specified in X86CallingConv.td
7998 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
7999 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8000 DAG.getConstant(10, MVT::i64));
8001 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8002 Addr, TrmpAddr, 10, false, false, 0);
8004 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8005 DAG.getConstant(12, MVT::i64));
8006 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12,
8009 // Jump to the nested function.
8010 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8011 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8012 DAG.getConstant(20, MVT::i64));
8013 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8014 Addr, TrmpAddr, 20, false, false, 0);
8016 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8017 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8018 DAG.getConstant(22, MVT::i64));
8019 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8020 TrmpAddr, 22, false, false, 0);
8023 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8024 return DAG.getMergeValues(Ops, 2, dl);
8026 const Function *Func =
8027 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8028 CallingConv::ID CC = Func->getCallingConv();
8033 llvm_unreachable("Unsupported calling convention");
8034 case CallingConv::C:
8035 case CallingConv::X86_StdCall: {
8036 // Pass 'nest' parameter in ECX.
8037 // Must be kept in sync with X86CallingConv.td
8040 // Check that ECX wasn't needed by an 'inreg' parameter.
8041 const FunctionType *FTy = Func->getFunctionType();
8042 const AttrListPtr &Attrs = Func->getAttributes();
8044 if (!Attrs.isEmpty() && !Func->isVarArg()) {
8045 unsigned InRegCount = 0;
8048 for (FunctionType::param_iterator I = FTy->param_begin(),
8049 E = FTy->param_end(); I != E; ++I, ++Idx)
8050 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8051 // FIXME: should only count parameters that are lowered to integers.
8052 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8054 if (InRegCount > 2) {
8055 report_fatal_error("Nest register in use - reduce number of inreg"
8061 case CallingConv::X86_FastCall:
8062 case CallingConv::X86_ThisCall:
8063 case CallingConv::Fast:
8064 // Pass 'nest' parameter in EAX.
8065 // Must be kept in sync with X86CallingConv.td
8070 SDValue OutChains[4];
8073 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8074 DAG.getConstant(10, MVT::i32));
8075 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8077 // This is storing the opcode for MOV32ri.
8078 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8079 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8080 OutChains[0] = DAG.getStore(Root, dl,
8081 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8082 Trmp, TrmpAddr, 0, false, false, 0);
8084 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8085 DAG.getConstant(1, MVT::i32));
8086 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1,
8089 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8090 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8091 DAG.getConstant(5, MVT::i32));
8092 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8093 TrmpAddr, 5, false, false, 1);
8095 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8096 DAG.getConstant(6, MVT::i32));
8097 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6,
8101 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8102 return DAG.getMergeValues(Ops, 2, dl);
8106 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8107 SelectionDAG &DAG) const {
8109 The rounding mode is in bits 11:10 of FPSR, and has the following
8116 FLT_ROUNDS, on the other hand, expects the following:
8123 To perform the conversion, we do:
8124 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8127 MachineFunction &MF = DAG.getMachineFunction();
8128 const TargetMachine &TM = MF.getTarget();
8129 const TargetFrameInfo &TFI = *TM.getFrameInfo();
8130 unsigned StackAlignment = TFI.getStackAlignment();
8131 EVT VT = Op.getValueType();
8132 DebugLoc dl = Op.getDebugLoc();
8134 // Save FP Control Word to stack slot
8135 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8136 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8138 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
8139 DAG.getEntryNode(), StackSlot);
8141 // Load FP Control Word from stack slot
8142 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0,
8145 // Transform as necessary
8147 DAG.getNode(ISD::SRL, dl, MVT::i16,
8148 DAG.getNode(ISD::AND, dl, MVT::i16,
8149 CWD, DAG.getConstant(0x800, MVT::i16)),
8150 DAG.getConstant(11, MVT::i8));
8152 DAG.getNode(ISD::SRL, dl, MVT::i16,
8153 DAG.getNode(ISD::AND, dl, MVT::i16,
8154 CWD, DAG.getConstant(0x400, MVT::i16)),
8155 DAG.getConstant(9, MVT::i8));
8158 DAG.getNode(ISD::AND, dl, MVT::i16,
8159 DAG.getNode(ISD::ADD, dl, MVT::i16,
8160 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
8161 DAG.getConstant(1, MVT::i16)),
8162 DAG.getConstant(3, MVT::i16));
8165 return DAG.getNode((VT.getSizeInBits() < 16 ?
8166 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
8169 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8170 EVT VT = Op.getValueType();
8172 unsigned NumBits = VT.getSizeInBits();
8173 DebugLoc dl = Op.getDebugLoc();
8175 Op = Op.getOperand(0);
8176 if (VT == MVT::i8) {
8177 // Zero extend to i32 since there is not an i8 bsr.
8179 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8182 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8183 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8184 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8186 // If src is zero (i.e. bsr sets ZF), returns NumBits.
8189 DAG.getConstant(NumBits+NumBits-1, OpVT),
8190 DAG.getConstant(X86::COND_E, MVT::i8),
8193 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8195 // Finally xor with NumBits-1.
8196 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8199 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8203 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8204 EVT VT = Op.getValueType();
8206 unsigned NumBits = VT.getSizeInBits();
8207 DebugLoc dl = Op.getDebugLoc();
8209 Op = Op.getOperand(0);
8210 if (VT == MVT::i8) {
8212 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8215 // Issue a bsf (scan bits forward) which also sets EFLAGS.
8216 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8217 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8219 // If src is zero (i.e. bsf sets ZF), returns NumBits.
8222 DAG.getConstant(NumBits, OpVT),
8223 DAG.getConstant(X86::COND_E, MVT::i8),
8226 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8229 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8233 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8234 EVT VT = Op.getValueType();
8235 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8236 DebugLoc dl = Op.getDebugLoc();
8238 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8239 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8240 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8241 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8242 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8244 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8245 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8246 // return AloBlo + AloBhi + AhiBlo;
8248 SDValue A = Op.getOperand(0);
8249 SDValue B = Op.getOperand(1);
8251 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8252 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8253 A, DAG.getConstant(32, MVT::i32));
8254 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8255 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8256 B, DAG.getConstant(32, MVT::i32));
8257 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8258 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8260 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8261 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8263 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8264 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8266 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8267 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8268 AloBhi, DAG.getConstant(32, MVT::i32));
8269 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8270 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8271 AhiBlo, DAG.getConstant(32, MVT::i32));
8272 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8273 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8277 SDValue X86TargetLowering::LowerSHL(SDValue Op, SelectionDAG &DAG) const {
8278 EVT VT = Op.getValueType();
8279 DebugLoc dl = Op.getDebugLoc();
8280 SDValue R = Op.getOperand(0);
8282 LLVMContext *Context = DAG.getContext();
8284 assert(Subtarget->hasSSE41() && "Cannot lower SHL without SSE4.1 or later");
8286 if (VT == MVT::v4i32) {
8287 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8288 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8289 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8291 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8293 std::vector<Constant*> CV(4, CI);
8294 Constant *C = ConstantVector::get(CV);
8295 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8296 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8297 PseudoSourceValue::getConstantPool(), 0,
8300 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8301 Op = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, Op);
8302 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8303 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8305 if (VT == MVT::v16i8) {
8307 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8308 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8309 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8311 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8312 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8314 std::vector<Constant*> CVM1(16, CM1);
8315 std::vector<Constant*> CVM2(16, CM2);
8316 Constant *C = ConstantVector::get(CVM1);
8317 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8318 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8319 PseudoSourceValue::getConstantPool(), 0,
8322 // r = pblendv(r, psllw(r & (char16)15, 4), a);
8323 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8324 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8325 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8326 DAG.getConstant(4, MVT::i32));
8327 R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8328 DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8331 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8333 C = ConstantVector::get(CVM2);
8334 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8335 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8336 PseudoSourceValue::getConstantPool(), 0, false, false, 16);
8338 // r = pblendv(r, psllw(r & (char16)63, 2), a);
8339 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8340 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8341 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8342 DAG.getConstant(2, MVT::i32));
8343 R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8344 DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8347 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8349 // return pblendv(r, r+r, a);
8350 R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8351 DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8352 R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8358 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8359 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8360 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8361 // looks for this combo and may remove the "setcc" instruction if the "setcc"
8362 // has only one use.
8363 SDNode *N = Op.getNode();
8364 SDValue LHS = N->getOperand(0);
8365 SDValue RHS = N->getOperand(1);
8366 unsigned BaseOp = 0;
8368 DebugLoc dl = Op.getDebugLoc();
8370 switch (Op.getOpcode()) {
8371 default: llvm_unreachable("Unknown ovf instruction!");
8373 // A subtract of one will be selected as a INC. Note that INC doesn't
8374 // set CF, so we can't do this for UADDO.
8375 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8376 if (C->getAPIntValue() == 1) {
8377 BaseOp = X86ISD::INC;
8381 BaseOp = X86ISD::ADD;
8385 BaseOp = X86ISD::ADD;
8389 // A subtract of one will be selected as a DEC. Note that DEC doesn't
8390 // set CF, so we can't do this for USUBO.
8391 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8392 if (C->getAPIntValue() == 1) {
8393 BaseOp = X86ISD::DEC;
8397 BaseOp = X86ISD::SUB;
8401 BaseOp = X86ISD::SUB;
8405 BaseOp = X86ISD::SMUL;
8409 BaseOp = X86ISD::UMUL;
8414 // Also sets EFLAGS.
8415 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
8416 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
8419 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
8420 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
8422 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8426 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
8427 DebugLoc dl = Op.getDebugLoc();
8429 if (!Subtarget->hasSSE2()) {
8430 SDValue Chain = Op.getOperand(0);
8431 SDValue Zero = DAG.getConstant(0,
8432 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8434 DAG.getRegister(X86::ESP, MVT::i32), // Base
8435 DAG.getTargetConstant(1, MVT::i8), // Scale
8436 DAG.getRegister(0, MVT::i32), // Index
8437 DAG.getTargetConstant(0, MVT::i32), // Disp
8438 DAG.getRegister(0, MVT::i32), // Segment.
8443 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
8444 array_lengthof(Ops));
8445 return SDValue(Res, 0);
8448 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
8450 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
8452 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8453 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8454 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
8455 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
8457 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
8458 if (!Op1 && !Op2 && !Op3 && Op4)
8459 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
8461 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
8462 if (Op1 && !Op2 && !Op3 && !Op4)
8463 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
8465 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
8467 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
8470 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8471 EVT T = Op.getValueType();
8472 DebugLoc dl = Op.getDebugLoc();
8475 switch(T.getSimpleVT().SimpleTy) {
8477 assert(false && "Invalid value type!");
8478 case MVT::i8: Reg = X86::AL; size = 1; break;
8479 case MVT::i16: Reg = X86::AX; size = 2; break;
8480 case MVT::i32: Reg = X86::EAX; size = 4; break;
8482 assert(Subtarget->is64Bit() && "Node not type legal!");
8483 Reg = X86::RAX; size = 8;
8486 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
8487 Op.getOperand(2), SDValue());
8488 SDValue Ops[] = { cpIn.getValue(0),
8491 DAG.getTargetConstant(size, MVT::i8),
8493 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8494 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
8496 DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
8500 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
8501 SelectionDAG &DAG) const {
8502 assert(Subtarget->is64Bit() && "Result not type legalized?");
8503 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8504 SDValue TheChain = Op.getOperand(0);
8505 DebugLoc dl = Op.getDebugLoc();
8506 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8507 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
8508 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
8510 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
8511 DAG.getConstant(32, MVT::i8));
8513 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
8516 return DAG.getMergeValues(Ops, 2, dl);
8519 SDValue X86TargetLowering::LowerBIT_CONVERT(SDValue Op,
8520 SelectionDAG &DAG) const {
8521 EVT SrcVT = Op.getOperand(0).getValueType();
8522 EVT DstVT = Op.getValueType();
8523 assert((Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
8524 Subtarget->hasMMX() && !DisableMMX) &&
8525 "Unexpected custom BIT_CONVERT");
8526 assert((DstVT == MVT::i64 ||
8527 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
8528 "Unexpected custom BIT_CONVERT");
8529 // i64 <=> MMX conversions are Legal.
8530 if (SrcVT==MVT::i64 && DstVT.isVector())
8532 if (DstVT==MVT::i64 && SrcVT.isVector())
8534 // MMX <=> MMX conversions are Legal.
8535 if (SrcVT.isVector() && DstVT.isVector())
8537 // All other conversions need to be expanded.
8540 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
8541 SDNode *Node = Op.getNode();
8542 DebugLoc dl = Node->getDebugLoc();
8543 EVT T = Node->getValueType(0);
8544 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
8545 DAG.getConstant(0, T), Node->getOperand(2));
8546 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
8547 cast<AtomicSDNode>(Node)->getMemoryVT(),
8548 Node->getOperand(0),
8549 Node->getOperand(1), negOp,
8550 cast<AtomicSDNode>(Node)->getSrcValue(),
8551 cast<AtomicSDNode>(Node)->getAlignment());
8554 /// LowerOperation - Provide custom lowering hooks for some operations.
8556 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8557 switch (Op.getOpcode()) {
8558 default: llvm_unreachable("Should not custom lower this!");
8559 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
8560 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
8561 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
8562 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
8563 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
8564 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
8565 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8566 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
8567 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
8568 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
8569 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
8570 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
8571 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
8572 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
8573 case ISD::SHL_PARTS:
8574 case ISD::SRA_PARTS:
8575 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
8576 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
8577 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
8578 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
8579 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
8580 case ISD::FABS: return LowerFABS(Op, DAG);
8581 case ISD::FNEG: return LowerFNEG(Op, DAG);
8582 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
8583 case ISD::SETCC: return LowerSETCC(Op, DAG);
8584 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
8585 case ISD::SELECT: return LowerSELECT(Op, DAG);
8586 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
8587 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
8588 case ISD::VASTART: return LowerVASTART(Op, DAG);
8589 case ISD::VAARG: return LowerVAARG(Op, DAG);
8590 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
8591 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8592 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
8593 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
8594 case ISD::FRAME_TO_ARGS_OFFSET:
8595 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
8596 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
8597 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
8598 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
8599 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
8600 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
8601 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
8602 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
8603 case ISD::SHL: return LowerSHL(Op, DAG);
8609 case ISD::UMULO: return LowerXALUO(Op, DAG);
8610 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
8611 case ISD::BIT_CONVERT: return LowerBIT_CONVERT(Op, DAG);
8615 void X86TargetLowering::
8616 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
8617 SelectionDAG &DAG, unsigned NewOp) const {
8618 EVT T = Node->getValueType(0);
8619 DebugLoc dl = Node->getDebugLoc();
8620 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
8622 SDValue Chain = Node->getOperand(0);
8623 SDValue In1 = Node->getOperand(1);
8624 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8625 Node->getOperand(2), DAG.getIntPtrConstant(0));
8626 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8627 Node->getOperand(2), DAG.getIntPtrConstant(1));
8628 SDValue Ops[] = { Chain, In1, In2L, In2H };
8629 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8631 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
8632 cast<MemSDNode>(Node)->getMemOperand());
8633 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
8634 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8635 Results.push_back(Result.getValue(2));
8638 /// ReplaceNodeResults - Replace a node with an illegal result type
8639 /// with a new node built out of custom code.
8640 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
8641 SmallVectorImpl<SDValue>&Results,
8642 SelectionDAG &DAG) const {
8643 DebugLoc dl = N->getDebugLoc();
8644 switch (N->getOpcode()) {
8646 assert(false && "Do not know how to custom type legalize this operation!");
8648 case ISD::FP_TO_SINT: {
8649 std::pair<SDValue,SDValue> Vals =
8650 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
8651 SDValue FIST = Vals.first, StackSlot = Vals.second;
8652 if (FIST.getNode() != 0) {
8653 EVT VT = N->getValueType(0);
8654 // Return a load from the stack slot.
8655 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0,
8660 case ISD::READCYCLECOUNTER: {
8661 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8662 SDValue TheChain = N->getOperand(0);
8663 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8664 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
8666 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
8668 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
8669 SDValue Ops[] = { eax, edx };
8670 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
8671 Results.push_back(edx.getValue(1));
8674 case ISD::ATOMIC_CMP_SWAP: {
8675 EVT T = N->getValueType(0);
8676 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
8677 SDValue cpInL, cpInH;
8678 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8679 DAG.getConstant(0, MVT::i32));
8680 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8681 DAG.getConstant(1, MVT::i32));
8682 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
8683 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
8685 SDValue swapInL, swapInH;
8686 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8687 DAG.getConstant(0, MVT::i32));
8688 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8689 DAG.getConstant(1, MVT::i32));
8690 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
8692 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
8693 swapInL.getValue(1));
8694 SDValue Ops[] = { swapInH.getValue(0),
8696 swapInH.getValue(1) };
8697 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8698 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
8699 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
8700 MVT::i32, Result.getValue(1));
8701 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
8702 MVT::i32, cpOutL.getValue(2));
8703 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
8704 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8705 Results.push_back(cpOutH.getValue(1));
8708 case ISD::ATOMIC_LOAD_ADD:
8709 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
8711 case ISD::ATOMIC_LOAD_AND:
8712 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
8714 case ISD::ATOMIC_LOAD_NAND:
8715 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
8717 case ISD::ATOMIC_LOAD_OR:
8718 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
8720 case ISD::ATOMIC_LOAD_SUB:
8721 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
8723 case ISD::ATOMIC_LOAD_XOR:
8724 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
8726 case ISD::ATOMIC_SWAP:
8727 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
8732 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
8734 default: return NULL;
8735 case X86ISD::BSF: return "X86ISD::BSF";
8736 case X86ISD::BSR: return "X86ISD::BSR";
8737 case X86ISD::SHLD: return "X86ISD::SHLD";
8738 case X86ISD::SHRD: return "X86ISD::SHRD";
8739 case X86ISD::FAND: return "X86ISD::FAND";
8740 case X86ISD::FOR: return "X86ISD::FOR";
8741 case X86ISD::FXOR: return "X86ISD::FXOR";
8742 case X86ISD::FSRL: return "X86ISD::FSRL";
8743 case X86ISD::FILD: return "X86ISD::FILD";
8744 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
8745 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
8746 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
8747 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
8748 case X86ISD::FLD: return "X86ISD::FLD";
8749 case X86ISD::FST: return "X86ISD::FST";
8750 case X86ISD::CALL: return "X86ISD::CALL";
8751 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
8752 case X86ISD::BT: return "X86ISD::BT";
8753 case X86ISD::CMP: return "X86ISD::CMP";
8754 case X86ISD::COMI: return "X86ISD::COMI";
8755 case X86ISD::UCOMI: return "X86ISD::UCOMI";
8756 case X86ISD::SETCC: return "X86ISD::SETCC";
8757 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
8758 case X86ISD::CMOV: return "X86ISD::CMOV";
8759 case X86ISD::BRCOND: return "X86ISD::BRCOND";
8760 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
8761 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
8762 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
8763 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
8764 case X86ISD::Wrapper: return "X86ISD::Wrapper";
8765 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
8766 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
8767 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
8768 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
8769 case X86ISD::PINSRB: return "X86ISD::PINSRB";
8770 case X86ISD::PINSRW: return "X86ISD::PINSRW";
8771 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
8772 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
8773 case X86ISD::FMAX: return "X86ISD::FMAX";
8774 case X86ISD::FMIN: return "X86ISD::FMIN";
8775 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
8776 case X86ISD::FRCP: return "X86ISD::FRCP";
8777 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
8778 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
8779 case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
8780 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
8781 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
8782 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
8783 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
8784 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
8785 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
8786 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
8787 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
8788 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
8789 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
8790 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
8791 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
8792 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
8793 case X86ISD::VSHL: return "X86ISD::VSHL";
8794 case X86ISD::VSRL: return "X86ISD::VSRL";
8795 case X86ISD::CMPPD: return "X86ISD::CMPPD";
8796 case X86ISD::CMPPS: return "X86ISD::CMPPS";
8797 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
8798 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
8799 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
8800 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
8801 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
8802 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
8803 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
8804 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
8805 case X86ISD::ADD: return "X86ISD::ADD";
8806 case X86ISD::SUB: return "X86ISD::SUB";
8807 case X86ISD::SMUL: return "X86ISD::SMUL";
8808 case X86ISD::UMUL: return "X86ISD::UMUL";
8809 case X86ISD::INC: return "X86ISD::INC";
8810 case X86ISD::DEC: return "X86ISD::DEC";
8811 case X86ISD::OR: return "X86ISD::OR";
8812 case X86ISD::XOR: return "X86ISD::XOR";
8813 case X86ISD::AND: return "X86ISD::AND";
8814 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
8815 case X86ISD::PTEST: return "X86ISD::PTEST";
8816 case X86ISD::TESTP: return "X86ISD::TESTP";
8817 case X86ISD::PALIGN: return "X86ISD::PALIGN";
8818 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
8819 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
8820 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
8821 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
8822 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
8823 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
8824 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
8825 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
8826 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
8827 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
8828 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD";
8829 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
8830 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
8831 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
8832 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
8833 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
8834 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
8835 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
8836 case X86ISD::MOVSD: return "X86ISD::MOVSD";
8837 case X86ISD::MOVSS: return "X86ISD::MOVSS";
8838 case X86ISD::UNPCKLPS: return "X86ISD::UNPCKLPS";
8839 case X86ISD::UNPCKLPD: return "X86ISD::UNPCKLPD";
8840 case X86ISD::UNPCKHPS: return "X86ISD::UNPCKHPS";
8841 case X86ISD::UNPCKHPD: return "X86ISD::UNPCKHPD";
8842 case X86ISD::PUNPCKLBW: return "X86ISD::PUNPCKLBW";
8843 case X86ISD::PUNPCKLWD: return "X86ISD::PUNPCKLWD";
8844 case X86ISD::PUNPCKLDQ: return "X86ISD::PUNPCKLDQ";
8845 case X86ISD::PUNPCKLQDQ: return "X86ISD::PUNPCKLQDQ";
8846 case X86ISD::PUNPCKHBW: return "X86ISD::PUNPCKHBW";
8847 case X86ISD::PUNPCKHWD: return "X86ISD::PUNPCKHWD";
8848 case X86ISD::PUNPCKHDQ: return "X86ISD::PUNPCKHDQ";
8849 case X86ISD::PUNPCKHQDQ: return "X86ISD::PUNPCKHQDQ";
8850 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
8851 case X86ISD::MINGW_ALLOCA: return "X86ISD::MINGW_ALLOCA";
8855 // isLegalAddressingMode - Return true if the addressing mode represented
8856 // by AM is legal for this target, for a load/store of the specified type.
8857 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
8858 const Type *Ty) const {
8859 // X86 supports extremely general addressing modes.
8860 CodeModel::Model M = getTargetMachine().getCodeModel();
8861 Reloc::Model R = getTargetMachine().getRelocationModel();
8863 // X86 allows a sign-extended 32-bit immediate field as a displacement.
8864 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
8869 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
8871 // If a reference to this global requires an extra load, we can't fold it.
8872 if (isGlobalStubReference(GVFlags))
8875 // If BaseGV requires a register for the PIC base, we cannot also have a
8876 // BaseReg specified.
8877 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
8880 // If lower 4G is not available, then we must use rip-relative addressing.
8881 if ((M != CodeModel::Small || R != Reloc::Static) &&
8882 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
8892 // These scales always work.
8897 // These scales are formed with basereg+scalereg. Only accept if there is
8902 default: // Other stuff never works.
8910 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
8911 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8913 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8914 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8915 if (NumBits1 <= NumBits2)
8920 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
8921 if (!VT1.isInteger() || !VT2.isInteger())
8923 unsigned NumBits1 = VT1.getSizeInBits();
8924 unsigned NumBits2 = VT2.getSizeInBits();
8925 if (NumBits1 <= NumBits2)
8930 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
8931 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
8932 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
8935 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
8936 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
8937 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
8940 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
8941 // i16 instructions are longer (0x66 prefix) and potentially slower.
8942 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
8945 /// isShuffleMaskLegal - Targets can use this to indicate that they only
8946 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
8947 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
8948 /// are assumed to be legal.
8950 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
8952 // Very little shuffling can be done for 64-bit vectors right now.
8953 if (VT.getSizeInBits() == 64)
8954 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
8956 // FIXME: pshufb, blends, shifts.
8957 return (VT.getVectorNumElements() == 2 ||
8958 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
8959 isMOVLMask(M, VT) ||
8960 isSHUFPMask(M, VT) ||
8961 isPSHUFDMask(M, VT) ||
8962 isPSHUFHWMask(M, VT) ||
8963 isPSHUFLWMask(M, VT) ||
8964 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
8965 isUNPCKLMask(M, VT) ||
8966 isUNPCKHMask(M, VT) ||
8967 isUNPCKL_v_undef_Mask(M, VT) ||
8968 isUNPCKH_v_undef_Mask(M, VT));
8972 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
8974 unsigned NumElts = VT.getVectorNumElements();
8975 // FIXME: This collection of masks seems suspect.
8978 if (NumElts == 4 && VT.getSizeInBits() == 128) {
8979 return (isMOVLMask(Mask, VT) ||
8980 isCommutedMOVLMask(Mask, VT, true) ||
8981 isSHUFPMask(Mask, VT) ||
8982 isCommutedSHUFPMask(Mask, VT));
8987 //===----------------------------------------------------------------------===//
8988 // X86 Scheduler Hooks
8989 //===----------------------------------------------------------------------===//
8991 // private utility function
8993 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
8994 MachineBasicBlock *MBB,
9001 TargetRegisterClass *RC,
9002 bool invSrc) const {
9003 // For the atomic bitwise operator, we generate
9006 // ld t1 = [bitinstr.addr]
9007 // op t2 = t1, [bitinstr.val]
9009 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9011 // fallthrough -->nextMBB
9012 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9013 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9014 MachineFunction::iterator MBBIter = MBB;
9017 /// First build the CFG
9018 MachineFunction *F = MBB->getParent();
9019 MachineBasicBlock *thisMBB = MBB;
9020 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9021 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9022 F->insert(MBBIter, newMBB);
9023 F->insert(MBBIter, nextMBB);
9025 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9026 nextMBB->splice(nextMBB->begin(), thisMBB,
9027 llvm::next(MachineBasicBlock::iterator(bInstr)),
9029 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9031 // Update thisMBB to fall through to newMBB
9032 thisMBB->addSuccessor(newMBB);
9034 // newMBB jumps to itself and fall through to nextMBB
9035 newMBB->addSuccessor(nextMBB);
9036 newMBB->addSuccessor(newMBB);
9038 // Insert instructions into newMBB based on incoming instruction
9039 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9040 "unexpected number of operands");
9041 DebugLoc dl = bInstr->getDebugLoc();
9042 MachineOperand& destOper = bInstr->getOperand(0);
9043 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9044 int numArgs = bInstr->getNumOperands() - 1;
9045 for (int i=0; i < numArgs; ++i)
9046 argOpers[i] = &bInstr->getOperand(i+1);
9048 // x86 address has 4 operands: base, index, scale, and displacement
9049 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9050 int valArgIndx = lastAddrIndx + 1;
9052 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9053 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9054 for (int i=0; i <= lastAddrIndx; ++i)
9055 (*MIB).addOperand(*argOpers[i]);
9057 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9059 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9064 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9065 assert((argOpers[valArgIndx]->isReg() ||
9066 argOpers[valArgIndx]->isImm()) &&
9068 if (argOpers[valArgIndx]->isReg())
9069 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9071 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9073 (*MIB).addOperand(*argOpers[valArgIndx]);
9075 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9078 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9079 for (int i=0; i <= lastAddrIndx; ++i)
9080 (*MIB).addOperand(*argOpers[i]);
9082 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9083 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9084 bInstr->memoperands_end());
9086 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9090 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9092 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9096 // private utility function: 64 bit atomics on 32 bit host.
9098 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9099 MachineBasicBlock *MBB,
9104 bool invSrc) const {
9105 // For the atomic bitwise operator, we generate
9106 // thisMBB (instructions are in pairs, except cmpxchg8b)
9107 // ld t1,t2 = [bitinstr.addr]
9109 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9110 // op t5, t6 <- out1, out2, [bitinstr.val]
9111 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
9112 // mov ECX, EBX <- t5, t6
9113 // mov EAX, EDX <- t1, t2
9114 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
9115 // mov t3, t4 <- EAX, EDX
9117 // result in out1, out2
9118 // fallthrough -->nextMBB
9120 const TargetRegisterClass *RC = X86::GR32RegisterClass;
9121 const unsigned LoadOpc = X86::MOV32rm;
9122 const unsigned NotOpc = X86::NOT32r;
9123 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9124 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9125 MachineFunction::iterator MBBIter = MBB;
9128 /// First build the CFG
9129 MachineFunction *F = MBB->getParent();
9130 MachineBasicBlock *thisMBB = MBB;
9131 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9132 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9133 F->insert(MBBIter, newMBB);
9134 F->insert(MBBIter, nextMBB);
9136 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9137 nextMBB->splice(nextMBB->begin(), thisMBB,
9138 llvm::next(MachineBasicBlock::iterator(bInstr)),
9140 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9142 // Update thisMBB to fall through to newMBB
9143 thisMBB->addSuccessor(newMBB);
9145 // newMBB jumps to itself and fall through to nextMBB
9146 newMBB->addSuccessor(nextMBB);
9147 newMBB->addSuccessor(newMBB);
9149 DebugLoc dl = bInstr->getDebugLoc();
9150 // Insert instructions into newMBB based on incoming instruction
9151 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9152 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9153 "unexpected number of operands");
9154 MachineOperand& dest1Oper = bInstr->getOperand(0);
9155 MachineOperand& dest2Oper = bInstr->getOperand(1);
9156 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9157 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9158 argOpers[i] = &bInstr->getOperand(i+2);
9160 // We use some of the operands multiple times, so conservatively just
9161 // clear any kill flags that might be present.
9162 if (argOpers[i]->isReg() && argOpers[i]->isUse())
9163 argOpers[i]->setIsKill(false);
9166 // x86 address has 5 operands: base, index, scale, displacement, and segment.
9167 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9169 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9170 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9171 for (int i=0; i <= lastAddrIndx; ++i)
9172 (*MIB).addOperand(*argOpers[i]);
9173 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9174 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9175 // add 4 to displacement.
9176 for (int i=0; i <= lastAddrIndx-2; ++i)
9177 (*MIB).addOperand(*argOpers[i]);
9178 MachineOperand newOp3 = *(argOpers[3]);
9180 newOp3.setImm(newOp3.getImm()+4);
9182 newOp3.setOffset(newOp3.getOffset()+4);
9183 (*MIB).addOperand(newOp3);
9184 (*MIB).addOperand(*argOpers[lastAddrIndx]);
9186 // t3/4 are defined later, at the bottom of the loop
9187 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9188 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9189 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9190 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9191 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9192 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9194 // The subsequent operations should be using the destination registers of
9195 //the PHI instructions.
9197 t1 = F->getRegInfo().createVirtualRegister(RC);
9198 t2 = F->getRegInfo().createVirtualRegister(RC);
9199 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9200 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9202 t1 = dest1Oper.getReg();
9203 t2 = dest2Oper.getReg();
9206 int valArgIndx = lastAddrIndx + 1;
9207 assert((argOpers[valArgIndx]->isReg() ||
9208 argOpers[valArgIndx]->isImm()) &&
9210 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9211 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9212 if (argOpers[valArgIndx]->isReg())
9213 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9215 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9216 if (regOpcL != X86::MOV32rr)
9218 (*MIB).addOperand(*argOpers[valArgIndx]);
9219 assert(argOpers[valArgIndx + 1]->isReg() ==
9220 argOpers[valArgIndx]->isReg());
9221 assert(argOpers[valArgIndx + 1]->isImm() ==
9222 argOpers[valArgIndx]->isImm());
9223 if (argOpers[valArgIndx + 1]->isReg())
9224 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9226 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9227 if (regOpcH != X86::MOV32rr)
9229 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9231 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9233 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9236 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9238 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9241 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9242 for (int i=0; i <= lastAddrIndx; ++i)
9243 (*MIB).addOperand(*argOpers[i]);
9245 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9246 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9247 bInstr->memoperands_end());
9249 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9250 MIB.addReg(X86::EAX);
9251 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9252 MIB.addReg(X86::EDX);
9255 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9257 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9261 // private utility function
9263 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9264 MachineBasicBlock *MBB,
9265 unsigned cmovOpc) const {
9266 // For the atomic min/max operator, we generate
9269 // ld t1 = [min/max.addr]
9270 // mov t2 = [min/max.val]
9272 // cmov[cond] t2 = t1
9274 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9276 // fallthrough -->nextMBB
9278 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9279 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9280 MachineFunction::iterator MBBIter = MBB;
9283 /// First build the CFG
9284 MachineFunction *F = MBB->getParent();
9285 MachineBasicBlock *thisMBB = MBB;
9286 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9287 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9288 F->insert(MBBIter, newMBB);
9289 F->insert(MBBIter, nextMBB);
9291 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9292 nextMBB->splice(nextMBB->begin(), thisMBB,
9293 llvm::next(MachineBasicBlock::iterator(mInstr)),
9295 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9297 // Update thisMBB to fall through to newMBB
9298 thisMBB->addSuccessor(newMBB);
9300 // newMBB jumps to newMBB and fall through to nextMBB
9301 newMBB->addSuccessor(nextMBB);
9302 newMBB->addSuccessor(newMBB);
9304 DebugLoc dl = mInstr->getDebugLoc();
9305 // Insert instructions into newMBB based on incoming instruction
9306 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9307 "unexpected number of operands");
9308 MachineOperand& destOper = mInstr->getOperand(0);
9309 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9310 int numArgs = mInstr->getNumOperands() - 1;
9311 for (int i=0; i < numArgs; ++i)
9312 argOpers[i] = &mInstr->getOperand(i+1);
9314 // x86 address has 4 operands: base, index, scale, and displacement
9315 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9316 int valArgIndx = lastAddrIndx + 1;
9318 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9319 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9320 for (int i=0; i <= lastAddrIndx; ++i)
9321 (*MIB).addOperand(*argOpers[i]);
9323 // We only support register and immediate values
9324 assert((argOpers[valArgIndx]->isReg() ||
9325 argOpers[valArgIndx]->isImm()) &&
9328 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9329 if (argOpers[valArgIndx]->isReg())
9330 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9332 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9333 (*MIB).addOperand(*argOpers[valArgIndx]);
9335 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9338 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
9343 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9344 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
9348 // Cmp and exchange if none has modified the memory location
9349 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
9350 for (int i=0; i <= lastAddrIndx; ++i)
9351 (*MIB).addOperand(*argOpers[i]);
9353 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9354 (*MIB).setMemRefs(mInstr->memoperands_begin(),
9355 mInstr->memoperands_end());
9357 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9358 MIB.addReg(X86::EAX);
9361 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9363 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
9367 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
9368 // or XMM0_V32I8 in AVX all of this code can be replaced with that
9371 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
9372 unsigned numArgs, bool memArg) const {
9374 assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
9375 "Target must have SSE4.2 or AVX features enabled");
9377 DebugLoc dl = MI->getDebugLoc();
9378 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9382 if (!Subtarget->hasAVX()) {
9384 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
9386 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
9389 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
9391 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
9394 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
9396 for (unsigned i = 0; i < numArgs; ++i) {
9397 MachineOperand &Op = MI->getOperand(i+1);
9399 if (!(Op.isReg() && Op.isImplicit()))
9403 BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
9406 MI->eraseFromParent();
9412 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
9414 MachineBasicBlock *MBB) const {
9415 // Emit code to save XMM registers to the stack. The ABI says that the
9416 // number of registers to save is given in %al, so it's theoretically
9417 // possible to do an indirect jump trick to avoid saving all of them,
9418 // however this code takes a simpler approach and just executes all
9419 // of the stores if %al is non-zero. It's less code, and it's probably
9420 // easier on the hardware branch predictor, and stores aren't all that
9421 // expensive anyway.
9423 // Create the new basic blocks. One block contains all the XMM stores,
9424 // and one block is the final destination regardless of whether any
9425 // stores were performed.
9426 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9427 MachineFunction *F = MBB->getParent();
9428 MachineFunction::iterator MBBIter = MBB;
9430 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
9431 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
9432 F->insert(MBBIter, XMMSaveMBB);
9433 F->insert(MBBIter, EndMBB);
9435 // Transfer the remainder of MBB and its successor edges to EndMBB.
9436 EndMBB->splice(EndMBB->begin(), MBB,
9437 llvm::next(MachineBasicBlock::iterator(MI)),
9439 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
9441 // The original block will now fall through to the XMM save block.
9442 MBB->addSuccessor(XMMSaveMBB);
9443 // The XMMSaveMBB will fall through to the end block.
9444 XMMSaveMBB->addSuccessor(EndMBB);
9446 // Now add the instructions.
9447 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9448 DebugLoc DL = MI->getDebugLoc();
9450 unsigned CountReg = MI->getOperand(0).getReg();
9451 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
9452 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
9454 if (!Subtarget->isTargetWin64()) {
9455 // If %al is 0, branch around the XMM save block.
9456 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
9457 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
9458 MBB->addSuccessor(EndMBB);
9461 // In the XMM save block, save all the XMM argument registers.
9462 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
9463 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
9464 MachineMemOperand *MMO =
9465 F->getMachineMemOperand(
9466 PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
9467 MachineMemOperand::MOStore, Offset,
9468 /*Size=*/16, /*Align=*/16);
9469 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
9470 .addFrameIndex(RegSaveFrameIndex)
9471 .addImm(/*Scale=*/1)
9472 .addReg(/*IndexReg=*/0)
9473 .addImm(/*Disp=*/Offset)
9474 .addReg(/*Segment=*/0)
9475 .addReg(MI->getOperand(i).getReg())
9476 .addMemOperand(MMO);
9479 MI->eraseFromParent(); // The pseudo instruction is gone now.
9485 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
9486 MachineBasicBlock *BB) const {
9487 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9488 DebugLoc DL = MI->getDebugLoc();
9490 // To "insert" a SELECT_CC instruction, we actually have to insert the
9491 // diamond control-flow pattern. The incoming instruction knows the
9492 // destination vreg to set, the condition code register to branch on, the
9493 // true/false values to select between, and a branch opcode to use.
9494 const BasicBlock *LLVM_BB = BB->getBasicBlock();
9495 MachineFunction::iterator It = BB;
9501 // cmpTY ccX, r1, r2
9503 // fallthrough --> copy0MBB
9504 MachineBasicBlock *thisMBB = BB;
9505 MachineFunction *F = BB->getParent();
9506 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9507 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9508 F->insert(It, copy0MBB);
9509 F->insert(It, sinkMBB);
9511 // If the EFLAGS register isn't dead in the terminator, then claim that it's
9512 // live into the sink and copy blocks.
9513 const MachineFunction *MF = BB->getParent();
9514 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
9515 BitVector ReservedRegs = TRI->getReservedRegs(*MF);
9517 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
9518 const MachineOperand &MO = MI->getOperand(I);
9519 if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
9520 unsigned Reg = MO.getReg();
9521 if (Reg != X86::EFLAGS) continue;
9522 copy0MBB->addLiveIn(Reg);
9523 sinkMBB->addLiveIn(Reg);
9526 // Transfer the remainder of BB and its successor edges to sinkMBB.
9527 sinkMBB->splice(sinkMBB->begin(), BB,
9528 llvm::next(MachineBasicBlock::iterator(MI)),
9530 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9532 // Add the true and fallthrough blocks as its successors.
9533 BB->addSuccessor(copy0MBB);
9534 BB->addSuccessor(sinkMBB);
9536 // Create the conditional branch instruction.
9538 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
9539 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
9542 // %FalseValue = ...
9543 // # fallthrough to sinkMBB
9544 copy0MBB->addSuccessor(sinkMBB);
9547 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9549 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
9550 TII->get(X86::PHI), MI->getOperand(0).getReg())
9551 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
9552 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
9554 MI->eraseFromParent(); // The pseudo instruction is gone now.
9559 X86TargetLowering::EmitLoweredMingwAlloca(MachineInstr *MI,
9560 MachineBasicBlock *BB) const {
9561 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9562 DebugLoc DL = MI->getDebugLoc();
9564 // The lowering is pretty easy: we're just emitting the call to _alloca. The
9565 // non-trivial part is impdef of ESP.
9566 // FIXME: The code should be tweaked as soon as we'll try to do codegen for
9569 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
9570 .addExternalSymbol("_alloca")
9571 .addReg(X86::EAX, RegState::Implicit)
9572 .addReg(X86::ESP, RegState::Implicit)
9573 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
9574 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
9575 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
9577 MI->eraseFromParent(); // The pseudo instruction is gone now.
9582 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
9583 MachineBasicBlock *BB) const {
9584 // This is pretty easy. We're taking the value that we received from
9585 // our load from the relocation, sticking it in either RDI (x86-64)
9586 // or EAX and doing an indirect call. The return value will then
9587 // be in the normal return register.
9588 const X86InstrInfo *TII
9589 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
9590 DebugLoc DL = MI->getDebugLoc();
9591 MachineFunction *F = BB->getParent();
9592 bool IsWin64 = Subtarget->isTargetWin64();
9594 assert(MI->getOperand(3).isGlobal() && "This should be a global");
9596 if (Subtarget->is64Bit()) {
9597 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9598 TII->get(X86::MOV64rm), X86::RDI)
9600 .addImm(0).addReg(0)
9601 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
9602 MI->getOperand(3).getTargetFlags())
9604 MIB = BuildMI(*BB, MI, DL, TII->get(IsWin64 ? X86::WINCALL64m : X86::CALL64m));
9605 addDirectMem(MIB, X86::RDI);
9606 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
9607 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9608 TII->get(X86::MOV32rm), X86::EAX)
9610 .addImm(0).addReg(0)
9611 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
9612 MI->getOperand(3).getTargetFlags())
9614 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
9615 addDirectMem(MIB, X86::EAX);
9617 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9618 TII->get(X86::MOV32rm), X86::EAX)
9619 .addReg(TII->getGlobalBaseReg(F))
9620 .addImm(0).addReg(0)
9621 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
9622 MI->getOperand(3).getTargetFlags())
9624 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
9625 addDirectMem(MIB, X86::EAX);
9628 MI->eraseFromParent(); // The pseudo instruction is gone now.
9633 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
9634 MachineBasicBlock *BB) const {
9635 switch (MI->getOpcode()) {
9636 default: assert(false && "Unexpected instr type to insert");
9637 case X86::MINGW_ALLOCA:
9638 return EmitLoweredMingwAlloca(MI, BB);
9639 case X86::TLSCall_32:
9640 case X86::TLSCall_64:
9641 return EmitLoweredTLSCall(MI, BB);
9643 case X86::CMOV_V1I64:
9644 case X86::CMOV_FR32:
9645 case X86::CMOV_FR64:
9646 case X86::CMOV_V4F32:
9647 case X86::CMOV_V2F64:
9648 case X86::CMOV_V2I64:
9649 case X86::CMOV_GR16:
9650 case X86::CMOV_GR32:
9651 case X86::CMOV_RFP32:
9652 case X86::CMOV_RFP64:
9653 case X86::CMOV_RFP80:
9654 return EmitLoweredSelect(MI, BB);
9656 case X86::FP32_TO_INT16_IN_MEM:
9657 case X86::FP32_TO_INT32_IN_MEM:
9658 case X86::FP32_TO_INT64_IN_MEM:
9659 case X86::FP64_TO_INT16_IN_MEM:
9660 case X86::FP64_TO_INT32_IN_MEM:
9661 case X86::FP64_TO_INT64_IN_MEM:
9662 case X86::FP80_TO_INT16_IN_MEM:
9663 case X86::FP80_TO_INT32_IN_MEM:
9664 case X86::FP80_TO_INT64_IN_MEM: {
9665 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9666 DebugLoc DL = MI->getDebugLoc();
9668 // Change the floating point control register to use "round towards zero"
9669 // mode when truncating to an integer value.
9670 MachineFunction *F = BB->getParent();
9671 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
9672 addFrameReference(BuildMI(*BB, MI, DL,
9673 TII->get(X86::FNSTCW16m)), CWFrameIdx);
9675 // Load the old value of the high byte of the control word...
9677 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
9678 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
9681 // Set the high part to be round to zero...
9682 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
9685 // Reload the modified control word now...
9686 addFrameReference(BuildMI(*BB, MI, DL,
9687 TII->get(X86::FLDCW16m)), CWFrameIdx);
9689 // Restore the memory image of control word to original value
9690 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
9693 // Get the X86 opcode to use.
9695 switch (MI->getOpcode()) {
9696 default: llvm_unreachable("illegal opcode!");
9697 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
9698 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
9699 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
9700 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
9701 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
9702 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
9703 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
9704 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
9705 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
9709 MachineOperand &Op = MI->getOperand(0);
9711 AM.BaseType = X86AddressMode::RegBase;
9712 AM.Base.Reg = Op.getReg();
9714 AM.BaseType = X86AddressMode::FrameIndexBase;
9715 AM.Base.FrameIndex = Op.getIndex();
9717 Op = MI->getOperand(1);
9719 AM.Scale = Op.getImm();
9720 Op = MI->getOperand(2);
9722 AM.IndexReg = Op.getImm();
9723 Op = MI->getOperand(3);
9724 if (Op.isGlobal()) {
9725 AM.GV = Op.getGlobal();
9727 AM.Disp = Op.getImm();
9729 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
9730 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
9732 // Reload the original control word now.
9733 addFrameReference(BuildMI(*BB, MI, DL,
9734 TII->get(X86::FLDCW16m)), CWFrameIdx);
9736 MI->eraseFromParent(); // The pseudo instruction is gone now.
9739 // String/text processing lowering.
9740 case X86::PCMPISTRM128REG:
9741 case X86::VPCMPISTRM128REG:
9742 return EmitPCMP(MI, BB, 3, false /* in-mem */);
9743 case X86::PCMPISTRM128MEM:
9744 case X86::VPCMPISTRM128MEM:
9745 return EmitPCMP(MI, BB, 3, true /* in-mem */);
9746 case X86::PCMPESTRM128REG:
9747 case X86::VPCMPESTRM128REG:
9748 return EmitPCMP(MI, BB, 5, false /* in mem */);
9749 case X86::PCMPESTRM128MEM:
9750 case X86::VPCMPESTRM128MEM:
9751 return EmitPCMP(MI, BB, 5, true /* in mem */);
9754 case X86::ATOMAND32:
9755 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
9756 X86::AND32ri, X86::MOV32rm,
9758 X86::NOT32r, X86::EAX,
9759 X86::GR32RegisterClass);
9761 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
9762 X86::OR32ri, X86::MOV32rm,
9764 X86::NOT32r, X86::EAX,
9765 X86::GR32RegisterClass);
9766 case X86::ATOMXOR32:
9767 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
9768 X86::XOR32ri, X86::MOV32rm,
9770 X86::NOT32r, X86::EAX,
9771 X86::GR32RegisterClass);
9772 case X86::ATOMNAND32:
9773 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
9774 X86::AND32ri, X86::MOV32rm,
9776 X86::NOT32r, X86::EAX,
9777 X86::GR32RegisterClass, true);
9778 case X86::ATOMMIN32:
9779 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
9780 case X86::ATOMMAX32:
9781 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
9782 case X86::ATOMUMIN32:
9783 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
9784 case X86::ATOMUMAX32:
9785 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
9787 case X86::ATOMAND16:
9788 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
9789 X86::AND16ri, X86::MOV16rm,
9791 X86::NOT16r, X86::AX,
9792 X86::GR16RegisterClass);
9794 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
9795 X86::OR16ri, X86::MOV16rm,
9797 X86::NOT16r, X86::AX,
9798 X86::GR16RegisterClass);
9799 case X86::ATOMXOR16:
9800 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
9801 X86::XOR16ri, X86::MOV16rm,
9803 X86::NOT16r, X86::AX,
9804 X86::GR16RegisterClass);
9805 case X86::ATOMNAND16:
9806 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
9807 X86::AND16ri, X86::MOV16rm,
9809 X86::NOT16r, X86::AX,
9810 X86::GR16RegisterClass, true);
9811 case X86::ATOMMIN16:
9812 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
9813 case X86::ATOMMAX16:
9814 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
9815 case X86::ATOMUMIN16:
9816 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
9817 case X86::ATOMUMAX16:
9818 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
9821 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
9822 X86::AND8ri, X86::MOV8rm,
9824 X86::NOT8r, X86::AL,
9825 X86::GR8RegisterClass);
9827 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
9828 X86::OR8ri, X86::MOV8rm,
9830 X86::NOT8r, X86::AL,
9831 X86::GR8RegisterClass);
9833 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
9834 X86::XOR8ri, X86::MOV8rm,
9836 X86::NOT8r, X86::AL,
9837 X86::GR8RegisterClass);
9838 case X86::ATOMNAND8:
9839 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
9840 X86::AND8ri, X86::MOV8rm,
9842 X86::NOT8r, X86::AL,
9843 X86::GR8RegisterClass, true);
9844 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
9845 // This group is for 64-bit host.
9846 case X86::ATOMAND64:
9847 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
9848 X86::AND64ri32, X86::MOV64rm,
9850 X86::NOT64r, X86::RAX,
9851 X86::GR64RegisterClass);
9853 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
9854 X86::OR64ri32, X86::MOV64rm,
9856 X86::NOT64r, X86::RAX,
9857 X86::GR64RegisterClass);
9858 case X86::ATOMXOR64:
9859 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
9860 X86::XOR64ri32, X86::MOV64rm,
9862 X86::NOT64r, X86::RAX,
9863 X86::GR64RegisterClass);
9864 case X86::ATOMNAND64:
9865 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
9866 X86::AND64ri32, X86::MOV64rm,
9868 X86::NOT64r, X86::RAX,
9869 X86::GR64RegisterClass, true);
9870 case X86::ATOMMIN64:
9871 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
9872 case X86::ATOMMAX64:
9873 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
9874 case X86::ATOMUMIN64:
9875 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
9876 case X86::ATOMUMAX64:
9877 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
9879 // This group does 64-bit operations on a 32-bit host.
9880 case X86::ATOMAND6432:
9881 return EmitAtomicBit6432WithCustomInserter(MI, BB,
9882 X86::AND32rr, X86::AND32rr,
9883 X86::AND32ri, X86::AND32ri,
9885 case X86::ATOMOR6432:
9886 return EmitAtomicBit6432WithCustomInserter(MI, BB,
9887 X86::OR32rr, X86::OR32rr,
9888 X86::OR32ri, X86::OR32ri,
9890 case X86::ATOMXOR6432:
9891 return EmitAtomicBit6432WithCustomInserter(MI, BB,
9892 X86::XOR32rr, X86::XOR32rr,
9893 X86::XOR32ri, X86::XOR32ri,
9895 case X86::ATOMNAND6432:
9896 return EmitAtomicBit6432WithCustomInserter(MI, BB,
9897 X86::AND32rr, X86::AND32rr,
9898 X86::AND32ri, X86::AND32ri,
9900 case X86::ATOMADD6432:
9901 return EmitAtomicBit6432WithCustomInserter(MI, BB,
9902 X86::ADD32rr, X86::ADC32rr,
9903 X86::ADD32ri, X86::ADC32ri,
9905 case X86::ATOMSUB6432:
9906 return EmitAtomicBit6432WithCustomInserter(MI, BB,
9907 X86::SUB32rr, X86::SBB32rr,
9908 X86::SUB32ri, X86::SBB32ri,
9910 case X86::ATOMSWAP6432:
9911 return EmitAtomicBit6432WithCustomInserter(MI, BB,
9912 X86::MOV32rr, X86::MOV32rr,
9913 X86::MOV32ri, X86::MOV32ri,
9915 case X86::VASTART_SAVE_XMM_REGS:
9916 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
9920 //===----------------------------------------------------------------------===//
9921 // X86 Optimization Hooks
9922 //===----------------------------------------------------------------------===//
9924 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9928 const SelectionDAG &DAG,
9929 unsigned Depth) const {
9930 unsigned Opc = Op.getOpcode();
9931 assert((Opc >= ISD::BUILTIN_OP_END ||
9932 Opc == ISD::INTRINSIC_WO_CHAIN ||
9933 Opc == ISD::INTRINSIC_W_CHAIN ||
9934 Opc == ISD::INTRINSIC_VOID) &&
9935 "Should use MaskedValueIsZero if you don't know whether Op"
9936 " is a target node!");
9938 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
9950 // These nodes' second result is a boolean.
9951 if (Op.getResNo() == 0)
9955 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
9956 Mask.getBitWidth() - 1);
9961 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
9962 /// node is a GlobalAddress + offset.
9963 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
9964 const GlobalValue* &GA,
9965 int64_t &Offset) const {
9966 if (N->getOpcode() == X86ISD::Wrapper) {
9967 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
9968 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
9969 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
9973 return TargetLowering::isGAPlusOffset(N, GA, Offset);
9976 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
9977 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
9978 /// if the load addresses are consecutive, non-overlapping, and in the right
9980 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
9981 const TargetLowering &TLI) {
9982 DebugLoc dl = N->getDebugLoc();
9983 EVT VT = N->getValueType(0);
9985 if (VT.getSizeInBits() != 128)
9988 SmallVector<SDValue, 16> Elts;
9989 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
9990 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
9992 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
9995 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
9996 /// generation and convert it from being a bunch of shuffles and extracts
9997 /// to a simple store and scalar loads to extract the elements.
9998 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
9999 const TargetLowering &TLI) {
10000 SDValue InputVector = N->getOperand(0);
10002 // Only operate on vectors of 4 elements, where the alternative shuffling
10003 // gets to be more expensive.
10004 if (InputVector.getValueType() != MVT::v4i32)
10007 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
10008 // single use which is a sign-extend or zero-extend, and all elements are
10010 SmallVector<SDNode *, 4> Uses;
10011 unsigned ExtractedElements = 0;
10012 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
10013 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
10014 if (UI.getUse().getResNo() != InputVector.getResNo())
10017 SDNode *Extract = *UI;
10018 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10021 if (Extract->getValueType(0) != MVT::i32)
10023 if (!Extract->hasOneUse())
10025 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
10026 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
10028 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
10031 // Record which element was extracted.
10032 ExtractedElements |=
10033 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
10035 Uses.push_back(Extract);
10038 // If not all the elements were used, this may not be worthwhile.
10039 if (ExtractedElements != 15)
10042 // Ok, we've now decided to do the transformation.
10043 DebugLoc dl = InputVector.getDebugLoc();
10045 // Store the value to a temporary stack slot.
10046 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
10047 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr, NULL,
10048 0, false, false, 0);
10050 // Replace each use (extract) with a load of the appropriate element.
10051 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
10052 UE = Uses.end(); UI != UE; ++UI) {
10053 SDNode *Extract = *UI;
10055 // Compute the element's address.
10056 SDValue Idx = Extract->getOperand(1);
10058 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
10059 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
10060 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
10062 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(),
10063 OffsetVal, StackPtr);
10065 // Load the scalar.
10066 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
10067 ScalarAddr, NULL, 0, false, false, 0);
10069 // Replace the exact with the load.
10070 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
10073 // The replacement was made in place; don't return anything.
10077 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
10078 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
10079 const X86Subtarget *Subtarget) {
10080 DebugLoc DL = N->getDebugLoc();
10081 SDValue Cond = N->getOperand(0);
10082 // Get the LHS/RHS of the select.
10083 SDValue LHS = N->getOperand(1);
10084 SDValue RHS = N->getOperand(2);
10086 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
10087 // instructions match the semantics of the common C idiom x<y?x:y but not
10088 // x<=y?x:y, because of how they handle negative zero (which can be
10089 // ignored in unsafe-math mode).
10090 if (Subtarget->hasSSE2() &&
10091 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
10092 Cond.getOpcode() == ISD::SETCC) {
10093 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
10095 unsigned Opcode = 0;
10096 // Check for x CC y ? x : y.
10097 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
10098 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
10102 // Converting this to a min would handle NaNs incorrectly, and swapping
10103 // the operands would cause it to handle comparisons between positive
10104 // and negative zero incorrectly.
10105 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10106 if (!UnsafeFPMath &&
10107 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10109 std::swap(LHS, RHS);
10111 Opcode = X86ISD::FMIN;
10114 // Converting this to a min would handle comparisons between positive
10115 // and negative zero incorrectly.
10116 if (!UnsafeFPMath &&
10117 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
10119 Opcode = X86ISD::FMIN;
10122 // Converting this to a min would handle both negative zeros and NaNs
10123 // incorrectly, but we can swap the operands to fix both.
10124 std::swap(LHS, RHS);
10128 Opcode = X86ISD::FMIN;
10132 // Converting this to a max would handle comparisons between positive
10133 // and negative zero incorrectly.
10134 if (!UnsafeFPMath &&
10135 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
10137 Opcode = X86ISD::FMAX;
10140 // Converting this to a max would handle NaNs incorrectly, and swapping
10141 // the operands would cause it to handle comparisons between positive
10142 // and negative zero incorrectly.
10143 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10144 if (!UnsafeFPMath &&
10145 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10147 std::swap(LHS, RHS);
10149 Opcode = X86ISD::FMAX;
10152 // Converting this to a max would handle both negative zeros and NaNs
10153 // incorrectly, but we can swap the operands to fix both.
10154 std::swap(LHS, RHS);
10158 Opcode = X86ISD::FMAX;
10161 // Check for x CC y ? y : x -- a min/max with reversed arms.
10162 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
10163 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
10167 // Converting this to a min would handle comparisons between positive
10168 // and negative zero incorrectly, and swapping the operands would
10169 // cause it to handle NaNs incorrectly.
10170 if (!UnsafeFPMath &&
10171 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
10172 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10174 std::swap(LHS, RHS);
10176 Opcode = X86ISD::FMIN;
10179 // Converting this to a min would handle NaNs incorrectly.
10180 if (!UnsafeFPMath &&
10181 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
10183 Opcode = X86ISD::FMIN;
10186 // Converting this to a min would handle both negative zeros and NaNs
10187 // incorrectly, but we can swap the operands to fix both.
10188 std::swap(LHS, RHS);
10192 Opcode = X86ISD::FMIN;
10196 // Converting this to a max would handle NaNs incorrectly.
10197 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10199 Opcode = X86ISD::FMAX;
10202 // Converting this to a max would handle comparisons between positive
10203 // and negative zero incorrectly, and swapping the operands would
10204 // cause it to handle NaNs incorrectly.
10205 if (!UnsafeFPMath &&
10206 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
10207 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10209 std::swap(LHS, RHS);
10211 Opcode = X86ISD::FMAX;
10214 // Converting this to a max would handle both negative zeros and NaNs
10215 // incorrectly, but we can swap the operands to fix both.
10216 std::swap(LHS, RHS);
10220 Opcode = X86ISD::FMAX;
10226 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
10229 // If this is a select between two integer constants, try to do some
10231 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
10232 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
10233 // Don't do this for crazy integer types.
10234 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
10235 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
10236 // so that TrueC (the true value) is larger than FalseC.
10237 bool NeedsCondInvert = false;
10239 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
10240 // Efficiently invertible.
10241 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
10242 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
10243 isa<ConstantSDNode>(Cond.getOperand(1))))) {
10244 NeedsCondInvert = true;
10245 std::swap(TrueC, FalseC);
10248 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
10249 if (FalseC->getAPIntValue() == 0 &&
10250 TrueC->getAPIntValue().isPowerOf2()) {
10251 if (NeedsCondInvert) // Invert the condition if needed.
10252 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10253 DAG.getConstant(1, Cond.getValueType()));
10255 // Zero extend the condition if needed.
10256 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
10258 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10259 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
10260 DAG.getConstant(ShAmt, MVT::i8));
10263 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
10264 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10265 if (NeedsCondInvert) // Invert the condition if needed.
10266 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10267 DAG.getConstant(1, Cond.getValueType()));
10269 // Zero extend the condition if needed.
10270 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10271 FalseC->getValueType(0), Cond);
10272 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10273 SDValue(FalseC, 0));
10276 // Optimize cases that will turn into an LEA instruction. This requires
10277 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10278 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10279 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10280 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10282 bool isFastMultiplier = false;
10284 switch ((unsigned char)Diff) {
10286 case 1: // result = add base, cond
10287 case 2: // result = lea base( , cond*2)
10288 case 3: // result = lea base(cond, cond*2)
10289 case 4: // result = lea base( , cond*4)
10290 case 5: // result = lea base(cond, cond*4)
10291 case 8: // result = lea base( , cond*8)
10292 case 9: // result = lea base(cond, cond*8)
10293 isFastMultiplier = true;
10298 if (isFastMultiplier) {
10299 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10300 if (NeedsCondInvert) // Invert the condition if needed.
10301 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10302 DAG.getConstant(1, Cond.getValueType()));
10304 // Zero extend the condition if needed.
10305 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10307 // Scale the condition by the difference.
10309 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10310 DAG.getConstant(Diff, Cond.getValueType()));
10312 // Add the base if non-zero.
10313 if (FalseC->getAPIntValue() != 0)
10314 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10315 SDValue(FalseC, 0));
10325 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
10326 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
10327 TargetLowering::DAGCombinerInfo &DCI) {
10328 DebugLoc DL = N->getDebugLoc();
10330 // If the flag operand isn't dead, don't touch this CMOV.
10331 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
10334 // If this is a select between two integer constants, try to do some
10335 // optimizations. Note that the operands are ordered the opposite of SELECT
10337 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
10338 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10339 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
10340 // larger than FalseC (the false value).
10341 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
10343 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
10344 CC = X86::GetOppositeBranchCondition(CC);
10345 std::swap(TrueC, FalseC);
10348 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
10349 // This is efficient for any integer data type (including i8/i16) and
10351 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
10352 SDValue Cond = N->getOperand(3);
10353 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10354 DAG.getConstant(CC, MVT::i8), Cond);
10356 // Zero extend the condition if needed.
10357 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
10359 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10360 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
10361 DAG.getConstant(ShAmt, MVT::i8));
10362 if (N->getNumValues() == 2) // Dead flag value?
10363 return DCI.CombineTo(N, Cond, SDValue());
10367 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
10368 // for any integer data type, including i8/i16.
10369 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10370 SDValue Cond = N->getOperand(3);
10371 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10372 DAG.getConstant(CC, MVT::i8), Cond);
10374 // Zero extend the condition if needed.
10375 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10376 FalseC->getValueType(0), Cond);
10377 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10378 SDValue(FalseC, 0));
10380 if (N->getNumValues() == 2) // Dead flag value?
10381 return DCI.CombineTo(N, Cond, SDValue());
10385 // Optimize cases that will turn into an LEA instruction. This requires
10386 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10387 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10388 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10389 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10391 bool isFastMultiplier = false;
10393 switch ((unsigned char)Diff) {
10395 case 1: // result = add base, cond
10396 case 2: // result = lea base( , cond*2)
10397 case 3: // result = lea base(cond, cond*2)
10398 case 4: // result = lea base( , cond*4)
10399 case 5: // result = lea base(cond, cond*4)
10400 case 8: // result = lea base( , cond*8)
10401 case 9: // result = lea base(cond, cond*8)
10402 isFastMultiplier = true;
10407 if (isFastMultiplier) {
10408 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10409 SDValue Cond = N->getOperand(3);
10410 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10411 DAG.getConstant(CC, MVT::i8), Cond);
10412 // Zero extend the condition if needed.
10413 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10415 // Scale the condition by the difference.
10417 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10418 DAG.getConstant(Diff, Cond.getValueType()));
10420 // Add the base if non-zero.
10421 if (FalseC->getAPIntValue() != 0)
10422 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10423 SDValue(FalseC, 0));
10424 if (N->getNumValues() == 2) // Dead flag value?
10425 return DCI.CombineTo(N, Cond, SDValue());
10435 /// PerformMulCombine - Optimize a single multiply with constant into two
10436 /// in order to implement it with two cheaper instructions, e.g.
10437 /// LEA + SHL, LEA + LEA.
10438 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
10439 TargetLowering::DAGCombinerInfo &DCI) {
10440 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10443 EVT VT = N->getValueType(0);
10444 if (VT != MVT::i64)
10447 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10450 uint64_t MulAmt = C->getZExtValue();
10451 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
10454 uint64_t MulAmt1 = 0;
10455 uint64_t MulAmt2 = 0;
10456 if ((MulAmt % 9) == 0) {
10458 MulAmt2 = MulAmt / 9;
10459 } else if ((MulAmt % 5) == 0) {
10461 MulAmt2 = MulAmt / 5;
10462 } else if ((MulAmt % 3) == 0) {
10464 MulAmt2 = MulAmt / 3;
10467 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
10468 DebugLoc DL = N->getDebugLoc();
10470 if (isPowerOf2_64(MulAmt2) &&
10471 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
10472 // If second multiplifer is pow2, issue it first. We want the multiply by
10473 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
10475 std::swap(MulAmt1, MulAmt2);
10478 if (isPowerOf2_64(MulAmt1))
10479 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
10480 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
10482 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
10483 DAG.getConstant(MulAmt1, VT));
10485 if (isPowerOf2_64(MulAmt2))
10486 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
10487 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
10489 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
10490 DAG.getConstant(MulAmt2, VT));
10492 // Do not add new nodes to DAG combiner worklist.
10493 DCI.CombineTo(N, NewMul, false);
10498 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
10499 SDValue N0 = N->getOperand(0);
10500 SDValue N1 = N->getOperand(1);
10501 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
10502 EVT VT = N0.getValueType();
10504 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
10505 // since the result of setcc_c is all zero's or all ones.
10506 if (N1C && N0.getOpcode() == ISD::AND &&
10507 N0.getOperand(1).getOpcode() == ISD::Constant) {
10508 SDValue N00 = N0.getOperand(0);
10509 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
10510 ((N00.getOpcode() == ISD::ANY_EXTEND ||
10511 N00.getOpcode() == ISD::ZERO_EXTEND) &&
10512 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
10513 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
10514 APInt ShAmt = N1C->getAPIntValue();
10515 Mask = Mask.shl(ShAmt);
10517 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
10518 N00, DAG.getConstant(Mask, VT));
10525 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
10527 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
10528 const X86Subtarget *Subtarget) {
10529 EVT VT = N->getValueType(0);
10530 if (!VT.isVector() && VT.isInteger() &&
10531 N->getOpcode() == ISD::SHL)
10532 return PerformSHLCombine(N, DAG);
10534 // On X86 with SSE2 support, we can transform this to a vector shift if
10535 // all elements are shifted by the same amount. We can't do this in legalize
10536 // because the a constant vector is typically transformed to a constant pool
10537 // so we have no knowledge of the shift amount.
10538 if (!Subtarget->hasSSE2())
10541 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
10544 SDValue ShAmtOp = N->getOperand(1);
10545 EVT EltVT = VT.getVectorElementType();
10546 DebugLoc DL = N->getDebugLoc();
10547 SDValue BaseShAmt = SDValue();
10548 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
10549 unsigned NumElts = VT.getVectorNumElements();
10551 for (; i != NumElts; ++i) {
10552 SDValue Arg = ShAmtOp.getOperand(i);
10553 if (Arg.getOpcode() == ISD::UNDEF) continue;
10557 for (; i != NumElts; ++i) {
10558 SDValue Arg = ShAmtOp.getOperand(i);
10559 if (Arg.getOpcode() == ISD::UNDEF) continue;
10560 if (Arg != BaseShAmt) {
10564 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
10565 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
10566 SDValue InVec = ShAmtOp.getOperand(0);
10567 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
10568 unsigned NumElts = InVec.getValueType().getVectorNumElements();
10570 for (; i != NumElts; ++i) {
10571 SDValue Arg = InVec.getOperand(i);
10572 if (Arg.getOpcode() == ISD::UNDEF) continue;
10576 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
10577 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
10578 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
10579 if (C->getZExtValue() == SplatIdx)
10580 BaseShAmt = InVec.getOperand(1);
10583 if (BaseShAmt.getNode() == 0)
10584 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
10585 DAG.getIntPtrConstant(0));
10589 // The shift amount is an i32.
10590 if (EltVT.bitsGT(MVT::i32))
10591 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
10592 else if (EltVT.bitsLT(MVT::i32))
10593 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
10595 // The shift amount is identical so we can do a vector shift.
10596 SDValue ValOp = N->getOperand(0);
10597 switch (N->getOpcode()) {
10599 llvm_unreachable("Unknown shift opcode!");
10602 if (VT == MVT::v2i64)
10603 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10604 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10606 if (VT == MVT::v4i32)
10607 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10608 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10610 if (VT == MVT::v8i16)
10611 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10612 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10616 if (VT == MVT::v4i32)
10617 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10618 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
10620 if (VT == MVT::v8i16)
10621 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10622 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
10626 if (VT == MVT::v2i64)
10627 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10628 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10630 if (VT == MVT::v4i32)
10631 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10632 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
10634 if (VT == MVT::v8i16)
10635 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10636 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10643 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
10644 TargetLowering::DAGCombinerInfo &DCI,
10645 const X86Subtarget *Subtarget) {
10646 if (DCI.isBeforeLegalizeOps())
10649 EVT VT = N->getValueType(0);
10650 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
10653 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
10654 SDValue N0 = N->getOperand(0);
10655 SDValue N1 = N->getOperand(1);
10656 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
10658 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
10660 if (!N0.hasOneUse() || !N1.hasOneUse())
10663 SDValue ShAmt0 = N0.getOperand(1);
10664 if (ShAmt0.getValueType() != MVT::i8)
10666 SDValue ShAmt1 = N1.getOperand(1);
10667 if (ShAmt1.getValueType() != MVT::i8)
10669 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
10670 ShAmt0 = ShAmt0.getOperand(0);
10671 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
10672 ShAmt1 = ShAmt1.getOperand(0);
10674 DebugLoc DL = N->getDebugLoc();
10675 unsigned Opc = X86ISD::SHLD;
10676 SDValue Op0 = N0.getOperand(0);
10677 SDValue Op1 = N1.getOperand(0);
10678 if (ShAmt0.getOpcode() == ISD::SUB) {
10679 Opc = X86ISD::SHRD;
10680 std::swap(Op0, Op1);
10681 std::swap(ShAmt0, ShAmt1);
10684 unsigned Bits = VT.getSizeInBits();
10685 if (ShAmt1.getOpcode() == ISD::SUB) {
10686 SDValue Sum = ShAmt1.getOperand(0);
10687 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
10688 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
10689 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
10690 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
10691 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
10692 return DAG.getNode(Opc, DL, VT,
10694 DAG.getNode(ISD::TRUNCATE, DL,
10697 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
10698 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
10700 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
10701 return DAG.getNode(Opc, DL, VT,
10702 N0.getOperand(0), N1.getOperand(0),
10703 DAG.getNode(ISD::TRUNCATE, DL,
10710 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
10711 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
10712 const X86Subtarget *Subtarget) {
10713 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
10714 // the FP state in cases where an emms may be missing.
10715 // A preferable solution to the general problem is to figure out the right
10716 // places to insert EMMS. This qualifies as a quick hack.
10718 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
10719 StoreSDNode *St = cast<StoreSDNode>(N);
10720 EVT VT = St->getValue().getValueType();
10721 if (VT.getSizeInBits() != 64)
10724 const Function *F = DAG.getMachineFunction().getFunction();
10725 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
10726 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
10727 && Subtarget->hasSSE2();
10728 if ((VT.isVector() ||
10729 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
10730 isa<LoadSDNode>(St->getValue()) &&
10731 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
10732 St->getChain().hasOneUse() && !St->isVolatile()) {
10733 SDNode* LdVal = St->getValue().getNode();
10734 LoadSDNode *Ld = 0;
10735 int TokenFactorIndex = -1;
10736 SmallVector<SDValue, 8> Ops;
10737 SDNode* ChainVal = St->getChain().getNode();
10738 // Must be a store of a load. We currently handle two cases: the load
10739 // is a direct child, and it's under an intervening TokenFactor. It is
10740 // possible to dig deeper under nested TokenFactors.
10741 if (ChainVal == LdVal)
10742 Ld = cast<LoadSDNode>(St->getChain());
10743 else if (St->getValue().hasOneUse() &&
10744 ChainVal->getOpcode() == ISD::TokenFactor) {
10745 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
10746 if (ChainVal->getOperand(i).getNode() == LdVal) {
10747 TokenFactorIndex = i;
10748 Ld = cast<LoadSDNode>(St->getValue());
10750 Ops.push_back(ChainVal->getOperand(i));
10754 if (!Ld || !ISD::isNormalLoad(Ld))
10757 // If this is not the MMX case, i.e. we are just turning i64 load/store
10758 // into f64 load/store, avoid the transformation if there are multiple
10759 // uses of the loaded value.
10760 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
10763 DebugLoc LdDL = Ld->getDebugLoc();
10764 DebugLoc StDL = N->getDebugLoc();
10765 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
10766 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
10768 if (Subtarget->is64Bit() || F64IsLegal) {
10769 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
10770 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
10771 Ld->getBasePtr(), Ld->getSrcValue(),
10772 Ld->getSrcValueOffset(), Ld->isVolatile(),
10773 Ld->isNonTemporal(), Ld->getAlignment());
10774 SDValue NewChain = NewLd.getValue(1);
10775 if (TokenFactorIndex != -1) {
10776 Ops.push_back(NewChain);
10777 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
10780 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
10781 St->getSrcValue(), St->getSrcValueOffset(),
10782 St->isVolatile(), St->isNonTemporal(),
10783 St->getAlignment());
10786 // Otherwise, lower to two pairs of 32-bit loads / stores.
10787 SDValue LoAddr = Ld->getBasePtr();
10788 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
10789 DAG.getConstant(4, MVT::i32));
10791 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
10792 Ld->getSrcValue(), Ld->getSrcValueOffset(),
10793 Ld->isVolatile(), Ld->isNonTemporal(),
10794 Ld->getAlignment());
10795 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
10796 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
10797 Ld->isVolatile(), Ld->isNonTemporal(),
10798 MinAlign(Ld->getAlignment(), 4));
10800 SDValue NewChain = LoLd.getValue(1);
10801 if (TokenFactorIndex != -1) {
10802 Ops.push_back(LoLd);
10803 Ops.push_back(HiLd);
10804 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
10808 LoAddr = St->getBasePtr();
10809 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
10810 DAG.getConstant(4, MVT::i32));
10812 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
10813 St->getSrcValue(), St->getSrcValueOffset(),
10814 St->isVolatile(), St->isNonTemporal(),
10815 St->getAlignment());
10816 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
10818 St->getSrcValueOffset() + 4,
10820 St->isNonTemporal(),
10821 MinAlign(St->getAlignment(), 4));
10822 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
10827 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
10828 /// X86ISD::FXOR nodes.
10829 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
10830 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
10831 // F[X]OR(0.0, x) -> x
10832 // F[X]OR(x, 0.0) -> x
10833 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
10834 if (C->getValueAPF().isPosZero())
10835 return N->getOperand(1);
10836 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
10837 if (C->getValueAPF().isPosZero())
10838 return N->getOperand(0);
10842 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
10843 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
10844 // FAND(0.0, x) -> 0.0
10845 // FAND(x, 0.0) -> 0.0
10846 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
10847 if (C->getValueAPF().isPosZero())
10848 return N->getOperand(0);
10849 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
10850 if (C->getValueAPF().isPosZero())
10851 return N->getOperand(1);
10855 static SDValue PerformBTCombine(SDNode *N,
10857 TargetLowering::DAGCombinerInfo &DCI) {
10858 // BT ignores high bits in the bit index operand.
10859 SDValue Op1 = N->getOperand(1);
10860 if (Op1.hasOneUse()) {
10861 unsigned BitWidth = Op1.getValueSizeInBits();
10862 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
10863 APInt KnownZero, KnownOne;
10864 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
10865 !DCI.isBeforeLegalizeOps());
10866 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10867 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
10868 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
10869 DCI.CommitTargetLoweringOpt(TLO);
10874 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
10875 SDValue Op = N->getOperand(0);
10876 if (Op.getOpcode() == ISD::BIT_CONVERT)
10877 Op = Op.getOperand(0);
10878 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
10879 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
10880 VT.getVectorElementType().getSizeInBits() ==
10881 OpVT.getVectorElementType().getSizeInBits()) {
10882 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
10887 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
10888 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
10889 // (and (i32 x86isd::setcc_carry), 1)
10890 // This eliminates the zext. This transformation is necessary because
10891 // ISD::SETCC is always legalized to i8.
10892 DebugLoc dl = N->getDebugLoc();
10893 SDValue N0 = N->getOperand(0);
10894 EVT VT = N->getValueType(0);
10895 if (N0.getOpcode() == ISD::AND &&
10897 N0.getOperand(0).hasOneUse()) {
10898 SDValue N00 = N0.getOperand(0);
10899 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
10901 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
10902 if (!C || C->getZExtValue() != 1)
10904 return DAG.getNode(ISD::AND, dl, VT,
10905 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
10906 N00.getOperand(0), N00.getOperand(1)),
10907 DAG.getConstant(1, VT));
10913 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
10914 DAGCombinerInfo &DCI) const {
10915 SelectionDAG &DAG = DCI.DAG;
10916 switch (N->getOpcode()) {
10918 case ISD::EXTRACT_VECTOR_ELT:
10919 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
10920 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
10921 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
10922 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
10925 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
10926 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
10927 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
10929 case X86ISD::FOR: return PerformFORCombine(N, DAG);
10930 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
10931 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
10932 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
10933 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
10934 case X86ISD::SHUFPS: // Handle all target specific shuffles
10935 case X86ISD::SHUFPD:
10936 case X86ISD::PALIGN:
10937 case X86ISD::PUNPCKHBW:
10938 case X86ISD::PUNPCKHWD:
10939 case X86ISD::PUNPCKHDQ:
10940 case X86ISD::PUNPCKHQDQ:
10941 case X86ISD::UNPCKHPS:
10942 case X86ISD::UNPCKHPD:
10943 case X86ISD::PUNPCKLBW:
10944 case X86ISD::PUNPCKLWD:
10945 case X86ISD::PUNPCKLDQ:
10946 case X86ISD::PUNPCKLQDQ:
10947 case X86ISD::UNPCKLPS:
10948 case X86ISD::UNPCKLPD:
10949 case X86ISD::MOVHLPS:
10950 case X86ISD::MOVLHPS:
10951 case X86ISD::PSHUFD:
10952 case X86ISD::PSHUFHW:
10953 case X86ISD::PSHUFLW:
10954 case X86ISD::MOVSS:
10955 case X86ISD::MOVSD:
10956 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
10962 /// isTypeDesirableForOp - Return true if the target has native support for
10963 /// the specified value type and it is 'desirable' to use the type for the
10964 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
10965 /// instruction encodings are longer and some i16 instructions are slow.
10966 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
10967 if (!isTypeLegal(VT))
10969 if (VT != MVT::i16)
10976 case ISD::SIGN_EXTEND:
10977 case ISD::ZERO_EXTEND:
10978 case ISD::ANY_EXTEND:
10991 /// IsDesirableToPromoteOp - This method query the target whether it is
10992 /// beneficial for dag combiner to promote the specified node. If true, it
10993 /// should return the desired promotion type by reference.
10994 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
10995 EVT VT = Op.getValueType();
10996 if (VT != MVT::i16)
10999 bool Promote = false;
11000 bool Commute = false;
11001 switch (Op.getOpcode()) {
11004 LoadSDNode *LD = cast<LoadSDNode>(Op);
11005 // If the non-extending load has a single use and it's not live out, then it
11006 // might be folded.
11007 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
11008 Op.hasOneUse()*/) {
11009 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11010 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
11011 // The only case where we'd want to promote LOAD (rather then it being
11012 // promoted as an operand is when it's only use is liveout.
11013 if (UI->getOpcode() != ISD::CopyToReg)
11020 case ISD::SIGN_EXTEND:
11021 case ISD::ZERO_EXTEND:
11022 case ISD::ANY_EXTEND:
11027 SDValue N0 = Op.getOperand(0);
11028 // Look out for (store (shl (load), x)).
11029 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
11042 SDValue N0 = Op.getOperand(0);
11043 SDValue N1 = Op.getOperand(1);
11044 if (!Commute && MayFoldLoad(N1))
11046 // Avoid disabling potential load folding opportunities.
11047 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
11049 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
11059 //===----------------------------------------------------------------------===//
11060 // X86 Inline Assembly Support
11061 //===----------------------------------------------------------------------===//
11063 static bool LowerToBSwap(CallInst *CI) {
11064 // FIXME: this should verify that we are targetting a 486 or better. If not,
11065 // we will turn this bswap into something that will be lowered to logical ops
11066 // instead of emitting the bswap asm. For now, we don't support 486 or lower
11067 // so don't worry about this.
11069 // Verify this is a simple bswap.
11070 if (CI->getNumArgOperands() != 1 ||
11071 CI->getType() != CI->getArgOperand(0)->getType() ||
11072 !CI->getType()->isIntegerTy())
11075 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11076 if (!Ty || Ty->getBitWidth() % 16 != 0)
11079 // Okay, we can do this xform, do so now.
11080 const Type *Tys[] = { Ty };
11081 Module *M = CI->getParent()->getParent()->getParent();
11082 Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
11084 Value *Op = CI->getArgOperand(0);
11085 Op = CallInst::Create(Int, Op, CI->getName(), CI);
11087 CI->replaceAllUsesWith(Op);
11088 CI->eraseFromParent();
11092 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
11093 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
11094 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
11096 std::string AsmStr = IA->getAsmString();
11098 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
11099 SmallVector<StringRef, 4> AsmPieces;
11100 SplitString(AsmStr, AsmPieces, "\n"); // ; as separator?
11102 switch (AsmPieces.size()) {
11103 default: return false;
11105 AsmStr = AsmPieces[0];
11107 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
11110 if (AsmPieces.size() == 2 &&
11111 (AsmPieces[0] == "bswap" ||
11112 AsmPieces[0] == "bswapq" ||
11113 AsmPieces[0] == "bswapl") &&
11114 (AsmPieces[1] == "$0" ||
11115 AsmPieces[1] == "${0:q}")) {
11116 // No need to check constraints, nothing other than the equivalent of
11117 // "=r,0" would be valid here.
11118 return LowerToBSwap(CI);
11120 // rorw $$8, ${0:w} --> llvm.bswap.i16
11121 if (CI->getType()->isIntegerTy(16) &&
11122 AsmPieces.size() == 3 &&
11123 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
11124 AsmPieces[1] == "$$8," &&
11125 AsmPieces[2] == "${0:w}" &&
11126 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
11128 const std::string &Constraints = IA->getConstraintString();
11129 SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
11130 std::sort(AsmPieces.begin(), AsmPieces.end());
11131 if (AsmPieces.size() == 4 &&
11132 AsmPieces[0] == "~{cc}" &&
11133 AsmPieces[1] == "~{dirflag}" &&
11134 AsmPieces[2] == "~{flags}" &&
11135 AsmPieces[3] == "~{fpsr}") {
11136 return LowerToBSwap(CI);
11141 if (CI->getType()->isIntegerTy(64) &&
11142 Constraints.size() >= 2 &&
11143 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
11144 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
11145 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
11146 SmallVector<StringRef, 4> Words;
11147 SplitString(AsmPieces[0], Words, " \t");
11148 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
11150 SplitString(AsmPieces[1], Words, " \t");
11151 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
11153 SplitString(AsmPieces[2], Words, " \t,");
11154 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
11155 Words[2] == "%edx") {
11156 return LowerToBSwap(CI);
11168 /// getConstraintType - Given a constraint letter, return the type of
11169 /// constraint it is for this target.
11170 X86TargetLowering::ConstraintType
11171 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
11172 if (Constraint.size() == 1) {
11173 switch (Constraint[0]) {
11185 return C_RegisterClass;
11193 return TargetLowering::getConstraintType(Constraint);
11196 /// LowerXConstraint - try to replace an X constraint, which matches anything,
11197 /// with another that has more specific requirements based on the type of the
11198 /// corresponding operand.
11199 const char *X86TargetLowering::
11200 LowerXConstraint(EVT ConstraintVT) const {
11201 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
11202 // 'f' like normal targets.
11203 if (ConstraintVT.isFloatingPoint()) {
11204 if (Subtarget->hasSSE2())
11206 if (Subtarget->hasSSE1())
11210 return TargetLowering::LowerXConstraint(ConstraintVT);
11213 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11214 /// vector. If it is invalid, don't add anything to Ops.
11215 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11217 std::vector<SDValue>&Ops,
11218 SelectionDAG &DAG) const {
11219 SDValue Result(0, 0);
11221 switch (Constraint) {
11224 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11225 if (C->getZExtValue() <= 31) {
11226 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11232 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11233 if (C->getZExtValue() <= 63) {
11234 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11240 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11241 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
11242 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11248 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11249 if (C->getZExtValue() <= 255) {
11250 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11256 // 32-bit signed value
11257 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11258 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
11259 C->getSExtValue())) {
11260 // Widen to 64 bits here to get it sign extended.
11261 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
11264 // FIXME gcc accepts some relocatable values here too, but only in certain
11265 // memory models; it's complicated.
11270 // 32-bit unsigned value
11271 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11272 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
11273 C->getZExtValue())) {
11274 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11278 // FIXME gcc accepts some relocatable values here too, but only in certain
11279 // memory models; it's complicated.
11283 // Literal immediates are always ok.
11284 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
11285 // Widen to 64 bits here to get it sign extended.
11286 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
11290 // In any sort of PIC mode addresses need to be computed at runtime by
11291 // adding in a register or some sort of table lookup. These can't
11292 // be used as immediates.
11293 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
11296 // If we are in non-pic codegen mode, we allow the address of a global (with
11297 // an optional displacement) to be used with 'i'.
11298 GlobalAddressSDNode *GA = 0;
11299 int64_t Offset = 0;
11301 // Match either (GA), (GA+C), (GA+C1+C2), etc.
11303 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
11304 Offset += GA->getOffset();
11306 } else if (Op.getOpcode() == ISD::ADD) {
11307 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
11308 Offset += C->getZExtValue();
11309 Op = Op.getOperand(0);
11312 } else if (Op.getOpcode() == ISD::SUB) {
11313 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
11314 Offset += -C->getZExtValue();
11315 Op = Op.getOperand(0);
11320 // Otherwise, this isn't something we can handle, reject it.
11324 const GlobalValue *GV = GA->getGlobal();
11325 // If we require an extra load to get this address, as in PIC mode, we
11326 // can't accept it.
11327 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
11328 getTargetMachine())))
11331 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
11332 GA->getValueType(0), Offset);
11337 if (Result.getNode()) {
11338 Ops.push_back(Result);
11341 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11344 std::vector<unsigned> X86TargetLowering::
11345 getRegClassForInlineAsmConstraint(const std::string &Constraint,
11347 if (Constraint.size() == 1) {
11348 // FIXME: not handling fp-stack yet!
11349 switch (Constraint[0]) { // GCC X86 Constraint Letters
11350 default: break; // Unknown constraint letter
11351 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
11352 if (Subtarget->is64Bit()) {
11353 if (VT == MVT::i32)
11354 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
11355 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
11356 X86::R10D,X86::R11D,X86::R12D,
11357 X86::R13D,X86::R14D,X86::R15D,
11358 X86::EBP, X86::ESP, 0);
11359 else if (VT == MVT::i16)
11360 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
11361 X86::SI, X86::DI, X86::R8W,X86::R9W,
11362 X86::R10W,X86::R11W,X86::R12W,
11363 X86::R13W,X86::R14W,X86::R15W,
11364 X86::BP, X86::SP, 0);
11365 else if (VT == MVT::i8)
11366 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
11367 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
11368 X86::R10B,X86::R11B,X86::R12B,
11369 X86::R13B,X86::R14B,X86::R15B,
11370 X86::BPL, X86::SPL, 0);
11372 else if (VT == MVT::i64)
11373 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
11374 X86::RSI, X86::RDI, X86::R8, X86::R9,
11375 X86::R10, X86::R11, X86::R12,
11376 X86::R13, X86::R14, X86::R15,
11377 X86::RBP, X86::RSP, 0);
11381 // 32-bit fallthrough
11382 case 'Q': // Q_REGS
11383 if (VT == MVT::i32)
11384 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
11385 else if (VT == MVT::i16)
11386 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
11387 else if (VT == MVT::i8)
11388 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
11389 else if (VT == MVT::i64)
11390 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
11395 return std::vector<unsigned>();
11398 std::pair<unsigned, const TargetRegisterClass*>
11399 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
11401 // First, see if this is a constraint that directly corresponds to an LLVM
11403 if (Constraint.size() == 1) {
11404 // GCC Constraint Letters
11405 switch (Constraint[0]) {
11407 case 'r': // GENERAL_REGS
11408 case 'l': // INDEX_REGS
11410 return std::make_pair(0U, X86::GR8RegisterClass);
11411 if (VT == MVT::i16)
11412 return std::make_pair(0U, X86::GR16RegisterClass);
11413 if (VT == MVT::i32 || !Subtarget->is64Bit())
11414 return std::make_pair(0U, X86::GR32RegisterClass);
11415 return std::make_pair(0U, X86::GR64RegisterClass);
11416 case 'R': // LEGACY_REGS
11418 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
11419 if (VT == MVT::i16)
11420 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
11421 if (VT == MVT::i32 || !Subtarget->is64Bit())
11422 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
11423 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
11424 case 'f': // FP Stack registers.
11425 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
11426 // value to the correct fpstack register class.
11427 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
11428 return std::make_pair(0U, X86::RFP32RegisterClass);
11429 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
11430 return std::make_pair(0U, X86::RFP64RegisterClass);
11431 return std::make_pair(0U, X86::RFP80RegisterClass);
11432 case 'y': // MMX_REGS if MMX allowed.
11433 if (!Subtarget->hasMMX()) break;
11434 return std::make_pair(0U, X86::VR64RegisterClass);
11435 case 'Y': // SSE_REGS if SSE2 allowed
11436 if (!Subtarget->hasSSE2()) break;
11438 case 'x': // SSE_REGS if SSE1 allowed
11439 if (!Subtarget->hasSSE1()) break;
11441 switch (VT.getSimpleVT().SimpleTy) {
11443 // Scalar SSE types.
11446 return std::make_pair(0U, X86::FR32RegisterClass);
11449 return std::make_pair(0U, X86::FR64RegisterClass);
11457 return std::make_pair(0U, X86::VR128RegisterClass);
11463 // Use the default implementation in TargetLowering to convert the register
11464 // constraint into a member of a register class.
11465 std::pair<unsigned, const TargetRegisterClass*> Res;
11466 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
11468 // Not found as a standard register?
11469 if (Res.second == 0) {
11470 // Map st(0) -> st(7) -> ST0
11471 if (Constraint.size() == 7 && Constraint[0] == '{' &&
11472 tolower(Constraint[1]) == 's' &&
11473 tolower(Constraint[2]) == 't' &&
11474 Constraint[3] == '(' &&
11475 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
11476 Constraint[5] == ')' &&
11477 Constraint[6] == '}') {
11479 Res.first = X86::ST0+Constraint[4]-'0';
11480 Res.second = X86::RFP80RegisterClass;
11484 // GCC allows "st(0)" to be called just plain "st".
11485 if (StringRef("{st}").equals_lower(Constraint)) {
11486 Res.first = X86::ST0;
11487 Res.second = X86::RFP80RegisterClass;
11492 if (StringRef("{flags}").equals_lower(Constraint)) {
11493 Res.first = X86::EFLAGS;
11494 Res.second = X86::CCRRegisterClass;
11498 // 'A' means EAX + EDX.
11499 if (Constraint == "A") {
11500 Res.first = X86::EAX;
11501 Res.second = X86::GR32_ADRegisterClass;
11507 // Otherwise, check to see if this is a register class of the wrong value
11508 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
11509 // turn into {ax},{dx}.
11510 if (Res.second->hasType(VT))
11511 return Res; // Correct type already, nothing to do.
11513 // All of the single-register GCC register classes map their values onto
11514 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
11515 // really want an 8-bit or 32-bit register, map to the appropriate register
11516 // class and return the appropriate register.
11517 if (Res.second == X86::GR16RegisterClass) {
11518 if (VT == MVT::i8) {
11519 unsigned DestReg = 0;
11520 switch (Res.first) {
11522 case X86::AX: DestReg = X86::AL; break;
11523 case X86::DX: DestReg = X86::DL; break;
11524 case X86::CX: DestReg = X86::CL; break;
11525 case X86::BX: DestReg = X86::BL; break;
11528 Res.first = DestReg;
11529 Res.second = X86::GR8RegisterClass;
11531 } else if (VT == MVT::i32) {
11532 unsigned DestReg = 0;
11533 switch (Res.first) {
11535 case X86::AX: DestReg = X86::EAX; break;
11536 case X86::DX: DestReg = X86::EDX; break;
11537 case X86::CX: DestReg = X86::ECX; break;
11538 case X86::BX: DestReg = X86::EBX; break;
11539 case X86::SI: DestReg = X86::ESI; break;
11540 case X86::DI: DestReg = X86::EDI; break;
11541 case X86::BP: DestReg = X86::EBP; break;
11542 case X86::SP: DestReg = X86::ESP; break;
11545 Res.first = DestReg;
11546 Res.second = X86::GR32RegisterClass;
11548 } else if (VT == MVT::i64) {
11549 unsigned DestReg = 0;
11550 switch (Res.first) {
11552 case X86::AX: DestReg = X86::RAX; break;
11553 case X86::DX: DestReg = X86::RDX; break;
11554 case X86::CX: DestReg = X86::RCX; break;
11555 case X86::BX: DestReg = X86::RBX; break;
11556 case X86::SI: DestReg = X86::RSI; break;
11557 case X86::DI: DestReg = X86::RDI; break;
11558 case X86::BP: DestReg = X86::RBP; break;
11559 case X86::SP: DestReg = X86::RSP; break;
11562 Res.first = DestReg;
11563 Res.second = X86::GR64RegisterClass;
11566 } else if (Res.second == X86::FR32RegisterClass ||
11567 Res.second == X86::FR64RegisterClass ||
11568 Res.second == X86::VR128RegisterClass) {
11569 // Handle references to XMM physical registers that got mapped into the
11570 // wrong class. This can happen with constraints like {xmm0} where the
11571 // target independent register mapper will just pick the first match it can
11572 // find, ignoring the required type.
11573 if (VT == MVT::f32)
11574 Res.second = X86::FR32RegisterClass;
11575 else if (VT == MVT::f64)
11576 Res.second = X86::FR64RegisterClass;
11577 else if (X86::VR128RegisterClass->hasType(VT))
11578 Res.second = X86::VR128RegisterClass;