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 // or SSE or MMX vectors.
1320 if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1321 VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1322 (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1323 report_fatal_error("SSE register return with SSE disabled");
1325 // Likewise we can't return F64 values with SSE1 only. gcc does so, but
1326 // llvm-gcc has never done it right and no one has noticed, so this
1327 // should be OK for now.
1328 if (ValVT == MVT::f64 &&
1329 (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1330 report_fatal_error("SSE2 register return with SSE2 disabled");
1332 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1333 // the RET instruction and handled by the FP Stackifier.
1334 if (VA.getLocReg() == X86::ST0 ||
1335 VA.getLocReg() == X86::ST1) {
1336 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1337 // change the value to the FP stack register class.
1338 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1339 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1340 RetOps.push_back(ValToCopy);
1341 // Don't emit a copytoreg.
1345 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1346 // which is returned in RAX / RDX.
1347 if (Subtarget->is64Bit()) {
1348 if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1349 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1350 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1351 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1354 // If we don't have SSE2 available, convert to v4f32 so the generated
1355 // register is legal.
1356 if (!Subtarget->hasSSE2())
1357 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32,ValToCopy);
1362 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1363 Flag = Chain.getValue(1);
1366 // The x86-64 ABI for returning structs by value requires that we copy
1367 // the sret argument into %rax for the return. We saved the argument into
1368 // a virtual register in the entry block, so now we copy the value out
1370 if (Subtarget->is64Bit() &&
1371 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1372 MachineFunction &MF = DAG.getMachineFunction();
1373 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1374 unsigned Reg = FuncInfo->getSRetReturnReg();
1376 "SRetReturnReg should have been set in LowerFormalArguments().");
1377 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1379 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1380 Flag = Chain.getValue(1);
1382 // RAX now acts like a return value.
1383 MRI.addLiveOut(X86::RAX);
1386 RetOps[0] = Chain; // Update chain.
1388 // Add the flag if we have it.
1390 RetOps.push_back(Flag);
1392 return DAG.getNode(X86ISD::RET_FLAG, dl,
1393 MVT::Other, &RetOps[0], RetOps.size());
1396 /// LowerCallResult - Lower the result values of a call into the
1397 /// appropriate copies out of appropriate physical registers.
1400 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1401 CallingConv::ID CallConv, bool isVarArg,
1402 const SmallVectorImpl<ISD::InputArg> &Ins,
1403 DebugLoc dl, SelectionDAG &DAG,
1404 SmallVectorImpl<SDValue> &InVals) const {
1406 // Assign locations to each value returned by this call.
1407 SmallVector<CCValAssign, 16> RVLocs;
1408 bool Is64Bit = Subtarget->is64Bit();
1409 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1410 RVLocs, *DAG.getContext());
1411 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1413 // Copy all of the result registers out of their specified physreg.
1414 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1415 CCValAssign &VA = RVLocs[i];
1416 EVT CopyVT = VA.getValVT();
1418 // If this is x86-64, and we disabled SSE, we can't return FP values
1419 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1420 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1421 report_fatal_error("SSE register return with SSE disabled");
1426 // If this is a call to a function that returns an fp value on the floating
1427 // point stack, we must guarantee the the value is popped from the stack, so
1428 // a CopyFromReg is not good enough - the copy instruction may be eliminated
1429 // if the return value is not used. We use the FpGET_ST0 instructions
1431 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
1432 // If we prefer to use the value in xmm registers, copy it out as f80 and
1433 // use a truncate to move it from fp stack reg to xmm reg.
1434 if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
1435 bool isST0 = VA.getLocReg() == X86::ST0;
1437 if (CopyVT == MVT::f32) Opc = isST0 ? X86::FpGET_ST0_32:X86::FpGET_ST1_32;
1438 if (CopyVT == MVT::f64) Opc = isST0 ? X86::FpGET_ST0_64:X86::FpGET_ST1_64;
1439 if (CopyVT == MVT::f80) Opc = isST0 ? X86::FpGET_ST0_80:X86::FpGET_ST1_80;
1440 SDValue Ops[] = { Chain, InFlag };
1441 Chain = SDValue(DAG.getMachineNode(Opc, dl, CopyVT, MVT::Other, MVT::Flag,
1443 Val = Chain.getValue(0);
1445 // Round the f80 to the right size, which also moves it to the appropriate
1447 if (CopyVT != VA.getValVT())
1448 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1449 // This truncation won't change the value.
1450 DAG.getIntPtrConstant(1));
1451 } else if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1452 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1453 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1454 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1455 MVT::v2i64, InFlag).getValue(1);
1456 Val = Chain.getValue(0);
1457 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1458 Val, DAG.getConstant(0, MVT::i64));
1460 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1461 MVT::i64, InFlag).getValue(1);
1462 Val = Chain.getValue(0);
1464 Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1466 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1467 CopyVT, InFlag).getValue(1);
1468 Val = Chain.getValue(0);
1470 InFlag = Chain.getValue(2);
1471 InVals.push_back(Val);
1478 //===----------------------------------------------------------------------===//
1479 // C & StdCall & Fast Calling Convention implementation
1480 //===----------------------------------------------------------------------===//
1481 // StdCall calling convention seems to be standard for many Windows' API
1482 // routines and around. It differs from C calling convention just a little:
1483 // callee should clean up the stack, not caller. Symbols should be also
1484 // decorated in some fancy way :) It doesn't support any vector arguments.
1485 // For info on fast calling convention see Fast Calling Convention (tail call)
1486 // implementation LowerX86_32FastCCCallTo.
1488 /// CallIsStructReturn - Determines whether a call uses struct return
1490 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1494 return Outs[0].Flags.isSRet();
1497 /// ArgsAreStructReturn - Determines whether a function uses struct
1498 /// return semantics.
1500 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1504 return Ins[0].Flags.isSRet();
1507 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1508 /// given CallingConvention value.
1509 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1510 if (Subtarget->is64Bit()) {
1511 if (CC == CallingConv::GHC)
1512 return CC_X86_64_GHC;
1513 else if (Subtarget->isTargetWin64())
1514 return CC_X86_Win64_C;
1519 if (CC == CallingConv::X86_FastCall)
1520 return CC_X86_32_FastCall;
1521 else if (CC == CallingConv::X86_ThisCall)
1522 return CC_X86_32_ThisCall;
1523 else if (CC == CallingConv::Fast)
1524 return CC_X86_32_FastCC;
1525 else if (CC == CallingConv::GHC)
1526 return CC_X86_32_GHC;
1531 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1532 /// by "Src" to address "Dst" with size and alignment information specified by
1533 /// the specific parameter attribute. The copy will be passed as a byval
1534 /// function parameter.
1536 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1537 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1539 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1541 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1542 /*isVolatile*/false, /*AlwaysInline=*/true,
1543 MachinePointerInfo(), MachinePointerInfo());
1546 /// IsTailCallConvention - Return true if the calling convention is one that
1547 /// supports tail call optimization.
1548 static bool IsTailCallConvention(CallingConv::ID CC) {
1549 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1552 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1553 /// a tailcall target by changing its ABI.
1554 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1555 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1559 X86TargetLowering::LowerMemArgument(SDValue Chain,
1560 CallingConv::ID CallConv,
1561 const SmallVectorImpl<ISD::InputArg> &Ins,
1562 DebugLoc dl, SelectionDAG &DAG,
1563 const CCValAssign &VA,
1564 MachineFrameInfo *MFI,
1566 // Create the nodes corresponding to a load from this parameter slot.
1567 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1568 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1569 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1572 // If value is passed by pointer we have address passed instead of the value
1574 if (VA.getLocInfo() == CCValAssign::Indirect)
1575 ValVT = VA.getLocVT();
1577 ValVT = VA.getValVT();
1579 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1580 // changed with more analysis.
1581 // In case of tail call optimization mark all arguments mutable. Since they
1582 // could be overwritten by lowering of arguments in case of a tail call.
1583 if (Flags.isByVal()) {
1584 int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1585 VA.getLocMemOffset(), isImmutable);
1586 return DAG.getFrameIndex(FI, getPointerTy());
1588 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1589 VA.getLocMemOffset(), isImmutable);
1590 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1591 return DAG.getLoad(ValVT, dl, Chain, FIN,
1592 MachinePointerInfo::getFixedStack(FI),
1598 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1599 CallingConv::ID CallConv,
1601 const SmallVectorImpl<ISD::InputArg> &Ins,
1604 SmallVectorImpl<SDValue> &InVals)
1606 MachineFunction &MF = DAG.getMachineFunction();
1607 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1609 const Function* Fn = MF.getFunction();
1610 if (Fn->hasExternalLinkage() &&
1611 Subtarget->isTargetCygMing() &&
1612 Fn->getName() == "main")
1613 FuncInfo->setForceFramePointer(true);
1615 MachineFrameInfo *MFI = MF.getFrameInfo();
1616 bool Is64Bit = Subtarget->is64Bit();
1617 bool IsWin64 = Subtarget->isTargetWin64();
1619 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1620 "Var args not supported with calling convention fastcc or ghc");
1622 // Assign locations to all of the incoming arguments.
1623 SmallVector<CCValAssign, 16> ArgLocs;
1624 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1625 ArgLocs, *DAG.getContext());
1626 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1628 unsigned LastVal = ~0U;
1630 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1631 CCValAssign &VA = ArgLocs[i];
1632 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1634 assert(VA.getValNo() != LastVal &&
1635 "Don't support value assigned to multiple locs yet");
1636 LastVal = VA.getValNo();
1638 if (VA.isRegLoc()) {
1639 EVT RegVT = VA.getLocVT();
1640 TargetRegisterClass *RC = NULL;
1641 if (RegVT == MVT::i32)
1642 RC = X86::GR32RegisterClass;
1643 else if (Is64Bit && RegVT == MVT::i64)
1644 RC = X86::GR64RegisterClass;
1645 else if (RegVT == MVT::f32)
1646 RC = X86::FR32RegisterClass;
1647 else if (RegVT == MVT::f64)
1648 RC = X86::FR64RegisterClass;
1649 else if (RegVT.isVector() && RegVT.getSizeInBits() == 256)
1650 RC = X86::VR256RegisterClass;
1651 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1652 RC = X86::VR128RegisterClass;
1653 else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1654 RC = X86::VR64RegisterClass;
1656 llvm_unreachable("Unknown argument type!");
1658 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1659 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1661 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1662 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1664 if (VA.getLocInfo() == CCValAssign::SExt)
1665 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1666 DAG.getValueType(VA.getValVT()));
1667 else if (VA.getLocInfo() == CCValAssign::ZExt)
1668 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1669 DAG.getValueType(VA.getValVT()));
1670 else if (VA.getLocInfo() == CCValAssign::BCvt)
1671 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1673 if (VA.isExtInLoc()) {
1674 // Handle MMX values passed in XMM regs.
1675 if (RegVT.isVector()) {
1676 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1677 ArgValue, DAG.getConstant(0, MVT::i64));
1678 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1680 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1683 assert(VA.isMemLoc());
1684 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1687 // If value is passed via pointer - do a load.
1688 if (VA.getLocInfo() == CCValAssign::Indirect)
1689 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
1690 MachinePointerInfo(), false, false, 0);
1692 InVals.push_back(ArgValue);
1695 // The x86-64 ABI for returning structs by value requires that we copy
1696 // the sret argument into %rax for the return. Save the argument into
1697 // a virtual register so that we can access it from the return points.
1698 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1699 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1700 unsigned Reg = FuncInfo->getSRetReturnReg();
1702 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1703 FuncInfo->setSRetReturnReg(Reg);
1705 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1706 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1709 unsigned StackSize = CCInfo.getNextStackOffset();
1710 // Align stack specially for tail calls.
1711 if (FuncIsMadeTailCallSafe(CallConv))
1712 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1714 // If the function takes variable number of arguments, make a frame index for
1715 // the start of the first vararg value... for expansion of llvm.va_start.
1717 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1718 CallConv != CallingConv::X86_ThisCall)) {
1719 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1722 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1724 // FIXME: We should really autogenerate these arrays
1725 static const unsigned GPR64ArgRegsWin64[] = {
1726 X86::RCX, X86::RDX, X86::R8, X86::R9
1728 static const unsigned XMMArgRegsWin64[] = {
1729 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1731 static const unsigned GPR64ArgRegs64Bit[] = {
1732 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1734 static const unsigned XMMArgRegs64Bit[] = {
1735 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1736 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1738 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1741 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1742 GPR64ArgRegs = GPR64ArgRegsWin64;
1743 XMMArgRegs = XMMArgRegsWin64;
1745 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1746 GPR64ArgRegs = GPR64ArgRegs64Bit;
1747 XMMArgRegs = XMMArgRegs64Bit;
1749 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1751 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1754 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1755 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1756 "SSE register cannot be used when SSE is disabled!");
1757 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1758 "SSE register cannot be used when SSE is disabled!");
1759 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1760 // Kernel mode asks for SSE to be disabled, so don't push them
1762 TotalNumXMMRegs = 0;
1764 // For X86-64, if there are vararg parameters that are passed via
1765 // registers, then we must store them to their spots on the stack so they
1766 // may be loaded by deferencing the result of va_next.
1767 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1768 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1769 FuncInfo->setRegSaveFrameIndex(
1770 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1773 // Store the integer parameter registers.
1774 SmallVector<SDValue, 8> MemOps;
1775 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1777 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1778 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1779 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1780 DAG.getIntPtrConstant(Offset));
1781 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1782 X86::GR64RegisterClass);
1783 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1785 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1786 MachinePointerInfo::getFixedStack(
1787 FuncInfo->getRegSaveFrameIndex(), Offset),
1789 MemOps.push_back(Store);
1793 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1794 // Now store the XMM (fp + vector) parameter registers.
1795 SmallVector<SDValue, 11> SaveXMMOps;
1796 SaveXMMOps.push_back(Chain);
1798 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1799 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1800 SaveXMMOps.push_back(ALVal);
1802 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1803 FuncInfo->getRegSaveFrameIndex()));
1804 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1805 FuncInfo->getVarArgsFPOffset()));
1807 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1808 unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1809 X86::VR128RegisterClass);
1810 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1811 SaveXMMOps.push_back(Val);
1813 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1815 &SaveXMMOps[0], SaveXMMOps.size()));
1818 if (!MemOps.empty())
1819 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1820 &MemOps[0], MemOps.size());
1824 // Some CCs need callee pop.
1825 if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1826 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1828 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1829 // If this is an sret function, the return should pop the hidden pointer.
1830 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1831 FuncInfo->setBytesToPopOnReturn(4);
1835 // RegSaveFrameIndex is X86-64 only.
1836 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1837 if (CallConv == CallingConv::X86_FastCall ||
1838 CallConv == CallingConv::X86_ThisCall)
1839 // fastcc functions can't have varargs.
1840 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1847 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1848 SDValue StackPtr, SDValue Arg,
1849 DebugLoc dl, SelectionDAG &DAG,
1850 const CCValAssign &VA,
1851 ISD::ArgFlagsTy Flags) const {
1852 const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1853 unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1854 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1855 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1856 if (Flags.isByVal())
1857 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1859 return DAG.getStore(Chain, dl, Arg, PtrOff,
1860 MachinePointerInfo::getStack(LocMemOffset),
1864 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1865 /// optimization is performed and it is required.
1867 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1868 SDValue &OutRetAddr, SDValue Chain,
1869 bool IsTailCall, bool Is64Bit,
1870 int FPDiff, DebugLoc dl) const {
1871 // Adjust the Return address stack slot.
1872 EVT VT = getPointerTy();
1873 OutRetAddr = getReturnAddressFrameIndex(DAG);
1875 // Load the "old" Return address.
1876 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
1878 return SDValue(OutRetAddr.getNode(), 1);
1881 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1882 /// optimization is performed and it is required (FPDiff!=0).
1884 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1885 SDValue Chain, SDValue RetAddrFrIdx,
1886 bool Is64Bit, int FPDiff, DebugLoc dl) {
1887 // Store the return address to the appropriate stack slot.
1888 if (!FPDiff) return Chain;
1889 // Calculate the new stack slot for the return address.
1890 int SlotSize = Is64Bit ? 8 : 4;
1891 int NewReturnAddrFI =
1892 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1893 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1894 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1895 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1896 MachinePointerInfo::getFixedStack(NewReturnAddrFI),
1902 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1903 CallingConv::ID CallConv, bool isVarArg,
1905 const SmallVectorImpl<ISD::OutputArg> &Outs,
1906 const SmallVectorImpl<SDValue> &OutVals,
1907 const SmallVectorImpl<ISD::InputArg> &Ins,
1908 DebugLoc dl, SelectionDAG &DAG,
1909 SmallVectorImpl<SDValue> &InVals) const {
1910 MachineFunction &MF = DAG.getMachineFunction();
1911 bool Is64Bit = Subtarget->is64Bit();
1912 bool IsStructRet = CallIsStructReturn(Outs);
1913 bool IsSibcall = false;
1916 // Check if it's really possible to do a tail call.
1917 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1918 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1919 Outs, OutVals, Ins, DAG);
1921 // Sibcalls are automatically detected tailcalls which do not require
1923 if (!GuaranteedTailCallOpt && isTailCall)
1930 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1931 "Var args not supported with calling convention fastcc or ghc");
1933 // Analyze operands of the call, assigning locations to each operand.
1934 SmallVector<CCValAssign, 16> ArgLocs;
1935 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1936 ArgLocs, *DAG.getContext());
1937 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1939 // Get a count of how many bytes are to be pushed on the stack.
1940 unsigned NumBytes = CCInfo.getNextStackOffset();
1942 // This is a sibcall. The memory operands are available in caller's
1943 // own caller's stack.
1945 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1946 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1949 if (isTailCall && !IsSibcall) {
1950 // Lower arguments at fp - stackoffset + fpdiff.
1951 unsigned NumBytesCallerPushed =
1952 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1953 FPDiff = NumBytesCallerPushed - NumBytes;
1955 // Set the delta of movement of the returnaddr stackslot.
1956 // But only set if delta is greater than previous delta.
1957 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1958 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1962 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1964 SDValue RetAddrFrIdx;
1965 // Load return adress for tail calls.
1966 if (isTailCall && FPDiff)
1967 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1968 Is64Bit, FPDiff, dl);
1970 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1971 SmallVector<SDValue, 8> MemOpChains;
1974 // Walk the register/memloc assignments, inserting copies/loads. In the case
1975 // of tail call optimization arguments are handle later.
1976 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1977 CCValAssign &VA = ArgLocs[i];
1978 EVT RegVT = VA.getLocVT();
1979 SDValue Arg = OutVals[i];
1980 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1981 bool isByVal = Flags.isByVal();
1983 // Promote the value if needed.
1984 switch (VA.getLocInfo()) {
1985 default: llvm_unreachable("Unknown loc info!");
1986 case CCValAssign::Full: break;
1987 case CCValAssign::SExt:
1988 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1990 case CCValAssign::ZExt:
1991 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1993 case CCValAssign::AExt:
1994 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1995 // Special case: passing MMX values in XMM registers.
1996 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1997 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1998 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2000 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2002 case CCValAssign::BCvt:
2003 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
2005 case CCValAssign::Indirect: {
2006 // Store the argument.
2007 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2008 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2009 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2010 MachinePointerInfo::getFixedStack(FI),
2017 if (VA.isRegLoc()) {
2018 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2019 if (isVarArg && Subtarget->isTargetWin64()) {
2020 // Win64 ABI requires argument XMM reg to be copied to the corresponding
2021 // shadow reg if callee is a varargs function.
2022 unsigned ShadowReg = 0;
2023 switch (VA.getLocReg()) {
2024 case X86::XMM0: ShadowReg = X86::RCX; break;
2025 case X86::XMM1: ShadowReg = X86::RDX; break;
2026 case X86::XMM2: ShadowReg = X86::R8; break;
2027 case X86::XMM3: ShadowReg = X86::R9; break;
2030 RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2032 } else if (!IsSibcall && (!isTailCall || isByVal)) {
2033 assert(VA.isMemLoc());
2034 if (StackPtr.getNode() == 0)
2035 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
2036 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2037 dl, DAG, VA, Flags));
2041 if (!MemOpChains.empty())
2042 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2043 &MemOpChains[0], MemOpChains.size());
2045 // Build a sequence of copy-to-reg nodes chained together with token chain
2046 // and flag operands which copy the outgoing args into registers.
2048 // Tail call byval lowering might overwrite argument registers so in case of
2049 // tail call optimization the copies to registers are lowered later.
2051 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2052 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2053 RegsToPass[i].second, InFlag);
2054 InFlag = Chain.getValue(1);
2057 if (Subtarget->isPICStyleGOT()) {
2058 // ELF / PIC requires GOT in the EBX register before function calls via PLT
2061 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
2062 DAG.getNode(X86ISD::GlobalBaseReg,
2063 DebugLoc(), getPointerTy()),
2065 InFlag = Chain.getValue(1);
2067 // If we are tail calling and generating PIC/GOT style code load the
2068 // address of the callee into ECX. The value in ecx is used as target of
2069 // the tail jump. This is done to circumvent the ebx/callee-saved problem
2070 // for tail calls on PIC/GOT architectures. Normally we would just put the
2071 // address of GOT into ebx and then call target@PLT. But for tail calls
2072 // ebx would be restored (since ebx is callee saved) before jumping to the
2075 // Note: The actual moving to ECX is done further down.
2076 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2077 if (G && !G->getGlobal()->hasHiddenVisibility() &&
2078 !G->getGlobal()->hasProtectedVisibility())
2079 Callee = LowerGlobalAddress(Callee, DAG);
2080 else if (isa<ExternalSymbolSDNode>(Callee))
2081 Callee = LowerExternalSymbol(Callee, DAG);
2085 if (Is64Bit && isVarArg && !Subtarget->isTargetWin64()) {
2086 // From AMD64 ABI document:
2087 // For calls that may call functions that use varargs or stdargs
2088 // (prototype-less calls or calls to functions containing ellipsis (...) in
2089 // the declaration) %al is used as hidden argument to specify the number
2090 // of SSE registers used. The contents of %al do not need to match exactly
2091 // the number of registers, but must be an ubound on the number of SSE
2092 // registers used and is in the range 0 - 8 inclusive.
2094 // Count the number of XMM registers allocated.
2095 static const unsigned XMMArgRegs[] = {
2096 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2097 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2099 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2100 assert((Subtarget->hasSSE1() || !NumXMMRegs)
2101 && "SSE registers cannot be used when SSE is disabled");
2103 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
2104 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
2105 InFlag = Chain.getValue(1);
2109 // For tail calls lower the arguments to the 'real' stack slot.
2111 // Force all the incoming stack arguments to be loaded from the stack
2112 // before any new outgoing arguments are stored to the stack, because the
2113 // outgoing stack slots may alias the incoming argument stack slots, and
2114 // the alias isn't otherwise explicit. This is slightly more conservative
2115 // than necessary, because it means that each store effectively depends
2116 // on every argument instead of just those arguments it would clobber.
2117 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2119 SmallVector<SDValue, 8> MemOpChains2;
2122 // Do not flag preceeding copytoreg stuff together with the following stuff.
2124 if (GuaranteedTailCallOpt) {
2125 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2126 CCValAssign &VA = ArgLocs[i];
2129 assert(VA.isMemLoc());
2130 SDValue Arg = OutVals[i];
2131 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2132 // Create frame index.
2133 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2134 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2135 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2136 FIN = DAG.getFrameIndex(FI, getPointerTy());
2138 if (Flags.isByVal()) {
2139 // Copy relative to framepointer.
2140 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2141 if (StackPtr.getNode() == 0)
2142 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2144 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2146 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2150 // Store relative to framepointer.
2151 MemOpChains2.push_back(
2152 DAG.getStore(ArgChain, dl, Arg, FIN,
2153 MachinePointerInfo::getFixedStack(FI),
2159 if (!MemOpChains2.empty())
2160 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2161 &MemOpChains2[0], MemOpChains2.size());
2163 // Copy arguments to their registers.
2164 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2165 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2166 RegsToPass[i].second, InFlag);
2167 InFlag = Chain.getValue(1);
2171 // Store the return address to the appropriate stack slot.
2172 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2176 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2177 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2178 // In the 64-bit large code model, we have to make all calls
2179 // through a register, since the call instruction's 32-bit
2180 // pc-relative offset may not be large enough to hold the whole
2182 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2183 // If the callee is a GlobalAddress node (quite common, every direct call
2184 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2187 // We should use extra load for direct calls to dllimported functions in
2189 const GlobalValue *GV = G->getGlobal();
2190 if (!GV->hasDLLImportLinkage()) {
2191 unsigned char OpFlags = 0;
2193 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2194 // external symbols most go through the PLT in PIC mode. If the symbol
2195 // has hidden or protected visibility, or if it is static or local, then
2196 // we don't need to use the PLT - we can directly call it.
2197 if (Subtarget->isTargetELF() &&
2198 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2199 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2200 OpFlags = X86II::MO_PLT;
2201 } else if (Subtarget->isPICStyleStubAny() &&
2202 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2203 Subtarget->getDarwinVers() < 9) {
2204 // PC-relative references to external symbols should go through $stub,
2205 // unless we're building with the leopard linker or later, which
2206 // automatically synthesizes these stubs.
2207 OpFlags = X86II::MO_DARWIN_STUB;
2210 Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2211 G->getOffset(), OpFlags);
2213 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2214 unsigned char OpFlags = 0;
2216 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2217 // symbols should go through the PLT.
2218 if (Subtarget->isTargetELF() &&
2219 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2220 OpFlags = X86II::MO_PLT;
2221 } else if (Subtarget->isPICStyleStubAny() &&
2222 Subtarget->getDarwinVers() < 9) {
2223 // PC-relative references to external symbols should go through $stub,
2224 // unless we're building with the leopard linker or later, which
2225 // automatically synthesizes these stubs.
2226 OpFlags = X86II::MO_DARWIN_STUB;
2229 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2233 // Returns a chain & a flag for retval copy to use.
2234 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2235 SmallVector<SDValue, 8> Ops;
2237 if (!IsSibcall && isTailCall) {
2238 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2239 DAG.getIntPtrConstant(0, true), InFlag);
2240 InFlag = Chain.getValue(1);
2243 Ops.push_back(Chain);
2244 Ops.push_back(Callee);
2247 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2249 // Add argument registers to the end of the list so that they are known live
2251 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2252 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2253 RegsToPass[i].second.getValueType()));
2255 // Add an implicit use GOT pointer in EBX.
2256 if (!isTailCall && Subtarget->isPICStyleGOT())
2257 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2259 // Add an implicit use of AL for non-Windows x86 64-bit vararg functions.
2260 if (Is64Bit && isVarArg && !Subtarget->isTargetWin64())
2261 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2263 if (InFlag.getNode())
2264 Ops.push_back(InFlag);
2268 //// If this is the first return lowered for this function, add the regs
2269 //// to the liveout set for the function.
2270 // This isn't right, although it's probably harmless on x86; liveouts
2271 // should be computed from returns not tail calls. Consider a void
2272 // function making a tail call to a function returning int.
2273 return DAG.getNode(X86ISD::TC_RETURN, dl,
2274 NodeTys, &Ops[0], Ops.size());
2277 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2278 InFlag = Chain.getValue(1);
2280 // Create the CALLSEQ_END node.
2281 unsigned NumBytesForCalleeToPush;
2282 if (Subtarget->IsCalleePop(isVarArg, CallConv))
2283 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2284 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2285 // If this is a call to a struct-return function, the callee
2286 // pops the hidden struct pointer, so we have to push it back.
2287 // This is common for Darwin/X86, Linux & Mingw32 targets.
2288 NumBytesForCalleeToPush = 4;
2290 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2292 // Returns a flag for retval copy to use.
2294 Chain = DAG.getCALLSEQ_END(Chain,
2295 DAG.getIntPtrConstant(NumBytes, true),
2296 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2299 InFlag = Chain.getValue(1);
2302 // Handle result values, copying them out of physregs into vregs that we
2304 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2305 Ins, dl, DAG, InVals);
2309 //===----------------------------------------------------------------------===//
2310 // Fast Calling Convention (tail call) implementation
2311 //===----------------------------------------------------------------------===//
2313 // Like std call, callee cleans arguments, convention except that ECX is
2314 // reserved for storing the tail called function address. Only 2 registers are
2315 // free for argument passing (inreg). Tail call optimization is performed
2317 // * tailcallopt is enabled
2318 // * caller/callee are fastcc
2319 // On X86_64 architecture with GOT-style position independent code only local
2320 // (within module) calls are supported at the moment.
2321 // To keep the stack aligned according to platform abi the function
2322 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2323 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2324 // If a tail called function callee has more arguments than the caller the
2325 // caller needs to make sure that there is room to move the RETADDR to. This is
2326 // achieved by reserving an area the size of the argument delta right after the
2327 // original REtADDR, but before the saved framepointer or the spilled registers
2328 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2340 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2341 /// for a 16 byte align requirement.
2343 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2344 SelectionDAG& DAG) const {
2345 MachineFunction &MF = DAG.getMachineFunction();
2346 const TargetMachine &TM = MF.getTarget();
2347 const TargetFrameInfo &TFI = *TM.getFrameInfo();
2348 unsigned StackAlignment = TFI.getStackAlignment();
2349 uint64_t AlignMask = StackAlignment - 1;
2350 int64_t Offset = StackSize;
2351 uint64_t SlotSize = TD->getPointerSize();
2352 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2353 // Number smaller than 12 so just add the difference.
2354 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2356 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2357 Offset = ((~AlignMask) & Offset) + StackAlignment +
2358 (StackAlignment-SlotSize);
2363 /// MatchingStackOffset - Return true if the given stack call argument is
2364 /// already available in the same position (relatively) of the caller's
2365 /// incoming argument stack.
2367 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2368 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2369 const X86InstrInfo *TII) {
2370 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2372 if (Arg.getOpcode() == ISD::CopyFromReg) {
2373 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2374 if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2376 MachineInstr *Def = MRI->getVRegDef(VR);
2379 if (!Flags.isByVal()) {
2380 if (!TII->isLoadFromStackSlot(Def, FI))
2383 unsigned Opcode = Def->getOpcode();
2384 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2385 Def->getOperand(1).isFI()) {
2386 FI = Def->getOperand(1).getIndex();
2387 Bytes = Flags.getByValSize();
2391 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2392 if (Flags.isByVal())
2393 // ByVal argument is passed in as a pointer but it's now being
2394 // dereferenced. e.g.
2395 // define @foo(%struct.X* %A) {
2396 // tail call @bar(%struct.X* byval %A)
2399 SDValue Ptr = Ld->getBasePtr();
2400 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2403 FI = FINode->getIndex();
2407 assert(FI != INT_MAX);
2408 if (!MFI->isFixedObjectIndex(FI))
2410 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2413 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2414 /// for tail call optimization. Targets which want to do tail call
2415 /// optimization should implement this function.
2417 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2418 CallingConv::ID CalleeCC,
2420 bool isCalleeStructRet,
2421 bool isCallerStructRet,
2422 const SmallVectorImpl<ISD::OutputArg> &Outs,
2423 const SmallVectorImpl<SDValue> &OutVals,
2424 const SmallVectorImpl<ISD::InputArg> &Ins,
2425 SelectionDAG& DAG) const {
2426 if (!IsTailCallConvention(CalleeCC) &&
2427 CalleeCC != CallingConv::C)
2430 // If -tailcallopt is specified, make fastcc functions tail-callable.
2431 const MachineFunction &MF = DAG.getMachineFunction();
2432 const Function *CallerF = DAG.getMachineFunction().getFunction();
2433 CallingConv::ID CallerCC = CallerF->getCallingConv();
2434 bool CCMatch = CallerCC == CalleeCC;
2436 if (GuaranteedTailCallOpt) {
2437 if (IsTailCallConvention(CalleeCC) && CCMatch)
2442 // Look for obvious safe cases to perform tail call optimization that do not
2443 // require ABI changes. This is what gcc calls sibcall.
2445 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2446 // emit a special epilogue.
2447 if (RegInfo->needsStackRealignment(MF))
2450 // Do not sibcall optimize vararg calls unless the call site is not passing
2452 if (isVarArg && !Outs.empty())
2455 // Also avoid sibcall optimization if either caller or callee uses struct
2456 // return semantics.
2457 if (isCalleeStructRet || isCallerStructRet)
2460 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2461 // Therefore if it's not used by the call it is not safe to optimize this into
2463 bool Unused = false;
2464 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2471 SmallVector<CCValAssign, 16> RVLocs;
2472 CCState CCInfo(CalleeCC, false, getTargetMachine(),
2473 RVLocs, *DAG.getContext());
2474 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2475 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2476 CCValAssign &VA = RVLocs[i];
2477 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2482 // If the calling conventions do not match, then we'd better make sure the
2483 // results are returned in the same way as what the caller expects.
2485 SmallVector<CCValAssign, 16> RVLocs1;
2486 CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2487 RVLocs1, *DAG.getContext());
2488 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2490 SmallVector<CCValAssign, 16> RVLocs2;
2491 CCState CCInfo2(CallerCC, false, getTargetMachine(),
2492 RVLocs2, *DAG.getContext());
2493 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2495 if (RVLocs1.size() != RVLocs2.size())
2497 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2498 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2500 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2502 if (RVLocs1[i].isRegLoc()) {
2503 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2506 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2512 // If the callee takes no arguments then go on to check the results of the
2514 if (!Outs.empty()) {
2515 // Check if stack adjustment is needed. For now, do not do this if any
2516 // argument is passed on the stack.
2517 SmallVector<CCValAssign, 16> ArgLocs;
2518 CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2519 ArgLocs, *DAG.getContext());
2520 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
2521 if (CCInfo.getNextStackOffset()) {
2522 MachineFunction &MF = DAG.getMachineFunction();
2523 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2525 if (Subtarget->isTargetWin64())
2526 // Win64 ABI has additional complications.
2529 // Check if the arguments are already laid out in the right way as
2530 // the caller's fixed stack objects.
2531 MachineFrameInfo *MFI = MF.getFrameInfo();
2532 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2533 const X86InstrInfo *TII =
2534 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2535 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2536 CCValAssign &VA = ArgLocs[i];
2537 SDValue Arg = OutVals[i];
2538 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2539 if (VA.getLocInfo() == CCValAssign::Indirect)
2541 if (!VA.isRegLoc()) {
2542 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2549 // If the tailcall address may be in a register, then make sure it's
2550 // possible to register allocate for it. In 32-bit, the call address can
2551 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2552 // callee-saved registers are restored. These happen to be the same
2553 // registers used to pass 'inreg' arguments so watch out for those.
2554 if (!Subtarget->is64Bit() &&
2555 !isa<GlobalAddressSDNode>(Callee) &&
2556 !isa<ExternalSymbolSDNode>(Callee)) {
2557 unsigned NumInRegs = 0;
2558 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2559 CCValAssign &VA = ArgLocs[i];
2562 unsigned Reg = VA.getLocReg();
2565 case X86::EAX: case X86::EDX: case X86::ECX:
2566 if (++NumInRegs == 3)
2578 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo) const {
2579 return X86::createFastISel(funcInfo);
2583 //===----------------------------------------------------------------------===//
2584 // Other Lowering Hooks
2585 //===----------------------------------------------------------------------===//
2587 static bool MayFoldLoad(SDValue Op) {
2588 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
2591 static bool MayFoldIntoStore(SDValue Op) {
2592 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
2595 static bool isTargetShuffle(unsigned Opcode) {
2597 default: return false;
2598 case X86ISD::PSHUFD:
2599 case X86ISD::PSHUFHW:
2600 case X86ISD::PSHUFLW:
2601 case X86ISD::SHUFPD:
2602 case X86ISD::PALIGN:
2603 case X86ISD::SHUFPS:
2604 case X86ISD::MOVLHPS:
2605 case X86ISD::MOVLHPD:
2606 case X86ISD::MOVHLPS:
2607 case X86ISD::MOVLPS:
2608 case X86ISD::MOVLPD:
2609 case X86ISD::MOVSHDUP:
2610 case X86ISD::MOVSLDUP:
2611 case X86ISD::MOVDDUP:
2614 case X86ISD::UNPCKLPS:
2615 case X86ISD::UNPCKLPD:
2616 case X86ISD::PUNPCKLWD:
2617 case X86ISD::PUNPCKLBW:
2618 case X86ISD::PUNPCKLDQ:
2619 case X86ISD::PUNPCKLQDQ:
2620 case X86ISD::UNPCKHPS:
2621 case X86ISD::UNPCKHPD:
2622 case X86ISD::PUNPCKHWD:
2623 case X86ISD::PUNPCKHBW:
2624 case X86ISD::PUNPCKHDQ:
2625 case X86ISD::PUNPCKHQDQ:
2631 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2632 SDValue V1, SelectionDAG &DAG) {
2634 default: llvm_unreachable("Unknown x86 shuffle node");
2635 case X86ISD::MOVSHDUP:
2636 case X86ISD::MOVSLDUP:
2637 case X86ISD::MOVDDUP:
2638 return DAG.getNode(Opc, dl, VT, V1);
2644 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2645 SDValue V1, unsigned TargetMask, SelectionDAG &DAG) {
2647 default: llvm_unreachable("Unknown x86 shuffle node");
2648 case X86ISD::PSHUFD:
2649 case X86ISD::PSHUFHW:
2650 case X86ISD::PSHUFLW:
2651 return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
2657 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2658 SDValue V1, SDValue V2, unsigned TargetMask, SelectionDAG &DAG) {
2660 default: llvm_unreachable("Unknown x86 shuffle node");
2661 case X86ISD::PALIGN:
2662 case X86ISD::SHUFPD:
2663 case X86ISD::SHUFPS:
2664 return DAG.getNode(Opc, dl, VT, V1, V2,
2665 DAG.getConstant(TargetMask, MVT::i8));
2670 static SDValue getTargetShuffleNode(unsigned Opc, DebugLoc dl, EVT VT,
2671 SDValue V1, SDValue V2, SelectionDAG &DAG) {
2673 default: llvm_unreachable("Unknown x86 shuffle node");
2674 case X86ISD::MOVLHPS:
2675 case X86ISD::MOVLHPD:
2676 case X86ISD::MOVHLPS:
2677 case X86ISD::MOVLPS:
2678 case X86ISD::MOVLPD:
2681 case X86ISD::UNPCKLPS:
2682 case X86ISD::UNPCKLPD:
2683 case X86ISD::PUNPCKLWD:
2684 case X86ISD::PUNPCKLBW:
2685 case X86ISD::PUNPCKLDQ:
2686 case X86ISD::PUNPCKLQDQ:
2687 case X86ISD::UNPCKHPS:
2688 case X86ISD::UNPCKHPD:
2689 case X86ISD::PUNPCKHWD:
2690 case X86ISD::PUNPCKHBW:
2691 case X86ISD::PUNPCKHDQ:
2692 case X86ISD::PUNPCKHQDQ:
2693 return DAG.getNode(Opc, dl, VT, V1, V2);
2698 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2699 MachineFunction &MF = DAG.getMachineFunction();
2700 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2701 int ReturnAddrIndex = FuncInfo->getRAIndex();
2703 if (ReturnAddrIndex == 0) {
2704 // Set up a frame object for the return address.
2705 uint64_t SlotSize = TD->getPointerSize();
2706 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2708 FuncInfo->setRAIndex(ReturnAddrIndex);
2711 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2715 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2716 bool hasSymbolicDisplacement) {
2717 // Offset should fit into 32 bit immediate field.
2718 if (!isInt<32>(Offset))
2721 // If we don't have a symbolic displacement - we don't have any extra
2723 if (!hasSymbolicDisplacement)
2726 // FIXME: Some tweaks might be needed for medium code model.
2727 if (M != CodeModel::Small && M != CodeModel::Kernel)
2730 // For small code model we assume that latest object is 16MB before end of 31
2731 // bits boundary. We may also accept pretty large negative constants knowing
2732 // that all objects are in the positive half of address space.
2733 if (M == CodeModel::Small && Offset < 16*1024*1024)
2736 // For kernel code model we know that all object resist in the negative half
2737 // of 32bits address space. We may not accept negative offsets, since they may
2738 // be just off and we may accept pretty large positive ones.
2739 if (M == CodeModel::Kernel && Offset > 0)
2745 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2746 /// specific condition code, returning the condition code and the LHS/RHS of the
2747 /// comparison to make.
2748 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2749 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2751 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2752 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2753 // X > -1 -> X == 0, jump !sign.
2754 RHS = DAG.getConstant(0, RHS.getValueType());
2755 return X86::COND_NS;
2756 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2757 // X < 0 -> X == 0, jump on sign.
2759 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2761 RHS = DAG.getConstant(0, RHS.getValueType());
2762 return X86::COND_LE;
2766 switch (SetCCOpcode) {
2767 default: llvm_unreachable("Invalid integer condition!");
2768 case ISD::SETEQ: return X86::COND_E;
2769 case ISD::SETGT: return X86::COND_G;
2770 case ISD::SETGE: return X86::COND_GE;
2771 case ISD::SETLT: return X86::COND_L;
2772 case ISD::SETLE: return X86::COND_LE;
2773 case ISD::SETNE: return X86::COND_NE;
2774 case ISD::SETULT: return X86::COND_B;
2775 case ISD::SETUGT: return X86::COND_A;
2776 case ISD::SETULE: return X86::COND_BE;
2777 case ISD::SETUGE: return X86::COND_AE;
2781 // First determine if it is required or is profitable to flip the operands.
2783 // If LHS is a foldable load, but RHS is not, flip the condition.
2784 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2785 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2786 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2787 std::swap(LHS, RHS);
2790 switch (SetCCOpcode) {
2796 std::swap(LHS, RHS);
2800 // On a floating point condition, the flags are set as follows:
2802 // 0 | 0 | 0 | X > Y
2803 // 0 | 0 | 1 | X < Y
2804 // 1 | 0 | 0 | X == Y
2805 // 1 | 1 | 1 | unordered
2806 switch (SetCCOpcode) {
2807 default: llvm_unreachable("Condcode should be pre-legalized away");
2809 case ISD::SETEQ: return X86::COND_E;
2810 case ISD::SETOLT: // flipped
2812 case ISD::SETGT: return X86::COND_A;
2813 case ISD::SETOLE: // flipped
2815 case ISD::SETGE: return X86::COND_AE;
2816 case ISD::SETUGT: // flipped
2818 case ISD::SETLT: return X86::COND_B;
2819 case ISD::SETUGE: // flipped
2821 case ISD::SETLE: return X86::COND_BE;
2823 case ISD::SETNE: return X86::COND_NE;
2824 case ISD::SETUO: return X86::COND_P;
2825 case ISD::SETO: return X86::COND_NP;
2827 case ISD::SETUNE: return X86::COND_INVALID;
2831 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2832 /// code. Current x86 isa includes the following FP cmov instructions:
2833 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2834 static bool hasFPCMov(unsigned X86CC) {
2850 /// isFPImmLegal - Returns true if the target can instruction select the
2851 /// specified FP immediate natively. If false, the legalizer will
2852 /// materialize the FP immediate as a load from a constant pool.
2853 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2854 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2855 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2861 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2862 /// the specified range (L, H].
2863 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2864 return (Val < 0) || (Val >= Low && Val < Hi);
2867 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2868 /// specified value.
2869 static bool isUndefOrEqual(int Val, int CmpVal) {
2870 if (Val < 0 || Val == CmpVal)
2875 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2876 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2877 /// the second operand.
2878 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2879 if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2880 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2881 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2882 return (Mask[0] < 2 && Mask[1] < 2);
2886 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2887 SmallVector<int, 8> M;
2889 return ::isPSHUFDMask(M, N->getValueType(0));
2892 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2893 /// is suitable for input to PSHUFHW.
2894 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2895 if (VT != MVT::v8i16)
2898 // Lower quadword copied in order or undef.
2899 for (int i = 0; i != 4; ++i)
2900 if (Mask[i] >= 0 && Mask[i] != i)
2903 // Upper quadword shuffled.
2904 for (int i = 4; i != 8; ++i)
2905 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2911 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2912 SmallVector<int, 8> M;
2914 return ::isPSHUFHWMask(M, N->getValueType(0));
2917 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2918 /// is suitable for input to PSHUFLW.
2919 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2920 if (VT != MVT::v8i16)
2923 // Upper quadword copied in order.
2924 for (int i = 4; i != 8; ++i)
2925 if (Mask[i] >= 0 && Mask[i] != i)
2928 // Lower quadword shuffled.
2929 for (int i = 0; i != 4; ++i)
2936 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2937 SmallVector<int, 8> M;
2939 return ::isPSHUFLWMask(M, N->getValueType(0));
2942 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2943 /// is suitable for input to PALIGNR.
2944 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2946 int i, e = VT.getVectorNumElements();
2948 // Do not handle v2i64 / v2f64 shuffles with palignr.
2949 if (e < 4 || !hasSSSE3)
2952 for (i = 0; i != e; ++i)
2956 // All undef, not a palignr.
2960 // Determine if it's ok to perform a palignr with only the LHS, since we
2961 // don't have access to the actual shuffle elements to see if RHS is undef.
2962 bool Unary = Mask[i] < (int)e;
2963 bool NeedsUnary = false;
2965 int s = Mask[i] - i;
2967 // Check the rest of the elements to see if they are consecutive.
2968 for (++i; i != e; ++i) {
2973 Unary = Unary && (m < (int)e);
2974 NeedsUnary = NeedsUnary || (m < s);
2976 if (NeedsUnary && !Unary)
2978 if (Unary && m != ((s+i) & (e-1)))
2980 if (!Unary && m != (s+i))
2986 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2987 SmallVector<int, 8> M;
2989 return ::isPALIGNRMask(M, N->getValueType(0), true);
2992 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2993 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2994 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2995 int NumElems = VT.getVectorNumElements();
2996 if (NumElems != 2 && NumElems != 4)
2999 int Half = NumElems / 2;
3000 for (int i = 0; i < Half; ++i)
3001 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3003 for (int i = Half; i < NumElems; ++i)
3004 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3010 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
3011 SmallVector<int, 8> M;
3013 return ::isSHUFPMask(M, N->getValueType(0));
3016 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
3017 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
3018 /// half elements to come from vector 1 (which would equal the dest.) and
3019 /// the upper half to come from vector 2.
3020 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3021 int NumElems = VT.getVectorNumElements();
3023 if (NumElems != 2 && NumElems != 4)
3026 int Half = NumElems / 2;
3027 for (int i = 0; i < Half; ++i)
3028 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
3030 for (int i = Half; i < NumElems; ++i)
3031 if (!isUndefOrInRange(Mask[i], 0, NumElems))
3036 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
3037 SmallVector<int, 8> M;
3039 return isCommutedSHUFPMask(M, N->getValueType(0));
3042 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3043 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3044 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
3045 if (N->getValueType(0).getVectorNumElements() != 4)
3048 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3049 return isUndefOrEqual(N->getMaskElt(0), 6) &&
3050 isUndefOrEqual(N->getMaskElt(1), 7) &&
3051 isUndefOrEqual(N->getMaskElt(2), 2) &&
3052 isUndefOrEqual(N->getMaskElt(3), 3);
3055 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3056 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3058 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
3059 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3064 return isUndefOrEqual(N->getMaskElt(0), 2) &&
3065 isUndefOrEqual(N->getMaskElt(1), 3) &&
3066 isUndefOrEqual(N->getMaskElt(2), 2) &&
3067 isUndefOrEqual(N->getMaskElt(3), 3);
3070 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3071 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3072 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
3073 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3075 if (NumElems != 2 && NumElems != 4)
3078 for (unsigned i = 0; i < NumElems/2; ++i)
3079 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
3082 for (unsigned i = NumElems/2; i < NumElems; ++i)
3083 if (!isUndefOrEqual(N->getMaskElt(i), i))
3089 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3090 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3091 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
3092 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3094 if (NumElems != 2 && NumElems != 4)
3097 for (unsigned i = 0; i < NumElems/2; ++i)
3098 if (!isUndefOrEqual(N->getMaskElt(i), i))
3101 for (unsigned i = 0; i < NumElems/2; ++i)
3102 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
3108 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
3109 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
3110 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3111 bool V2IsSplat = false) {
3112 int NumElts = VT.getVectorNumElements();
3113 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3116 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3118 int BitI1 = Mask[i+1];
3119 if (!isUndefOrEqual(BitI, j))
3122 if (!isUndefOrEqual(BitI1, NumElts))
3125 if (!isUndefOrEqual(BitI1, j + NumElts))
3132 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3133 SmallVector<int, 8> M;
3135 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
3138 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
3139 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
3140 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
3141 bool V2IsSplat = false) {
3142 int NumElts = VT.getVectorNumElements();
3143 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
3146 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
3148 int BitI1 = Mask[i+1];
3149 if (!isUndefOrEqual(BitI, j + NumElts/2))
3152 if (isUndefOrEqual(BitI1, NumElts))
3155 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
3162 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
3163 SmallVector<int, 8> M;
3165 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
3168 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
3169 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
3171 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3172 int NumElems = VT.getVectorNumElements();
3173 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3176 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
3178 int BitI1 = Mask[i+1];
3179 if (!isUndefOrEqual(BitI, j))
3181 if (!isUndefOrEqual(BitI1, j))
3187 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
3188 SmallVector<int, 8> M;
3190 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
3193 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
3194 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
3196 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
3197 int NumElems = VT.getVectorNumElements();
3198 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
3201 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
3203 int BitI1 = Mask[i+1];
3204 if (!isUndefOrEqual(BitI, j))
3206 if (!isUndefOrEqual(BitI1, j))
3212 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
3213 SmallVector<int, 8> M;
3215 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
3218 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
3219 /// specifies a shuffle of elements that is suitable for input to MOVSS,
3220 /// MOVSD, and MOVD, i.e. setting the lowest element.
3221 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
3222 if (VT.getVectorElementType().getSizeInBits() < 32)
3225 int NumElts = VT.getVectorNumElements();
3227 if (!isUndefOrEqual(Mask[0], NumElts))
3230 for (int i = 1; i < NumElts; ++i)
3231 if (!isUndefOrEqual(Mask[i], i))
3237 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3238 SmallVector<int, 8> M;
3240 return ::isMOVLMask(M, N->getValueType(0));
3243 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3244 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3245 /// element of vector 2 and the other elements to come from vector 1 in order.
3246 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3247 bool V2IsSplat = false, bool V2IsUndef = false) {
3248 int NumOps = VT.getVectorNumElements();
3249 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3252 if (!isUndefOrEqual(Mask[0], 0))
3255 for (int i = 1; i < NumOps; ++i)
3256 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3257 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3258 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3264 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3265 bool V2IsUndef = false) {
3266 SmallVector<int, 8> M;
3268 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3271 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3272 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3273 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3274 if (N->getValueType(0).getVectorNumElements() != 4)
3277 // Expect 1, 1, 3, 3
3278 for (unsigned i = 0; i < 2; ++i) {
3279 int Elt = N->getMaskElt(i);
3280 if (Elt >= 0 && Elt != 1)
3285 for (unsigned i = 2; i < 4; ++i) {
3286 int Elt = N->getMaskElt(i);
3287 if (Elt >= 0 && Elt != 3)
3292 // Don't use movshdup if it can be done with a shufps.
3293 // FIXME: verify that matching u, u, 3, 3 is what we want.
3297 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3298 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3299 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3300 if (N->getValueType(0).getVectorNumElements() != 4)
3303 // Expect 0, 0, 2, 2
3304 for (unsigned i = 0; i < 2; ++i)
3305 if (N->getMaskElt(i) > 0)
3309 for (unsigned i = 2; i < 4; ++i) {
3310 int Elt = N->getMaskElt(i);
3311 if (Elt >= 0 && Elt != 2)
3316 // Don't use movsldup if it can be done with a shufps.
3320 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3321 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3322 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3323 int e = N->getValueType(0).getVectorNumElements() / 2;
3325 for (int i = 0; i < e; ++i)
3326 if (!isUndefOrEqual(N->getMaskElt(i), i))
3328 for (int i = 0; i < e; ++i)
3329 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3334 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3335 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3336 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3337 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3338 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3340 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3342 for (int i = 0; i < NumOperands; ++i) {
3343 int Val = SVOp->getMaskElt(NumOperands-i-1);
3344 if (Val < 0) Val = 0;
3345 if (Val >= NumOperands) Val -= NumOperands;
3347 if (i != NumOperands - 1)
3353 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3354 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3355 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3356 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3358 // 8 nodes, but we only care about the last 4.
3359 for (unsigned i = 7; i >= 4; --i) {
3360 int Val = SVOp->getMaskElt(i);
3369 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3370 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3371 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3372 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3374 // 8 nodes, but we only care about the first 4.
3375 for (int i = 3; i >= 0; --i) {
3376 int Val = SVOp->getMaskElt(i);
3385 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3386 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3387 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3388 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3389 EVT VVT = N->getValueType(0);
3390 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3394 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3395 Val = SVOp->getMaskElt(i);
3399 return (Val - i) * EltSize;
3402 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3404 bool X86::isZeroNode(SDValue Elt) {
3405 return ((isa<ConstantSDNode>(Elt) &&
3406 cast<ConstantSDNode>(Elt)->isNullValue()) ||
3407 (isa<ConstantFPSDNode>(Elt) &&
3408 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3411 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3412 /// their permute mask.
3413 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3414 SelectionDAG &DAG) {
3415 EVT VT = SVOp->getValueType(0);
3416 unsigned NumElems = VT.getVectorNumElements();
3417 SmallVector<int, 8> MaskVec;
3419 for (unsigned i = 0; i != NumElems; ++i) {
3420 int idx = SVOp->getMaskElt(i);
3422 MaskVec.push_back(idx);
3423 else if (idx < (int)NumElems)
3424 MaskVec.push_back(idx + NumElems);
3426 MaskVec.push_back(idx - NumElems);
3428 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3429 SVOp->getOperand(0), &MaskVec[0]);
3432 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3433 /// the two vector operands have swapped position.
3434 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3435 unsigned NumElems = VT.getVectorNumElements();
3436 for (unsigned i = 0; i != NumElems; ++i) {
3440 else if (idx < (int)NumElems)
3441 Mask[i] = idx + NumElems;
3443 Mask[i] = idx - NumElems;
3447 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3448 /// match movhlps. The lower half elements should come from upper half of
3449 /// V1 (and in order), and the upper half elements should come from the upper
3450 /// half of V2 (and in order).
3451 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3452 if (Op->getValueType(0).getVectorNumElements() != 4)
3454 for (unsigned i = 0, e = 2; i != e; ++i)
3455 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3457 for (unsigned i = 2; i != 4; ++i)
3458 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3463 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3464 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3466 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3467 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3469 N = N->getOperand(0).getNode();
3470 if (!ISD::isNON_EXTLoad(N))
3473 *LD = cast<LoadSDNode>(N);
3477 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3478 /// match movlp{s|d}. The lower half elements should come from lower half of
3479 /// V1 (and in order), and the upper half elements should come from the upper
3480 /// half of V2 (and in order). And since V1 will become the source of the
3481 /// MOVLP, it must be either a vector load or a scalar load to vector.
3482 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3483 ShuffleVectorSDNode *Op) {
3484 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3486 // Is V2 is a vector load, don't do this transformation. We will try to use
3487 // load folding shufps op.
3488 if (ISD::isNON_EXTLoad(V2))
3491 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3493 if (NumElems != 2 && NumElems != 4)
3495 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3496 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3498 for (unsigned i = NumElems/2; i != NumElems; ++i)
3499 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3504 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3506 static bool isSplatVector(SDNode *N) {
3507 if (N->getOpcode() != ISD::BUILD_VECTOR)
3510 SDValue SplatValue = N->getOperand(0);
3511 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3512 if (N->getOperand(i) != SplatValue)
3517 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3518 /// to an zero vector.
3519 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3520 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3521 SDValue V1 = N->getOperand(0);
3522 SDValue V2 = N->getOperand(1);
3523 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3524 for (unsigned i = 0; i != NumElems; ++i) {
3525 int Idx = N->getMaskElt(i);
3526 if (Idx >= (int)NumElems) {
3527 unsigned Opc = V2.getOpcode();
3528 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3530 if (Opc != ISD::BUILD_VECTOR ||
3531 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3533 } else if (Idx >= 0) {
3534 unsigned Opc = V1.getOpcode();
3535 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3537 if (Opc != ISD::BUILD_VECTOR ||
3538 !X86::isZeroNode(V1.getOperand(Idx)))
3545 /// getZeroVector - Returns a vector of specified type with all zero elements.
3547 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3549 assert(VT.isVector() && "Expected a vector type");
3551 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted
3552 // to their dest type. This ensures they get CSE'd.
3554 if (VT.getSizeInBits() == 64) { // MMX
3555 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3556 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3557 } else if (VT.getSizeInBits() == 128) {
3558 if (HasSSE2) { // SSE2
3559 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3560 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3562 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3563 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3565 } else if (VT.getSizeInBits() == 256) { // AVX
3566 // 256-bit logic and arithmetic instructions in AVX are
3567 // all floating-point, no support for integer ops. Default
3568 // to emitting fp zeroed vectors then.
3569 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3570 SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
3571 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops, 8);
3573 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3576 /// getOnesVector - Returns a vector of specified type with all bits set.
3578 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3579 assert(VT.isVector() && "Expected a vector type");
3581 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3582 // type. This ensures they get CSE'd.
3583 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3585 if (VT.getSizeInBits() == 64) // MMX
3586 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3588 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3589 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3593 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3594 /// that point to V2 points to its first element.
3595 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3596 EVT VT = SVOp->getValueType(0);
3597 unsigned NumElems = VT.getVectorNumElements();
3599 bool Changed = false;
3600 SmallVector<int, 8> MaskVec;
3601 SVOp->getMask(MaskVec);
3603 for (unsigned i = 0; i != NumElems; ++i) {
3604 if (MaskVec[i] > (int)NumElems) {
3605 MaskVec[i] = NumElems;
3610 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3611 SVOp->getOperand(1), &MaskVec[0]);
3612 return SDValue(SVOp, 0);
3615 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3616 /// operation of specified width.
3617 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3619 unsigned NumElems = VT.getVectorNumElements();
3620 SmallVector<int, 8> Mask;
3621 Mask.push_back(NumElems);
3622 for (unsigned i = 1; i != NumElems; ++i)
3624 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3627 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3628 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3630 unsigned NumElems = VT.getVectorNumElements();
3631 SmallVector<int, 8> Mask;
3632 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3634 Mask.push_back(i + NumElems);
3636 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3639 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3640 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3642 unsigned NumElems = VT.getVectorNumElements();
3643 unsigned Half = NumElems/2;
3644 SmallVector<int, 8> Mask;
3645 for (unsigned i = 0; i != Half; ++i) {
3646 Mask.push_back(i + Half);
3647 Mask.push_back(i + NumElems + Half);
3649 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3652 /// PromoteSplat - Promote a splat of v4i32, v8i16 or v16i8 to v4f32.
3653 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
3654 EVT PVT = MVT::v4f32;
3655 EVT VT = SV->getValueType(0);
3656 DebugLoc dl = SV->getDebugLoc();
3657 SDValue V1 = SV->getOperand(0);
3658 int NumElems = VT.getVectorNumElements();
3659 int EltNo = SV->getSplatIndex();
3661 // unpack elements to the correct location
3662 while (NumElems > 4) {
3663 if (EltNo < NumElems/2) {
3664 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3666 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3667 EltNo -= NumElems/2;
3672 // Perform the splat.
3673 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3674 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3675 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3676 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3679 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3680 /// vector of zero or undef vector. This produces a shuffle where the low
3681 /// element of V2 is swizzled into the zero/undef vector, landing at element
3682 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3683 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3684 bool isZero, bool HasSSE2,
3685 SelectionDAG &DAG) {
3686 EVT VT = V2.getValueType();
3688 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3689 unsigned NumElems = VT.getVectorNumElements();
3690 SmallVector<int, 16> MaskVec;
3691 for (unsigned i = 0; i != NumElems; ++i)
3692 // If this is the insertion idx, put the low elt of V2 here.
3693 MaskVec.push_back(i == Idx ? NumElems : i);
3694 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3697 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
3698 /// element of the result of the vector shuffle.
3699 SDValue getShuffleScalarElt(SDNode *N, int Index, SelectionDAG &DAG,
3702 return SDValue(); // Limit search depth.
3704 SDValue V = SDValue(N, 0);
3705 EVT VT = V.getValueType();
3706 unsigned Opcode = V.getOpcode();
3708 // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
3709 if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
3710 Index = SV->getMaskElt(Index);
3713 return DAG.getUNDEF(VT.getVectorElementType());
3715 int NumElems = VT.getVectorNumElements();
3716 SDValue NewV = (Index < NumElems) ? SV->getOperand(0) : SV->getOperand(1);
3717 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG, Depth+1);
3720 // Recurse into target specific vector shuffles to find scalars.
3721 if (isTargetShuffle(Opcode)) {
3722 int NumElems = VT.getVectorNumElements();
3723 SmallVector<unsigned, 16> ShuffleMask;
3727 case X86ISD::SHUFPS:
3728 case X86ISD::SHUFPD:
3729 ImmN = N->getOperand(N->getNumOperands()-1);
3730 DecodeSHUFPSMask(NumElems,
3731 cast<ConstantSDNode>(ImmN)->getZExtValue(),
3734 case X86ISD::PUNPCKHBW:
3735 case X86ISD::PUNPCKHWD:
3736 case X86ISD::PUNPCKHDQ:
3737 case X86ISD::PUNPCKHQDQ:
3738 DecodePUNPCKHMask(NumElems, ShuffleMask);
3740 case X86ISD::UNPCKHPS:
3741 case X86ISD::UNPCKHPD:
3742 DecodeUNPCKHPMask(NumElems, ShuffleMask);
3744 case X86ISD::PUNPCKLBW:
3745 case X86ISD::PUNPCKLWD:
3746 case X86ISD::PUNPCKLDQ:
3747 case X86ISD::PUNPCKLQDQ:
3748 DecodePUNPCKLMask(NumElems, ShuffleMask);
3750 case X86ISD::UNPCKLPS:
3751 case X86ISD::UNPCKLPD:
3752 DecodeUNPCKLPMask(NumElems, ShuffleMask);
3754 case X86ISD::MOVHLPS:
3755 DecodeMOVHLPSMask(NumElems, ShuffleMask);
3757 case X86ISD::MOVLHPS:
3758 DecodeMOVLHPSMask(NumElems, ShuffleMask);
3760 case X86ISD::PSHUFD:
3761 ImmN = N->getOperand(N->getNumOperands()-1);
3762 DecodePSHUFMask(NumElems,
3763 cast<ConstantSDNode>(ImmN)->getZExtValue(),
3766 case X86ISD::PSHUFHW:
3767 ImmN = N->getOperand(N->getNumOperands()-1);
3768 DecodePSHUFHWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3771 case X86ISD::PSHUFLW:
3772 ImmN = N->getOperand(N->getNumOperands()-1);
3773 DecodePSHUFLWMask(cast<ConstantSDNode>(ImmN)->getZExtValue(),
3777 case X86ISD::MOVSD: {
3778 // The index 0 always comes from the first element of the second source,
3779 // this is why MOVSS and MOVSD are used in the first place. The other
3780 // elements come from the other positions of the first source vector.
3781 unsigned OpNum = (Index == 0) ? 1 : 0;
3782 return getShuffleScalarElt(V.getOperand(OpNum).getNode(), Index, DAG,
3786 assert("not implemented for target shuffle node");
3790 Index = ShuffleMask[Index];
3792 return DAG.getUNDEF(VT.getVectorElementType());
3794 SDValue NewV = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
3795 return getShuffleScalarElt(NewV.getNode(), Index % NumElems, DAG,
3799 // Actual nodes that may contain scalar elements
3800 if (Opcode == ISD::BIT_CONVERT) {
3801 V = V.getOperand(0);
3802 EVT SrcVT = V.getValueType();
3803 unsigned NumElems = VT.getVectorNumElements();
3805 if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
3809 if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
3810 return (Index == 0) ? V.getOperand(0)
3811 : DAG.getUNDEF(VT.getVectorElementType());
3813 if (V.getOpcode() == ISD::BUILD_VECTOR)
3814 return V.getOperand(Index);
3819 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
3820 /// shuffle operation which come from a consecutively from a zero. The
3821 /// search can start in two diferent directions, from left or right.
3823 unsigned getNumOfConsecutiveZeros(SDNode *N, int NumElems,
3824 bool ZerosFromLeft, SelectionDAG &DAG) {
3827 while (i < NumElems) {
3828 unsigned Index = ZerosFromLeft ? i : NumElems-i-1;
3829 SDValue Elt = getShuffleScalarElt(N, Index, DAG, 0);
3830 if (!(Elt.getNode() &&
3831 (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt))))
3839 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies from MaskI to
3840 /// MaskE correspond consecutively to elements from one of the vector operands,
3841 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
3843 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp, int MaskI, int MaskE,
3844 int OpIdx, int NumElems, unsigned &OpNum) {
3845 bool SeenV1 = false;
3846 bool SeenV2 = false;
3848 for (int i = MaskI; i <= MaskE; ++i, ++OpIdx) {
3849 int Idx = SVOp->getMaskElt(i);
3850 // Ignore undef indicies
3859 // Only accept consecutive elements from the same vector
3860 if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
3864 OpNum = SeenV1 ? 0 : 1;
3868 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
3869 /// logical left shift of a vector.
3870 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3871 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3872 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3873 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3874 false /* check zeros from right */, DAG);
3880 // Considering the elements in the mask that are not consecutive zeros,
3881 // check if they consecutively come from only one of the source vectors.
3883 // V1 = {X, A, B, C} 0
3885 // vector_shuffle V1, V2 <1, 2, 3, X>
3887 if (!isShuffleMaskConsecutive(SVOp,
3888 0, // Mask Start Index
3889 NumElems-NumZeros-1, // Mask End Index
3890 NumZeros, // Where to start looking in the src vector
3891 NumElems, // Number of elements in vector
3892 OpSrc)) // Which source operand ?
3897 ShVal = SVOp->getOperand(OpSrc);
3901 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
3902 /// logical left shift of a vector.
3903 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3904 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3905 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3906 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems,
3907 true /* check zeros from left */, DAG);
3913 // Considering the elements in the mask that are not consecutive zeros,
3914 // check if they consecutively come from only one of the source vectors.
3916 // 0 { A, B, X, X } = V2
3918 // vector_shuffle V1, V2 <X, X, 4, 5>
3920 if (!isShuffleMaskConsecutive(SVOp,
3921 NumZeros, // Mask Start Index
3922 NumElems-1, // Mask End Index
3923 0, // Where to start looking in the src vector
3924 NumElems, // Number of elements in vector
3925 OpSrc)) // Which source operand ?
3930 ShVal = SVOp->getOperand(OpSrc);
3934 /// isVectorShift - Returns true if the shuffle can be implemented as a
3935 /// logical left or right shift of a vector.
3936 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3937 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3938 if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
3939 isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
3945 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3947 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3948 unsigned NumNonZero, unsigned NumZero,
3950 const TargetLowering &TLI) {
3954 DebugLoc dl = Op.getDebugLoc();
3957 for (unsigned i = 0; i < 16; ++i) {
3958 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3959 if (ThisIsNonZero && First) {
3961 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3963 V = DAG.getUNDEF(MVT::v8i16);
3968 SDValue ThisElt(0, 0), LastElt(0, 0);
3969 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3970 if (LastIsNonZero) {
3971 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3972 MVT::i16, Op.getOperand(i-1));
3974 if (ThisIsNonZero) {
3975 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3976 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3977 ThisElt, DAG.getConstant(8, MVT::i8));
3979 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3983 if (ThisElt.getNode())
3984 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3985 DAG.getIntPtrConstant(i/2));
3989 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3992 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3994 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3995 unsigned NumNonZero, unsigned NumZero,
3997 const TargetLowering &TLI) {
4001 DebugLoc dl = Op.getDebugLoc();
4004 for (unsigned i = 0; i < 8; ++i) {
4005 bool isNonZero = (NonZeros & (1 << i)) != 0;
4009 V = getZeroVector(MVT::v8i16, true, DAG, dl);
4011 V = DAG.getUNDEF(MVT::v8i16);
4014 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4015 MVT::v8i16, V, Op.getOperand(i),
4016 DAG.getIntPtrConstant(i));
4023 /// getVShift - Return a vector logical shift node.
4025 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4026 unsigned NumBits, SelectionDAG &DAG,
4027 const TargetLowering &TLI, DebugLoc dl) {
4028 bool isMMX = VT.getSizeInBits() == 64;
4029 EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
4030 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
4031 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
4032 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4033 DAG.getNode(Opc, dl, ShVT, SrcOp,
4034 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
4038 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
4039 SelectionDAG &DAG) const {
4041 // Check if the scalar load can be widened into a vector load. And if
4042 // the address is "base + cst" see if the cst can be "absorbed" into
4043 // the shuffle mask.
4044 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4045 SDValue Ptr = LD->getBasePtr();
4046 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4048 EVT PVT = LD->getValueType(0);
4049 if (PVT != MVT::i32 && PVT != MVT::f32)
4054 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4055 FI = FINode->getIndex();
4057 } else if (Ptr.getOpcode() == ISD::ADD &&
4058 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
4059 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4060 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4061 Offset = Ptr.getConstantOperandVal(1);
4062 Ptr = Ptr.getOperand(0);
4067 SDValue Chain = LD->getChain();
4068 // Make sure the stack object alignment is at least 16.
4069 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4070 if (DAG.InferPtrAlignment(Ptr) < 16) {
4071 if (MFI->isFixedObjectIndex(FI)) {
4072 // Can't change the alignment. FIXME: It's possible to compute
4073 // the exact stack offset and reference FI + adjust offset instead.
4074 // If someone *really* cares about this. That's the way to implement it.
4077 MFI->setObjectAlignment(FI, 16);
4081 // (Offset % 16) must be multiple of 4. Then address is then
4082 // Ptr + (Offset & ~15).
4085 if ((Offset % 16) & 3)
4087 int64_t StartOffset = Offset & ~15;
4089 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
4090 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
4092 int EltNo = (Offset - StartOffset) >> 2;
4093 int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
4094 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
4095 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,
4096 LD->getPointerInfo().getWithOffset(StartOffset),
4098 // Canonicalize it to a v4i32 shuffle.
4099 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
4100 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4101 DAG.getVectorShuffle(MVT::v4i32, dl, V1,
4102 DAG.getUNDEF(MVT::v4i32),&Mask[0]));
4108 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
4109 /// vector of type 'VT', see if the elements can be replaced by a single large
4110 /// load which has the same value as a build_vector whose operands are 'elts'.
4112 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4114 /// FIXME: we'd also like to handle the case where the last elements are zero
4115 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4116 /// There's even a handy isZeroNode for that purpose.
4117 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
4118 DebugLoc &DL, SelectionDAG &DAG) {
4119 EVT EltVT = VT.getVectorElementType();
4120 unsigned NumElems = Elts.size();
4122 LoadSDNode *LDBase = NULL;
4123 unsigned LastLoadedElt = -1U;
4125 // For each element in the initializer, see if we've found a load or an undef.
4126 // If we don't find an initial load element, or later load elements are
4127 // non-consecutive, bail out.
4128 for (unsigned i = 0; i < NumElems; ++i) {
4129 SDValue Elt = Elts[i];
4131 if (!Elt.getNode() ||
4132 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4135 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4137 LDBase = cast<LoadSDNode>(Elt.getNode());
4141 if (Elt.getOpcode() == ISD::UNDEF)
4144 LoadSDNode *LD = cast<LoadSDNode>(Elt);
4145 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
4150 // If we have found an entire vector of loads and undefs, then return a large
4151 // load of the entire vector width starting at the base pointer. If we found
4152 // consecutive loads for the low half, generate a vzext_load node.
4153 if (LastLoadedElt == NumElems - 1) {
4154 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
4155 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4156 LDBase->getPointerInfo(),
4157 LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
4158 return DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4159 LDBase->getPointerInfo(),
4160 LDBase->isVolatile(), LDBase->isNonTemporal(),
4161 LDBase->getAlignment());
4162 } else if (NumElems == 4 && LastLoadedElt == 1) {
4163 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4164 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4165 SDValue ResNode = DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys,
4167 LDBase->getMemOperand());
4168 return DAG.getNode(ISD::BIT_CONVERT, DL, VT, ResNode);
4174 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
4175 DebugLoc dl = Op.getDebugLoc();
4176 // All zero's are handled with pxor in SSE2 and above, xorps in SSE1.
4177 // All one's are handled with pcmpeqd. In AVX, zero's are handled with
4178 // vpxor in 128-bit and xor{pd,ps} in 256-bit, but no 256 version of pcmpeqd
4179 // is present, so AllOnes is ignored.
4180 if (ISD::isBuildVectorAllZeros(Op.getNode()) ||
4181 (Op.getValueType().getSizeInBits() != 256 &&
4182 ISD::isBuildVectorAllOnes(Op.getNode()))) {
4183 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
4184 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
4185 // eliminated on x86-32 hosts.
4186 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
4189 if (ISD::isBuildVectorAllOnes(Op.getNode()))
4190 return getOnesVector(Op.getValueType(), DAG, dl);
4191 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
4194 EVT VT = Op.getValueType();
4195 EVT ExtVT = VT.getVectorElementType();
4196 unsigned EVTBits = ExtVT.getSizeInBits();
4198 unsigned NumElems = Op.getNumOperands();
4199 unsigned NumZero = 0;
4200 unsigned NumNonZero = 0;
4201 unsigned NonZeros = 0;
4202 bool IsAllConstants = true;
4203 SmallSet<SDValue, 8> Values;
4204 for (unsigned i = 0; i < NumElems; ++i) {
4205 SDValue Elt = Op.getOperand(i);
4206 if (Elt.getOpcode() == ISD::UNDEF)
4209 if (Elt.getOpcode() != ISD::Constant &&
4210 Elt.getOpcode() != ISD::ConstantFP)
4211 IsAllConstants = false;
4212 if (X86::isZeroNode(Elt))
4215 NonZeros |= (1 << i);
4220 // All undef vector. Return an UNDEF. All zero vectors were handled above.
4221 if (NumNonZero == 0)
4222 return DAG.getUNDEF(VT);
4224 // Special case for single non-zero, non-undef, element.
4225 if (NumNonZero == 1) {
4226 unsigned Idx = CountTrailingZeros_32(NonZeros);
4227 SDValue Item = Op.getOperand(Idx);
4229 // If this is an insertion of an i64 value on x86-32, and if the top bits of
4230 // the value are obviously zero, truncate the value to i32 and do the
4231 // insertion that way. Only do this if the value is non-constant or if the
4232 // value is a constant being inserted into element 0. It is cheaper to do
4233 // a constant pool load than it is to do a movd + shuffle.
4234 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
4235 (!IsAllConstants || Idx == 0)) {
4236 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
4237 // Handle MMX and SSE both.
4238 EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
4239 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
4241 // Truncate the value (which may itself be a constant) to i32, and
4242 // convert it to a vector with movd (S2V+shuffle to zero extend).
4243 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
4244 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
4245 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4246 Subtarget->hasSSE2(), DAG);
4248 // Now we have our 32-bit value zero extended in the low element of
4249 // a vector. If Idx != 0, swizzle it into place.
4251 SmallVector<int, 4> Mask;
4252 Mask.push_back(Idx);
4253 for (unsigned i = 1; i != VecElts; ++i)
4255 Item = DAG.getVectorShuffle(VecVT, dl, Item,
4256 DAG.getUNDEF(Item.getValueType()),
4259 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
4263 // If we have a constant or non-constant insertion into the low element of
4264 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
4265 // the rest of the elements. This will be matched as movd/movq/movss/movsd
4266 // depending on what the source datatype is.
4269 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4270 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
4271 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
4272 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4273 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
4274 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
4276 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
4277 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
4278 EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
4279 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
4280 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
4281 Subtarget->hasSSE2(), DAG);
4282 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
4286 // Is it a vector logical left shift?
4287 if (NumElems == 2 && Idx == 1 &&
4288 X86::isZeroNode(Op.getOperand(0)) &&
4289 !X86::isZeroNode(Op.getOperand(1))) {
4290 unsigned NumBits = VT.getSizeInBits();
4291 return getVShift(true, VT,
4292 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4293 VT, Op.getOperand(1)),
4294 NumBits/2, DAG, *this, dl);
4297 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
4300 // Otherwise, if this is a vector with i32 or f32 elements, and the element
4301 // is a non-constant being inserted into an element other than the low one,
4302 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
4303 // movd/movss) to move this into the low element, then shuffle it into
4305 if (EVTBits == 32) {
4306 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
4308 // Turn it into a shuffle of zero and zero-extended scalar to vector.
4309 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
4310 Subtarget->hasSSE2(), DAG);
4311 SmallVector<int, 8> MaskVec;
4312 for (unsigned i = 0; i < NumElems; i++)
4313 MaskVec.push_back(i == Idx ? 0 : 1);
4314 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
4318 // Splat is obviously ok. Let legalizer expand it to a shuffle.
4319 if (Values.size() == 1) {
4320 if (EVTBits == 32) {
4321 // Instead of a shuffle like this:
4322 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
4323 // Check if it's possible to issue this instead.
4324 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
4325 unsigned Idx = CountTrailingZeros_32(NonZeros);
4326 SDValue Item = Op.getOperand(Idx);
4327 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
4328 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
4333 // A vector full of immediates; various special cases are already
4334 // handled, so this is best done with a single constant-pool load.
4338 // Let legalizer expand 2-wide build_vectors.
4339 if (EVTBits == 64) {
4340 if (NumNonZero == 1) {
4341 // One half is zero or undef.
4342 unsigned Idx = CountTrailingZeros_32(NonZeros);
4343 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
4344 Op.getOperand(Idx));
4345 return getShuffleVectorZeroOrUndef(V2, Idx, true,
4346 Subtarget->hasSSE2(), DAG);
4351 // If element VT is < 32 bits, convert it to inserts into a zero vector.
4352 if (EVTBits == 8 && NumElems == 16) {
4353 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
4355 if (V.getNode()) return V;
4358 if (EVTBits == 16 && NumElems == 8) {
4359 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
4361 if (V.getNode()) return V;
4364 // If element VT is == 32 bits, turn it into a number of shuffles.
4365 SmallVector<SDValue, 8> V;
4367 if (NumElems == 4 && NumZero > 0) {
4368 for (unsigned i = 0; i < 4; ++i) {
4369 bool isZero = !(NonZeros & (1 << i));
4371 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4373 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4376 for (unsigned i = 0; i < 2; ++i) {
4377 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
4380 V[i] = V[i*2]; // Must be a zero vector.
4383 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
4386 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
4389 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
4394 SmallVector<int, 8> MaskVec;
4395 bool Reverse = (NonZeros & 0x3) == 2;
4396 for (unsigned i = 0; i < 2; ++i)
4397 MaskVec.push_back(Reverse ? 1-i : i);
4398 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
4399 for (unsigned i = 0; i < 2; ++i)
4400 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
4401 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
4404 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
4405 // Check for a build vector of consecutive loads.
4406 for (unsigned i = 0; i < NumElems; ++i)
4407 V[i] = Op.getOperand(i);
4409 // Check for elements which are consecutive loads.
4410 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
4414 // For SSE 4.1, use insertps to put the high elements into the low element.
4415 if (getSubtarget()->hasSSE41()) {
4417 if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
4418 Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
4420 Result = DAG.getUNDEF(VT);
4422 for (unsigned i = 1; i < NumElems; ++i) {
4423 if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
4424 Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
4425 Op.getOperand(i), DAG.getIntPtrConstant(i));
4430 // Otherwise, expand into a number of unpckl*, start by extending each of
4431 // our (non-undef) elements to the full vector width with the element in the
4432 // bottom slot of the vector (which generates no code for SSE).
4433 for (unsigned i = 0; i < NumElems; ++i) {
4434 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
4435 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4437 V[i] = DAG.getUNDEF(VT);
4440 // Next, we iteratively mix elements, e.g. for v4f32:
4441 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4442 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4443 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
4444 unsigned EltStride = NumElems >> 1;
4445 while (EltStride != 0) {
4446 for (unsigned i = 0; i < EltStride; ++i) {
4447 // If V[i+EltStride] is undef and this is the first round of mixing,
4448 // then it is safe to just drop this shuffle: V[i] is already in the
4449 // right place, the one element (since it's the first round) being
4450 // inserted as undef can be dropped. This isn't safe for successive
4451 // rounds because they will permute elements within both vectors.
4452 if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
4453 EltStride == NumElems/2)
4456 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
4466 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4467 // We support concatenate two MMX registers and place them in a MMX
4468 // register. This is better than doing a stack convert.
4469 DebugLoc dl = Op.getDebugLoc();
4470 EVT ResVT = Op.getValueType();
4471 assert(Op.getNumOperands() == 2);
4472 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4473 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4475 SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
4476 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4477 InVec = Op.getOperand(1);
4478 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4479 unsigned NumElts = ResVT.getVectorNumElements();
4480 VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4481 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4482 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4484 InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
4485 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4486 Mask[0] = 0; Mask[1] = 2;
4487 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4489 return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4492 // v8i16 shuffles - Prefer shuffles in the following order:
4493 // 1. [all] pshuflw, pshufhw, optional move
4494 // 2. [ssse3] 1 x pshufb
4495 // 3. [ssse3] 2 x pshufb + 1 x por
4496 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4498 X86TargetLowering::LowerVECTOR_SHUFFLEv8i16(SDValue Op,
4499 SelectionDAG &DAG) const {
4500 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4501 SDValue V1 = SVOp->getOperand(0);
4502 SDValue V2 = SVOp->getOperand(1);
4503 DebugLoc dl = SVOp->getDebugLoc();
4504 SmallVector<int, 8> MaskVals;
4506 // Determine if more than 1 of the words in each of the low and high quadwords
4507 // of the result come from the same quadword of one of the two inputs. Undef
4508 // mask values count as coming from any quadword, for better codegen.
4509 SmallVector<unsigned, 4> LoQuad(4);
4510 SmallVector<unsigned, 4> HiQuad(4);
4511 BitVector InputQuads(4);
4512 for (unsigned i = 0; i < 8; ++i) {
4513 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4514 int EltIdx = SVOp->getMaskElt(i);
4515 MaskVals.push_back(EltIdx);
4524 InputQuads.set(EltIdx / 4);
4527 int BestLoQuad = -1;
4528 unsigned MaxQuad = 1;
4529 for (unsigned i = 0; i < 4; ++i) {
4530 if (LoQuad[i] > MaxQuad) {
4532 MaxQuad = LoQuad[i];
4536 int BestHiQuad = -1;
4538 for (unsigned i = 0; i < 4; ++i) {
4539 if (HiQuad[i] > MaxQuad) {
4541 MaxQuad = HiQuad[i];
4545 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4546 // of the two input vectors, shuffle them into one input vector so only a
4547 // single pshufb instruction is necessary. If There are more than 2 input
4548 // quads, disable the next transformation since it does not help SSSE3.
4549 bool V1Used = InputQuads[0] || InputQuads[1];
4550 bool V2Used = InputQuads[2] || InputQuads[3];
4551 if (Subtarget->hasSSSE3()) {
4552 if (InputQuads.count() == 2 && V1Used && V2Used) {
4553 BestLoQuad = InputQuads.find_first();
4554 BestHiQuad = InputQuads.find_next(BestLoQuad);
4556 if (InputQuads.count() > 2) {
4562 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4563 // the shuffle mask. If a quad is scored as -1, that means that it contains
4564 // words from all 4 input quadwords.
4566 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4567 SmallVector<int, 8> MaskV;
4568 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4569 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4570 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4571 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
4572 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
4573 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
4575 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4576 // source words for the shuffle, to aid later transformations.
4577 bool AllWordsInNewV = true;
4578 bool InOrder[2] = { true, true };
4579 for (unsigned i = 0; i != 8; ++i) {
4580 int idx = MaskVals[i];
4582 InOrder[i/4] = false;
4583 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4585 AllWordsInNewV = false;
4589 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4590 if (AllWordsInNewV) {
4591 for (int i = 0; i != 8; ++i) {
4592 int idx = MaskVals[i];
4595 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4596 if ((idx != i) && idx < 4)
4598 if ((idx != i) && idx > 3)
4607 // If we've eliminated the use of V2, and the new mask is a pshuflw or
4608 // pshufhw, that's as cheap as it gets. Return the new shuffle.
4609 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4610 unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
4611 unsigned TargetMask = 0;
4612 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4613 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4614 TargetMask = pshufhw ? X86::getShufflePSHUFHWImmediate(NewV.getNode()):
4615 X86::getShufflePSHUFLWImmediate(NewV.getNode());
4616 V1 = NewV.getOperand(0);
4617 return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
4621 // If we have SSSE3, and all words of the result are from 1 input vector,
4622 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
4623 // is present, fall back to case 4.
4624 if (Subtarget->hasSSSE3()) {
4625 SmallVector<SDValue,16> pshufbMask;
4627 // If we have elements from both input vectors, set the high bit of the
4628 // shuffle mask element to zero out elements that come from V2 in the V1
4629 // mask, and elements that come from V1 in the V2 mask, so that the two
4630 // results can be OR'd together.
4631 bool TwoInputs = V1Used && V2Used;
4632 for (unsigned i = 0; i != 8; ++i) {
4633 int EltIdx = MaskVals[i] * 2;
4634 if (TwoInputs && (EltIdx >= 16)) {
4635 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4636 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4639 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4640 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4642 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
4643 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4644 DAG.getNode(ISD::BUILD_VECTOR, dl,
4645 MVT::v16i8, &pshufbMask[0], 16));
4647 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4649 // Calculate the shuffle mask for the second input, shuffle it, and
4650 // OR it with the first shuffled input.
4652 for (unsigned i = 0; i != 8; ++i) {
4653 int EltIdx = MaskVals[i] * 2;
4655 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4656 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4659 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4660 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4662 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
4663 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4664 DAG.getNode(ISD::BUILD_VECTOR, dl,
4665 MVT::v16i8, &pshufbMask[0], 16));
4666 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4667 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4670 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4671 // and update MaskVals with new element order.
4672 BitVector InOrder(8);
4673 if (BestLoQuad >= 0) {
4674 SmallVector<int, 8> MaskV;
4675 for (int i = 0; i != 4; ++i) {
4676 int idx = MaskVals[i];
4678 MaskV.push_back(-1);
4680 } else if ((idx / 4) == BestLoQuad) {
4681 MaskV.push_back(idx & 3);
4684 MaskV.push_back(-1);
4687 for (unsigned i = 4; i != 8; ++i)
4689 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4692 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4693 NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
4695 X86::getShufflePSHUFLWImmediate(NewV.getNode()),
4699 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4700 // and update MaskVals with the new element order.
4701 if (BestHiQuad >= 0) {
4702 SmallVector<int, 8> MaskV;
4703 for (unsigned i = 0; i != 4; ++i)
4705 for (unsigned i = 4; i != 8; ++i) {
4706 int idx = MaskVals[i];
4708 MaskV.push_back(-1);
4710 } else if ((idx / 4) == BestHiQuad) {
4711 MaskV.push_back((idx & 3) + 4);
4714 MaskV.push_back(-1);
4717 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4720 if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSSE3())
4721 NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
4723 X86::getShufflePSHUFHWImmediate(NewV.getNode()),
4727 // In case BestHi & BestLo were both -1, which means each quadword has a word
4728 // from each of the four input quadwords, calculate the InOrder bitvector now
4729 // before falling through to the insert/extract cleanup.
4730 if (BestLoQuad == -1 && BestHiQuad == -1) {
4732 for (int i = 0; i != 8; ++i)
4733 if (MaskVals[i] < 0 || MaskVals[i] == i)
4737 // The other elements are put in the right place using pextrw and pinsrw.
4738 for (unsigned i = 0; i != 8; ++i) {
4741 int EltIdx = MaskVals[i];
4744 SDValue ExtOp = (EltIdx < 8)
4745 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4746 DAG.getIntPtrConstant(EltIdx))
4747 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4748 DAG.getIntPtrConstant(EltIdx - 8));
4749 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4750 DAG.getIntPtrConstant(i));
4755 // v16i8 shuffles - Prefer shuffles in the following order:
4756 // 1. [ssse3] 1 x pshufb
4757 // 2. [ssse3] 2 x pshufb + 1 x por
4758 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
4760 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4762 const X86TargetLowering &TLI) {
4763 SDValue V1 = SVOp->getOperand(0);
4764 SDValue V2 = SVOp->getOperand(1);
4765 DebugLoc dl = SVOp->getDebugLoc();
4766 SmallVector<int, 16> MaskVals;
4767 SVOp->getMask(MaskVals);
4769 // If we have SSSE3, case 1 is generated when all result bytes come from
4770 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
4771 // present, fall back to case 3.
4772 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4775 for (unsigned i = 0; i < 16; ++i) {
4776 int EltIdx = MaskVals[i];
4785 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4786 if (TLI.getSubtarget()->hasSSSE3()) {
4787 SmallVector<SDValue,16> pshufbMask;
4789 // If all result elements are from one input vector, then only translate
4790 // undef mask values to 0x80 (zero out result) in the pshufb mask.
4792 // Otherwise, we have elements from both input vectors, and must zero out
4793 // elements that come from V2 in the first mask, and V1 in the second mask
4794 // so that we can OR them together.
4795 bool TwoInputs = !(V1Only || V2Only);
4796 for (unsigned i = 0; i != 16; ++i) {
4797 int EltIdx = MaskVals[i];
4798 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4799 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4802 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4804 // If all the elements are from V2, assign it to V1 and return after
4805 // building the first pshufb.
4808 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4809 DAG.getNode(ISD::BUILD_VECTOR, dl,
4810 MVT::v16i8, &pshufbMask[0], 16));
4814 // Calculate the shuffle mask for the second input, shuffle it, and
4815 // OR it with the first shuffled input.
4817 for (unsigned i = 0; i != 16; ++i) {
4818 int EltIdx = MaskVals[i];
4820 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4823 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4825 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4826 DAG.getNode(ISD::BUILD_VECTOR, dl,
4827 MVT::v16i8, &pshufbMask[0], 16));
4828 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4831 // No SSSE3 - Calculate in place words and then fix all out of place words
4832 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
4833 // the 16 different words that comprise the two doublequadword input vectors.
4834 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4835 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4836 SDValue NewV = V2Only ? V2 : V1;
4837 for (int i = 0; i != 8; ++i) {
4838 int Elt0 = MaskVals[i*2];
4839 int Elt1 = MaskVals[i*2+1];
4841 // This word of the result is all undef, skip it.
4842 if (Elt0 < 0 && Elt1 < 0)
4845 // This word of the result is already in the correct place, skip it.
4846 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4848 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4851 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4852 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4855 // If Elt0 and Elt1 are defined, are consecutive, and can be load
4856 // using a single extract together, load it and store it.
4857 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4858 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4859 DAG.getIntPtrConstant(Elt1 / 2));
4860 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4861 DAG.getIntPtrConstant(i));
4865 // If Elt1 is defined, extract it from the appropriate source. If the
4866 // source byte is not also odd, shift the extracted word left 8 bits
4867 // otherwise clear the bottom 8 bits if we need to do an or.
4869 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4870 DAG.getIntPtrConstant(Elt1 / 2));
4871 if ((Elt1 & 1) == 0)
4872 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4873 DAG.getConstant(8, TLI.getShiftAmountTy()));
4875 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4876 DAG.getConstant(0xFF00, MVT::i16));
4878 // If Elt0 is defined, extract it from the appropriate source. If the
4879 // source byte is not also even, shift the extracted word right 8 bits. If
4880 // Elt1 was also defined, OR the extracted values together before
4881 // inserting them in the result.
4883 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4884 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4885 if ((Elt0 & 1) != 0)
4886 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4887 DAG.getConstant(8, TLI.getShiftAmountTy()));
4889 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4890 DAG.getConstant(0x00FF, MVT::i16));
4891 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4894 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4895 DAG.getIntPtrConstant(i));
4897 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4900 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4901 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
4902 /// done when every pair / quad of shuffle mask elements point to elements in
4903 /// the right sequence. e.g.
4904 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
4906 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4907 SelectionDAG &DAG, DebugLoc dl) {
4908 EVT VT = SVOp->getValueType(0);
4909 SDValue V1 = SVOp->getOperand(0);
4910 SDValue V2 = SVOp->getOperand(1);
4911 unsigned NumElems = VT.getVectorNumElements();
4912 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4914 switch (VT.getSimpleVT().SimpleTy) {
4915 default: assert(false && "Unexpected!");
4916 case MVT::v4f32: NewVT = MVT::v2f64; break;
4917 case MVT::v4i32: NewVT = MVT::v2i64; break;
4918 case MVT::v8i16: NewVT = MVT::v4i32; break;
4919 case MVT::v16i8: NewVT = MVT::v4i32; break;
4922 int Scale = NumElems / NewWidth;
4923 SmallVector<int, 8> MaskVec;
4924 for (unsigned i = 0; i < NumElems; i += Scale) {
4926 for (int j = 0; j < Scale; ++j) {
4927 int EltIdx = SVOp->getMaskElt(i+j);
4931 StartIdx = EltIdx - (EltIdx % Scale);
4932 if (EltIdx != StartIdx + j)
4936 MaskVec.push_back(-1);
4938 MaskVec.push_back(StartIdx / Scale);
4941 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4942 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4943 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4946 /// getVZextMovL - Return a zero-extending vector move low node.
4948 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4949 SDValue SrcOp, SelectionDAG &DAG,
4950 const X86Subtarget *Subtarget, DebugLoc dl) {
4951 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4952 LoadSDNode *LD = NULL;
4953 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4954 LD = dyn_cast<LoadSDNode>(SrcOp);
4956 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4958 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4959 if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4960 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4961 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4962 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4964 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4965 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4966 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4967 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4975 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4976 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4977 DAG.getNode(ISD::BIT_CONVERT, dl,
4981 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4984 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4985 SDValue V1 = SVOp->getOperand(0);
4986 SDValue V2 = SVOp->getOperand(1);
4987 DebugLoc dl = SVOp->getDebugLoc();
4988 EVT VT = SVOp->getValueType(0);
4990 SmallVector<std::pair<int, int>, 8> Locs;
4992 SmallVector<int, 8> Mask1(4U, -1);
4993 SmallVector<int, 8> PermMask;
4994 SVOp->getMask(PermMask);
4998 for (unsigned i = 0; i != 4; ++i) {
4999 int Idx = PermMask[i];
5001 Locs[i] = std::make_pair(-1, -1);
5003 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
5005 Locs[i] = std::make_pair(0, NumLo);
5009 Locs[i] = std::make_pair(1, NumHi);
5011 Mask1[2+NumHi] = Idx;
5017 if (NumLo <= 2 && NumHi <= 2) {
5018 // If no more than two elements come from either vector. This can be
5019 // implemented with two shuffles. First shuffle gather the elements.
5020 // The second shuffle, which takes the first shuffle as both of its
5021 // vector operands, put the elements into the right order.
5022 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5024 SmallVector<int, 8> Mask2(4U, -1);
5026 for (unsigned i = 0; i != 4; ++i) {
5027 if (Locs[i].first == -1)
5030 unsigned Idx = (i < 2) ? 0 : 4;
5031 Idx += Locs[i].first * 2 + Locs[i].second;
5036 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
5037 } else if (NumLo == 3 || NumHi == 3) {
5038 // Otherwise, we must have three elements from one vector, call it X, and
5039 // one element from the other, call it Y. First, use a shufps to build an
5040 // intermediate vector with the one element from Y and the element from X
5041 // that will be in the same half in the final destination (the indexes don't
5042 // matter). Then, use a shufps to build the final vector, taking the half
5043 // containing the element from Y from the intermediate, and the other half
5046 // Normalize it so the 3 elements come from V1.
5047 CommuteVectorShuffleMask(PermMask, VT);
5051 // Find the element from V2.
5053 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
5054 int Val = PermMask[HiIndex];
5061 Mask1[0] = PermMask[HiIndex];
5063 Mask1[2] = PermMask[HiIndex^1];
5065 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5068 Mask1[0] = PermMask[0];
5069 Mask1[1] = PermMask[1];
5070 Mask1[2] = HiIndex & 1 ? 6 : 4;
5071 Mask1[3] = HiIndex & 1 ? 4 : 6;
5072 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
5074 Mask1[0] = HiIndex & 1 ? 2 : 0;
5075 Mask1[1] = HiIndex & 1 ? 0 : 2;
5076 Mask1[2] = PermMask[2];
5077 Mask1[3] = PermMask[3];
5082 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
5086 // Break it into (shuffle shuffle_hi, shuffle_lo).
5088 SmallVector<int,8> LoMask(4U, -1);
5089 SmallVector<int,8> HiMask(4U, -1);
5091 SmallVector<int,8> *MaskPtr = &LoMask;
5092 unsigned MaskIdx = 0;
5095 for (unsigned i = 0; i != 4; ++i) {
5102 int Idx = PermMask[i];
5104 Locs[i] = std::make_pair(-1, -1);
5105 } else if (Idx < 4) {
5106 Locs[i] = std::make_pair(MaskIdx, LoIdx);
5107 (*MaskPtr)[LoIdx] = Idx;
5110 Locs[i] = std::make_pair(MaskIdx, HiIdx);
5111 (*MaskPtr)[HiIdx] = Idx;
5116 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
5117 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
5118 SmallVector<int, 8> MaskOps;
5119 for (unsigned i = 0; i != 4; ++i) {
5120 if (Locs[i].first == -1) {
5121 MaskOps.push_back(-1);
5123 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
5124 MaskOps.push_back(Idx);
5127 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
5130 static bool MayFoldVectorLoad(SDValue V) {
5131 if (V.hasOneUse() && V.getOpcode() == ISD::BIT_CONVERT)
5132 V = V.getOperand(0);
5133 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5134 V = V.getOperand(0);
5140 // FIXME: the version above should always be used. Since there's
5141 // a bug where several vector shuffles can't be folded because the
5142 // DAG is not updated during lowering and a node claims to have two
5143 // uses while it only has one, use this version, and let isel match
5144 // another instruction if the load really happens to have more than
5145 // one use. Remove this version after this bug get fixed.
5146 static bool RelaxedMayFoldVectorLoad(SDValue V) {
5147 if (V.hasOneUse() && V.getOpcode() == ISD::BIT_CONVERT)
5148 V = V.getOperand(0);
5149 if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5150 V = V.getOperand(0);
5151 if (ISD::isNormalLoad(V.getNode()))
5156 /// CanFoldShuffleIntoVExtract - Check if the current shuffle is used by
5157 /// a vector extract, and if both can be later optimized into a single load.
5158 /// This is done in visitEXTRACT_VECTOR_ELT and the conditions are checked
5159 /// here because otherwise a target specific shuffle node is going to be
5160 /// emitted for this shuffle, and the optimization not done.
5161 /// FIXME: This is probably not the best approach, but fix the problem
5162 /// until the right path is decided.
5164 bool CanXFormVExtractWithShuffleIntoLoad(SDValue V, SelectionDAG &DAG,
5165 const TargetLowering &TLI) {
5166 EVT VT = V.getValueType();
5167 ShuffleVectorSDNode *SVOp = dyn_cast<ShuffleVectorSDNode>(V);
5169 // Be sure that the vector shuffle is present in a pattern like this:
5170 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), c) -> (f32 load $addr)
5174 SDNode *N = *V.getNode()->use_begin();
5175 if (N->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5178 SDValue EltNo = N->getOperand(1);
5179 if (!isa<ConstantSDNode>(EltNo))
5182 // If the bit convert changed the number of elements, it is unsafe
5183 // to examine the mask.
5184 bool HasShuffleIntoBitcast = false;
5185 if (V.getOpcode() == ISD::BIT_CONVERT) {
5186 EVT SrcVT = V.getOperand(0).getValueType();
5187 if (SrcVT.getVectorNumElements() != VT.getVectorNumElements())
5189 V = V.getOperand(0);
5190 HasShuffleIntoBitcast = true;
5193 // Select the input vector, guarding against out of range extract vector.
5194 unsigned NumElems = VT.getVectorNumElements();
5195 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5196 int Idx = (Elt > NumElems) ? -1 : SVOp->getMaskElt(Elt);
5197 V = (Idx < (int)NumElems) ? V.getOperand(0) : V.getOperand(1);
5199 // Skip one more bit_convert if necessary
5200 if (V.getOpcode() == ISD::BIT_CONVERT)
5201 V = V.getOperand(0);
5203 if (ISD::isNormalLoad(V.getNode())) {
5204 // Is the original load suitable?
5205 LoadSDNode *LN0 = cast<LoadSDNode>(V);
5207 // FIXME: avoid the multi-use bug that is preventing lots of
5208 // of foldings to be detected, this is still wrong of course, but
5209 // give the temporary desired behavior, and if it happens that
5210 // the load has real more uses, during isel it will not fold, and
5211 // will generate poor code.
5212 if (!LN0 || LN0->isVolatile()) // || !LN0->hasOneUse()
5215 if (!HasShuffleIntoBitcast)
5218 // If there's a bitcast before the shuffle, check if the load type and
5219 // alignment is valid.
5220 unsigned Align = LN0->getAlignment();
5222 TLI.getTargetData()->getABITypeAlignment(
5223 VT.getTypeForEVT(*DAG.getContext()));
5225 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
5233 SDValue getMOVLowToHigh(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG,
5235 SDValue V1 = Op.getOperand(0);
5236 SDValue V2 = Op.getOperand(1);
5237 EVT VT = Op.getValueType();
5239 assert(VT != MVT::v2i64 && "unsupported shuffle type");
5241 if (HasSSE2 && VT == MVT::v2f64)
5242 return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
5245 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V2, DAG);
5249 SDValue getMOVHighToLow(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG) {
5250 SDValue V1 = Op.getOperand(0);
5251 SDValue V2 = Op.getOperand(1);
5252 EVT VT = Op.getValueType();
5254 assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
5255 "unsupported shuffle type");
5257 if (V2.getOpcode() == ISD::UNDEF)
5261 return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
5265 SDValue getMOVLP(SDValue &Op, DebugLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
5266 SDValue V1 = Op.getOperand(0);
5267 SDValue V2 = Op.getOperand(1);
5268 EVT VT = Op.getValueType();
5269 unsigned NumElems = VT.getVectorNumElements();
5271 // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
5272 // operand of these instructions is only memory, so check if there's a
5273 // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
5275 bool CanFoldLoad = false;
5277 // Trivial case, when V2 comes from a load.
5278 if (MayFoldVectorLoad(V2))
5281 // When V1 is a load, it can be folded later into a store in isel, example:
5282 // (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
5284 // (MOVLPSmr addr:$src1, VR128:$src2)
5285 // So, recognize this potential and also use MOVLPS or MOVLPD
5286 if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
5290 if (HasSSE2 && NumElems == 2)
5291 return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
5294 return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
5297 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5298 // movl and movlp will both match v2i64, but v2i64 is never matched by
5299 // movl earlier because we make it strict to avoid messing with the movlp load
5300 // folding logic (see the code above getMOVLP call). Match it here then,
5301 // this is horrible, but will stay like this until we move all shuffle
5302 // matching to x86 specific nodes. Note that for the 1st condition all
5303 // types are matched with movsd.
5304 if ((HasSSE2 && NumElems == 2) || !X86::isMOVLMask(SVOp))
5305 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5307 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5310 assert(VT != MVT::v4i32 && "unsupported shuffle type");
5312 // Invert the operand order and use SHUFPS to match it.
5313 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V2, V1,
5314 X86::getShuffleSHUFImmediate(SVOp), DAG);
5317 static inline unsigned getUNPCKLOpcode(EVT VT) {
5318 switch(VT.getSimpleVT().SimpleTy) {
5319 case MVT::v4i32: return X86ISD::PUNPCKLDQ;
5320 case MVT::v2i64: return X86ISD::PUNPCKLQDQ;
5321 case MVT::v4f32: return X86ISD::UNPCKLPS;
5322 case MVT::v2f64: return X86ISD::UNPCKLPD;
5323 case MVT::v16i8: return X86ISD::PUNPCKLBW;
5324 case MVT::v8i16: return X86ISD::PUNPCKLWD;
5326 llvm_unreachable("Unknow type for unpckl");
5331 static inline unsigned getUNPCKHOpcode(EVT VT) {
5332 switch(VT.getSimpleVT().SimpleTy) {
5333 case MVT::v4i32: return X86ISD::PUNPCKHDQ;
5334 case MVT::v2i64: return X86ISD::PUNPCKHQDQ;
5335 case MVT::v4f32: return X86ISD::UNPCKHPS;
5336 case MVT::v2f64: return X86ISD::UNPCKHPD;
5337 case MVT::v16i8: return X86ISD::PUNPCKHBW;
5338 case MVT::v8i16: return X86ISD::PUNPCKHWD;
5340 llvm_unreachable("Unknow type for unpckh");
5346 SDValue NormalizeVectorShuffle(SDValue Op, SelectionDAG &DAG,
5347 const TargetLowering &TLI,
5348 const X86Subtarget *Subtarget) {
5349 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5350 EVT VT = Op.getValueType();
5351 DebugLoc dl = Op.getDebugLoc();
5352 SDValue V1 = Op.getOperand(0);
5353 SDValue V2 = Op.getOperand(1);
5355 if (isZeroShuffle(SVOp))
5356 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
5358 // Handle splat operations
5359 if (SVOp->isSplat()) {
5360 // Special case, this is the only place now where it's
5361 // allowed to return a vector_shuffle operation without
5362 // using a target specific node, because *hopefully* it
5363 // will be optimized away by the dag combiner.
5364 if (VT.getVectorNumElements() <= 4 &&
5365 CanXFormVExtractWithShuffleIntoLoad(Op, DAG, TLI))
5368 // Handle splats by matching through known masks
5369 if (VT.getVectorNumElements() <= 4)
5372 // Canonize all of the remaining to v4f32.
5373 return PromoteSplat(SVOp, DAG);
5376 // If the shuffle can be profitably rewritten as a narrower shuffle, then
5378 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
5379 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5380 if (NewOp.getNode())
5381 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, NewOp);
5382 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
5383 // FIXME: Figure out a cleaner way to do this.
5384 // Try to make use of movq to zero out the top part.
5385 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
5386 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5387 if (NewOp.getNode()) {
5388 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
5389 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
5390 DAG, Subtarget, dl);
5392 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
5393 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, dl);
5394 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
5395 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
5396 DAG, Subtarget, dl);
5403 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
5404 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5405 SDValue V1 = Op.getOperand(0);
5406 SDValue V2 = Op.getOperand(1);
5407 EVT VT = Op.getValueType();
5408 DebugLoc dl = Op.getDebugLoc();
5409 unsigned NumElems = VT.getVectorNumElements();
5410 bool isMMX = VT.getSizeInBits() == 64;
5411 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
5412 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
5413 bool V1IsSplat = false;
5414 bool V2IsSplat = false;
5415 bool HasSSE2 = Subtarget->hasSSE2() || Subtarget->hasAVX();
5416 bool HasSSE3 = Subtarget->hasSSE3() || Subtarget->hasAVX();
5417 bool HasSSSE3 = Subtarget->hasSSSE3() || Subtarget->hasAVX();
5418 MachineFunction &MF = DAG.getMachineFunction();
5419 bool OptForSize = MF.getFunction()->hasFnAttr(Attribute::OptimizeForSize);
5421 // FIXME: this is somehow handled during isel by MMX pattern fragments. Remove
5422 // the check or come up with another solution when all MMX move to intrinsics,
5423 // but don't allow this to be considered legal, we don't want vector_shuffle
5424 // operations to be matched during isel anymore.
5425 if (isMMX && SVOp->isSplat())
5428 // Vector shuffle lowering takes 3 steps:
5430 // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
5431 // narrowing and commutation of operands should be handled.
5432 // 2) Matching of shuffles with known shuffle masks to x86 target specific
5434 // 3) Rewriting of unmatched masks into new generic shuffle operations,
5435 // so the shuffle can be broken into other shuffles and the legalizer can
5436 // try the lowering again.
5438 // The general ideia is that no vector_shuffle operation should be left to
5439 // be matched during isel, all of them must be converted to a target specific
5442 // Normalize the input vectors. Here splats, zeroed vectors, profitable
5443 // narrowing and commutation of operands should be handled. The actual code
5444 // doesn't include all of those, work in progress...
5445 SDValue NewOp = NormalizeVectorShuffle(Op, DAG, *this, Subtarget);
5446 if (NewOp.getNode())
5449 // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
5450 // unpckh_undef). Only use pshufd if speed is more important than size.
5451 if (OptForSize && X86::isUNPCKL_v_undef_Mask(SVOp))
5452 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5453 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5454 if (OptForSize && X86::isUNPCKH_v_undef_Mask(SVOp))
5455 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5456 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5458 if (X86::isMOVDDUPMask(SVOp) && HasSSE3 && V2IsUndef &&
5459 RelaxedMayFoldVectorLoad(V1) && !isMMX)
5460 return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
5462 if (!isMMX && X86::isMOVHLPS_v_undef_Mask(SVOp))
5463 return getMOVHighToLow(Op, dl, DAG);
5465 // Use to match splats
5466 if (HasSSE2 && X86::isUNPCKHMask(SVOp) && V2IsUndef &&
5467 (VT == MVT::v2f64 || VT == MVT::v2i64))
5468 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5470 if (X86::isPSHUFDMask(SVOp)) {
5471 // The actual implementation will match the mask in the if above and then
5472 // during isel it can match several different instructions, not only pshufd
5473 // as its name says, sad but true, emulate the behavior for now...
5474 if (X86::isMOVDDUPMask(SVOp) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
5475 return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
5477 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5479 if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
5480 return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
5482 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5483 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V1,
5486 if (VT == MVT::v4f32)
5487 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V1,
5491 // Check if this can be converted into a logical shift.
5492 bool isLeft = false;
5495 bool isShift = getSubtarget()->hasSSE2() &&
5496 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
5497 if (isShift && ShVal.hasOneUse()) {
5498 // If the shifted value has multiple uses, it may be cheaper to use
5499 // v_set0 + movlhps or movhlps, etc.
5500 EVT EltVT = VT.getVectorElementType();
5501 ShAmt *= EltVT.getSizeInBits();
5502 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5505 if (X86::isMOVLMask(SVOp)) {
5508 if (ISD::isBuildVectorAllZeros(V1.getNode()))
5509 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
5510 if (!isMMX && !X86::isMOVLPMask(SVOp)) {
5511 if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
5512 return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
5514 if (VT == MVT::v4i32 || VT == MVT::v4f32)
5515 return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
5519 // FIXME: fold these into legal mask.
5521 if (X86::isMOVLHPSMask(SVOp) && !X86::isUNPCKLMask(SVOp))
5522 return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
5524 if (X86::isMOVHLPSMask(SVOp))
5525 return getMOVHighToLow(Op, dl, DAG);
5527 if (X86::isMOVSHDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5528 return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
5530 if (X86::isMOVSLDUPMask(SVOp) && HasSSE3 && V2IsUndef && NumElems == 4)
5531 return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
5533 if (X86::isMOVLPMask(SVOp))
5534 return getMOVLP(Op, dl, DAG, HasSSE2);
5537 if (ShouldXformToMOVHLPS(SVOp) ||
5538 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
5539 return CommuteVectorShuffle(SVOp, DAG);
5542 // No better options. Use a vshl / vsrl.
5543 EVT EltVT = VT.getVectorElementType();
5544 ShAmt *= EltVT.getSizeInBits();
5545 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
5548 bool Commuted = false;
5549 // FIXME: This should also accept a bitcast of a splat? Be careful, not
5550 // 1,1,1,1 -> v8i16 though.
5551 V1IsSplat = isSplatVector(V1.getNode());
5552 V2IsSplat = isSplatVector(V2.getNode());
5554 // Canonicalize the splat or undef, if present, to be on the RHS.
5555 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
5556 Op = CommuteVectorShuffle(SVOp, DAG);
5557 SVOp = cast<ShuffleVectorSDNode>(Op);
5558 V1 = SVOp->getOperand(0);
5559 V2 = SVOp->getOperand(1);
5560 std::swap(V1IsSplat, V2IsSplat);
5561 std::swap(V1IsUndef, V2IsUndef);
5565 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
5566 // Shuffling low element of v1 into undef, just return v1.
5569 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
5570 // the instruction selector will not match, so get a canonical MOVL with
5571 // swapped operands to undo the commute.
5572 return getMOVL(DAG, dl, VT, V2, V1);
5575 if (X86::isUNPCKLMask(SVOp))
5577 Op : getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V2, DAG);
5579 if (X86::isUNPCKHMask(SVOp))
5581 Op : getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V2, DAG);
5584 // Normalize mask so all entries that point to V2 points to its first
5585 // element then try to match unpck{h|l} again. If match, return a
5586 // new vector_shuffle with the corrected mask.
5587 SDValue NewMask = NormalizeMask(SVOp, DAG);
5588 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
5589 if (NSVOp != SVOp) {
5590 if (X86::isUNPCKLMask(NSVOp, true)) {
5592 } else if (X86::isUNPCKHMask(NSVOp, true)) {
5599 // Commute is back and try unpck* again.
5600 // FIXME: this seems wrong.
5601 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
5602 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
5604 if (X86::isUNPCKLMask(NewSVOp))
5606 NewOp : getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V2, V1, DAG);
5608 if (X86::isUNPCKHMask(NewSVOp))
5610 NewOp : getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V2, V1, DAG);
5613 // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
5615 // Normalize the node to match x86 shuffle ops if needed
5616 if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
5617 return CommuteVectorShuffle(SVOp, DAG);
5619 // The checks below are all present in isShuffleMaskLegal, but they are
5620 // inlined here right now to enable us to directly emit target specific
5621 // nodes, and remove one by one until they don't return Op anymore.
5622 SmallVector<int, 16> M;
5625 if (isPALIGNRMask(M, VT, HasSSSE3))
5626 return getTargetShuffleNode(X86ISD::PALIGN, dl, VT, V1, V2,
5627 X86::getShufflePALIGNRImmediate(SVOp),
5630 // Only a few shuffle masks are handled for 64-bit vectors (MMX), and
5631 // 64-bit vectors which made to this point can't be handled, they are
5636 if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
5637 SVOp->getSplatIndex() == 0 && V2IsUndef) {
5638 if (VT == MVT::v2f64)
5639 return getTargetShuffleNode(X86ISD::UNPCKLPD, dl, VT, V1, V1, DAG);
5640 if (VT == MVT::v2i64)
5641 return getTargetShuffleNode(X86ISD::PUNPCKLQDQ, dl, VT, V1, V1, DAG);
5644 if (isPSHUFHWMask(M, VT))
5645 return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
5646 X86::getShufflePSHUFHWImmediate(SVOp),
5649 if (isPSHUFLWMask(M, VT))
5650 return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
5651 X86::getShufflePSHUFLWImmediate(SVOp),
5654 if (isSHUFPMask(M, VT)) {
5655 unsigned TargetMask = X86::getShuffleSHUFImmediate(SVOp);
5656 if (VT == MVT::v4f32 || VT == MVT::v4i32)
5657 return getTargetShuffleNode(X86ISD::SHUFPS, dl, VT, V1, V2,
5659 if (VT == MVT::v2f64 || VT == MVT::v2i64)
5660 return getTargetShuffleNode(X86ISD::SHUFPD, dl, VT, V1, V2,
5664 if (X86::isUNPCKL_v_undef_Mask(SVOp))
5665 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5666 return getTargetShuffleNode(getUNPCKLOpcode(VT), dl, VT, V1, V1, DAG);
5667 if (X86::isUNPCKH_v_undef_Mask(SVOp))
5668 if (VT != MVT::v2i64 && VT != MVT::v2f64)
5669 return getTargetShuffleNode(getUNPCKHOpcode(VT), dl, VT, V1, V1, DAG);
5671 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
5672 if (VT == MVT::v8i16) {
5673 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, DAG);
5674 if (NewOp.getNode())
5678 if (VT == MVT::v16i8) {
5679 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
5680 if (NewOp.getNode())
5684 // Handle all 4 wide cases with a number of shuffles except for MMX.
5685 if (NumElems == 4 && !isMMX)
5686 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
5692 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
5693 SelectionDAG &DAG) const {
5694 EVT VT = Op.getValueType();
5695 DebugLoc dl = Op.getDebugLoc();
5696 if (VT.getSizeInBits() == 8) {
5697 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
5698 Op.getOperand(0), Op.getOperand(1));
5699 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5700 DAG.getValueType(VT));
5701 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5702 } else if (VT.getSizeInBits() == 16) {
5703 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5704 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
5706 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5707 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5708 DAG.getNode(ISD::BIT_CONVERT, dl,
5712 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
5713 Op.getOperand(0), Op.getOperand(1));
5714 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
5715 DAG.getValueType(VT));
5716 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5717 } else if (VT == MVT::f32) {
5718 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
5719 // the result back to FR32 register. It's only worth matching if the
5720 // result has a single use which is a store or a bitcast to i32. And in
5721 // the case of a store, it's not worth it if the index is a constant 0,
5722 // because a MOVSSmr can be used instead, which is smaller and faster.
5723 if (!Op.hasOneUse())
5725 SDNode *User = *Op.getNode()->use_begin();
5726 if ((User->getOpcode() != ISD::STORE ||
5727 (isa<ConstantSDNode>(Op.getOperand(1)) &&
5728 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
5729 (User->getOpcode() != ISD::BIT_CONVERT ||
5730 User->getValueType(0) != MVT::i32))
5732 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5733 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
5736 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
5737 } else if (VT == MVT::i32) {
5738 // ExtractPS works with constant index.
5739 if (isa<ConstantSDNode>(Op.getOperand(1)))
5747 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5748 SelectionDAG &DAG) const {
5749 if (!isa<ConstantSDNode>(Op.getOperand(1)))
5752 if (Subtarget->hasSSE41()) {
5753 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
5758 EVT VT = Op.getValueType();
5759 DebugLoc dl = Op.getDebugLoc();
5760 // TODO: handle v16i8.
5761 if (VT.getSizeInBits() == 16) {
5762 SDValue Vec = Op.getOperand(0);
5763 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5765 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
5766 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
5767 DAG.getNode(ISD::BIT_CONVERT, dl,
5770 // Transform it so it match pextrw which produces a 32-bit result.
5771 EVT EltVT = MVT::i32;
5772 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
5773 Op.getOperand(0), Op.getOperand(1));
5774 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
5775 DAG.getValueType(VT));
5776 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
5777 } else if (VT.getSizeInBits() == 32) {
5778 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5782 // SHUFPS the element to the lowest double word, then movss.
5783 int Mask[4] = { Idx, -1, -1, -1 };
5784 EVT VVT = Op.getOperand(0).getValueType();
5785 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5786 DAG.getUNDEF(VVT), Mask);
5787 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5788 DAG.getIntPtrConstant(0));
5789 } else if (VT.getSizeInBits() == 64) {
5790 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
5791 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
5792 // to match extract_elt for f64.
5793 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5797 // UNPCKHPD the element to the lowest double word, then movsd.
5798 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
5799 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
5800 int Mask[2] = { 1, -1 };
5801 EVT VVT = Op.getOperand(0).getValueType();
5802 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
5803 DAG.getUNDEF(VVT), Mask);
5804 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
5805 DAG.getIntPtrConstant(0));
5812 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
5813 SelectionDAG &DAG) const {
5814 EVT VT = Op.getValueType();
5815 EVT EltVT = VT.getVectorElementType();
5816 DebugLoc dl = Op.getDebugLoc();
5818 SDValue N0 = Op.getOperand(0);
5819 SDValue N1 = Op.getOperand(1);
5820 SDValue N2 = Op.getOperand(2);
5822 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
5823 isa<ConstantSDNode>(N2)) {
5825 if (VT == MVT::v8i16)
5826 Opc = X86ISD::PINSRW;
5827 else if (VT == MVT::v4i16)
5828 Opc = X86ISD::MMX_PINSRW;
5829 else if (VT == MVT::v16i8)
5830 Opc = X86ISD::PINSRB;
5832 Opc = X86ISD::PINSRB;
5834 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
5836 if (N1.getValueType() != MVT::i32)
5837 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5838 if (N2.getValueType() != MVT::i32)
5839 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5840 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
5841 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
5842 // Bits [7:6] of the constant are the source select. This will always be
5843 // zero here. The DAG Combiner may combine an extract_elt index into these
5844 // bits. For example (insert (extract, 3), 2) could be matched by putting
5845 // the '3' into bits [7:6] of X86ISD::INSERTPS.
5846 // Bits [5:4] of the constant are the destination select. This is the
5847 // value of the incoming immediate.
5848 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
5849 // combine either bitwise AND or insert of float 0.0 to set these bits.
5850 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
5851 // Create this as a scalar to vector..
5852 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
5853 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
5854 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
5855 // PINSR* works with constant index.
5862 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
5863 EVT VT = Op.getValueType();
5864 EVT EltVT = VT.getVectorElementType();
5866 if (Subtarget->hasSSE41())
5867 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
5869 if (EltVT == MVT::i8)
5872 DebugLoc dl = Op.getDebugLoc();
5873 SDValue N0 = Op.getOperand(0);
5874 SDValue N1 = Op.getOperand(1);
5875 SDValue N2 = Op.getOperand(2);
5877 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
5878 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
5879 // as its second argument.
5880 if (N1.getValueType() != MVT::i32)
5881 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5882 if (N2.getValueType() != MVT::i32)
5883 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5884 return DAG.getNode(VT == MVT::v8i16 ? X86ISD::PINSRW : X86ISD::MMX_PINSRW,
5885 dl, VT, N0, N1, N2);
5891 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5892 DebugLoc dl = Op.getDebugLoc();
5894 if (Op.getValueType() == MVT::v1i64 &&
5895 Op.getOperand(0).getValueType() == MVT::i64)
5896 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5898 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5899 EVT VT = MVT::v2i32;
5900 switch (Op.getValueType().getSimpleVT().SimpleTy) {
5907 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
5908 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
5911 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5912 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5913 // one of the above mentioned nodes. It has to be wrapped because otherwise
5914 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5915 // be used to form addressing mode. These wrapped nodes will be selected
5918 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
5919 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5921 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5923 unsigned char OpFlag = 0;
5924 unsigned WrapperKind = X86ISD::Wrapper;
5925 CodeModel::Model M = getTargetMachine().getCodeModel();
5927 if (Subtarget->isPICStyleRIPRel() &&
5928 (M == CodeModel::Small || M == CodeModel::Kernel))
5929 WrapperKind = X86ISD::WrapperRIP;
5930 else if (Subtarget->isPICStyleGOT())
5931 OpFlag = X86II::MO_GOTOFF;
5932 else if (Subtarget->isPICStyleStubPIC())
5933 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5935 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5937 CP->getOffset(), OpFlag);
5938 DebugLoc DL = CP->getDebugLoc();
5939 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5940 // With PIC, the address is actually $g + Offset.
5942 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5943 DAG.getNode(X86ISD::GlobalBaseReg,
5944 DebugLoc(), getPointerTy()),
5951 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
5952 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5954 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5956 unsigned char OpFlag = 0;
5957 unsigned WrapperKind = X86ISD::Wrapper;
5958 CodeModel::Model M = getTargetMachine().getCodeModel();
5960 if (Subtarget->isPICStyleRIPRel() &&
5961 (M == CodeModel::Small || M == CodeModel::Kernel))
5962 WrapperKind = X86ISD::WrapperRIP;
5963 else if (Subtarget->isPICStyleGOT())
5964 OpFlag = X86II::MO_GOTOFF;
5965 else if (Subtarget->isPICStyleStubPIC())
5966 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5968 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5970 DebugLoc DL = JT->getDebugLoc();
5971 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5973 // With PIC, the address is actually $g + Offset.
5975 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5976 DAG.getNode(X86ISD::GlobalBaseReg,
5977 DebugLoc(), getPointerTy()),
5985 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
5986 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5988 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5990 unsigned char OpFlag = 0;
5991 unsigned WrapperKind = X86ISD::Wrapper;
5992 CodeModel::Model M = getTargetMachine().getCodeModel();
5994 if (Subtarget->isPICStyleRIPRel() &&
5995 (M == CodeModel::Small || M == CodeModel::Kernel))
5996 WrapperKind = X86ISD::WrapperRIP;
5997 else if (Subtarget->isPICStyleGOT())
5998 OpFlag = X86II::MO_GOTOFF;
5999 else if (Subtarget->isPICStyleStubPIC())
6000 OpFlag = X86II::MO_PIC_BASE_OFFSET;
6002 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
6004 DebugLoc DL = Op.getDebugLoc();
6005 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6008 // With PIC, the address is actually $g + Offset.
6009 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
6010 !Subtarget->is64Bit()) {
6011 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6012 DAG.getNode(X86ISD::GlobalBaseReg,
6013 DebugLoc(), getPointerTy()),
6021 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
6022 // Create the TargetBlockAddressAddress node.
6023 unsigned char OpFlags =
6024 Subtarget->ClassifyBlockAddressReference();
6025 CodeModel::Model M = getTargetMachine().getCodeModel();
6026 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
6027 DebugLoc dl = Op.getDebugLoc();
6028 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
6029 /*isTarget=*/true, OpFlags);
6031 if (Subtarget->isPICStyleRIPRel() &&
6032 (M == CodeModel::Small || M == CodeModel::Kernel))
6033 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6035 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6037 // With PIC, the address is actually $g + Offset.
6038 if (isGlobalRelativeToPICBase(OpFlags)) {
6039 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6040 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6048 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
6050 SelectionDAG &DAG) const {
6051 // Create the TargetGlobalAddress node, folding in the constant
6052 // offset if it is legal.
6053 unsigned char OpFlags =
6054 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
6055 CodeModel::Model M = getTargetMachine().getCodeModel();
6057 if (OpFlags == X86II::MO_NO_FLAG &&
6058 X86::isOffsetSuitableForCodeModel(Offset, M)) {
6059 // A direct static reference to a global.
6060 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
6063 Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
6066 if (Subtarget->isPICStyleRIPRel() &&
6067 (M == CodeModel::Small || M == CodeModel::Kernel))
6068 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
6070 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
6072 // With PIC, the address is actually $g + Offset.
6073 if (isGlobalRelativeToPICBase(OpFlags)) {
6074 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6075 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
6079 // For globals that require a load from a stub to get the address, emit the
6081 if (isGlobalStubReference(OpFlags))
6082 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
6083 MachinePointerInfo::getGOT(), false, false, 0);
6085 // If there was a non-zero offset that we didn't fold, create an explicit
6088 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
6089 DAG.getConstant(Offset, getPointerTy()));
6095 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
6096 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
6097 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
6098 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
6102 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
6103 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
6104 unsigned char OperandFlags) {
6105 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6106 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6107 DebugLoc dl = GA->getDebugLoc();
6108 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6109 GA->getValueType(0),
6113 SDValue Ops[] = { Chain, TGA, *InFlag };
6114 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
6116 SDValue Ops[] = { Chain, TGA };
6117 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
6120 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6121 MFI->setAdjustsStack(true);
6123 SDValue Flag = Chain.getValue(1);
6124 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
6127 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
6129 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6132 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
6133 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
6134 DAG.getNode(X86ISD::GlobalBaseReg,
6135 DebugLoc(), PtrVT), InFlag);
6136 InFlag = Chain.getValue(1);
6138 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
6141 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
6143 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6145 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
6146 X86::RAX, X86II::MO_TLSGD);
6149 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
6150 // "local exec" model.
6151 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
6152 const EVT PtrVT, TLSModel::Model model,
6154 DebugLoc dl = GA->getDebugLoc();
6156 // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
6157 Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
6158 is64Bit ? 257 : 256));
6160 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
6161 DAG.getIntPtrConstant(0),
6162 MachinePointerInfo(Ptr), false, false, 0);
6164 unsigned char OperandFlags = 0;
6165 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
6167 unsigned WrapperKind = X86ISD::Wrapper;
6168 if (model == TLSModel::LocalExec) {
6169 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
6170 } else if (is64Bit) {
6171 assert(model == TLSModel::InitialExec);
6172 OperandFlags = X86II::MO_GOTTPOFF;
6173 WrapperKind = X86ISD::WrapperRIP;
6175 assert(model == TLSModel::InitialExec);
6176 OperandFlags = X86II::MO_INDNTPOFF;
6179 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
6181 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
6182 GA->getValueType(0),
6183 GA->getOffset(), OperandFlags);
6184 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
6186 if (model == TLSModel::InitialExec)
6187 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
6188 MachinePointerInfo::getGOT(), false, false, 0);
6190 // The address of the thread local variable is the add of the thread
6191 // pointer with the offset of the variable.
6192 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
6196 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
6198 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
6199 const GlobalValue *GV = GA->getGlobal();
6201 if (Subtarget->isTargetELF()) {
6202 // TODO: implement the "local dynamic" model
6203 // TODO: implement the "initial exec"model for pic executables
6205 // If GV is an alias then use the aliasee for determining
6206 // thread-localness.
6207 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
6208 GV = GA->resolveAliasedGlobal(false);
6210 TLSModel::Model model
6211 = getTLSModel(GV, getTargetMachine().getRelocationModel());
6214 case TLSModel::GeneralDynamic:
6215 case TLSModel::LocalDynamic: // not implemented
6216 if (Subtarget->is64Bit())
6217 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
6218 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
6220 case TLSModel::InitialExec:
6221 case TLSModel::LocalExec:
6222 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
6223 Subtarget->is64Bit());
6225 } else if (Subtarget->isTargetDarwin()) {
6226 // Darwin only has one model of TLS. Lower to that.
6227 unsigned char OpFlag = 0;
6228 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
6229 X86ISD::WrapperRIP : X86ISD::Wrapper;
6231 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
6233 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
6234 !Subtarget->is64Bit();
6236 OpFlag = X86II::MO_TLVP_PIC_BASE;
6238 OpFlag = X86II::MO_TLVP;
6239 DebugLoc DL = Op.getDebugLoc();
6240 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
6242 GA->getOffset(), OpFlag);
6243 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
6245 // With PIC32, the address is actually $g + Offset.
6247 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
6248 DAG.getNode(X86ISD::GlobalBaseReg,
6249 DebugLoc(), getPointerTy()),
6252 // Lowering the machine isd will make sure everything is in the right
6254 SDValue Args[] = { Offset };
6255 SDValue Chain = DAG.getNode(X86ISD::TLSCALL, DL, MVT::Other, Args, 1);
6257 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
6258 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6259 MFI->setAdjustsStack(true);
6261 // And our return value (tls address) is in the standard call return value
6263 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
6264 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
6268 "TLS not implemented for this target.");
6270 llvm_unreachable("Unreachable");
6275 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
6276 /// take a 2 x i32 value to shift plus a shift amount.
6277 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
6278 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
6279 EVT VT = Op.getValueType();
6280 unsigned VTBits = VT.getSizeInBits();
6281 DebugLoc dl = Op.getDebugLoc();
6282 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
6283 SDValue ShOpLo = Op.getOperand(0);
6284 SDValue ShOpHi = Op.getOperand(1);
6285 SDValue ShAmt = Op.getOperand(2);
6286 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6287 DAG.getConstant(VTBits - 1, MVT::i8))
6288 : DAG.getConstant(0, VT);
6291 if (Op.getOpcode() == ISD::SHL_PARTS) {
6292 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
6293 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
6295 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
6296 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
6299 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
6300 DAG.getConstant(VTBits, MVT::i8));
6301 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6302 AndNode, DAG.getConstant(0, MVT::i8));
6305 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6306 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
6307 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
6309 if (Op.getOpcode() == ISD::SHL_PARTS) {
6310 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6311 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6313 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
6314 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
6317 SDValue Ops[2] = { Lo, Hi };
6318 return DAG.getMergeValues(Ops, 2, dl);
6321 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
6322 SelectionDAG &DAG) const {
6323 EVT SrcVT = Op.getOperand(0).getValueType();
6325 if (SrcVT.isVector()) {
6326 if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64)
6331 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
6332 "Unknown SINT_TO_FP to lower!");
6334 // These are really Legal; return the operand so the caller accepts it as
6336 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
6338 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
6339 Subtarget->is64Bit()) {
6343 DebugLoc dl = Op.getDebugLoc();
6344 unsigned Size = SrcVT.getSizeInBits()/8;
6345 MachineFunction &MF = DAG.getMachineFunction();
6346 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
6347 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6348 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6350 MachinePointerInfo::getFixedStack(SSFI),
6352 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
6355 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
6357 SelectionDAG &DAG) const {
6359 DebugLoc DL = Op.getDebugLoc();
6361 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
6363 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
6365 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
6367 unsigned ByteSize = SrcVT.getSizeInBits()/8;
6369 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6370 MachineMemOperand *MMO =
6371 DAG.getMachineFunction()
6372 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6373 MachineMemOperand::MOLoad, ByteSize, ByteSize);
6375 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
6376 SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
6378 Tys, Ops, array_lengthof(Ops),
6382 Chain = Result.getValue(1);
6383 SDValue InFlag = Result.getValue(2);
6385 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
6386 // shouldn't be necessary except that RFP cannot be live across
6387 // multiple blocks. When stackifier is fixed, they can be uncoupled.
6388 MachineFunction &MF = DAG.getMachineFunction();
6389 unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
6390 int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
6391 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6392 Tys = DAG.getVTList(MVT::Other);
6394 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
6396 MachineMemOperand *MMO =
6397 DAG.getMachineFunction()
6398 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6399 MachineMemOperand::MOStore, SSFISize, SSFISize);
6401 Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
6402 Ops, array_lengthof(Ops),
6403 Op.getValueType(), MMO);
6404 Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
6405 MachinePointerInfo::getFixedStack(SSFI),
6412 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
6413 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
6414 SelectionDAG &DAG) const {
6415 // This algorithm is not obvious. Here it is in C code, more or less:
6417 double uint64_to_double( uint32_t hi, uint32_t lo ) {
6418 static const __m128i exp = { 0x4330000045300000ULL, 0 };
6419 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
6421 // Copy ints to xmm registers.
6422 __m128i xh = _mm_cvtsi32_si128( hi );
6423 __m128i xl = _mm_cvtsi32_si128( lo );
6425 // Combine into low half of a single xmm register.
6426 __m128i x = _mm_unpacklo_epi32( xh, xl );
6430 // Merge in appropriate exponents to give the integer bits the right
6432 x = _mm_unpacklo_epi32( x, exp );
6434 // Subtract away the biases to deal with the IEEE-754 double precision
6436 d = _mm_sub_pd( (__m128d) x, bias );
6438 // All conversions up to here are exact. The correctly rounded result is
6439 // calculated using the current rounding mode using the following
6441 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
6442 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
6443 // store doesn't really need to be here (except
6444 // maybe to zero the other double)
6449 DebugLoc dl = Op.getDebugLoc();
6450 LLVMContext *Context = DAG.getContext();
6452 // Build some magic constants.
6453 std::vector<Constant*> CV0;
6454 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
6455 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
6456 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6457 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
6458 Constant *C0 = ConstantVector::get(CV0);
6459 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
6461 std::vector<Constant*> CV1;
6463 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
6465 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
6466 Constant *C1 = ConstantVector::get(CV1);
6467 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
6469 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6470 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6472 DAG.getIntPtrConstant(1)));
6473 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6474 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6476 DAG.getIntPtrConstant(0)));
6477 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
6478 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
6479 MachinePointerInfo::getConstantPool(),
6481 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
6482 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
6483 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
6484 MachinePointerInfo::getConstantPool(),
6486 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
6488 // Add the halves; easiest way is to swap them into another reg first.
6489 int ShufMask[2] = { 1, -1 };
6490 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
6491 DAG.getUNDEF(MVT::v2f64), ShufMask);
6492 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
6493 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
6494 DAG.getIntPtrConstant(0));
6497 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
6498 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
6499 SelectionDAG &DAG) const {
6500 DebugLoc dl = Op.getDebugLoc();
6501 // FP constant to bias correct the final result.
6502 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
6505 // Load the 32-bit value into an XMM register.
6506 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
6507 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
6509 DAG.getIntPtrConstant(0)));
6511 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6512 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
6513 DAG.getIntPtrConstant(0));
6515 // Or the load with the bias.
6516 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
6517 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
6518 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6520 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
6521 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6522 MVT::v2f64, Bias)));
6523 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
6524 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
6525 DAG.getIntPtrConstant(0));
6527 // Subtract the bias.
6528 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
6530 // Handle final rounding.
6531 EVT DestVT = Op.getValueType();
6533 if (DestVT.bitsLT(MVT::f64)) {
6534 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
6535 DAG.getIntPtrConstant(0));
6536 } else if (DestVT.bitsGT(MVT::f64)) {
6537 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
6540 // Handle final rounding.
6544 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
6545 SelectionDAG &DAG) const {
6546 SDValue N0 = Op.getOperand(0);
6547 DebugLoc dl = Op.getDebugLoc();
6549 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
6550 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
6551 // the optimization here.
6552 if (DAG.SignBitIsZero(N0))
6553 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
6555 EVT SrcVT = N0.getValueType();
6556 EVT DstVT = Op.getValueType();
6557 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
6558 return LowerUINT_TO_FP_i64(Op, DAG);
6559 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
6560 return LowerUINT_TO_FP_i32(Op, DAG);
6562 // Make a 64-bit buffer, and use it to build an FILD.
6563 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
6564 if (SrcVT == MVT::i32) {
6565 SDValue WordOff = DAG.getConstant(4, getPointerTy());
6566 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
6567 getPointerTy(), StackSlot, WordOff);
6568 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6569 StackSlot, MachinePointerInfo(),
6571 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
6572 OffsetSlot, MachinePointerInfo(),
6574 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
6578 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
6579 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
6580 StackSlot, MachinePointerInfo(),
6582 // For i64 source, we need to add the appropriate power of 2 if the input
6583 // was negative. This is the same as the optimization in
6584 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
6585 // we must be careful to do the computation in x87 extended precision, not
6586 // in SSE. (The generic code can't know it's OK to do this, or how to.)
6587 int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
6588 MachineMemOperand *MMO =
6589 DAG.getMachineFunction()
6590 .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6591 MachineMemOperand::MOLoad, 8, 8);
6593 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
6594 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
6595 SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops, 3,
6598 APInt FF(32, 0x5F800000ULL);
6600 // Check whether the sign bit is set.
6601 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
6602 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
6605 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
6606 SDValue FudgePtr = DAG.getConstantPool(
6607 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
6610 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
6611 SDValue Zero = DAG.getIntPtrConstant(0);
6612 SDValue Four = DAG.getIntPtrConstant(4);
6613 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
6615 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
6617 // Load the value out, extending it from f32 to f80.
6618 // FIXME: Avoid the extend by constructing the right constant pool?
6619 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, MVT::f80, dl, DAG.getEntryNode(),
6620 FudgePtr, MachinePointerInfo::getConstantPool(),
6621 MVT::f32, false, false, 4);
6622 // Extend everything to 80 bits to force it to be done on x87.
6623 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
6624 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
6627 std::pair<SDValue,SDValue> X86TargetLowering::
6628 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
6629 DebugLoc DL = Op.getDebugLoc();
6631 EVT DstTy = Op.getValueType();
6634 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
6638 assert(DstTy.getSimpleVT() <= MVT::i64 &&
6639 DstTy.getSimpleVT() >= MVT::i16 &&
6640 "Unknown FP_TO_SINT to lower!");
6642 // These are really Legal.
6643 if (DstTy == MVT::i32 &&
6644 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6645 return std::make_pair(SDValue(), SDValue());
6646 if (Subtarget->is64Bit() &&
6647 DstTy == MVT::i64 &&
6648 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
6649 return std::make_pair(SDValue(), SDValue());
6651 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
6653 MachineFunction &MF = DAG.getMachineFunction();
6654 unsigned MemSize = DstTy.getSizeInBits()/8;
6655 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6656 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6661 switch (DstTy.getSimpleVT().SimpleTy) {
6662 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
6663 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
6664 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
6665 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
6668 SDValue Chain = DAG.getEntryNode();
6669 SDValue Value = Op.getOperand(0);
6670 EVT TheVT = Op.getOperand(0).getValueType();
6671 if (isScalarFPTypeInSSEReg(TheVT)) {
6672 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
6673 Chain = DAG.getStore(Chain, DL, Value, StackSlot,
6674 MachinePointerInfo::getFixedStack(SSFI),
6676 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
6678 Chain, StackSlot, DAG.getValueType(TheVT)
6681 MachineMemOperand *MMO =
6682 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6683 MachineMemOperand::MOLoad, MemSize, MemSize);
6684 Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, 3,
6686 Chain = Value.getValue(1);
6687 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
6688 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6691 MachineMemOperand *MMO =
6692 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
6693 MachineMemOperand::MOStore, MemSize, MemSize);
6695 // Build the FP_TO_INT*_IN_MEM
6696 SDValue Ops[] = { Chain, Value, StackSlot };
6697 SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
6698 Ops, 3, DstTy, MMO);
6700 return std::make_pair(FIST, StackSlot);
6703 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
6704 SelectionDAG &DAG) const {
6705 if (Op.getValueType().isVector()) {
6706 if (Op.getValueType() == MVT::v2i32 &&
6707 Op.getOperand(0).getValueType() == MVT::v2f64) {
6713 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
6714 SDValue FIST = Vals.first, StackSlot = Vals.second;
6715 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
6716 if (FIST.getNode() == 0) return Op;
6719 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6720 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6723 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
6724 SelectionDAG &DAG) const {
6725 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
6726 SDValue FIST = Vals.first, StackSlot = Vals.second;
6727 assert(FIST.getNode() && "Unexpected failure");
6730 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
6731 FIST, StackSlot, MachinePointerInfo(), false, false, 0);
6734 SDValue X86TargetLowering::LowerFABS(SDValue Op,
6735 SelectionDAG &DAG) const {
6736 LLVMContext *Context = DAG.getContext();
6737 DebugLoc dl = Op.getDebugLoc();
6738 EVT VT = Op.getValueType();
6741 EltVT = VT.getVectorElementType();
6742 std::vector<Constant*> CV;
6743 if (EltVT == MVT::f64) {
6744 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
6748 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
6754 Constant *C = ConstantVector::get(CV);
6755 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6756 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6757 MachinePointerInfo::getConstantPool(),
6759 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
6762 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
6763 LLVMContext *Context = DAG.getContext();
6764 DebugLoc dl = Op.getDebugLoc();
6765 EVT VT = Op.getValueType();
6768 EltVT = VT.getVectorElementType();
6769 std::vector<Constant*> CV;
6770 if (EltVT == MVT::f64) {
6771 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
6775 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
6781 Constant *C = ConstantVector::get(CV);
6782 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6783 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6784 MachinePointerInfo::getConstantPool(),
6786 if (VT.isVector()) {
6787 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
6788 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
6789 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
6791 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
6793 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
6797 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
6798 LLVMContext *Context = DAG.getContext();
6799 SDValue Op0 = Op.getOperand(0);
6800 SDValue Op1 = Op.getOperand(1);
6801 DebugLoc dl = Op.getDebugLoc();
6802 EVT VT = Op.getValueType();
6803 EVT SrcVT = Op1.getValueType();
6805 // If second operand is smaller, extend it first.
6806 if (SrcVT.bitsLT(VT)) {
6807 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
6810 // And if it is bigger, shrink it first.
6811 if (SrcVT.bitsGT(VT)) {
6812 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
6816 // At this point the operands and the result should have the same
6817 // type, and that won't be f80 since that is not custom lowered.
6819 // First get the sign bit of second operand.
6820 std::vector<Constant*> CV;
6821 if (SrcVT == MVT::f64) {
6822 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
6823 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6825 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
6826 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6827 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6828 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6830 Constant *C = ConstantVector::get(CV);
6831 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6832 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
6833 MachinePointerInfo::getConstantPool(),
6835 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
6837 // Shift sign bit right or left if the two operands have different types.
6838 if (SrcVT.bitsGT(VT)) {
6839 // Op0 is MVT::f32, Op1 is MVT::f64.
6840 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
6841 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
6842 DAG.getConstant(32, MVT::i32));
6843 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
6844 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
6845 DAG.getIntPtrConstant(0));
6848 // Clear first operand sign bit.
6850 if (VT == MVT::f64) {
6851 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
6852 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
6854 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
6855 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6856 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6857 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
6859 C = ConstantVector::get(CV);
6860 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
6861 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
6862 MachinePointerInfo::getConstantPool(),
6864 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
6866 // Or the value with the sign bit.
6867 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
6870 /// Emit nodes that will be selected as "test Op0,Op0", or something
6872 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
6873 SelectionDAG &DAG) const {
6874 DebugLoc dl = Op.getDebugLoc();
6876 // CF and OF aren't always set the way we want. Determine which
6877 // of these we need.
6878 bool NeedCF = false;
6879 bool NeedOF = false;
6882 case X86::COND_A: case X86::COND_AE:
6883 case X86::COND_B: case X86::COND_BE:
6886 case X86::COND_G: case X86::COND_GE:
6887 case X86::COND_L: case X86::COND_LE:
6888 case X86::COND_O: case X86::COND_NO:
6893 // See if we can use the EFLAGS value from the operand instead of
6894 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
6895 // we prove that the arithmetic won't overflow, we can't use OF or CF.
6896 if (Op.getResNo() != 0 || NeedOF || NeedCF)
6897 // Emit a CMP with 0, which is the TEST pattern.
6898 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6899 DAG.getConstant(0, Op.getValueType()));
6901 unsigned Opcode = 0;
6902 unsigned NumOperands = 0;
6903 switch (Op.getNode()->getOpcode()) {
6905 // Due to an isel shortcoming, be conservative if this add is likely to be
6906 // selected as part of a load-modify-store instruction. When the root node
6907 // in a match is a store, isel doesn't know how to remap non-chain non-flag
6908 // uses of other nodes in the match, such as the ADD in this case. This
6909 // leads to the ADD being left around and reselected, with the result being
6910 // two adds in the output. Alas, even if none our users are stores, that
6911 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
6912 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
6913 // climbing the DAG back to the root, and it doesn't seem to be worth the
6915 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6916 UE = Op.getNode()->use_end(); UI != UE; ++UI)
6917 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
6920 if (ConstantSDNode *C =
6921 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
6922 // An add of one will be selected as an INC.
6923 if (C->getAPIntValue() == 1) {
6924 Opcode = X86ISD::INC;
6929 // An add of negative one (subtract of one) will be selected as a DEC.
6930 if (C->getAPIntValue().isAllOnesValue()) {
6931 Opcode = X86ISD::DEC;
6937 // Otherwise use a regular EFLAGS-setting add.
6938 Opcode = X86ISD::ADD;
6942 // If the primary and result isn't used, don't bother using X86ISD::AND,
6943 // because a TEST instruction will be better.
6944 bool NonFlagUse = false;
6945 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6946 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
6948 unsigned UOpNo = UI.getOperandNo();
6949 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
6950 // Look pass truncate.
6951 UOpNo = User->use_begin().getOperandNo();
6952 User = *User->use_begin();
6955 if (User->getOpcode() != ISD::BRCOND &&
6956 User->getOpcode() != ISD::SETCC &&
6957 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
6970 // Due to the ISEL shortcoming noted above, be conservative if this op is
6971 // likely to be selected as part of a load-modify-store instruction.
6972 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6973 UE = Op.getNode()->use_end(); UI != UE; ++UI)
6974 if (UI->getOpcode() == ISD::STORE)
6977 // Otherwise use a regular EFLAGS-setting instruction.
6978 switch (Op.getNode()->getOpcode()) {
6979 default: llvm_unreachable("unexpected operator!");
6980 case ISD::SUB: Opcode = X86ISD::SUB; break;
6981 case ISD::OR: Opcode = X86ISD::OR; break;
6982 case ISD::XOR: Opcode = X86ISD::XOR; break;
6983 case ISD::AND: Opcode = X86ISD::AND; break;
6995 return SDValue(Op.getNode(), 1);
7002 // Emit a CMP with 0, which is the TEST pattern.
7003 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
7004 DAG.getConstant(0, Op.getValueType()));
7006 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
7007 SmallVector<SDValue, 4> Ops;
7008 for (unsigned i = 0; i != NumOperands; ++i)
7009 Ops.push_back(Op.getOperand(i));
7011 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
7012 DAG.ReplaceAllUsesWith(Op, New);
7013 return SDValue(New.getNode(), 1);
7016 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
7018 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
7019 SelectionDAG &DAG) const {
7020 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
7021 if (C->getAPIntValue() == 0)
7022 return EmitTest(Op0, X86CC, DAG);
7024 DebugLoc dl = Op0.getDebugLoc();
7025 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
7028 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
7029 /// if it's possible.
7030 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
7031 DebugLoc dl, SelectionDAG &DAG) const {
7032 SDValue Op0 = And.getOperand(0);
7033 SDValue Op1 = And.getOperand(1);
7034 if (Op0.getOpcode() == ISD::TRUNCATE)
7035 Op0 = Op0.getOperand(0);
7036 if (Op1.getOpcode() == ISD::TRUNCATE)
7037 Op1 = Op1.getOperand(0);
7040 if (Op1.getOpcode() == ISD::SHL)
7041 std::swap(Op0, Op1);
7042 if (Op0.getOpcode() == ISD::SHL) {
7043 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
7044 if (And00C->getZExtValue() == 1) {
7045 // If we looked past a truncate, check that it's only truncating away
7047 unsigned BitWidth = Op0.getValueSizeInBits();
7048 unsigned AndBitWidth = And.getValueSizeInBits();
7049 if (BitWidth > AndBitWidth) {
7050 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
7051 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
7052 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
7056 RHS = Op0.getOperand(1);
7058 } else if (Op1.getOpcode() == ISD::Constant) {
7059 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
7060 SDValue AndLHS = Op0;
7061 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
7062 LHS = AndLHS.getOperand(0);
7063 RHS = AndLHS.getOperand(1);
7067 if (LHS.getNode()) {
7068 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
7069 // instruction. Since the shift amount is in-range-or-undefined, we know
7070 // that doing a bittest on the i32 value is ok. We extend to i32 because
7071 // the encoding for the i16 version is larger than the i32 version.
7072 // Also promote i16 to i32 for performance / code size reason.
7073 if (LHS.getValueType() == MVT::i8 ||
7074 LHS.getValueType() == MVT::i16)
7075 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
7077 // If the operand types disagree, extend the shift amount to match. Since
7078 // BT ignores high bits (like shifts) we can use anyextend.
7079 if (LHS.getValueType() != RHS.getValueType())
7080 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
7082 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
7083 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
7084 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7085 DAG.getConstant(Cond, MVT::i8), BT);
7091 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
7092 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
7093 SDValue Op0 = Op.getOperand(0);
7094 SDValue Op1 = Op.getOperand(1);
7095 DebugLoc dl = Op.getDebugLoc();
7096 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7098 // Optimize to BT if possible.
7099 // Lower (X & (1 << N)) == 0 to BT(X, N).
7100 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
7101 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
7102 if (Op0.getOpcode() == ISD::AND &&
7104 Op1.getOpcode() == ISD::Constant &&
7105 cast<ConstantSDNode>(Op1)->isNullValue() &&
7106 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7107 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
7108 if (NewSetCC.getNode())
7112 // Look for "(setcc) == / != 1" to avoid unncessary setcc.
7113 if (Op0.getOpcode() == X86ISD::SETCC &&
7114 Op1.getOpcode() == ISD::Constant &&
7115 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
7116 cast<ConstantSDNode>(Op1)->isNullValue()) &&
7117 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
7118 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
7119 bool Invert = (CC == ISD::SETNE) ^
7120 cast<ConstantSDNode>(Op1)->isNullValue();
7122 CCode = X86::GetOppositeBranchCondition(CCode);
7123 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7124 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
7127 bool isFP = Op1.getValueType().isFloatingPoint();
7128 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
7129 if (X86CC == X86::COND_INVALID)
7132 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
7134 // Use sbb x, x to materialize carry bit into a GPR.
7135 if (X86CC == X86::COND_B)
7136 return DAG.getNode(ISD::AND, dl, MVT::i8,
7137 DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
7138 DAG.getConstant(X86CC, MVT::i8), Cond),
7139 DAG.getConstant(1, MVT::i8));
7141 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7142 DAG.getConstant(X86CC, MVT::i8), Cond);
7145 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
7147 SDValue Op0 = Op.getOperand(0);
7148 SDValue Op1 = Op.getOperand(1);
7149 SDValue CC = Op.getOperand(2);
7150 EVT VT = Op.getValueType();
7151 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
7152 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
7153 DebugLoc dl = Op.getDebugLoc();
7157 EVT VT0 = Op0.getValueType();
7158 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
7159 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
7162 switch (SetCCOpcode) {
7165 case ISD::SETEQ: SSECC = 0; break;
7167 case ISD::SETGT: Swap = true; // Fallthrough
7169 case ISD::SETOLT: SSECC = 1; break;
7171 case ISD::SETGE: Swap = true; // Fallthrough
7173 case ISD::SETOLE: SSECC = 2; break;
7174 case ISD::SETUO: SSECC = 3; break;
7176 case ISD::SETNE: SSECC = 4; break;
7177 case ISD::SETULE: Swap = true;
7178 case ISD::SETUGE: SSECC = 5; break;
7179 case ISD::SETULT: Swap = true;
7180 case ISD::SETUGT: SSECC = 6; break;
7181 case ISD::SETO: SSECC = 7; break;
7184 std::swap(Op0, Op1);
7186 // In the two special cases we can't handle, emit two comparisons.
7188 if (SetCCOpcode == ISD::SETUEQ) {
7190 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
7191 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
7192 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
7194 else if (SetCCOpcode == ISD::SETONE) {
7196 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
7197 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
7198 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
7200 llvm_unreachable("Illegal FP comparison");
7202 // Handle all other FP comparisons here.
7203 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
7206 // We are handling one of the integer comparisons here. Since SSE only has
7207 // GT and EQ comparisons for integer, swapping operands and multiple
7208 // operations may be required for some comparisons.
7209 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
7210 bool Swap = false, Invert = false, FlipSigns = false;
7212 switch (VT.getSimpleVT().SimpleTy) {
7215 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
7217 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
7219 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
7220 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
7223 switch (SetCCOpcode) {
7225 case ISD::SETNE: Invert = true;
7226 case ISD::SETEQ: Opc = EQOpc; break;
7227 case ISD::SETLT: Swap = true;
7228 case ISD::SETGT: Opc = GTOpc; break;
7229 case ISD::SETGE: Swap = true;
7230 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
7231 case ISD::SETULT: Swap = true;
7232 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
7233 case ISD::SETUGE: Swap = true;
7234 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
7237 std::swap(Op0, Op1);
7239 // Since SSE has no unsigned integer comparisons, we need to flip the sign
7240 // bits of the inputs before performing those operations.
7242 EVT EltVT = VT.getVectorElementType();
7243 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
7245 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
7246 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
7248 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
7249 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
7252 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
7254 // If the logical-not of the result is required, perform that now.
7256 Result = DAG.getNOT(dl, Result, VT);
7261 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
7262 static bool isX86LogicalCmp(SDValue Op) {
7263 unsigned Opc = Op.getNode()->getOpcode();
7264 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
7266 if (Op.getResNo() == 1 &&
7267 (Opc == X86ISD::ADD ||
7268 Opc == X86ISD::SUB ||
7269 Opc == X86ISD::SMUL ||
7270 Opc == X86ISD::UMUL ||
7271 Opc == X86ISD::INC ||
7272 Opc == X86ISD::DEC ||
7273 Opc == X86ISD::OR ||
7274 Opc == X86ISD::XOR ||
7275 Opc == X86ISD::AND))
7281 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7282 bool addTest = true;
7283 SDValue Cond = Op.getOperand(0);
7284 DebugLoc dl = Op.getDebugLoc();
7287 if (Cond.getOpcode() == ISD::SETCC) {
7288 SDValue NewCond = LowerSETCC(Cond, DAG);
7289 if (NewCond.getNode())
7293 // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
7294 SDValue Op1 = Op.getOperand(1);
7295 SDValue Op2 = Op.getOperand(2);
7296 if (Cond.getOpcode() == X86ISD::SETCC &&
7297 cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
7298 SDValue Cmp = Cond.getOperand(1);
7299 if (Cmp.getOpcode() == X86ISD::CMP) {
7300 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
7301 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
7302 ConstantSDNode *RHSC =
7303 dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
7304 if (N1C && N1C->isAllOnesValue() &&
7305 N2C && N2C->isNullValue() &&
7306 RHSC && RHSC->isNullValue()) {
7307 SDValue CmpOp0 = Cmp.getOperand(0);
7308 Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
7309 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
7310 return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
7311 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
7316 // Look pass (and (setcc_carry (cmp ...)), 1).
7317 if (Cond.getOpcode() == ISD::AND &&
7318 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7319 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7320 if (C && C->getAPIntValue() == 1)
7321 Cond = Cond.getOperand(0);
7324 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7325 // setting operand in place of the X86ISD::SETCC.
7326 if (Cond.getOpcode() == X86ISD::SETCC ||
7327 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7328 CC = Cond.getOperand(0);
7330 SDValue Cmp = Cond.getOperand(1);
7331 unsigned Opc = Cmp.getOpcode();
7332 EVT VT = Op.getValueType();
7334 bool IllegalFPCMov = false;
7335 if (VT.isFloatingPoint() && !VT.isVector() &&
7336 !isScalarFPTypeInSSEReg(VT)) // FPStack?
7337 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
7339 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
7340 Opc == X86ISD::BT) { // FIXME
7347 // Look pass the truncate.
7348 if (Cond.getOpcode() == ISD::TRUNCATE)
7349 Cond = Cond.getOperand(0);
7351 // We know the result of AND is compared against zero. Try to match
7353 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7354 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7355 if (NewSetCC.getNode()) {
7356 CC = NewSetCC.getOperand(0);
7357 Cond = NewSetCC.getOperand(1);
7364 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7365 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7368 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
7369 // condition is true.
7370 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
7371 SDValue Ops[] = { Op2, Op1, CC, Cond };
7372 return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
7375 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
7376 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
7377 // from the AND / OR.
7378 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
7379 Opc = Op.getOpcode();
7380 if (Opc != ISD::OR && Opc != ISD::AND)
7382 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7383 Op.getOperand(0).hasOneUse() &&
7384 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
7385 Op.getOperand(1).hasOneUse());
7388 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
7389 // 1 and that the SETCC node has a single use.
7390 static bool isXor1OfSetCC(SDValue Op) {
7391 if (Op.getOpcode() != ISD::XOR)
7393 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7394 if (N1C && N1C->getAPIntValue() == 1) {
7395 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
7396 Op.getOperand(0).hasOneUse();
7401 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
7402 bool addTest = true;
7403 SDValue Chain = Op.getOperand(0);
7404 SDValue Cond = Op.getOperand(1);
7405 SDValue Dest = Op.getOperand(2);
7406 DebugLoc dl = Op.getDebugLoc();
7409 if (Cond.getOpcode() == ISD::SETCC) {
7410 SDValue NewCond = LowerSETCC(Cond, DAG);
7411 if (NewCond.getNode())
7415 // FIXME: LowerXALUO doesn't handle these!!
7416 else if (Cond.getOpcode() == X86ISD::ADD ||
7417 Cond.getOpcode() == X86ISD::SUB ||
7418 Cond.getOpcode() == X86ISD::SMUL ||
7419 Cond.getOpcode() == X86ISD::UMUL)
7420 Cond = LowerXALUO(Cond, DAG);
7423 // Look pass (and (setcc_carry (cmp ...)), 1).
7424 if (Cond.getOpcode() == ISD::AND &&
7425 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
7426 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
7427 if (C && C->getAPIntValue() == 1)
7428 Cond = Cond.getOperand(0);
7431 // If condition flag is set by a X86ISD::CMP, then use it as the condition
7432 // setting operand in place of the X86ISD::SETCC.
7433 if (Cond.getOpcode() == X86ISD::SETCC ||
7434 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
7435 CC = Cond.getOperand(0);
7437 SDValue Cmp = Cond.getOperand(1);
7438 unsigned Opc = Cmp.getOpcode();
7439 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
7440 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
7444 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
7448 // These can only come from an arithmetic instruction with overflow,
7449 // e.g. SADDO, UADDO.
7450 Cond = Cond.getNode()->getOperand(1);
7457 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
7458 SDValue Cmp = Cond.getOperand(0).getOperand(1);
7459 if (CondOpc == ISD::OR) {
7460 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
7461 // two branches instead of an explicit OR instruction with a
7463 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7464 isX86LogicalCmp(Cmp)) {
7465 CC = Cond.getOperand(0).getOperand(0);
7466 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7467 Chain, Dest, CC, Cmp);
7468 CC = Cond.getOperand(1).getOperand(0);
7472 } else { // ISD::AND
7473 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
7474 // two branches instead of an explicit AND instruction with a
7475 // separate test. However, we only do this if this block doesn't
7476 // have a fall-through edge, because this requires an explicit
7477 // jmp when the condition is false.
7478 if (Cmp == Cond.getOperand(1).getOperand(1) &&
7479 isX86LogicalCmp(Cmp) &&
7480 Op.getNode()->hasOneUse()) {
7481 X86::CondCode CCode =
7482 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7483 CCode = X86::GetOppositeBranchCondition(CCode);
7484 CC = DAG.getConstant(CCode, MVT::i8);
7485 SDNode *User = *Op.getNode()->use_begin();
7486 // Look for an unconditional branch following this conditional branch.
7487 // We need this because we need to reverse the successors in order
7488 // to implement FCMP_OEQ.
7489 if (User->getOpcode() == ISD::BR) {
7490 SDValue FalseBB = User->getOperand(1);
7492 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
7493 assert(NewBR == User);
7497 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7498 Chain, Dest, CC, Cmp);
7499 X86::CondCode CCode =
7500 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
7501 CCode = X86::GetOppositeBranchCondition(CCode);
7502 CC = DAG.getConstant(CCode, MVT::i8);
7508 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
7509 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
7510 // It should be transformed during dag combiner except when the condition
7511 // is set by a arithmetics with overflow node.
7512 X86::CondCode CCode =
7513 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
7514 CCode = X86::GetOppositeBranchCondition(CCode);
7515 CC = DAG.getConstant(CCode, MVT::i8);
7516 Cond = Cond.getOperand(0).getOperand(1);
7522 // Look pass the truncate.
7523 if (Cond.getOpcode() == ISD::TRUNCATE)
7524 Cond = Cond.getOperand(0);
7526 // We know the result of AND is compared against zero. Try to match
7528 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
7529 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
7530 if (NewSetCC.getNode()) {
7531 CC = NewSetCC.getOperand(0);
7532 Cond = NewSetCC.getOperand(1);
7539 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
7540 Cond = EmitTest(Cond, X86::COND_NE, DAG);
7542 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
7543 Chain, Dest, CC, Cond);
7547 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
7548 // Calls to _alloca is needed to probe the stack when allocating more than 4k
7549 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
7550 // that the guard pages used by the OS virtual memory manager are allocated in
7551 // correct sequence.
7553 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
7554 SelectionDAG &DAG) const {
7555 assert(Subtarget->isTargetCygMing() &&
7556 "This should be used only on Cygwin/Mingw targets");
7557 DebugLoc dl = Op.getDebugLoc();
7560 SDValue Chain = Op.getOperand(0);
7561 SDValue Size = Op.getOperand(1);
7562 // FIXME: Ensure alignment here
7566 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
7568 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
7569 Flag = Chain.getValue(1);
7571 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
7573 Chain = DAG.getNode(X86ISD::MINGW_ALLOCA, dl, NodeTys, Chain, Flag);
7574 Flag = Chain.getValue(1);
7576 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
7578 SDValue Ops1[2] = { Chain.getValue(0), Chain };
7579 return DAG.getMergeValues(Ops1, 2, dl);
7582 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
7583 MachineFunction &MF = DAG.getMachineFunction();
7584 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
7586 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
7587 DebugLoc DL = Op.getDebugLoc();
7589 if (!Subtarget->is64Bit()) {
7590 // vastart just stores the address of the VarArgsFrameIndex slot into the
7591 // memory location argument.
7592 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7594 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
7595 MachinePointerInfo(SV), false, false, 0);
7599 // gp_offset (0 - 6 * 8)
7600 // fp_offset (48 - 48 + 8 * 16)
7601 // overflow_arg_area (point to parameters coming in memory).
7603 SmallVector<SDValue, 8> MemOps;
7604 SDValue FIN = Op.getOperand(1);
7606 SDValue Store = DAG.getStore(Op.getOperand(0), DL,
7607 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
7609 FIN, MachinePointerInfo(SV), false, false, 0);
7610 MemOps.push_back(Store);
7613 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7614 FIN, DAG.getIntPtrConstant(4));
7615 Store = DAG.getStore(Op.getOperand(0), DL,
7616 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
7618 FIN, MachinePointerInfo(SV, 4), false, false, 0);
7619 MemOps.push_back(Store);
7621 // Store ptr to overflow_arg_area
7622 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7623 FIN, DAG.getIntPtrConstant(4));
7624 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
7626 Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
7627 MachinePointerInfo(SV, 8),
7629 MemOps.push_back(Store);
7631 // Store ptr to reg_save_area.
7632 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
7633 FIN, DAG.getIntPtrConstant(8));
7634 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
7636 Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
7637 MachinePointerInfo(SV, 16), false, false, 0);
7638 MemOps.push_back(Store);
7639 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
7640 &MemOps[0], MemOps.size());
7643 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
7644 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
7645 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
7647 report_fatal_error("VAArgInst is not yet implemented for x86-64!");
7651 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
7652 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
7653 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
7654 SDValue Chain = Op.getOperand(0);
7655 SDValue DstPtr = Op.getOperand(1);
7656 SDValue SrcPtr = Op.getOperand(2);
7657 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
7658 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7659 DebugLoc DL = Op.getDebugLoc();
7661 return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
7662 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
7664 MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
7668 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
7669 DebugLoc dl = Op.getDebugLoc();
7670 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7672 default: return SDValue(); // Don't custom lower most intrinsics.
7673 // Comparison intrinsics.
7674 case Intrinsic::x86_sse_comieq_ss:
7675 case Intrinsic::x86_sse_comilt_ss:
7676 case Intrinsic::x86_sse_comile_ss:
7677 case Intrinsic::x86_sse_comigt_ss:
7678 case Intrinsic::x86_sse_comige_ss:
7679 case Intrinsic::x86_sse_comineq_ss:
7680 case Intrinsic::x86_sse_ucomieq_ss:
7681 case Intrinsic::x86_sse_ucomilt_ss:
7682 case Intrinsic::x86_sse_ucomile_ss:
7683 case Intrinsic::x86_sse_ucomigt_ss:
7684 case Intrinsic::x86_sse_ucomige_ss:
7685 case Intrinsic::x86_sse_ucomineq_ss:
7686 case Intrinsic::x86_sse2_comieq_sd:
7687 case Intrinsic::x86_sse2_comilt_sd:
7688 case Intrinsic::x86_sse2_comile_sd:
7689 case Intrinsic::x86_sse2_comigt_sd:
7690 case Intrinsic::x86_sse2_comige_sd:
7691 case Intrinsic::x86_sse2_comineq_sd:
7692 case Intrinsic::x86_sse2_ucomieq_sd:
7693 case Intrinsic::x86_sse2_ucomilt_sd:
7694 case Intrinsic::x86_sse2_ucomile_sd:
7695 case Intrinsic::x86_sse2_ucomigt_sd:
7696 case Intrinsic::x86_sse2_ucomige_sd:
7697 case Intrinsic::x86_sse2_ucomineq_sd: {
7699 ISD::CondCode CC = ISD::SETCC_INVALID;
7702 case Intrinsic::x86_sse_comieq_ss:
7703 case Intrinsic::x86_sse2_comieq_sd:
7707 case Intrinsic::x86_sse_comilt_ss:
7708 case Intrinsic::x86_sse2_comilt_sd:
7712 case Intrinsic::x86_sse_comile_ss:
7713 case Intrinsic::x86_sse2_comile_sd:
7717 case Intrinsic::x86_sse_comigt_ss:
7718 case Intrinsic::x86_sse2_comigt_sd:
7722 case Intrinsic::x86_sse_comige_ss:
7723 case Intrinsic::x86_sse2_comige_sd:
7727 case Intrinsic::x86_sse_comineq_ss:
7728 case Intrinsic::x86_sse2_comineq_sd:
7732 case Intrinsic::x86_sse_ucomieq_ss:
7733 case Intrinsic::x86_sse2_ucomieq_sd:
7734 Opc = X86ISD::UCOMI;
7737 case Intrinsic::x86_sse_ucomilt_ss:
7738 case Intrinsic::x86_sse2_ucomilt_sd:
7739 Opc = X86ISD::UCOMI;
7742 case Intrinsic::x86_sse_ucomile_ss:
7743 case Intrinsic::x86_sse2_ucomile_sd:
7744 Opc = X86ISD::UCOMI;
7747 case Intrinsic::x86_sse_ucomigt_ss:
7748 case Intrinsic::x86_sse2_ucomigt_sd:
7749 Opc = X86ISD::UCOMI;
7752 case Intrinsic::x86_sse_ucomige_ss:
7753 case Intrinsic::x86_sse2_ucomige_sd:
7754 Opc = X86ISD::UCOMI;
7757 case Intrinsic::x86_sse_ucomineq_ss:
7758 case Intrinsic::x86_sse2_ucomineq_sd:
7759 Opc = X86ISD::UCOMI;
7764 SDValue LHS = Op.getOperand(1);
7765 SDValue RHS = Op.getOperand(2);
7766 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
7767 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
7768 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
7769 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
7770 DAG.getConstant(X86CC, MVT::i8), Cond);
7771 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7773 // ptest and testp intrinsics. The intrinsic these come from are designed to
7774 // return an integer value, not just an instruction so lower it to the ptest
7775 // or testp pattern and a setcc for the result.
7776 case Intrinsic::x86_sse41_ptestz:
7777 case Intrinsic::x86_sse41_ptestc:
7778 case Intrinsic::x86_sse41_ptestnzc:
7779 case Intrinsic::x86_avx_ptestz_256:
7780 case Intrinsic::x86_avx_ptestc_256:
7781 case Intrinsic::x86_avx_ptestnzc_256:
7782 case Intrinsic::x86_avx_vtestz_ps:
7783 case Intrinsic::x86_avx_vtestc_ps:
7784 case Intrinsic::x86_avx_vtestnzc_ps:
7785 case Intrinsic::x86_avx_vtestz_pd:
7786 case Intrinsic::x86_avx_vtestc_pd:
7787 case Intrinsic::x86_avx_vtestnzc_pd:
7788 case Intrinsic::x86_avx_vtestz_ps_256:
7789 case Intrinsic::x86_avx_vtestc_ps_256:
7790 case Intrinsic::x86_avx_vtestnzc_ps_256:
7791 case Intrinsic::x86_avx_vtestz_pd_256:
7792 case Intrinsic::x86_avx_vtestc_pd_256:
7793 case Intrinsic::x86_avx_vtestnzc_pd_256: {
7794 bool IsTestPacked = false;
7797 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
7798 case Intrinsic::x86_avx_vtestz_ps:
7799 case Intrinsic::x86_avx_vtestz_pd:
7800 case Intrinsic::x86_avx_vtestz_ps_256:
7801 case Intrinsic::x86_avx_vtestz_pd_256:
7802 IsTestPacked = true; // Fallthrough
7803 case Intrinsic::x86_sse41_ptestz:
7804 case Intrinsic::x86_avx_ptestz_256:
7806 X86CC = X86::COND_E;
7808 case Intrinsic::x86_avx_vtestc_ps:
7809 case Intrinsic::x86_avx_vtestc_pd:
7810 case Intrinsic::x86_avx_vtestc_ps_256:
7811 case Intrinsic::x86_avx_vtestc_pd_256:
7812 IsTestPacked = true; // Fallthrough
7813 case Intrinsic::x86_sse41_ptestc:
7814 case Intrinsic::x86_avx_ptestc_256:
7816 X86CC = X86::COND_B;
7818 case Intrinsic::x86_avx_vtestnzc_ps:
7819 case Intrinsic::x86_avx_vtestnzc_pd:
7820 case Intrinsic::x86_avx_vtestnzc_ps_256:
7821 case Intrinsic::x86_avx_vtestnzc_pd_256:
7822 IsTestPacked = true; // Fallthrough
7823 case Intrinsic::x86_sse41_ptestnzc:
7824 case Intrinsic::x86_avx_ptestnzc_256:
7826 X86CC = X86::COND_A;
7830 SDValue LHS = Op.getOperand(1);
7831 SDValue RHS = Op.getOperand(2);
7832 unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
7833 SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
7834 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
7835 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
7836 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
7839 // Fix vector shift instructions where the last operand is a non-immediate
7841 case Intrinsic::x86_sse2_pslli_w:
7842 case Intrinsic::x86_sse2_pslli_d:
7843 case Intrinsic::x86_sse2_pslli_q:
7844 case Intrinsic::x86_sse2_psrli_w:
7845 case Intrinsic::x86_sse2_psrli_d:
7846 case Intrinsic::x86_sse2_psrli_q:
7847 case Intrinsic::x86_sse2_psrai_w:
7848 case Intrinsic::x86_sse2_psrai_d:
7849 case Intrinsic::x86_mmx_pslli_w:
7850 case Intrinsic::x86_mmx_pslli_d:
7851 case Intrinsic::x86_mmx_pslli_q:
7852 case Intrinsic::x86_mmx_psrli_w:
7853 case Intrinsic::x86_mmx_psrli_d:
7854 case Intrinsic::x86_mmx_psrli_q:
7855 case Intrinsic::x86_mmx_psrai_w:
7856 case Intrinsic::x86_mmx_psrai_d: {
7857 SDValue ShAmt = Op.getOperand(2);
7858 if (isa<ConstantSDNode>(ShAmt))
7861 unsigned NewIntNo = 0;
7862 EVT ShAmtVT = MVT::v4i32;
7864 case Intrinsic::x86_sse2_pslli_w:
7865 NewIntNo = Intrinsic::x86_sse2_psll_w;
7867 case Intrinsic::x86_sse2_pslli_d:
7868 NewIntNo = Intrinsic::x86_sse2_psll_d;
7870 case Intrinsic::x86_sse2_pslli_q:
7871 NewIntNo = Intrinsic::x86_sse2_psll_q;
7873 case Intrinsic::x86_sse2_psrli_w:
7874 NewIntNo = Intrinsic::x86_sse2_psrl_w;
7876 case Intrinsic::x86_sse2_psrli_d:
7877 NewIntNo = Intrinsic::x86_sse2_psrl_d;
7879 case Intrinsic::x86_sse2_psrli_q:
7880 NewIntNo = Intrinsic::x86_sse2_psrl_q;
7882 case Intrinsic::x86_sse2_psrai_w:
7883 NewIntNo = Intrinsic::x86_sse2_psra_w;
7885 case Intrinsic::x86_sse2_psrai_d:
7886 NewIntNo = Intrinsic::x86_sse2_psra_d;
7889 ShAmtVT = MVT::v2i32;
7891 case Intrinsic::x86_mmx_pslli_w:
7892 NewIntNo = Intrinsic::x86_mmx_psll_w;
7894 case Intrinsic::x86_mmx_pslli_d:
7895 NewIntNo = Intrinsic::x86_mmx_psll_d;
7897 case Intrinsic::x86_mmx_pslli_q:
7898 NewIntNo = Intrinsic::x86_mmx_psll_q;
7900 case Intrinsic::x86_mmx_psrli_w:
7901 NewIntNo = Intrinsic::x86_mmx_psrl_w;
7903 case Intrinsic::x86_mmx_psrli_d:
7904 NewIntNo = Intrinsic::x86_mmx_psrl_d;
7906 case Intrinsic::x86_mmx_psrli_q:
7907 NewIntNo = Intrinsic::x86_mmx_psrl_q;
7909 case Intrinsic::x86_mmx_psrai_w:
7910 NewIntNo = Intrinsic::x86_mmx_psra_w;
7912 case Intrinsic::x86_mmx_psrai_d:
7913 NewIntNo = Intrinsic::x86_mmx_psra_d;
7915 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7921 // The vector shift intrinsics with scalars uses 32b shift amounts but
7922 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
7926 ShOps[1] = DAG.getConstant(0, MVT::i32);
7927 if (ShAmtVT == MVT::v4i32) {
7928 ShOps[2] = DAG.getUNDEF(MVT::i32);
7929 ShOps[3] = DAG.getUNDEF(MVT::i32);
7930 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
7932 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
7935 EVT VT = Op.getValueType();
7936 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
7937 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7938 DAG.getConstant(NewIntNo, MVT::i32),
7939 Op.getOperand(1), ShAmt);
7944 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
7945 SelectionDAG &DAG) const {
7946 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7947 MFI->setReturnAddressIsTaken(true);
7949 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7950 DebugLoc dl = Op.getDebugLoc();
7953 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7955 DAG.getConstant(TD->getPointerSize(),
7956 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
7957 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7958 DAG.getNode(ISD::ADD, dl, getPointerTy(),
7960 MachinePointerInfo(), false, false, 0);
7963 // Just load the return address.
7964 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
7965 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7966 RetAddrFI, MachinePointerInfo(), false, false, 0);
7969 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
7970 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7971 MFI->setFrameAddressIsTaken(true);
7973 EVT VT = Op.getValueType();
7974 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
7975 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7976 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
7977 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
7979 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
7980 MachinePointerInfo(),
7985 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
7986 SelectionDAG &DAG) const {
7987 return DAG.getIntPtrConstant(2*TD->getPointerSize());
7990 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
7991 MachineFunction &MF = DAG.getMachineFunction();
7992 SDValue Chain = Op.getOperand(0);
7993 SDValue Offset = Op.getOperand(1);
7994 SDValue Handler = Op.getOperand(2);
7995 DebugLoc dl = Op.getDebugLoc();
7997 SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
7998 Subtarget->is64Bit() ? X86::RBP : X86::EBP,
8000 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
8002 SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), Frame,
8003 DAG.getIntPtrConstant(TD->getPointerSize()));
8004 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
8005 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
8007 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
8008 MF.getRegInfo().addLiveOut(StoreAddrReg);
8010 return DAG.getNode(X86ISD::EH_RETURN, dl,
8012 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
8015 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
8016 SelectionDAG &DAG) const {
8017 SDValue Root = Op.getOperand(0);
8018 SDValue Trmp = Op.getOperand(1); // trampoline
8019 SDValue FPtr = Op.getOperand(2); // nested function
8020 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
8021 DebugLoc dl = Op.getDebugLoc();
8023 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
8025 if (Subtarget->is64Bit()) {
8026 SDValue OutChains[6];
8028 // Large code-model.
8029 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
8030 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
8032 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
8033 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
8035 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
8037 // Load the pointer to the nested function into R11.
8038 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
8039 SDValue Addr = Trmp;
8040 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8041 Addr, MachinePointerInfo(TrmpAddr),
8044 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8045 DAG.getConstant(2, MVT::i64));
8046 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
8047 MachinePointerInfo(TrmpAddr, 2),
8050 // Load the 'nest' parameter value into R10.
8051 // R10 is specified in X86CallingConv.td
8052 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
8053 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8054 DAG.getConstant(10, MVT::i64));
8055 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8056 Addr, MachinePointerInfo(TrmpAddr, 10),
8059 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8060 DAG.getConstant(12, MVT::i64));
8061 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
8062 MachinePointerInfo(TrmpAddr, 12),
8065 // Jump to the nested function.
8066 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
8067 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8068 DAG.getConstant(20, MVT::i64));
8069 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
8070 Addr, MachinePointerInfo(TrmpAddr, 20),
8073 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
8074 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
8075 DAG.getConstant(22, MVT::i64));
8076 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
8077 MachinePointerInfo(TrmpAddr, 22),
8081 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
8082 return DAG.getMergeValues(Ops, 2, dl);
8084 const Function *Func =
8085 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
8086 CallingConv::ID CC = Func->getCallingConv();
8091 llvm_unreachable("Unsupported calling convention");
8092 case CallingConv::C:
8093 case CallingConv::X86_StdCall: {
8094 // Pass 'nest' parameter in ECX.
8095 // Must be kept in sync with X86CallingConv.td
8098 // Check that ECX wasn't needed by an 'inreg' parameter.
8099 const FunctionType *FTy = Func->getFunctionType();
8100 const AttrListPtr &Attrs = Func->getAttributes();
8102 if (!Attrs.isEmpty() && !Func->isVarArg()) {
8103 unsigned InRegCount = 0;
8106 for (FunctionType::param_iterator I = FTy->param_begin(),
8107 E = FTy->param_end(); I != E; ++I, ++Idx)
8108 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
8109 // FIXME: should only count parameters that are lowered to integers.
8110 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
8112 if (InRegCount > 2) {
8113 report_fatal_error("Nest register in use - reduce number of inreg"
8119 case CallingConv::X86_FastCall:
8120 case CallingConv::X86_ThisCall:
8121 case CallingConv::Fast:
8122 // Pass 'nest' parameter in EAX.
8123 // Must be kept in sync with X86CallingConv.td
8128 SDValue OutChains[4];
8131 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8132 DAG.getConstant(10, MVT::i32));
8133 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
8135 // This is storing the opcode for MOV32ri.
8136 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
8137 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
8138 OutChains[0] = DAG.getStore(Root, dl,
8139 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
8140 Trmp, MachinePointerInfo(TrmpAddr),
8143 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8144 DAG.getConstant(1, MVT::i32));
8145 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
8146 MachinePointerInfo(TrmpAddr, 1),
8149 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
8150 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8151 DAG.getConstant(5, MVT::i32));
8152 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
8153 MachinePointerInfo(TrmpAddr, 5),
8156 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
8157 DAG.getConstant(6, MVT::i32));
8158 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
8159 MachinePointerInfo(TrmpAddr, 6),
8163 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
8164 return DAG.getMergeValues(Ops, 2, dl);
8168 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
8169 SelectionDAG &DAG) const {
8171 The rounding mode is in bits 11:10 of FPSR, and has the following
8178 FLT_ROUNDS, on the other hand, expects the following:
8185 To perform the conversion, we do:
8186 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
8189 MachineFunction &MF = DAG.getMachineFunction();
8190 const TargetMachine &TM = MF.getTarget();
8191 const TargetFrameInfo &TFI = *TM.getFrameInfo();
8192 unsigned StackAlignment = TFI.getStackAlignment();
8193 EVT VT = Op.getValueType();
8194 DebugLoc DL = Op.getDebugLoc();
8196 // Save FP Control Word to stack slot
8197 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
8198 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
8201 MachineMemOperand *MMO =
8202 MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
8203 MachineMemOperand::MOStore, 2, 2);
8205 SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
8206 SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
8207 DAG.getVTList(MVT::Other),
8208 Ops, 2, MVT::i16, MMO);
8210 // Load FP Control Word from stack slot
8211 SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
8212 MachinePointerInfo(), false, false, 0);
8214 // Transform as necessary
8216 DAG.getNode(ISD::SRL, DL, MVT::i16,
8217 DAG.getNode(ISD::AND, DL, MVT::i16,
8218 CWD, DAG.getConstant(0x800, MVT::i16)),
8219 DAG.getConstant(11, MVT::i8));
8221 DAG.getNode(ISD::SRL, DL, MVT::i16,
8222 DAG.getNode(ISD::AND, DL, MVT::i16,
8223 CWD, DAG.getConstant(0x400, MVT::i16)),
8224 DAG.getConstant(9, MVT::i8));
8227 DAG.getNode(ISD::AND, DL, MVT::i16,
8228 DAG.getNode(ISD::ADD, DL, MVT::i16,
8229 DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
8230 DAG.getConstant(1, MVT::i16)),
8231 DAG.getConstant(3, MVT::i16));
8234 return DAG.getNode((VT.getSizeInBits() < 16 ?
8235 ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
8238 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
8239 EVT VT = Op.getValueType();
8241 unsigned NumBits = VT.getSizeInBits();
8242 DebugLoc dl = Op.getDebugLoc();
8244 Op = Op.getOperand(0);
8245 if (VT == MVT::i8) {
8246 // Zero extend to i32 since there is not an i8 bsr.
8248 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8251 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
8252 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8253 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
8255 // If src is zero (i.e. bsr sets ZF), returns NumBits.
8258 DAG.getConstant(NumBits+NumBits-1, OpVT),
8259 DAG.getConstant(X86::COND_E, MVT::i8),
8262 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8264 // Finally xor with NumBits-1.
8265 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
8268 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8272 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
8273 EVT VT = Op.getValueType();
8275 unsigned NumBits = VT.getSizeInBits();
8276 DebugLoc dl = Op.getDebugLoc();
8278 Op = Op.getOperand(0);
8279 if (VT == MVT::i8) {
8281 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
8284 // Issue a bsf (scan bits forward) which also sets EFLAGS.
8285 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
8286 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
8288 // If src is zero (i.e. bsf sets ZF), returns NumBits.
8291 DAG.getConstant(NumBits, OpVT),
8292 DAG.getConstant(X86::COND_E, MVT::i8),
8295 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
8298 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
8302 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
8303 EVT VT = Op.getValueType();
8304 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
8305 DebugLoc dl = Op.getDebugLoc();
8307 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
8308 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
8309 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
8310 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
8311 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
8313 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
8314 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
8315 // return AloBlo + AloBhi + AhiBlo;
8317 SDValue A = Op.getOperand(0);
8318 SDValue B = Op.getOperand(1);
8320 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8321 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8322 A, DAG.getConstant(32, MVT::i32));
8323 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8324 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8325 B, DAG.getConstant(32, MVT::i32));
8326 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8327 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8329 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8330 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8332 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8333 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
8335 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8336 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8337 AloBhi, DAG.getConstant(32, MVT::i32));
8338 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8339 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8340 AhiBlo, DAG.getConstant(32, MVT::i32));
8341 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
8342 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
8346 SDValue X86TargetLowering::LowerSHL(SDValue Op, SelectionDAG &DAG) const {
8347 EVT VT = Op.getValueType();
8348 DebugLoc dl = Op.getDebugLoc();
8349 SDValue R = Op.getOperand(0);
8351 LLVMContext *Context = DAG.getContext();
8353 assert(Subtarget->hasSSE41() && "Cannot lower SHL without SSE4.1 or later");
8355 if (VT == MVT::v4i32) {
8356 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8357 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8358 Op.getOperand(1), DAG.getConstant(23, MVT::i32));
8360 ConstantInt *CI = ConstantInt::get(*Context, APInt(32, 0x3f800000U));
8362 std::vector<Constant*> CV(4, CI);
8363 Constant *C = ConstantVector::get(CV);
8364 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8365 SDValue Addend = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8366 MachinePointerInfo::getConstantPool(),
8369 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Addend);
8370 Op = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, Op);
8371 Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
8372 return DAG.getNode(ISD::MUL, dl, VT, Op, R);
8374 if (VT == MVT::v16i8) {
8376 Op = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8377 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8378 Op.getOperand(1), DAG.getConstant(5, MVT::i32));
8380 ConstantInt *CM1 = ConstantInt::get(*Context, APInt(8, 15));
8381 ConstantInt *CM2 = ConstantInt::get(*Context, APInt(8, 63));
8383 std::vector<Constant*> CVM1(16, CM1);
8384 std::vector<Constant*> CVM2(16, CM2);
8385 Constant *C = ConstantVector::get(CVM1);
8386 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8387 SDValue M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8388 MachinePointerInfo::getConstantPool(),
8391 // r = pblendv(r, psllw(r & (char16)15, 4), a);
8392 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8393 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8394 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8395 DAG.getConstant(4, MVT::i32));
8396 R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8397 DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8400 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8402 C = ConstantVector::get(CVM2);
8403 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
8404 M = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
8405 MachinePointerInfo::getConstantPool(),
8408 // r = pblendv(r, psllw(r & (char16)63, 2), a);
8409 M = DAG.getNode(ISD::AND, dl, VT, R, M);
8410 M = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8411 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32), M,
8412 DAG.getConstant(2, MVT::i32));
8413 R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8414 DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8417 Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
8419 // return pblendv(r, r+r, a);
8420 R = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
8421 DAG.getConstant(Intrinsic::x86_sse41_pblendvb, MVT::i32),
8422 R, DAG.getNode(ISD::ADD, dl, VT, R, R), Op);
8428 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
8429 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
8430 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
8431 // looks for this combo and may remove the "setcc" instruction if the "setcc"
8432 // has only one use.
8433 SDNode *N = Op.getNode();
8434 SDValue LHS = N->getOperand(0);
8435 SDValue RHS = N->getOperand(1);
8436 unsigned BaseOp = 0;
8438 DebugLoc dl = Op.getDebugLoc();
8440 switch (Op.getOpcode()) {
8441 default: llvm_unreachable("Unknown ovf instruction!");
8443 // A subtract of one will be selected as a INC. Note that INC doesn't
8444 // set CF, so we can't do this for UADDO.
8445 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8446 if (C->getAPIntValue() == 1) {
8447 BaseOp = X86ISD::INC;
8451 BaseOp = X86ISD::ADD;
8455 BaseOp = X86ISD::ADD;
8459 // A subtract of one will be selected as a DEC. Note that DEC doesn't
8460 // set CF, so we can't do this for USUBO.
8461 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
8462 if (C->getAPIntValue() == 1) {
8463 BaseOp = X86ISD::DEC;
8467 BaseOp = X86ISD::SUB;
8471 BaseOp = X86ISD::SUB;
8475 BaseOp = X86ISD::SMUL;
8479 BaseOp = X86ISD::UMUL;
8484 // Also sets EFLAGS.
8485 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
8486 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
8489 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
8490 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
8492 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
8496 SDValue X86TargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const{
8497 DebugLoc dl = Op.getDebugLoc();
8499 if (!Subtarget->hasSSE2()) {
8500 SDValue Chain = Op.getOperand(0);
8501 SDValue Zero = DAG.getConstant(0,
8502 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
8504 DAG.getRegister(X86::ESP, MVT::i32), // Base
8505 DAG.getTargetConstant(1, MVT::i8), // Scale
8506 DAG.getRegister(0, MVT::i32), // Index
8507 DAG.getTargetConstant(0, MVT::i32), // Disp
8508 DAG.getRegister(0, MVT::i32), // Segment.
8513 DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops,
8514 array_lengthof(Ops));
8515 return SDValue(Res, 0);
8518 unsigned isDev = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
8520 return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
8522 unsigned Op1 = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8523 unsigned Op2 = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
8524 unsigned Op3 = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
8525 unsigned Op4 = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
8527 // def : Pat<(membarrier (i8 0), (i8 0), (i8 0), (i8 1), (i8 1)), (SFENCE)>;
8528 if (!Op1 && !Op2 && !Op3 && Op4)
8529 return DAG.getNode(X86ISD::SFENCE, dl, MVT::Other, Op.getOperand(0));
8531 // def : Pat<(membarrier (i8 1), (i8 0), (i8 0), (i8 0), (i8 1)), (LFENCE)>;
8532 if (Op1 && !Op2 && !Op3 && !Op4)
8533 return DAG.getNode(X86ISD::LFENCE, dl, MVT::Other, Op.getOperand(0));
8535 // def : Pat<(membarrier (i8 imm), (i8 imm), (i8 imm), (i8 imm), (i8 1)),
8537 return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
8540 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8541 EVT T = Op.getValueType();
8542 DebugLoc DL = Op.getDebugLoc();
8545 switch(T.getSimpleVT().SimpleTy) {
8547 assert(false && "Invalid value type!");
8548 case MVT::i8: Reg = X86::AL; size = 1; break;
8549 case MVT::i16: Reg = X86::AX; size = 2; break;
8550 case MVT::i32: Reg = X86::EAX; size = 4; break;
8552 assert(Subtarget->is64Bit() && "Node not type legal!");
8553 Reg = X86::RAX; size = 8;
8556 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
8557 Op.getOperand(2), SDValue());
8558 SDValue Ops[] = { cpIn.getValue(0),
8561 DAG.getTargetConstant(size, MVT::i8),
8563 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8564 MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
8565 SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
8568 DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
8572 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
8573 SelectionDAG &DAG) const {
8574 assert(Subtarget->is64Bit() && "Result not type legalized?");
8575 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8576 SDValue TheChain = Op.getOperand(0);
8577 DebugLoc dl = Op.getDebugLoc();
8578 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8579 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
8580 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
8582 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
8583 DAG.getConstant(32, MVT::i8));
8585 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
8588 return DAG.getMergeValues(Ops, 2, dl);
8591 SDValue X86TargetLowering::LowerBIT_CONVERT(SDValue Op,
8592 SelectionDAG &DAG) const {
8593 EVT SrcVT = Op.getOperand(0).getValueType();
8594 EVT DstVT = Op.getValueType();
8595 assert((Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
8596 Subtarget->hasMMX() && !DisableMMX) &&
8597 "Unexpected custom BIT_CONVERT");
8598 assert((DstVT == MVT::i64 ||
8599 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
8600 "Unexpected custom BIT_CONVERT");
8601 // i64 <=> MMX conversions are Legal.
8602 if (SrcVT==MVT::i64 && DstVT.isVector())
8604 if (DstVT==MVT::i64 && SrcVT.isVector())
8606 // MMX <=> MMX conversions are Legal.
8607 if (SrcVT.isVector() && DstVT.isVector())
8609 // All other conversions need to be expanded.
8612 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
8613 SDNode *Node = Op.getNode();
8614 DebugLoc dl = Node->getDebugLoc();
8615 EVT T = Node->getValueType(0);
8616 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
8617 DAG.getConstant(0, T), Node->getOperand(2));
8618 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
8619 cast<AtomicSDNode>(Node)->getMemoryVT(),
8620 Node->getOperand(0),
8621 Node->getOperand(1), negOp,
8622 cast<AtomicSDNode>(Node)->getSrcValue(),
8623 cast<AtomicSDNode>(Node)->getAlignment());
8626 /// LowerOperation - Provide custom lowering hooks for some operations.
8628 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8629 switch (Op.getOpcode()) {
8630 default: llvm_unreachable("Should not custom lower this!");
8631 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op,DAG);
8632 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
8633 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
8634 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
8635 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
8636 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
8637 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8638 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
8639 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
8640 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
8641 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
8642 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
8643 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
8644 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
8645 case ISD::SHL_PARTS:
8646 case ISD::SRA_PARTS:
8647 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
8648 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
8649 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
8650 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
8651 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
8652 case ISD::FABS: return LowerFABS(Op, DAG);
8653 case ISD::FNEG: return LowerFNEG(Op, DAG);
8654 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
8655 case ISD::SETCC: return LowerSETCC(Op, DAG);
8656 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
8657 case ISD::SELECT: return LowerSELECT(Op, DAG);
8658 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
8659 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
8660 case ISD::VASTART: return LowerVASTART(Op, DAG);
8661 case ISD::VAARG: return LowerVAARG(Op, DAG);
8662 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
8663 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
8664 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
8665 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
8666 case ISD::FRAME_TO_ARGS_OFFSET:
8667 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
8668 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
8669 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
8670 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
8671 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
8672 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
8673 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
8674 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
8675 case ISD::SHL: return LowerSHL(Op, DAG);
8681 case ISD::UMULO: return LowerXALUO(Op, DAG);
8682 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
8683 case ISD::BIT_CONVERT: return LowerBIT_CONVERT(Op, DAG);
8687 void X86TargetLowering::
8688 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
8689 SelectionDAG &DAG, unsigned NewOp) const {
8690 EVT T = Node->getValueType(0);
8691 DebugLoc dl = Node->getDebugLoc();
8692 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
8694 SDValue Chain = Node->getOperand(0);
8695 SDValue In1 = Node->getOperand(1);
8696 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8697 Node->getOperand(2), DAG.getIntPtrConstant(0));
8698 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8699 Node->getOperand(2), DAG.getIntPtrConstant(1));
8700 SDValue Ops[] = { Chain, In1, In2L, In2H };
8701 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
8703 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
8704 cast<MemSDNode>(Node)->getMemOperand());
8705 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
8706 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8707 Results.push_back(Result.getValue(2));
8710 /// ReplaceNodeResults - Replace a node with an illegal result type
8711 /// with a new node built out of custom code.
8712 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
8713 SmallVectorImpl<SDValue>&Results,
8714 SelectionDAG &DAG) const {
8715 DebugLoc dl = N->getDebugLoc();
8716 switch (N->getOpcode()) {
8718 assert(false && "Do not know how to custom type legalize this operation!");
8720 case ISD::FP_TO_SINT: {
8721 std::pair<SDValue,SDValue> Vals =
8722 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
8723 SDValue FIST = Vals.first, StackSlot = Vals.second;
8724 if (FIST.getNode() != 0) {
8725 EVT VT = N->getValueType(0);
8726 // Return a load from the stack slot.
8727 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
8728 MachinePointerInfo(), false, false, 0));
8732 case ISD::READCYCLECOUNTER: {
8733 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8734 SDValue TheChain = N->getOperand(0);
8735 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
8736 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
8738 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
8740 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
8741 SDValue Ops[] = { eax, edx };
8742 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
8743 Results.push_back(edx.getValue(1));
8746 case ISD::ATOMIC_CMP_SWAP: {
8747 EVT T = N->getValueType(0);
8748 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
8749 SDValue cpInL, cpInH;
8750 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8751 DAG.getConstant(0, MVT::i32));
8752 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
8753 DAG.getConstant(1, MVT::i32));
8754 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
8755 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
8757 SDValue swapInL, swapInH;
8758 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8759 DAG.getConstant(0, MVT::i32));
8760 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
8761 DAG.getConstant(1, MVT::i32));
8762 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
8764 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
8765 swapInL.getValue(1));
8766 SDValue Ops[] = { swapInH.getValue(0),
8768 swapInH.getValue(1) };
8769 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
8770 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
8771 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
8772 MVT::i32, Result.getValue(1));
8773 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
8774 MVT::i32, cpOutL.getValue(2));
8775 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
8776 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
8777 Results.push_back(cpOutH.getValue(1));
8780 case ISD::ATOMIC_LOAD_ADD:
8781 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
8783 case ISD::ATOMIC_LOAD_AND:
8784 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
8786 case ISD::ATOMIC_LOAD_NAND:
8787 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
8789 case ISD::ATOMIC_LOAD_OR:
8790 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
8792 case ISD::ATOMIC_LOAD_SUB:
8793 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
8795 case ISD::ATOMIC_LOAD_XOR:
8796 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
8798 case ISD::ATOMIC_SWAP:
8799 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
8804 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
8806 default: return NULL;
8807 case X86ISD::BSF: return "X86ISD::BSF";
8808 case X86ISD::BSR: return "X86ISD::BSR";
8809 case X86ISD::SHLD: return "X86ISD::SHLD";
8810 case X86ISD::SHRD: return "X86ISD::SHRD";
8811 case X86ISD::FAND: return "X86ISD::FAND";
8812 case X86ISD::FOR: return "X86ISD::FOR";
8813 case X86ISD::FXOR: return "X86ISD::FXOR";
8814 case X86ISD::FSRL: return "X86ISD::FSRL";
8815 case X86ISD::FILD: return "X86ISD::FILD";
8816 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
8817 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
8818 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
8819 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
8820 case X86ISD::FLD: return "X86ISD::FLD";
8821 case X86ISD::FST: return "X86ISD::FST";
8822 case X86ISD::CALL: return "X86ISD::CALL";
8823 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
8824 case X86ISD::BT: return "X86ISD::BT";
8825 case X86ISD::CMP: return "X86ISD::CMP";
8826 case X86ISD::COMI: return "X86ISD::COMI";
8827 case X86ISD::UCOMI: return "X86ISD::UCOMI";
8828 case X86ISD::SETCC: return "X86ISD::SETCC";
8829 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
8830 case X86ISD::CMOV: return "X86ISD::CMOV";
8831 case X86ISD::BRCOND: return "X86ISD::BRCOND";
8832 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
8833 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
8834 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
8835 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
8836 case X86ISD::Wrapper: return "X86ISD::Wrapper";
8837 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
8838 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
8839 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
8840 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
8841 case X86ISD::PINSRB: return "X86ISD::PINSRB";
8842 case X86ISD::PINSRW: return "X86ISD::PINSRW";
8843 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
8844 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
8845 case X86ISD::FMAX: return "X86ISD::FMAX";
8846 case X86ISD::FMIN: return "X86ISD::FMIN";
8847 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
8848 case X86ISD::FRCP: return "X86ISD::FRCP";
8849 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
8850 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
8851 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
8852 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
8853 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
8854 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
8855 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
8856 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
8857 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
8858 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
8859 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
8860 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
8861 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
8862 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
8863 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
8864 case X86ISD::VSHL: return "X86ISD::VSHL";
8865 case X86ISD::VSRL: return "X86ISD::VSRL";
8866 case X86ISD::CMPPD: return "X86ISD::CMPPD";
8867 case X86ISD::CMPPS: return "X86ISD::CMPPS";
8868 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
8869 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
8870 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
8871 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
8872 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
8873 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
8874 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
8875 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
8876 case X86ISD::ADD: return "X86ISD::ADD";
8877 case X86ISD::SUB: return "X86ISD::SUB";
8878 case X86ISD::SMUL: return "X86ISD::SMUL";
8879 case X86ISD::UMUL: return "X86ISD::UMUL";
8880 case X86ISD::INC: return "X86ISD::INC";
8881 case X86ISD::DEC: return "X86ISD::DEC";
8882 case X86ISD::OR: return "X86ISD::OR";
8883 case X86ISD::XOR: return "X86ISD::XOR";
8884 case X86ISD::AND: return "X86ISD::AND";
8885 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
8886 case X86ISD::PTEST: return "X86ISD::PTEST";
8887 case X86ISD::TESTP: return "X86ISD::TESTP";
8888 case X86ISD::PALIGN: return "X86ISD::PALIGN";
8889 case X86ISD::PSHUFD: return "X86ISD::PSHUFD";
8890 case X86ISD::PSHUFHW: return "X86ISD::PSHUFHW";
8891 case X86ISD::PSHUFHW_LD: return "X86ISD::PSHUFHW_LD";
8892 case X86ISD::PSHUFLW: return "X86ISD::PSHUFLW";
8893 case X86ISD::PSHUFLW_LD: return "X86ISD::PSHUFLW_LD";
8894 case X86ISD::SHUFPS: return "X86ISD::SHUFPS";
8895 case X86ISD::SHUFPD: return "X86ISD::SHUFPD";
8896 case X86ISD::MOVLHPS: return "X86ISD::MOVLHPS";
8897 case X86ISD::MOVLHPD: return "X86ISD::MOVLHPD";
8898 case X86ISD::MOVHLPS: return "X86ISD::MOVHLPS";
8899 case X86ISD::MOVHLPD: return "X86ISD::MOVHLPD";
8900 case X86ISD::MOVLPS: return "X86ISD::MOVLPS";
8901 case X86ISD::MOVLPD: return "X86ISD::MOVLPD";
8902 case X86ISD::MOVDDUP: return "X86ISD::MOVDDUP";
8903 case X86ISD::MOVSHDUP: return "X86ISD::MOVSHDUP";
8904 case X86ISD::MOVSLDUP: return "X86ISD::MOVSLDUP";
8905 case X86ISD::MOVSHDUP_LD: return "X86ISD::MOVSHDUP_LD";
8906 case X86ISD::MOVSLDUP_LD: return "X86ISD::MOVSLDUP_LD";
8907 case X86ISD::MOVSD: return "X86ISD::MOVSD";
8908 case X86ISD::MOVSS: return "X86ISD::MOVSS";
8909 case X86ISD::UNPCKLPS: return "X86ISD::UNPCKLPS";
8910 case X86ISD::UNPCKLPD: return "X86ISD::UNPCKLPD";
8911 case X86ISD::UNPCKHPS: return "X86ISD::UNPCKHPS";
8912 case X86ISD::UNPCKHPD: return "X86ISD::UNPCKHPD";
8913 case X86ISD::PUNPCKLBW: return "X86ISD::PUNPCKLBW";
8914 case X86ISD::PUNPCKLWD: return "X86ISD::PUNPCKLWD";
8915 case X86ISD::PUNPCKLDQ: return "X86ISD::PUNPCKLDQ";
8916 case X86ISD::PUNPCKLQDQ: return "X86ISD::PUNPCKLQDQ";
8917 case X86ISD::PUNPCKHBW: return "X86ISD::PUNPCKHBW";
8918 case X86ISD::PUNPCKHWD: return "X86ISD::PUNPCKHWD";
8919 case X86ISD::PUNPCKHDQ: return "X86ISD::PUNPCKHDQ";
8920 case X86ISD::PUNPCKHQDQ: return "X86ISD::PUNPCKHQDQ";
8921 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
8922 case X86ISD::MINGW_ALLOCA: return "X86ISD::MINGW_ALLOCA";
8926 // isLegalAddressingMode - Return true if the addressing mode represented
8927 // by AM is legal for this target, for a load/store of the specified type.
8928 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
8929 const Type *Ty) const {
8930 // X86 supports extremely general addressing modes.
8931 CodeModel::Model M = getTargetMachine().getCodeModel();
8932 Reloc::Model R = getTargetMachine().getRelocationModel();
8934 // X86 allows a sign-extended 32-bit immediate field as a displacement.
8935 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
8940 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
8942 // If a reference to this global requires an extra load, we can't fold it.
8943 if (isGlobalStubReference(GVFlags))
8946 // If BaseGV requires a register for the PIC base, we cannot also have a
8947 // BaseReg specified.
8948 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
8951 // If lower 4G is not available, then we must use rip-relative addressing.
8952 if ((M != CodeModel::Small || R != Reloc::Static) &&
8953 Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
8963 // These scales always work.
8968 // These scales are formed with basereg+scalereg. Only accept if there is
8973 default: // Other stuff never works.
8981 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
8982 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
8984 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
8985 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
8986 if (NumBits1 <= NumBits2)
8991 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
8992 if (!VT1.isInteger() || !VT2.isInteger())
8994 unsigned NumBits1 = VT1.getSizeInBits();
8995 unsigned NumBits2 = VT2.getSizeInBits();
8996 if (NumBits1 <= NumBits2)
9001 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
9002 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9003 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
9006 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
9007 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
9008 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
9011 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
9012 // i16 instructions are longer (0x66 prefix) and potentially slower.
9013 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
9016 /// isShuffleMaskLegal - Targets can use this to indicate that they only
9017 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
9018 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
9019 /// are assumed to be legal.
9021 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
9023 // Very little shuffling can be done for 64-bit vectors right now.
9024 if (VT.getSizeInBits() == 64)
9025 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
9027 // FIXME: pshufb, blends, shifts.
9028 return (VT.getVectorNumElements() == 2 ||
9029 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
9030 isMOVLMask(M, VT) ||
9031 isSHUFPMask(M, VT) ||
9032 isPSHUFDMask(M, VT) ||
9033 isPSHUFHWMask(M, VT) ||
9034 isPSHUFLWMask(M, VT) ||
9035 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
9036 isUNPCKLMask(M, VT) ||
9037 isUNPCKHMask(M, VT) ||
9038 isUNPCKL_v_undef_Mask(M, VT) ||
9039 isUNPCKH_v_undef_Mask(M, VT));
9043 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
9045 unsigned NumElts = VT.getVectorNumElements();
9046 // FIXME: This collection of masks seems suspect.
9049 if (NumElts == 4 && VT.getSizeInBits() == 128) {
9050 return (isMOVLMask(Mask, VT) ||
9051 isCommutedMOVLMask(Mask, VT, true) ||
9052 isSHUFPMask(Mask, VT) ||
9053 isCommutedSHUFPMask(Mask, VT));
9058 //===----------------------------------------------------------------------===//
9059 // X86 Scheduler Hooks
9060 //===----------------------------------------------------------------------===//
9062 // private utility function
9064 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
9065 MachineBasicBlock *MBB,
9072 TargetRegisterClass *RC,
9073 bool invSrc) const {
9074 // For the atomic bitwise operator, we generate
9077 // ld t1 = [bitinstr.addr]
9078 // op t2 = t1, [bitinstr.val]
9080 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9082 // fallthrough -->nextMBB
9083 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9084 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9085 MachineFunction::iterator MBBIter = MBB;
9088 /// First build the CFG
9089 MachineFunction *F = MBB->getParent();
9090 MachineBasicBlock *thisMBB = MBB;
9091 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9092 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9093 F->insert(MBBIter, newMBB);
9094 F->insert(MBBIter, nextMBB);
9096 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9097 nextMBB->splice(nextMBB->begin(), thisMBB,
9098 llvm::next(MachineBasicBlock::iterator(bInstr)),
9100 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9102 // Update thisMBB to fall through to newMBB
9103 thisMBB->addSuccessor(newMBB);
9105 // newMBB jumps to itself and fall through to nextMBB
9106 newMBB->addSuccessor(nextMBB);
9107 newMBB->addSuccessor(newMBB);
9109 // Insert instructions into newMBB based on incoming instruction
9110 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9111 "unexpected number of operands");
9112 DebugLoc dl = bInstr->getDebugLoc();
9113 MachineOperand& destOper = bInstr->getOperand(0);
9114 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9115 int numArgs = bInstr->getNumOperands() - 1;
9116 for (int i=0; i < numArgs; ++i)
9117 argOpers[i] = &bInstr->getOperand(i+1);
9119 // x86 address has 4 operands: base, index, scale, and displacement
9120 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9121 int valArgIndx = lastAddrIndx + 1;
9123 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9124 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
9125 for (int i=0; i <= lastAddrIndx; ++i)
9126 (*MIB).addOperand(*argOpers[i]);
9128 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
9130 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
9135 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9136 assert((argOpers[valArgIndx]->isReg() ||
9137 argOpers[valArgIndx]->isImm()) &&
9139 if (argOpers[valArgIndx]->isReg())
9140 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
9142 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
9144 (*MIB).addOperand(*argOpers[valArgIndx]);
9146 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), EAXreg);
9149 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
9150 for (int i=0; i <= lastAddrIndx; ++i)
9151 (*MIB).addOperand(*argOpers[i]);
9153 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9154 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9155 bInstr->memoperands_end());
9157 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9161 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9163 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9167 // private utility function: 64 bit atomics on 32 bit host.
9169 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
9170 MachineBasicBlock *MBB,
9175 bool invSrc) const {
9176 // For the atomic bitwise operator, we generate
9177 // thisMBB (instructions are in pairs, except cmpxchg8b)
9178 // ld t1,t2 = [bitinstr.addr]
9180 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
9181 // op t5, t6 <- out1, out2, [bitinstr.val]
9182 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
9183 // mov ECX, EBX <- t5, t6
9184 // mov EAX, EDX <- t1, t2
9185 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
9186 // mov t3, t4 <- EAX, EDX
9188 // result in out1, out2
9189 // fallthrough -->nextMBB
9191 const TargetRegisterClass *RC = X86::GR32RegisterClass;
9192 const unsigned LoadOpc = X86::MOV32rm;
9193 const unsigned NotOpc = X86::NOT32r;
9194 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9195 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9196 MachineFunction::iterator MBBIter = MBB;
9199 /// First build the CFG
9200 MachineFunction *F = MBB->getParent();
9201 MachineBasicBlock *thisMBB = MBB;
9202 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9203 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9204 F->insert(MBBIter, newMBB);
9205 F->insert(MBBIter, nextMBB);
9207 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9208 nextMBB->splice(nextMBB->begin(), thisMBB,
9209 llvm::next(MachineBasicBlock::iterator(bInstr)),
9211 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9213 // Update thisMBB to fall through to newMBB
9214 thisMBB->addSuccessor(newMBB);
9216 // newMBB jumps to itself and fall through to nextMBB
9217 newMBB->addSuccessor(nextMBB);
9218 newMBB->addSuccessor(newMBB);
9220 DebugLoc dl = bInstr->getDebugLoc();
9221 // Insert instructions into newMBB based on incoming instruction
9222 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
9223 assert(bInstr->getNumOperands() < X86::AddrNumOperands + 14 &&
9224 "unexpected number of operands");
9225 MachineOperand& dest1Oper = bInstr->getOperand(0);
9226 MachineOperand& dest2Oper = bInstr->getOperand(1);
9227 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9228 for (int i=0; i < 2 + X86::AddrNumOperands; ++i) {
9229 argOpers[i] = &bInstr->getOperand(i+2);
9231 // We use some of the operands multiple times, so conservatively just
9232 // clear any kill flags that might be present.
9233 if (argOpers[i]->isReg() && argOpers[i]->isUse())
9234 argOpers[i]->setIsKill(false);
9237 // x86 address has 5 operands: base, index, scale, displacement, and segment.
9238 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9240 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
9241 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
9242 for (int i=0; i <= lastAddrIndx; ++i)
9243 (*MIB).addOperand(*argOpers[i]);
9244 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
9245 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
9246 // add 4 to displacement.
9247 for (int i=0; i <= lastAddrIndx-2; ++i)
9248 (*MIB).addOperand(*argOpers[i]);
9249 MachineOperand newOp3 = *(argOpers[3]);
9251 newOp3.setImm(newOp3.getImm()+4);
9253 newOp3.setOffset(newOp3.getOffset()+4);
9254 (*MIB).addOperand(newOp3);
9255 (*MIB).addOperand(*argOpers[lastAddrIndx]);
9257 // t3/4 are defined later, at the bottom of the loop
9258 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
9259 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
9260 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
9261 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
9262 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
9263 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
9265 // The subsequent operations should be using the destination registers of
9266 //the PHI instructions.
9268 t1 = F->getRegInfo().createVirtualRegister(RC);
9269 t2 = F->getRegInfo().createVirtualRegister(RC);
9270 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
9271 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
9273 t1 = dest1Oper.getReg();
9274 t2 = dest2Oper.getReg();
9277 int valArgIndx = lastAddrIndx + 1;
9278 assert((argOpers[valArgIndx]->isReg() ||
9279 argOpers[valArgIndx]->isImm()) &&
9281 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
9282 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
9283 if (argOpers[valArgIndx]->isReg())
9284 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
9286 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
9287 if (regOpcL != X86::MOV32rr)
9289 (*MIB).addOperand(*argOpers[valArgIndx]);
9290 assert(argOpers[valArgIndx + 1]->isReg() ==
9291 argOpers[valArgIndx]->isReg());
9292 assert(argOpers[valArgIndx + 1]->isImm() ==
9293 argOpers[valArgIndx]->isImm());
9294 if (argOpers[valArgIndx + 1]->isReg())
9295 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
9297 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
9298 if (regOpcH != X86::MOV32rr)
9300 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
9302 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9304 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EDX);
9307 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EBX);
9309 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::ECX);
9312 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
9313 for (int i=0; i <= lastAddrIndx; ++i)
9314 (*MIB).addOperand(*argOpers[i]);
9316 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9317 (*MIB).setMemRefs(bInstr->memoperands_begin(),
9318 bInstr->memoperands_end());
9320 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t3);
9321 MIB.addReg(X86::EAX);
9322 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t4);
9323 MIB.addReg(X86::EDX);
9326 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9328 bInstr->eraseFromParent(); // The pseudo instruction is gone now.
9332 // private utility function
9334 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
9335 MachineBasicBlock *MBB,
9336 unsigned cmovOpc) const {
9337 // For the atomic min/max operator, we generate
9340 // ld t1 = [min/max.addr]
9341 // mov t2 = [min/max.val]
9343 // cmov[cond] t2 = t1
9345 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
9347 // fallthrough -->nextMBB
9349 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9350 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9351 MachineFunction::iterator MBBIter = MBB;
9354 /// First build the CFG
9355 MachineFunction *F = MBB->getParent();
9356 MachineBasicBlock *thisMBB = MBB;
9357 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
9358 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
9359 F->insert(MBBIter, newMBB);
9360 F->insert(MBBIter, nextMBB);
9362 // Transfer the remainder of thisMBB and its successor edges to nextMBB.
9363 nextMBB->splice(nextMBB->begin(), thisMBB,
9364 llvm::next(MachineBasicBlock::iterator(mInstr)),
9366 nextMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
9368 // Update thisMBB to fall through to newMBB
9369 thisMBB->addSuccessor(newMBB);
9371 // newMBB jumps to newMBB and fall through to nextMBB
9372 newMBB->addSuccessor(nextMBB);
9373 newMBB->addSuccessor(newMBB);
9375 DebugLoc dl = mInstr->getDebugLoc();
9376 // Insert instructions into newMBB based on incoming instruction
9377 assert(mInstr->getNumOperands() < X86::AddrNumOperands + 4 &&
9378 "unexpected number of operands");
9379 MachineOperand& destOper = mInstr->getOperand(0);
9380 MachineOperand* argOpers[2 + X86::AddrNumOperands];
9381 int numArgs = mInstr->getNumOperands() - 1;
9382 for (int i=0; i < numArgs; ++i)
9383 argOpers[i] = &mInstr->getOperand(i+1);
9385 // x86 address has 4 operands: base, index, scale, and displacement
9386 int lastAddrIndx = X86::AddrNumOperands - 1; // [0,3]
9387 int valArgIndx = lastAddrIndx + 1;
9389 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9390 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
9391 for (int i=0; i <= lastAddrIndx; ++i)
9392 (*MIB).addOperand(*argOpers[i]);
9394 // We only support register and immediate values
9395 assert((argOpers[valArgIndx]->isReg() ||
9396 argOpers[valArgIndx]->isImm()) &&
9399 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9400 if (argOpers[valArgIndx]->isReg())
9401 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), t2);
9403 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
9404 (*MIB).addOperand(*argOpers[valArgIndx]);
9406 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), X86::EAX);
9409 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
9414 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
9415 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
9419 // Cmp and exchange if none has modified the memory location
9420 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
9421 for (int i=0; i <= lastAddrIndx; ++i)
9422 (*MIB).addOperand(*argOpers[i]);
9424 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
9425 (*MIB).setMemRefs(mInstr->memoperands_begin(),
9426 mInstr->memoperands_end());
9428 MIB = BuildMI(newMBB, dl, TII->get(TargetOpcode::COPY), destOper.getReg());
9429 MIB.addReg(X86::EAX);
9432 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
9434 mInstr->eraseFromParent(); // The pseudo instruction is gone now.
9438 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
9439 // or XMM0_V32I8 in AVX all of this code can be replaced with that
9442 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
9443 unsigned numArgs, bool memArg) const {
9445 assert((Subtarget->hasSSE42() || Subtarget->hasAVX()) &&
9446 "Target must have SSE4.2 or AVX features enabled");
9448 DebugLoc dl = MI->getDebugLoc();
9449 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9453 if (!Subtarget->hasAVX()) {
9455 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
9457 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
9460 Opc = numArgs == 3 ? X86::VPCMPISTRM128rm : X86::VPCMPESTRM128rm;
9462 Opc = numArgs == 3 ? X86::VPCMPISTRM128rr : X86::VPCMPESTRM128rr;
9465 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
9467 for (unsigned i = 0; i < numArgs; ++i) {
9468 MachineOperand &Op = MI->getOperand(i+1);
9470 if (!(Op.isReg() && Op.isImplicit()))
9474 BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
9477 MI->eraseFromParent();
9483 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
9485 MachineBasicBlock *MBB) const {
9486 // Emit code to save XMM registers to the stack. The ABI says that the
9487 // number of registers to save is given in %al, so it's theoretically
9488 // possible to do an indirect jump trick to avoid saving all of them,
9489 // however this code takes a simpler approach and just executes all
9490 // of the stores if %al is non-zero. It's less code, and it's probably
9491 // easier on the hardware branch predictor, and stores aren't all that
9492 // expensive anyway.
9494 // Create the new basic blocks. One block contains all the XMM stores,
9495 // and one block is the final destination regardless of whether any
9496 // stores were performed.
9497 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
9498 MachineFunction *F = MBB->getParent();
9499 MachineFunction::iterator MBBIter = MBB;
9501 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
9502 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
9503 F->insert(MBBIter, XMMSaveMBB);
9504 F->insert(MBBIter, EndMBB);
9506 // Transfer the remainder of MBB and its successor edges to EndMBB.
9507 EndMBB->splice(EndMBB->begin(), MBB,
9508 llvm::next(MachineBasicBlock::iterator(MI)),
9510 EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
9512 // The original block will now fall through to the XMM save block.
9513 MBB->addSuccessor(XMMSaveMBB);
9514 // The XMMSaveMBB will fall through to the end block.
9515 XMMSaveMBB->addSuccessor(EndMBB);
9517 // Now add the instructions.
9518 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9519 DebugLoc DL = MI->getDebugLoc();
9521 unsigned CountReg = MI->getOperand(0).getReg();
9522 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
9523 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
9525 if (!Subtarget->isTargetWin64()) {
9526 // If %al is 0, branch around the XMM save block.
9527 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
9528 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
9529 MBB->addSuccessor(EndMBB);
9532 // In the XMM save block, save all the XMM argument registers.
9533 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
9534 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
9535 MachineMemOperand *MMO =
9536 F->getMachineMemOperand(
9537 MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
9538 MachineMemOperand::MOStore,
9539 /*Size=*/16, /*Align=*/16);
9540 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
9541 .addFrameIndex(RegSaveFrameIndex)
9542 .addImm(/*Scale=*/1)
9543 .addReg(/*IndexReg=*/0)
9544 .addImm(/*Disp=*/Offset)
9545 .addReg(/*Segment=*/0)
9546 .addReg(MI->getOperand(i).getReg())
9547 .addMemOperand(MMO);
9550 MI->eraseFromParent(); // The pseudo instruction is gone now.
9556 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
9557 MachineBasicBlock *BB) const {
9558 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9559 DebugLoc DL = MI->getDebugLoc();
9561 // To "insert" a SELECT_CC instruction, we actually have to insert the
9562 // diamond control-flow pattern. The incoming instruction knows the
9563 // destination vreg to set, the condition code register to branch on, the
9564 // true/false values to select between, and a branch opcode to use.
9565 const BasicBlock *LLVM_BB = BB->getBasicBlock();
9566 MachineFunction::iterator It = BB;
9572 // cmpTY ccX, r1, r2
9574 // fallthrough --> copy0MBB
9575 MachineBasicBlock *thisMBB = BB;
9576 MachineFunction *F = BB->getParent();
9577 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9578 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
9579 F->insert(It, copy0MBB);
9580 F->insert(It, sinkMBB);
9582 // If the EFLAGS register isn't dead in the terminator, then claim that it's
9583 // live into the sink and copy blocks.
9584 const MachineFunction *MF = BB->getParent();
9585 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
9586 BitVector ReservedRegs = TRI->getReservedRegs(*MF);
9588 for (unsigned I = 0, E = MI->getNumOperands(); I != E; ++I) {
9589 const MachineOperand &MO = MI->getOperand(I);
9590 if (!MO.isReg() || !MO.isUse() || MO.isKill()) continue;
9591 unsigned Reg = MO.getReg();
9592 if (Reg != X86::EFLAGS) continue;
9593 copy0MBB->addLiveIn(Reg);
9594 sinkMBB->addLiveIn(Reg);
9597 // Transfer the remainder of BB and its successor edges to sinkMBB.
9598 sinkMBB->splice(sinkMBB->begin(), BB,
9599 llvm::next(MachineBasicBlock::iterator(MI)),
9601 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9603 // Add the true and fallthrough blocks as its successors.
9604 BB->addSuccessor(copy0MBB);
9605 BB->addSuccessor(sinkMBB);
9607 // Create the conditional branch instruction.
9609 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
9610 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
9613 // %FalseValue = ...
9614 // # fallthrough to sinkMBB
9615 copy0MBB->addSuccessor(sinkMBB);
9618 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9620 BuildMI(*sinkMBB, sinkMBB->begin(), DL,
9621 TII->get(X86::PHI), MI->getOperand(0).getReg())
9622 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
9623 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
9625 MI->eraseFromParent(); // The pseudo instruction is gone now.
9630 X86TargetLowering::EmitLoweredMingwAlloca(MachineInstr *MI,
9631 MachineBasicBlock *BB) const {
9632 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9633 DebugLoc DL = MI->getDebugLoc();
9635 // The lowering is pretty easy: we're just emitting the call to _alloca. The
9636 // non-trivial part is impdef of ESP.
9637 // FIXME: The code should be tweaked as soon as we'll try to do codegen for
9640 BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
9641 .addExternalSymbol("_alloca")
9642 .addReg(X86::EAX, RegState::Implicit)
9643 .addReg(X86::ESP, RegState::Implicit)
9644 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
9645 .addReg(X86::ESP, RegState::Define | RegState::Implicit)
9646 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
9648 MI->eraseFromParent(); // The pseudo instruction is gone now.
9653 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
9654 MachineBasicBlock *BB) const {
9655 // This is pretty easy. We're taking the value that we received from
9656 // our load from the relocation, sticking it in either RDI (x86-64)
9657 // or EAX and doing an indirect call. The return value will then
9658 // be in the normal return register.
9659 const X86InstrInfo *TII
9660 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
9661 DebugLoc DL = MI->getDebugLoc();
9662 MachineFunction *F = BB->getParent();
9663 bool IsWin64 = Subtarget->isTargetWin64();
9665 assert(MI->getOperand(3).isGlobal() && "This should be a global");
9667 if (Subtarget->is64Bit()) {
9668 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9669 TII->get(X86::MOV64rm), X86::RDI)
9671 .addImm(0).addReg(0)
9672 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
9673 MI->getOperand(3).getTargetFlags())
9675 MIB = BuildMI(*BB, MI, DL, TII->get(IsWin64 ? X86::WINCALL64m : X86::CALL64m));
9676 addDirectMem(MIB, X86::RDI);
9677 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
9678 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9679 TII->get(X86::MOV32rm), X86::EAX)
9681 .addImm(0).addReg(0)
9682 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
9683 MI->getOperand(3).getTargetFlags())
9685 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
9686 addDirectMem(MIB, X86::EAX);
9688 MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
9689 TII->get(X86::MOV32rm), X86::EAX)
9690 .addReg(TII->getGlobalBaseReg(F))
9691 .addImm(0).addReg(0)
9692 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
9693 MI->getOperand(3).getTargetFlags())
9695 MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
9696 addDirectMem(MIB, X86::EAX);
9699 MI->eraseFromParent(); // The pseudo instruction is gone now.
9704 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
9705 MachineBasicBlock *BB) const {
9706 switch (MI->getOpcode()) {
9707 default: assert(false && "Unexpected instr type to insert");
9708 case X86::MINGW_ALLOCA:
9709 return EmitLoweredMingwAlloca(MI, BB);
9710 case X86::TLSCall_32:
9711 case X86::TLSCall_64:
9712 return EmitLoweredTLSCall(MI, BB);
9714 case X86::CMOV_V1I64:
9715 case X86::CMOV_FR32:
9716 case X86::CMOV_FR64:
9717 case X86::CMOV_V4F32:
9718 case X86::CMOV_V2F64:
9719 case X86::CMOV_V2I64:
9720 case X86::CMOV_GR16:
9721 case X86::CMOV_GR32:
9722 case X86::CMOV_RFP32:
9723 case X86::CMOV_RFP64:
9724 case X86::CMOV_RFP80:
9725 return EmitLoweredSelect(MI, BB);
9727 case X86::FP32_TO_INT16_IN_MEM:
9728 case X86::FP32_TO_INT32_IN_MEM:
9729 case X86::FP32_TO_INT64_IN_MEM:
9730 case X86::FP64_TO_INT16_IN_MEM:
9731 case X86::FP64_TO_INT32_IN_MEM:
9732 case X86::FP64_TO_INT64_IN_MEM:
9733 case X86::FP80_TO_INT16_IN_MEM:
9734 case X86::FP80_TO_INT32_IN_MEM:
9735 case X86::FP80_TO_INT64_IN_MEM: {
9736 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
9737 DebugLoc DL = MI->getDebugLoc();
9739 // Change the floating point control register to use "round towards zero"
9740 // mode when truncating to an integer value.
9741 MachineFunction *F = BB->getParent();
9742 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
9743 addFrameReference(BuildMI(*BB, MI, DL,
9744 TII->get(X86::FNSTCW16m)), CWFrameIdx);
9746 // Load the old value of the high byte of the control word...
9748 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
9749 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
9752 // Set the high part to be round to zero...
9753 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
9756 // Reload the modified control word now...
9757 addFrameReference(BuildMI(*BB, MI, DL,
9758 TII->get(X86::FLDCW16m)), CWFrameIdx);
9760 // Restore the memory image of control word to original value
9761 addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
9764 // Get the X86 opcode to use.
9766 switch (MI->getOpcode()) {
9767 default: llvm_unreachable("illegal opcode!");
9768 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
9769 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
9770 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
9771 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
9772 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
9773 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
9774 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
9775 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
9776 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
9780 MachineOperand &Op = MI->getOperand(0);
9782 AM.BaseType = X86AddressMode::RegBase;
9783 AM.Base.Reg = Op.getReg();
9785 AM.BaseType = X86AddressMode::FrameIndexBase;
9786 AM.Base.FrameIndex = Op.getIndex();
9788 Op = MI->getOperand(1);
9790 AM.Scale = Op.getImm();
9791 Op = MI->getOperand(2);
9793 AM.IndexReg = Op.getImm();
9794 Op = MI->getOperand(3);
9795 if (Op.isGlobal()) {
9796 AM.GV = Op.getGlobal();
9798 AM.Disp = Op.getImm();
9800 addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
9801 .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
9803 // Reload the original control word now.
9804 addFrameReference(BuildMI(*BB, MI, DL,
9805 TII->get(X86::FLDCW16m)), CWFrameIdx);
9807 MI->eraseFromParent(); // The pseudo instruction is gone now.
9810 // String/text processing lowering.
9811 case X86::PCMPISTRM128REG:
9812 case X86::VPCMPISTRM128REG:
9813 return EmitPCMP(MI, BB, 3, false /* in-mem */);
9814 case X86::PCMPISTRM128MEM:
9815 case X86::VPCMPISTRM128MEM:
9816 return EmitPCMP(MI, BB, 3, true /* in-mem */);
9817 case X86::PCMPESTRM128REG:
9818 case X86::VPCMPESTRM128REG:
9819 return EmitPCMP(MI, BB, 5, false /* in mem */);
9820 case X86::PCMPESTRM128MEM:
9821 case X86::VPCMPESTRM128MEM:
9822 return EmitPCMP(MI, BB, 5, true /* in mem */);
9825 case X86::ATOMAND32:
9826 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
9827 X86::AND32ri, X86::MOV32rm,
9829 X86::NOT32r, X86::EAX,
9830 X86::GR32RegisterClass);
9832 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
9833 X86::OR32ri, X86::MOV32rm,
9835 X86::NOT32r, X86::EAX,
9836 X86::GR32RegisterClass);
9837 case X86::ATOMXOR32:
9838 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
9839 X86::XOR32ri, X86::MOV32rm,
9841 X86::NOT32r, X86::EAX,
9842 X86::GR32RegisterClass);
9843 case X86::ATOMNAND32:
9844 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
9845 X86::AND32ri, X86::MOV32rm,
9847 X86::NOT32r, X86::EAX,
9848 X86::GR32RegisterClass, true);
9849 case X86::ATOMMIN32:
9850 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
9851 case X86::ATOMMAX32:
9852 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
9853 case X86::ATOMUMIN32:
9854 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
9855 case X86::ATOMUMAX32:
9856 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
9858 case X86::ATOMAND16:
9859 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
9860 X86::AND16ri, X86::MOV16rm,
9862 X86::NOT16r, X86::AX,
9863 X86::GR16RegisterClass);
9865 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
9866 X86::OR16ri, X86::MOV16rm,
9868 X86::NOT16r, X86::AX,
9869 X86::GR16RegisterClass);
9870 case X86::ATOMXOR16:
9871 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
9872 X86::XOR16ri, X86::MOV16rm,
9874 X86::NOT16r, X86::AX,
9875 X86::GR16RegisterClass);
9876 case X86::ATOMNAND16:
9877 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
9878 X86::AND16ri, X86::MOV16rm,
9880 X86::NOT16r, X86::AX,
9881 X86::GR16RegisterClass, true);
9882 case X86::ATOMMIN16:
9883 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
9884 case X86::ATOMMAX16:
9885 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
9886 case X86::ATOMUMIN16:
9887 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
9888 case X86::ATOMUMAX16:
9889 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
9892 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
9893 X86::AND8ri, X86::MOV8rm,
9895 X86::NOT8r, X86::AL,
9896 X86::GR8RegisterClass);
9898 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
9899 X86::OR8ri, X86::MOV8rm,
9901 X86::NOT8r, X86::AL,
9902 X86::GR8RegisterClass);
9904 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
9905 X86::XOR8ri, X86::MOV8rm,
9907 X86::NOT8r, X86::AL,
9908 X86::GR8RegisterClass);
9909 case X86::ATOMNAND8:
9910 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
9911 X86::AND8ri, X86::MOV8rm,
9913 X86::NOT8r, X86::AL,
9914 X86::GR8RegisterClass, true);
9915 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
9916 // This group is for 64-bit host.
9917 case X86::ATOMAND64:
9918 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
9919 X86::AND64ri32, X86::MOV64rm,
9921 X86::NOT64r, X86::RAX,
9922 X86::GR64RegisterClass);
9924 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
9925 X86::OR64ri32, X86::MOV64rm,
9927 X86::NOT64r, X86::RAX,
9928 X86::GR64RegisterClass);
9929 case X86::ATOMXOR64:
9930 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
9931 X86::XOR64ri32, X86::MOV64rm,
9933 X86::NOT64r, X86::RAX,
9934 X86::GR64RegisterClass);
9935 case X86::ATOMNAND64:
9936 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
9937 X86::AND64ri32, X86::MOV64rm,
9939 X86::NOT64r, X86::RAX,
9940 X86::GR64RegisterClass, true);
9941 case X86::ATOMMIN64:
9942 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
9943 case X86::ATOMMAX64:
9944 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
9945 case X86::ATOMUMIN64:
9946 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
9947 case X86::ATOMUMAX64:
9948 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
9950 // This group does 64-bit operations on a 32-bit host.
9951 case X86::ATOMAND6432:
9952 return EmitAtomicBit6432WithCustomInserter(MI, BB,
9953 X86::AND32rr, X86::AND32rr,
9954 X86::AND32ri, X86::AND32ri,
9956 case X86::ATOMOR6432:
9957 return EmitAtomicBit6432WithCustomInserter(MI, BB,
9958 X86::OR32rr, X86::OR32rr,
9959 X86::OR32ri, X86::OR32ri,
9961 case X86::ATOMXOR6432:
9962 return EmitAtomicBit6432WithCustomInserter(MI, BB,
9963 X86::XOR32rr, X86::XOR32rr,
9964 X86::XOR32ri, X86::XOR32ri,
9966 case X86::ATOMNAND6432:
9967 return EmitAtomicBit6432WithCustomInserter(MI, BB,
9968 X86::AND32rr, X86::AND32rr,
9969 X86::AND32ri, X86::AND32ri,
9971 case X86::ATOMADD6432:
9972 return EmitAtomicBit6432WithCustomInserter(MI, BB,
9973 X86::ADD32rr, X86::ADC32rr,
9974 X86::ADD32ri, X86::ADC32ri,
9976 case X86::ATOMSUB6432:
9977 return EmitAtomicBit6432WithCustomInserter(MI, BB,
9978 X86::SUB32rr, X86::SBB32rr,
9979 X86::SUB32ri, X86::SBB32ri,
9981 case X86::ATOMSWAP6432:
9982 return EmitAtomicBit6432WithCustomInserter(MI, BB,
9983 X86::MOV32rr, X86::MOV32rr,
9984 X86::MOV32ri, X86::MOV32ri,
9986 case X86::VASTART_SAVE_XMM_REGS:
9987 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
9991 //===----------------------------------------------------------------------===//
9992 // X86 Optimization Hooks
9993 //===----------------------------------------------------------------------===//
9995 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
9999 const SelectionDAG &DAG,
10000 unsigned Depth) const {
10001 unsigned Opc = Op.getOpcode();
10002 assert((Opc >= ISD::BUILTIN_OP_END ||
10003 Opc == ISD::INTRINSIC_WO_CHAIN ||
10004 Opc == ISD::INTRINSIC_W_CHAIN ||
10005 Opc == ISD::INTRINSIC_VOID) &&
10006 "Should use MaskedValueIsZero if you don't know whether Op"
10007 " is a target node!");
10009 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
10021 // These nodes' second result is a boolean.
10022 if (Op.getResNo() == 0)
10025 case X86ISD::SETCC:
10026 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
10027 Mask.getBitWidth() - 1);
10032 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
10033 unsigned Depth) const {
10034 // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
10035 if (Op.getOpcode() == X86ISD::SETCC_CARRY)
10036 return Op.getValueType().getScalarType().getSizeInBits();
10042 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
10043 /// node is a GlobalAddress + offset.
10044 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
10045 const GlobalValue* &GA,
10046 int64_t &Offset) const {
10047 if (N->getOpcode() == X86ISD::Wrapper) {
10048 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
10049 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
10050 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
10054 return TargetLowering::isGAPlusOffset(N, GA, Offset);
10057 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
10058 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
10059 /// if the load addresses are consecutive, non-overlapping, and in the right
10061 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
10062 const TargetLowering &TLI) {
10063 DebugLoc dl = N->getDebugLoc();
10064 EVT VT = N->getValueType(0);
10066 if (VT.getSizeInBits() != 128)
10069 SmallVector<SDValue, 16> Elts;
10070 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
10071 Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
10073 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
10076 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
10077 /// generation and convert it from being a bunch of shuffles and extracts
10078 /// to a simple store and scalar loads to extract the elements.
10079 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
10080 const TargetLowering &TLI) {
10081 SDValue InputVector = N->getOperand(0);
10083 // Only operate on vectors of 4 elements, where the alternative shuffling
10084 // gets to be more expensive.
10085 if (InputVector.getValueType() != MVT::v4i32)
10088 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
10089 // single use which is a sign-extend or zero-extend, and all elements are
10091 SmallVector<SDNode *, 4> Uses;
10092 unsigned ExtractedElements = 0;
10093 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
10094 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
10095 if (UI.getUse().getResNo() != InputVector.getResNo())
10098 SDNode *Extract = *UI;
10099 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10102 if (Extract->getValueType(0) != MVT::i32)
10104 if (!Extract->hasOneUse())
10106 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
10107 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
10109 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
10112 // Record which element was extracted.
10113 ExtractedElements |=
10114 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
10116 Uses.push_back(Extract);
10119 // If not all the elements were used, this may not be worthwhile.
10120 if (ExtractedElements != 15)
10123 // Ok, we've now decided to do the transformation.
10124 DebugLoc dl = InputVector.getDebugLoc();
10126 // Store the value to a temporary stack slot.
10127 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
10128 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
10129 MachinePointerInfo(), false, false, 0);
10131 // Replace each use (extract) with a load of the appropriate element.
10132 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
10133 UE = Uses.end(); UI != UE; ++UI) {
10134 SDNode *Extract = *UI;
10136 // Compute the element's address.
10137 SDValue Idx = Extract->getOperand(1);
10139 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
10140 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
10141 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
10143 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(),
10144 StackPtr, OffsetVal);
10146 // Load the scalar.
10147 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
10148 ScalarAddr, MachinePointerInfo(),
10151 // Replace the exact with the load.
10152 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
10155 // The replacement was made in place; don't return anything.
10159 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
10160 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
10161 const X86Subtarget *Subtarget) {
10162 DebugLoc DL = N->getDebugLoc();
10163 SDValue Cond = N->getOperand(0);
10164 // Get the LHS/RHS of the select.
10165 SDValue LHS = N->getOperand(1);
10166 SDValue RHS = N->getOperand(2);
10168 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
10169 // instructions match the semantics of the common C idiom x<y?x:y but not
10170 // x<=y?x:y, because of how they handle negative zero (which can be
10171 // ignored in unsafe-math mode).
10172 if (Subtarget->hasSSE2() &&
10173 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
10174 Cond.getOpcode() == ISD::SETCC) {
10175 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
10177 unsigned Opcode = 0;
10178 // Check for x CC y ? x : y.
10179 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
10180 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
10184 // Converting this to a min would handle NaNs incorrectly, and swapping
10185 // the operands would cause it to handle comparisons between positive
10186 // and negative zero incorrectly.
10187 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10188 if (!UnsafeFPMath &&
10189 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10191 std::swap(LHS, RHS);
10193 Opcode = X86ISD::FMIN;
10196 // Converting this to a min would handle comparisons between positive
10197 // and negative zero incorrectly.
10198 if (!UnsafeFPMath &&
10199 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
10201 Opcode = X86ISD::FMIN;
10204 // Converting this to a min would handle both negative zeros and NaNs
10205 // incorrectly, but we can swap the operands to fix both.
10206 std::swap(LHS, RHS);
10210 Opcode = X86ISD::FMIN;
10214 // Converting this to a max would handle comparisons between positive
10215 // and negative zero incorrectly.
10216 if (!UnsafeFPMath &&
10217 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
10219 Opcode = X86ISD::FMAX;
10222 // Converting this to a max would handle NaNs incorrectly, and swapping
10223 // the operands would cause it to handle comparisons between positive
10224 // and negative zero incorrectly.
10225 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
10226 if (!UnsafeFPMath &&
10227 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
10229 std::swap(LHS, RHS);
10231 Opcode = X86ISD::FMAX;
10234 // Converting this to a max would handle both negative zeros and NaNs
10235 // incorrectly, but we can swap the operands to fix both.
10236 std::swap(LHS, RHS);
10240 Opcode = X86ISD::FMAX;
10243 // Check for x CC y ? y : x -- a min/max with reversed arms.
10244 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
10245 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
10249 // Converting this to a min would handle comparisons between positive
10250 // and negative zero incorrectly, and swapping the operands would
10251 // cause it to handle NaNs incorrectly.
10252 if (!UnsafeFPMath &&
10253 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
10254 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10256 std::swap(LHS, RHS);
10258 Opcode = X86ISD::FMIN;
10261 // Converting this to a min would handle NaNs incorrectly.
10262 if (!UnsafeFPMath &&
10263 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
10265 Opcode = X86ISD::FMIN;
10268 // Converting this to a min would handle both negative zeros and NaNs
10269 // incorrectly, but we can swap the operands to fix both.
10270 std::swap(LHS, RHS);
10274 Opcode = X86ISD::FMIN;
10278 // Converting this to a max would handle NaNs incorrectly.
10279 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10281 Opcode = X86ISD::FMAX;
10284 // Converting this to a max would handle comparisons between positive
10285 // and negative zero incorrectly, and swapping the operands would
10286 // cause it to handle NaNs incorrectly.
10287 if (!UnsafeFPMath &&
10288 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
10289 if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
10291 std::swap(LHS, RHS);
10293 Opcode = X86ISD::FMAX;
10296 // Converting this to a max would handle both negative zeros and NaNs
10297 // incorrectly, but we can swap the operands to fix both.
10298 std::swap(LHS, RHS);
10302 Opcode = X86ISD::FMAX;
10308 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
10311 // If this is a select between two integer constants, try to do some
10313 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
10314 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
10315 // Don't do this for crazy integer types.
10316 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
10317 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
10318 // so that TrueC (the true value) is larger than FalseC.
10319 bool NeedsCondInvert = false;
10321 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
10322 // Efficiently invertible.
10323 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
10324 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
10325 isa<ConstantSDNode>(Cond.getOperand(1))))) {
10326 NeedsCondInvert = true;
10327 std::swap(TrueC, FalseC);
10330 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
10331 if (FalseC->getAPIntValue() == 0 &&
10332 TrueC->getAPIntValue().isPowerOf2()) {
10333 if (NeedsCondInvert) // Invert the condition if needed.
10334 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10335 DAG.getConstant(1, Cond.getValueType()));
10337 // Zero extend the condition if needed.
10338 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
10340 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10341 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
10342 DAG.getConstant(ShAmt, MVT::i8));
10345 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
10346 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10347 if (NeedsCondInvert) // Invert the condition if needed.
10348 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10349 DAG.getConstant(1, Cond.getValueType()));
10351 // Zero extend the condition if needed.
10352 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10353 FalseC->getValueType(0), Cond);
10354 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10355 SDValue(FalseC, 0));
10358 // Optimize cases that will turn into an LEA instruction. This requires
10359 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10360 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10361 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10362 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10364 bool isFastMultiplier = false;
10366 switch ((unsigned char)Diff) {
10368 case 1: // result = add base, cond
10369 case 2: // result = lea base( , cond*2)
10370 case 3: // result = lea base(cond, cond*2)
10371 case 4: // result = lea base( , cond*4)
10372 case 5: // result = lea base(cond, cond*4)
10373 case 8: // result = lea base( , cond*8)
10374 case 9: // result = lea base(cond, cond*8)
10375 isFastMultiplier = true;
10380 if (isFastMultiplier) {
10381 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10382 if (NeedsCondInvert) // Invert the condition if needed.
10383 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
10384 DAG.getConstant(1, Cond.getValueType()));
10386 // Zero extend the condition if needed.
10387 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10389 // Scale the condition by the difference.
10391 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10392 DAG.getConstant(Diff, Cond.getValueType()));
10394 // Add the base if non-zero.
10395 if (FalseC->getAPIntValue() != 0)
10396 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10397 SDValue(FalseC, 0));
10407 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
10408 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
10409 TargetLowering::DAGCombinerInfo &DCI) {
10410 DebugLoc DL = N->getDebugLoc();
10412 // If the flag operand isn't dead, don't touch this CMOV.
10413 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
10416 // If this is a select between two integer constants, try to do some
10417 // optimizations. Note that the operands are ordered the opposite of SELECT
10419 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
10420 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
10421 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
10422 // larger than FalseC (the false value).
10423 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
10425 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
10426 CC = X86::GetOppositeBranchCondition(CC);
10427 std::swap(TrueC, FalseC);
10430 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
10431 // This is efficient for any integer data type (including i8/i16) and
10433 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
10434 SDValue Cond = N->getOperand(3);
10435 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10436 DAG.getConstant(CC, MVT::i8), Cond);
10438 // Zero extend the condition if needed.
10439 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
10441 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
10442 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
10443 DAG.getConstant(ShAmt, MVT::i8));
10444 if (N->getNumValues() == 2) // Dead flag value?
10445 return DCI.CombineTo(N, Cond, SDValue());
10449 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
10450 // for any integer data type, including i8/i16.
10451 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
10452 SDValue Cond = N->getOperand(3);
10453 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10454 DAG.getConstant(CC, MVT::i8), Cond);
10456 // Zero extend the condition if needed.
10457 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
10458 FalseC->getValueType(0), Cond);
10459 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10460 SDValue(FalseC, 0));
10462 if (N->getNumValues() == 2) // Dead flag value?
10463 return DCI.CombineTo(N, Cond, SDValue());
10467 // Optimize cases that will turn into an LEA instruction. This requires
10468 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
10469 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
10470 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
10471 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
10473 bool isFastMultiplier = false;
10475 switch ((unsigned char)Diff) {
10477 case 1: // result = add base, cond
10478 case 2: // result = lea base( , cond*2)
10479 case 3: // result = lea base(cond, cond*2)
10480 case 4: // result = lea base( , cond*4)
10481 case 5: // result = lea base(cond, cond*4)
10482 case 8: // result = lea base( , cond*8)
10483 case 9: // result = lea base(cond, cond*8)
10484 isFastMultiplier = true;
10489 if (isFastMultiplier) {
10490 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
10491 SDValue Cond = N->getOperand(3);
10492 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
10493 DAG.getConstant(CC, MVT::i8), Cond);
10494 // Zero extend the condition if needed.
10495 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
10497 // Scale the condition by the difference.
10499 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
10500 DAG.getConstant(Diff, Cond.getValueType()));
10502 // Add the base if non-zero.
10503 if (FalseC->getAPIntValue() != 0)
10504 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
10505 SDValue(FalseC, 0));
10506 if (N->getNumValues() == 2) // Dead flag value?
10507 return DCI.CombineTo(N, Cond, SDValue());
10517 /// PerformMulCombine - Optimize a single multiply with constant into two
10518 /// in order to implement it with two cheaper instructions, e.g.
10519 /// LEA + SHL, LEA + LEA.
10520 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
10521 TargetLowering::DAGCombinerInfo &DCI) {
10522 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10525 EVT VT = N->getValueType(0);
10526 if (VT != MVT::i64)
10529 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10532 uint64_t MulAmt = C->getZExtValue();
10533 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
10536 uint64_t MulAmt1 = 0;
10537 uint64_t MulAmt2 = 0;
10538 if ((MulAmt % 9) == 0) {
10540 MulAmt2 = MulAmt / 9;
10541 } else if ((MulAmt % 5) == 0) {
10543 MulAmt2 = MulAmt / 5;
10544 } else if ((MulAmt % 3) == 0) {
10546 MulAmt2 = MulAmt / 3;
10549 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
10550 DebugLoc DL = N->getDebugLoc();
10552 if (isPowerOf2_64(MulAmt2) &&
10553 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
10554 // If second multiplifer is pow2, issue it first. We want the multiply by
10555 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
10557 std::swap(MulAmt1, MulAmt2);
10560 if (isPowerOf2_64(MulAmt1))
10561 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
10562 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
10564 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
10565 DAG.getConstant(MulAmt1, VT));
10567 if (isPowerOf2_64(MulAmt2))
10568 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
10569 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
10571 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
10572 DAG.getConstant(MulAmt2, VT));
10574 // Do not add new nodes to DAG combiner worklist.
10575 DCI.CombineTo(N, NewMul, false);
10580 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
10581 SDValue N0 = N->getOperand(0);
10582 SDValue N1 = N->getOperand(1);
10583 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
10584 EVT VT = N0.getValueType();
10586 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
10587 // since the result of setcc_c is all zero's or all ones.
10588 if (N1C && N0.getOpcode() == ISD::AND &&
10589 N0.getOperand(1).getOpcode() == ISD::Constant) {
10590 SDValue N00 = N0.getOperand(0);
10591 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
10592 ((N00.getOpcode() == ISD::ANY_EXTEND ||
10593 N00.getOpcode() == ISD::ZERO_EXTEND) &&
10594 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
10595 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
10596 APInt ShAmt = N1C->getAPIntValue();
10597 Mask = Mask.shl(ShAmt);
10599 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
10600 N00, DAG.getConstant(Mask, VT));
10607 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
10609 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
10610 const X86Subtarget *Subtarget) {
10611 EVT VT = N->getValueType(0);
10612 if (!VT.isVector() && VT.isInteger() &&
10613 N->getOpcode() == ISD::SHL)
10614 return PerformSHLCombine(N, DAG);
10616 // On X86 with SSE2 support, we can transform this to a vector shift if
10617 // all elements are shifted by the same amount. We can't do this in legalize
10618 // because the a constant vector is typically transformed to a constant pool
10619 // so we have no knowledge of the shift amount.
10620 if (!Subtarget->hasSSE2())
10623 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
10626 SDValue ShAmtOp = N->getOperand(1);
10627 EVT EltVT = VT.getVectorElementType();
10628 DebugLoc DL = N->getDebugLoc();
10629 SDValue BaseShAmt = SDValue();
10630 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
10631 unsigned NumElts = VT.getVectorNumElements();
10633 for (; i != NumElts; ++i) {
10634 SDValue Arg = ShAmtOp.getOperand(i);
10635 if (Arg.getOpcode() == ISD::UNDEF) continue;
10639 for (; i != NumElts; ++i) {
10640 SDValue Arg = ShAmtOp.getOperand(i);
10641 if (Arg.getOpcode() == ISD::UNDEF) continue;
10642 if (Arg != BaseShAmt) {
10646 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
10647 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
10648 SDValue InVec = ShAmtOp.getOperand(0);
10649 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
10650 unsigned NumElts = InVec.getValueType().getVectorNumElements();
10652 for (; i != NumElts; ++i) {
10653 SDValue Arg = InVec.getOperand(i);
10654 if (Arg.getOpcode() == ISD::UNDEF) continue;
10658 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
10659 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
10660 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
10661 if (C->getZExtValue() == SplatIdx)
10662 BaseShAmt = InVec.getOperand(1);
10665 if (BaseShAmt.getNode() == 0)
10666 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
10667 DAG.getIntPtrConstant(0));
10671 // The shift amount is an i32.
10672 if (EltVT.bitsGT(MVT::i32))
10673 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
10674 else if (EltVT.bitsLT(MVT::i32))
10675 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
10677 // The shift amount is identical so we can do a vector shift.
10678 SDValue ValOp = N->getOperand(0);
10679 switch (N->getOpcode()) {
10681 llvm_unreachable("Unknown shift opcode!");
10684 if (VT == MVT::v2i64)
10685 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10686 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
10688 if (VT == MVT::v4i32)
10689 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10690 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
10692 if (VT == MVT::v8i16)
10693 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10694 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
10698 if (VT == MVT::v4i32)
10699 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10700 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
10702 if (VT == MVT::v8i16)
10703 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10704 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
10708 if (VT == MVT::v2i64)
10709 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10710 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
10712 if (VT == MVT::v4i32)
10713 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10714 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
10716 if (VT == MVT::v8i16)
10717 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
10718 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
10725 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
10726 TargetLowering::DAGCombinerInfo &DCI,
10727 const X86Subtarget *Subtarget) {
10728 if (DCI.isBeforeLegalizeOps())
10731 EVT VT = N->getValueType(0);
10732 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
10735 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
10736 SDValue N0 = N->getOperand(0);
10737 SDValue N1 = N->getOperand(1);
10738 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
10740 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
10742 if (!N0.hasOneUse() || !N1.hasOneUse())
10745 SDValue ShAmt0 = N0.getOperand(1);
10746 if (ShAmt0.getValueType() != MVT::i8)
10748 SDValue ShAmt1 = N1.getOperand(1);
10749 if (ShAmt1.getValueType() != MVT::i8)
10751 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
10752 ShAmt0 = ShAmt0.getOperand(0);
10753 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
10754 ShAmt1 = ShAmt1.getOperand(0);
10756 DebugLoc DL = N->getDebugLoc();
10757 unsigned Opc = X86ISD::SHLD;
10758 SDValue Op0 = N0.getOperand(0);
10759 SDValue Op1 = N1.getOperand(0);
10760 if (ShAmt0.getOpcode() == ISD::SUB) {
10761 Opc = X86ISD::SHRD;
10762 std::swap(Op0, Op1);
10763 std::swap(ShAmt0, ShAmt1);
10766 unsigned Bits = VT.getSizeInBits();
10767 if (ShAmt1.getOpcode() == ISD::SUB) {
10768 SDValue Sum = ShAmt1.getOperand(0);
10769 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
10770 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
10771 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
10772 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
10773 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
10774 return DAG.getNode(Opc, DL, VT,
10776 DAG.getNode(ISD::TRUNCATE, DL,
10779 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
10780 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
10782 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
10783 return DAG.getNode(Opc, DL, VT,
10784 N0.getOperand(0), N1.getOperand(0),
10785 DAG.getNode(ISD::TRUNCATE, DL,
10792 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
10793 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
10794 const X86Subtarget *Subtarget) {
10795 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
10796 // the FP state in cases where an emms may be missing.
10797 // A preferable solution to the general problem is to figure out the right
10798 // places to insert EMMS. This qualifies as a quick hack.
10800 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
10801 StoreSDNode *St = cast<StoreSDNode>(N);
10802 EVT VT = St->getValue().getValueType();
10803 if (VT.getSizeInBits() != 64)
10806 const Function *F = DAG.getMachineFunction().getFunction();
10807 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
10808 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
10809 && Subtarget->hasSSE2();
10810 if ((VT.isVector() ||
10811 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
10812 isa<LoadSDNode>(St->getValue()) &&
10813 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
10814 St->getChain().hasOneUse() && !St->isVolatile()) {
10815 SDNode* LdVal = St->getValue().getNode();
10816 LoadSDNode *Ld = 0;
10817 int TokenFactorIndex = -1;
10818 SmallVector<SDValue, 8> Ops;
10819 SDNode* ChainVal = St->getChain().getNode();
10820 // Must be a store of a load. We currently handle two cases: the load
10821 // is a direct child, and it's under an intervening TokenFactor. It is
10822 // possible to dig deeper under nested TokenFactors.
10823 if (ChainVal == LdVal)
10824 Ld = cast<LoadSDNode>(St->getChain());
10825 else if (St->getValue().hasOneUse() &&
10826 ChainVal->getOpcode() == ISD::TokenFactor) {
10827 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
10828 if (ChainVal->getOperand(i).getNode() == LdVal) {
10829 TokenFactorIndex = i;
10830 Ld = cast<LoadSDNode>(St->getValue());
10832 Ops.push_back(ChainVal->getOperand(i));
10836 if (!Ld || !ISD::isNormalLoad(Ld))
10839 // If this is not the MMX case, i.e. we are just turning i64 load/store
10840 // into f64 load/store, avoid the transformation if there are multiple
10841 // uses of the loaded value.
10842 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
10845 DebugLoc LdDL = Ld->getDebugLoc();
10846 DebugLoc StDL = N->getDebugLoc();
10847 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
10848 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
10850 if (Subtarget->is64Bit() || F64IsLegal) {
10851 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
10852 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
10853 Ld->getPointerInfo(), Ld->isVolatile(),
10854 Ld->isNonTemporal(), Ld->getAlignment());
10855 SDValue NewChain = NewLd.getValue(1);
10856 if (TokenFactorIndex != -1) {
10857 Ops.push_back(NewChain);
10858 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
10861 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
10862 St->getPointerInfo(),
10863 St->isVolatile(), St->isNonTemporal(),
10864 St->getAlignment());
10867 // Otherwise, lower to two pairs of 32-bit loads / stores.
10868 SDValue LoAddr = Ld->getBasePtr();
10869 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
10870 DAG.getConstant(4, MVT::i32));
10872 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
10873 Ld->getPointerInfo(),
10874 Ld->isVolatile(), Ld->isNonTemporal(),
10875 Ld->getAlignment());
10876 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
10877 Ld->getPointerInfo().getWithOffset(4),
10878 Ld->isVolatile(), Ld->isNonTemporal(),
10879 MinAlign(Ld->getAlignment(), 4));
10881 SDValue NewChain = LoLd.getValue(1);
10882 if (TokenFactorIndex != -1) {
10883 Ops.push_back(LoLd);
10884 Ops.push_back(HiLd);
10885 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
10889 LoAddr = St->getBasePtr();
10890 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
10891 DAG.getConstant(4, MVT::i32));
10893 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
10894 St->getPointerInfo(),
10895 St->isVolatile(), St->isNonTemporal(),
10896 St->getAlignment());
10897 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
10898 St->getPointerInfo().getWithOffset(4),
10900 St->isNonTemporal(),
10901 MinAlign(St->getAlignment(), 4));
10902 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
10907 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
10908 /// X86ISD::FXOR nodes.
10909 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
10910 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
10911 // F[X]OR(0.0, x) -> x
10912 // F[X]OR(x, 0.0) -> x
10913 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
10914 if (C->getValueAPF().isPosZero())
10915 return N->getOperand(1);
10916 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
10917 if (C->getValueAPF().isPosZero())
10918 return N->getOperand(0);
10922 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
10923 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
10924 // FAND(0.0, x) -> 0.0
10925 // FAND(x, 0.0) -> 0.0
10926 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
10927 if (C->getValueAPF().isPosZero())
10928 return N->getOperand(0);
10929 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
10930 if (C->getValueAPF().isPosZero())
10931 return N->getOperand(1);
10935 static SDValue PerformBTCombine(SDNode *N,
10937 TargetLowering::DAGCombinerInfo &DCI) {
10938 // BT ignores high bits in the bit index operand.
10939 SDValue Op1 = N->getOperand(1);
10940 if (Op1.hasOneUse()) {
10941 unsigned BitWidth = Op1.getValueSizeInBits();
10942 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
10943 APInt KnownZero, KnownOne;
10944 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
10945 !DCI.isBeforeLegalizeOps());
10946 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10947 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
10948 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
10949 DCI.CommitTargetLoweringOpt(TLO);
10954 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
10955 SDValue Op = N->getOperand(0);
10956 if (Op.getOpcode() == ISD::BIT_CONVERT)
10957 Op = Op.getOperand(0);
10958 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
10959 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
10960 VT.getVectorElementType().getSizeInBits() ==
10961 OpVT.getVectorElementType().getSizeInBits()) {
10962 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
10967 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
10968 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
10969 // (and (i32 x86isd::setcc_carry), 1)
10970 // This eliminates the zext. This transformation is necessary because
10971 // ISD::SETCC is always legalized to i8.
10972 DebugLoc dl = N->getDebugLoc();
10973 SDValue N0 = N->getOperand(0);
10974 EVT VT = N->getValueType(0);
10975 if (N0.getOpcode() == ISD::AND &&
10977 N0.getOperand(0).hasOneUse()) {
10978 SDValue N00 = N0.getOperand(0);
10979 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
10981 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
10982 if (!C || C->getZExtValue() != 1)
10984 return DAG.getNode(ISD::AND, dl, VT,
10985 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
10986 N00.getOperand(0), N00.getOperand(1)),
10987 DAG.getConstant(1, VT));
10993 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
10994 DAGCombinerInfo &DCI) const {
10995 SelectionDAG &DAG = DCI.DAG;
10996 switch (N->getOpcode()) {
10998 case ISD::EXTRACT_VECTOR_ELT:
10999 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
11000 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
11001 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
11002 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
11005 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
11006 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
11007 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
11009 case X86ISD::FOR: return PerformFORCombine(N, DAG);
11010 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
11011 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
11012 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
11013 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
11014 case X86ISD::SHUFPS: // Handle all target specific shuffles
11015 case X86ISD::SHUFPD:
11016 case X86ISD::PALIGN:
11017 case X86ISD::PUNPCKHBW:
11018 case X86ISD::PUNPCKHWD:
11019 case X86ISD::PUNPCKHDQ:
11020 case X86ISD::PUNPCKHQDQ:
11021 case X86ISD::UNPCKHPS:
11022 case X86ISD::UNPCKHPD:
11023 case X86ISD::PUNPCKLBW:
11024 case X86ISD::PUNPCKLWD:
11025 case X86ISD::PUNPCKLDQ:
11026 case X86ISD::PUNPCKLQDQ:
11027 case X86ISD::UNPCKLPS:
11028 case X86ISD::UNPCKLPD:
11029 case X86ISD::MOVHLPS:
11030 case X86ISD::MOVLHPS:
11031 case X86ISD::PSHUFD:
11032 case X86ISD::PSHUFHW:
11033 case X86ISD::PSHUFLW:
11034 case X86ISD::MOVSS:
11035 case X86ISD::MOVSD:
11036 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
11042 /// isTypeDesirableForOp - Return true if the target has native support for
11043 /// the specified value type and it is 'desirable' to use the type for the
11044 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
11045 /// instruction encodings are longer and some i16 instructions are slow.
11046 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
11047 if (!isTypeLegal(VT))
11049 if (VT != MVT::i16)
11056 case ISD::SIGN_EXTEND:
11057 case ISD::ZERO_EXTEND:
11058 case ISD::ANY_EXTEND:
11071 /// IsDesirableToPromoteOp - This method query the target whether it is
11072 /// beneficial for dag combiner to promote the specified node. If true, it
11073 /// should return the desired promotion type by reference.
11074 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
11075 EVT VT = Op.getValueType();
11076 if (VT != MVT::i16)
11079 bool Promote = false;
11080 bool Commute = false;
11081 switch (Op.getOpcode()) {
11084 LoadSDNode *LD = cast<LoadSDNode>(Op);
11085 // If the non-extending load has a single use and it's not live out, then it
11086 // might be folded.
11087 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
11088 Op.hasOneUse()*/) {
11089 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11090 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
11091 // The only case where we'd want to promote LOAD (rather then it being
11092 // promoted as an operand is when it's only use is liveout.
11093 if (UI->getOpcode() != ISD::CopyToReg)
11100 case ISD::SIGN_EXTEND:
11101 case ISD::ZERO_EXTEND:
11102 case ISD::ANY_EXTEND:
11107 SDValue N0 = Op.getOperand(0);
11108 // Look out for (store (shl (load), x)).
11109 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
11122 SDValue N0 = Op.getOperand(0);
11123 SDValue N1 = Op.getOperand(1);
11124 if (!Commute && MayFoldLoad(N1))
11126 // Avoid disabling potential load folding opportunities.
11127 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
11129 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
11139 //===----------------------------------------------------------------------===//
11140 // X86 Inline Assembly Support
11141 //===----------------------------------------------------------------------===//
11143 static bool LowerToBSwap(CallInst *CI) {
11144 // FIXME: this should verify that we are targetting a 486 or better. If not,
11145 // we will turn this bswap into something that will be lowered to logical ops
11146 // instead of emitting the bswap asm. For now, we don't support 486 or lower
11147 // so don't worry about this.
11149 // Verify this is a simple bswap.
11150 if (CI->getNumArgOperands() != 1 ||
11151 CI->getType() != CI->getArgOperand(0)->getType() ||
11152 !CI->getType()->isIntegerTy())
11155 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
11156 if (!Ty || Ty->getBitWidth() % 16 != 0)
11159 // Okay, we can do this xform, do so now.
11160 const Type *Tys[] = { Ty };
11161 Module *M = CI->getParent()->getParent()->getParent();
11162 Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
11164 Value *Op = CI->getArgOperand(0);
11165 Op = CallInst::Create(Int, Op, CI->getName(), CI);
11167 CI->replaceAllUsesWith(Op);
11168 CI->eraseFromParent();
11172 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
11173 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
11174 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
11176 std::string AsmStr = IA->getAsmString();
11178 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
11179 SmallVector<StringRef, 4> AsmPieces;
11180 SplitString(AsmStr, AsmPieces, "\n"); // ; as separator?
11182 switch (AsmPieces.size()) {
11183 default: return false;
11185 AsmStr = AsmPieces[0];
11187 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
11190 if (AsmPieces.size() == 2 &&
11191 (AsmPieces[0] == "bswap" ||
11192 AsmPieces[0] == "bswapq" ||
11193 AsmPieces[0] == "bswapl") &&
11194 (AsmPieces[1] == "$0" ||
11195 AsmPieces[1] == "${0:q}")) {
11196 // No need to check constraints, nothing other than the equivalent of
11197 // "=r,0" would be valid here.
11198 return LowerToBSwap(CI);
11200 // rorw $$8, ${0:w} --> llvm.bswap.i16
11201 if (CI->getType()->isIntegerTy(16) &&
11202 AsmPieces.size() == 3 &&
11203 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
11204 AsmPieces[1] == "$$8," &&
11205 AsmPieces[2] == "${0:w}" &&
11206 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
11208 const std::string &Constraints = IA->getConstraintString();
11209 SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
11210 std::sort(AsmPieces.begin(), AsmPieces.end());
11211 if (AsmPieces.size() == 4 &&
11212 AsmPieces[0] == "~{cc}" &&
11213 AsmPieces[1] == "~{dirflag}" &&
11214 AsmPieces[2] == "~{flags}" &&
11215 AsmPieces[3] == "~{fpsr}") {
11216 return LowerToBSwap(CI);
11221 if (CI->getType()->isIntegerTy(64) &&
11222 Constraints.size() >= 2 &&
11223 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
11224 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
11225 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
11226 SmallVector<StringRef, 4> Words;
11227 SplitString(AsmPieces[0], Words, " \t");
11228 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
11230 SplitString(AsmPieces[1], Words, " \t");
11231 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
11233 SplitString(AsmPieces[2], Words, " \t,");
11234 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
11235 Words[2] == "%edx") {
11236 return LowerToBSwap(CI);
11248 /// getConstraintType - Given a constraint letter, return the type of
11249 /// constraint it is for this target.
11250 X86TargetLowering::ConstraintType
11251 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
11252 if (Constraint.size() == 1) {
11253 switch (Constraint[0]) {
11265 return C_RegisterClass;
11273 return TargetLowering::getConstraintType(Constraint);
11276 /// Examine constraint type and operand type and determine a weight value,
11277 /// where: -1 = invalid match, and 0 = so-so match to 3 = good match.
11278 /// This object must already have been set up with the operand type
11279 /// and the current alternative constraint selected.
11280 int X86TargetLowering::getSingleConstraintMatchWeight(
11281 AsmOperandInfo &info, const char *constraint) const {
11283 Value *CallOperandVal = info.CallOperandVal;
11284 // If we don't have a value, we can't do a match,
11285 // but allow it at the lowest weight.
11286 if (CallOperandVal == NULL)
11288 // Look at the constraint type.
11289 switch (*constraint) {
11291 return TargetLowering::getSingleConstraintMatchWeight(info, constraint);
11294 if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
11295 if (C->getZExtValue() <= 31)
11304 /// LowerXConstraint - try to replace an X constraint, which matches anything,
11305 /// with another that has more specific requirements based on the type of the
11306 /// corresponding operand.
11307 const char *X86TargetLowering::
11308 LowerXConstraint(EVT ConstraintVT) const {
11309 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
11310 // 'f' like normal targets.
11311 if (ConstraintVT.isFloatingPoint()) {
11312 if (Subtarget->hasSSE2())
11314 if (Subtarget->hasSSE1())
11318 return TargetLowering::LowerXConstraint(ConstraintVT);
11321 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
11322 /// vector. If it is invalid, don't add anything to Ops.
11323 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11325 std::vector<SDValue>&Ops,
11326 SelectionDAG &DAG) const {
11327 SDValue Result(0, 0);
11329 switch (Constraint) {
11332 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11333 if (C->getZExtValue() <= 31) {
11334 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11340 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11341 if (C->getZExtValue() <= 63) {
11342 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11348 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11349 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
11350 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11356 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11357 if (C->getZExtValue() <= 255) {
11358 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11364 // 32-bit signed value
11365 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11366 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
11367 C->getSExtValue())) {
11368 // Widen to 64 bits here to get it sign extended.
11369 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
11372 // FIXME gcc accepts some relocatable values here too, but only in certain
11373 // memory models; it's complicated.
11378 // 32-bit unsigned value
11379 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11380 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
11381 C->getZExtValue())) {
11382 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
11386 // FIXME gcc accepts some relocatable values here too, but only in certain
11387 // memory models; it's complicated.
11391 // Literal immediates are always ok.
11392 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
11393 // Widen to 64 bits here to get it sign extended.
11394 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
11398 // In any sort of PIC mode addresses need to be computed at runtime by
11399 // adding in a register or some sort of table lookup. These can't
11400 // be used as immediates.
11401 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
11404 // If we are in non-pic codegen mode, we allow the address of a global (with
11405 // an optional displacement) to be used with 'i'.
11406 GlobalAddressSDNode *GA = 0;
11407 int64_t Offset = 0;
11409 // Match either (GA), (GA+C), (GA+C1+C2), etc.
11411 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
11412 Offset += GA->getOffset();
11414 } else if (Op.getOpcode() == ISD::ADD) {
11415 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
11416 Offset += C->getZExtValue();
11417 Op = Op.getOperand(0);
11420 } else if (Op.getOpcode() == ISD::SUB) {
11421 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
11422 Offset += -C->getZExtValue();
11423 Op = Op.getOperand(0);
11428 // Otherwise, this isn't something we can handle, reject it.
11432 const GlobalValue *GV = GA->getGlobal();
11433 // If we require an extra load to get this address, as in PIC mode, we
11434 // can't accept it.
11435 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
11436 getTargetMachine())))
11439 Result = DAG.getTargetGlobalAddress(GV, Op.getDebugLoc(),
11440 GA->getValueType(0), Offset);
11445 if (Result.getNode()) {
11446 Ops.push_back(Result);
11449 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11452 std::vector<unsigned> X86TargetLowering::
11453 getRegClassForInlineAsmConstraint(const std::string &Constraint,
11455 if (Constraint.size() == 1) {
11456 // FIXME: not handling fp-stack yet!
11457 switch (Constraint[0]) { // GCC X86 Constraint Letters
11458 default: break; // Unknown constraint letter
11459 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
11460 if (Subtarget->is64Bit()) {
11461 if (VT == MVT::i32)
11462 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
11463 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
11464 X86::R10D,X86::R11D,X86::R12D,
11465 X86::R13D,X86::R14D,X86::R15D,
11466 X86::EBP, X86::ESP, 0);
11467 else if (VT == MVT::i16)
11468 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
11469 X86::SI, X86::DI, X86::R8W,X86::R9W,
11470 X86::R10W,X86::R11W,X86::R12W,
11471 X86::R13W,X86::R14W,X86::R15W,
11472 X86::BP, X86::SP, 0);
11473 else if (VT == MVT::i8)
11474 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
11475 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
11476 X86::R10B,X86::R11B,X86::R12B,
11477 X86::R13B,X86::R14B,X86::R15B,
11478 X86::BPL, X86::SPL, 0);
11480 else if (VT == MVT::i64)
11481 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
11482 X86::RSI, X86::RDI, X86::R8, X86::R9,
11483 X86::R10, X86::R11, X86::R12,
11484 X86::R13, X86::R14, X86::R15,
11485 X86::RBP, X86::RSP, 0);
11489 // 32-bit fallthrough
11490 case 'Q': // Q_REGS
11491 if (VT == MVT::i32)
11492 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
11493 else if (VT == MVT::i16)
11494 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
11495 else if (VT == MVT::i8)
11496 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
11497 else if (VT == MVT::i64)
11498 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
11503 return std::vector<unsigned>();
11506 std::pair<unsigned, const TargetRegisterClass*>
11507 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
11509 // First, see if this is a constraint that directly corresponds to an LLVM
11511 if (Constraint.size() == 1) {
11512 // GCC Constraint Letters
11513 switch (Constraint[0]) {
11515 case 'r': // GENERAL_REGS
11516 case 'l': // INDEX_REGS
11518 return std::make_pair(0U, X86::GR8RegisterClass);
11519 if (VT == MVT::i16)
11520 return std::make_pair(0U, X86::GR16RegisterClass);
11521 if (VT == MVT::i32 || !Subtarget->is64Bit())
11522 return std::make_pair(0U, X86::GR32RegisterClass);
11523 return std::make_pair(0U, X86::GR64RegisterClass);
11524 case 'R': // LEGACY_REGS
11526 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
11527 if (VT == MVT::i16)
11528 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
11529 if (VT == MVT::i32 || !Subtarget->is64Bit())
11530 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
11531 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
11532 case 'f': // FP Stack registers.
11533 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
11534 // value to the correct fpstack register class.
11535 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
11536 return std::make_pair(0U, X86::RFP32RegisterClass);
11537 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
11538 return std::make_pair(0U, X86::RFP64RegisterClass);
11539 return std::make_pair(0U, X86::RFP80RegisterClass);
11540 case 'y': // MMX_REGS if MMX allowed.
11541 if (!Subtarget->hasMMX()) break;
11542 return std::make_pair(0U, X86::VR64RegisterClass);
11543 case 'Y': // SSE_REGS if SSE2 allowed
11544 if (!Subtarget->hasSSE2()) break;
11546 case 'x': // SSE_REGS if SSE1 allowed
11547 if (!Subtarget->hasSSE1()) break;
11549 switch (VT.getSimpleVT().SimpleTy) {
11551 // Scalar SSE types.
11554 return std::make_pair(0U, X86::FR32RegisterClass);
11557 return std::make_pair(0U, X86::FR64RegisterClass);
11565 return std::make_pair(0U, X86::VR128RegisterClass);
11571 // Use the default implementation in TargetLowering to convert the register
11572 // constraint into a member of a register class.
11573 std::pair<unsigned, const TargetRegisterClass*> Res;
11574 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
11576 // Not found as a standard register?
11577 if (Res.second == 0) {
11578 // Map st(0) -> st(7) -> ST0
11579 if (Constraint.size() == 7 && Constraint[0] == '{' &&
11580 tolower(Constraint[1]) == 's' &&
11581 tolower(Constraint[2]) == 't' &&
11582 Constraint[3] == '(' &&
11583 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
11584 Constraint[5] == ')' &&
11585 Constraint[6] == '}') {
11587 Res.first = X86::ST0+Constraint[4]-'0';
11588 Res.second = X86::RFP80RegisterClass;
11592 // GCC allows "st(0)" to be called just plain "st".
11593 if (StringRef("{st}").equals_lower(Constraint)) {
11594 Res.first = X86::ST0;
11595 Res.second = X86::RFP80RegisterClass;
11600 if (StringRef("{flags}").equals_lower(Constraint)) {
11601 Res.first = X86::EFLAGS;
11602 Res.second = X86::CCRRegisterClass;
11606 // 'A' means EAX + EDX.
11607 if (Constraint == "A") {
11608 Res.first = X86::EAX;
11609 Res.second = X86::GR32_ADRegisterClass;
11615 // Otherwise, check to see if this is a register class of the wrong value
11616 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
11617 // turn into {ax},{dx}.
11618 if (Res.second->hasType(VT))
11619 return Res; // Correct type already, nothing to do.
11621 // All of the single-register GCC register classes map their values onto
11622 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
11623 // really want an 8-bit or 32-bit register, map to the appropriate register
11624 // class and return the appropriate register.
11625 if (Res.second == X86::GR16RegisterClass) {
11626 if (VT == MVT::i8) {
11627 unsigned DestReg = 0;
11628 switch (Res.first) {
11630 case X86::AX: DestReg = X86::AL; break;
11631 case X86::DX: DestReg = X86::DL; break;
11632 case X86::CX: DestReg = X86::CL; break;
11633 case X86::BX: DestReg = X86::BL; break;
11636 Res.first = DestReg;
11637 Res.second = X86::GR8RegisterClass;
11639 } else if (VT == MVT::i32) {
11640 unsigned DestReg = 0;
11641 switch (Res.first) {
11643 case X86::AX: DestReg = X86::EAX; break;
11644 case X86::DX: DestReg = X86::EDX; break;
11645 case X86::CX: DestReg = X86::ECX; break;
11646 case X86::BX: DestReg = X86::EBX; break;
11647 case X86::SI: DestReg = X86::ESI; break;
11648 case X86::DI: DestReg = X86::EDI; break;
11649 case X86::BP: DestReg = X86::EBP; break;
11650 case X86::SP: DestReg = X86::ESP; break;
11653 Res.first = DestReg;
11654 Res.second = X86::GR32RegisterClass;
11656 } else if (VT == MVT::i64) {
11657 unsigned DestReg = 0;
11658 switch (Res.first) {
11660 case X86::AX: DestReg = X86::RAX; break;
11661 case X86::DX: DestReg = X86::RDX; break;
11662 case X86::CX: DestReg = X86::RCX; break;
11663 case X86::BX: DestReg = X86::RBX; break;
11664 case X86::SI: DestReg = X86::RSI; break;
11665 case X86::DI: DestReg = X86::RDI; break;
11666 case X86::BP: DestReg = X86::RBP; break;
11667 case X86::SP: DestReg = X86::RSP; break;
11670 Res.first = DestReg;
11671 Res.second = X86::GR64RegisterClass;
11674 } else if (Res.second == X86::FR32RegisterClass ||
11675 Res.second == X86::FR64RegisterClass ||
11676 Res.second == X86::VR128RegisterClass) {
11677 // Handle references to XMM physical registers that got mapped into the
11678 // wrong class. This can happen with constraints like {xmm0} where the
11679 // target independent register mapper will just pick the first match it can
11680 // find, ignoring the required type.
11681 if (VT == MVT::f32)
11682 Res.second = X86::FR32RegisterClass;
11683 else if (VT == MVT::f64)
11684 Res.second = X86::FR64RegisterClass;
11685 else if (X86::VR128RegisterClass->hasType(VT))
11686 Res.second = X86::VR128RegisterClass;