1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
16 #include "X86InstrBuilder.h"
17 #include "X86ISelLowering.h"
18 #include "X86TargetMachine.h"
19 #include "X86TargetObjectFile.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/GlobalAlias.h"
24 #include "llvm/GlobalVariable.h"
25 #include "llvm/Function.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Intrinsics.h"
28 #include "llvm/LLVMContext.h"
29 #include "llvm/ADT/BitVector.h"
30 #include "llvm/ADT/VectorExtras.h"
31 #include "llvm/CodeGen/MachineFrameInfo.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/PseudoSourceValue.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Target/TargetOptions.h"
41 #include "llvm/ADT/SmallSet.h"
42 #include "llvm/ADT/StringExtras.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/raw_ostream.h"
48 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
50 // Disable16Bit - 16-bit operations typically have a larger encoding than
51 // corresponding 32-bit instructions, and 16-bit code is slow on some
52 // processors. This is an experimental flag to disable 16-bit operations
53 // (which forces them to be Legalized to 32-bit operations).
55 Disable16Bit("disable-16bit", cl::Hidden,
56 cl::desc("Disable use of 16-bit instructions"));
58 // Forward declarations.
59 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
62 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
63 switch (TM.getSubtarget<X86Subtarget>().TargetType) {
64 default: llvm_unreachable("unknown subtarget type");
65 case X86Subtarget::isDarwin:
66 if (TM.getSubtarget<X86Subtarget>().is64Bit())
67 return new X8664_MachoTargetObjectFile();
68 return new X8632_MachoTargetObjectFile();
69 case X86Subtarget::isELF:
70 return new TargetLoweringObjectFileELF();
71 case X86Subtarget::isMingw:
72 case X86Subtarget::isCygwin:
73 case X86Subtarget::isWindows:
74 return new TargetLoweringObjectFileCOFF();
79 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
80 : TargetLowering(TM, createTLOF(TM)) {
81 Subtarget = &TM.getSubtarget<X86Subtarget>();
82 X86ScalarSSEf64 = Subtarget->hasSSE2();
83 X86ScalarSSEf32 = Subtarget->hasSSE1();
84 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
86 RegInfo = TM.getRegisterInfo();
89 // Set up the TargetLowering object.
91 // X86 is weird, it always uses i8 for shift amounts and setcc results.
92 setShiftAmountType(MVT::i8);
93 setBooleanContents(ZeroOrOneBooleanContent);
94 setSchedulingPreference(SchedulingForRegPressure);
95 setStackPointerRegisterToSaveRestore(X86StackPtr);
97 if (Subtarget->isTargetDarwin()) {
98 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
99 setUseUnderscoreSetJmp(false);
100 setUseUnderscoreLongJmp(false);
101 } else if (Subtarget->isTargetMingw()) {
102 // MS runtime is weird: it exports _setjmp, but longjmp!
103 setUseUnderscoreSetJmp(true);
104 setUseUnderscoreLongJmp(false);
106 setUseUnderscoreSetJmp(true);
107 setUseUnderscoreLongJmp(true);
110 // Set up the register classes.
111 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
113 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
114 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
115 if (Subtarget->is64Bit())
116 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
118 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
120 // We don't accept any truncstore of integer registers.
121 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
123 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
124 setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
126 setTruncStoreAction(MVT::i32, MVT::i16, Expand);
127 setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
128 setTruncStoreAction(MVT::i16, MVT::i8, Expand);
130 // SETOEQ and SETUNE require checking two conditions.
131 setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
132 setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
133 setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
134 setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
135 setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
136 setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
138 // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
140 setOperationAction(ISD::UINT_TO_FP , MVT::i1 , Promote);
141 setOperationAction(ISD::UINT_TO_FP , MVT::i8 , Promote);
142 setOperationAction(ISD::UINT_TO_FP , MVT::i16 , Promote);
144 if (Subtarget->is64Bit()) {
145 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Promote);
146 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Expand);
147 } else if (!UseSoftFloat) {
148 if (X86ScalarSSEf64) {
149 // We have an impenetrably clever algorithm for ui64->double only.
150 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
152 // We have an algorithm for SSE2, and we turn this into a 64-bit
153 // FILD for other targets.
154 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
157 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
159 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
160 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
163 // SSE has no i16 to fp conversion, only i32
164 if (X86ScalarSSEf32) {
165 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
166 // f32 and f64 cases are Legal, f80 case is not
167 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
169 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
170 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
173 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
174 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
177 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
178 // are Legal, f80 is custom lowered.
179 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
180 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
182 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
184 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
185 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
187 if (X86ScalarSSEf32) {
188 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
189 // f32 and f64 cases are Legal, f80 case is not
190 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
192 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
193 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
196 // Handle FP_TO_UINT by promoting the destination to a larger signed
198 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
199 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
200 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
202 if (Subtarget->is64Bit()) {
203 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
204 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
205 } else if (!UseSoftFloat) {
206 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
207 // Expand FP_TO_UINT into a select.
208 // FIXME: We would like to use a Custom expander here eventually to do
209 // the optimal thing for SSE vs. the default expansion in the legalizer.
210 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
212 // With SSE3 we can use fisttpll to convert to a signed i64; without
213 // SSE, we're stuck with a fistpll.
214 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
217 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
218 if (!X86ScalarSSEf64) {
219 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
220 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
223 // Scalar integer divide and remainder are lowered to use operations that
224 // produce two results, to match the available instructions. This exposes
225 // the two-result form to trivial CSE, which is able to combine x/y and x%y
226 // into a single instruction.
228 // Scalar integer multiply-high is also lowered to use two-result
229 // operations, to match the available instructions. However, plain multiply
230 // (low) operations are left as Legal, as there are single-result
231 // instructions for this in x86. Using the two-result multiply instructions
232 // when both high and low results are needed must be arranged by dagcombine.
233 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
234 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
235 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
236 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
237 setOperationAction(ISD::SREM , MVT::i8 , Expand);
238 setOperationAction(ISD::UREM , MVT::i8 , Expand);
239 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
240 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
241 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
242 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
243 setOperationAction(ISD::SREM , MVT::i16 , Expand);
244 setOperationAction(ISD::UREM , MVT::i16 , Expand);
245 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
246 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
247 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
248 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
249 setOperationAction(ISD::SREM , MVT::i32 , Expand);
250 setOperationAction(ISD::UREM , MVT::i32 , Expand);
251 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
252 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
253 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
254 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
255 setOperationAction(ISD::SREM , MVT::i64 , Expand);
256 setOperationAction(ISD::UREM , MVT::i64 , Expand);
258 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
259 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
260 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
261 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
262 if (Subtarget->is64Bit())
263 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
264 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
265 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
266 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
267 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
268 setOperationAction(ISD::FREM , MVT::f32 , Expand);
269 setOperationAction(ISD::FREM , MVT::f64 , Expand);
270 setOperationAction(ISD::FREM , MVT::f80 , Expand);
271 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
273 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
274 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
275 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
276 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
278 setOperationAction(ISD::CTTZ , MVT::i16 , Expand);
279 setOperationAction(ISD::CTLZ , MVT::i16 , Expand);
281 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
282 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
284 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
285 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
286 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
287 if (Subtarget->is64Bit()) {
288 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
289 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
290 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
293 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
294 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
296 // These should be promoted to a larger select which is supported.
297 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
298 // X86 wants to expand cmov itself.
299 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
301 setOperationAction(ISD::SELECT , MVT::i16 , Expand);
303 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
304 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
305 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
306 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
307 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
308 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
310 setOperationAction(ISD::SETCC , MVT::i16 , Expand);
312 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
313 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
314 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
315 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
316 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
317 if (Subtarget->is64Bit()) {
318 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
319 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
321 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
324 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
325 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
326 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
327 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
328 if (Subtarget->is64Bit())
329 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
330 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
331 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
332 if (Subtarget->is64Bit()) {
333 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
334 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
335 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
336 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
337 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
339 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
340 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
341 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
342 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
343 if (Subtarget->is64Bit()) {
344 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
345 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
346 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
349 if (Subtarget->hasSSE1())
350 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
352 if (!Subtarget->hasSSE2())
353 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
355 // Expand certain atomics
356 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
357 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
358 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
359 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
361 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
362 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
363 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
364 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
366 if (!Subtarget->is64Bit()) {
367 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
368 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
369 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
370 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
371 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
372 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
373 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
376 // Use the default ISD::DBG_STOPPOINT.
377 setOperationAction(ISD::DBG_STOPPOINT, MVT::Other, Expand);
378 // FIXME - use subtarget debug flags
379 if (!Subtarget->isTargetDarwin() &&
380 !Subtarget->isTargetELF() &&
381 !Subtarget->isTargetCygMing()) {
382 setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
383 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
386 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
387 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
388 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
389 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
390 if (Subtarget->is64Bit()) {
391 setExceptionPointerRegister(X86::RAX);
392 setExceptionSelectorRegister(X86::RDX);
394 setExceptionPointerRegister(X86::EAX);
395 setExceptionSelectorRegister(X86::EDX);
397 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
398 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
400 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
402 setOperationAction(ISD::TRAP, MVT::Other, Legal);
404 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
405 setOperationAction(ISD::VASTART , MVT::Other, Custom);
406 setOperationAction(ISD::VAEND , MVT::Other, Expand);
407 if (Subtarget->is64Bit()) {
408 setOperationAction(ISD::VAARG , MVT::Other, Custom);
409 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
411 setOperationAction(ISD::VAARG , MVT::Other, Expand);
412 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
415 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
416 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
417 if (Subtarget->is64Bit())
418 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
419 if (Subtarget->isTargetCygMing())
420 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
422 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
424 if (!UseSoftFloat && X86ScalarSSEf64) {
425 // f32 and f64 use SSE.
426 // Set up the FP register classes.
427 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
428 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
430 // Use ANDPD to simulate FABS.
431 setOperationAction(ISD::FABS , MVT::f64, Custom);
432 setOperationAction(ISD::FABS , MVT::f32, Custom);
434 // Use XORP to simulate FNEG.
435 setOperationAction(ISD::FNEG , MVT::f64, Custom);
436 setOperationAction(ISD::FNEG , MVT::f32, Custom);
438 // Use ANDPD and ORPD to simulate FCOPYSIGN.
439 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
440 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
442 // We don't support sin/cos/fmod
443 setOperationAction(ISD::FSIN , MVT::f64, Expand);
444 setOperationAction(ISD::FCOS , MVT::f64, Expand);
445 setOperationAction(ISD::FSIN , MVT::f32, Expand);
446 setOperationAction(ISD::FCOS , MVT::f32, Expand);
448 // Expand FP immediates into loads from the stack, except for the special
450 addLegalFPImmediate(APFloat(+0.0)); // xorpd
451 addLegalFPImmediate(APFloat(+0.0f)); // xorps
452 } else if (!UseSoftFloat && X86ScalarSSEf32) {
453 // Use SSE for f32, x87 for f64.
454 // Set up the FP register classes.
455 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
456 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
458 // Use ANDPS to simulate FABS.
459 setOperationAction(ISD::FABS , MVT::f32, Custom);
461 // Use XORP to simulate FNEG.
462 setOperationAction(ISD::FNEG , MVT::f32, Custom);
464 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
466 // Use ANDPS and ORPS to simulate FCOPYSIGN.
467 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
468 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
470 // We don't support sin/cos/fmod
471 setOperationAction(ISD::FSIN , MVT::f32, Expand);
472 setOperationAction(ISD::FCOS , MVT::f32, Expand);
474 // Special cases we handle for FP constants.
475 addLegalFPImmediate(APFloat(+0.0f)); // xorps
476 addLegalFPImmediate(APFloat(+0.0)); // FLD0
477 addLegalFPImmediate(APFloat(+1.0)); // FLD1
478 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
479 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
482 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
483 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
485 } else if (!UseSoftFloat) {
486 // f32 and f64 in x87.
487 // Set up the FP register classes.
488 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
489 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
491 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
492 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
493 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
494 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
497 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
498 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
500 addLegalFPImmediate(APFloat(+0.0)); // FLD0
501 addLegalFPImmediate(APFloat(+1.0)); // FLD1
502 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
503 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
504 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
505 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
506 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
507 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
510 // Long double always uses X87.
512 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
513 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
514 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
517 APFloat TmpFlt(+0.0);
518 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
520 addLegalFPImmediate(TmpFlt); // FLD0
522 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
523 APFloat TmpFlt2(+1.0);
524 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
526 addLegalFPImmediate(TmpFlt2); // FLD1
527 TmpFlt2.changeSign();
528 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
532 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
533 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
537 // Always use a library call for pow.
538 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
539 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
540 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
542 setOperationAction(ISD::FLOG, MVT::f80, Expand);
543 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
544 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
545 setOperationAction(ISD::FEXP, MVT::f80, Expand);
546 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
548 // First set operation action for all vector types to either promote
549 // (for widening) or expand (for scalarization). Then we will selectively
550 // turn on ones that can be effectively codegen'd.
551 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
552 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
553 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
554 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
555 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
556 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
557 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
558 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
559 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
560 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
561 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
562 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
563 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
564 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
565 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
566 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
567 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
568 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
569 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
570 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
571 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
572 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
573 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
574 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
575 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
576 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
577 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
578 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
579 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
580 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
581 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
582 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
583 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
584 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
585 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
586 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
587 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
588 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
589 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
590 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
591 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
592 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
593 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
594 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
595 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
596 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
597 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
598 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
599 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
600 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
603 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
604 // with -msoft-float, disable use of MMX as well.
605 if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
606 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
607 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
608 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
609 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
610 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
612 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
613 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
614 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
615 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
617 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
618 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
619 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
620 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
622 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
623 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
625 setOperationAction(ISD::AND, MVT::v8i8, Promote);
626 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
627 setOperationAction(ISD::AND, MVT::v4i16, Promote);
628 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
629 setOperationAction(ISD::AND, MVT::v2i32, Promote);
630 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
631 setOperationAction(ISD::AND, MVT::v1i64, Legal);
633 setOperationAction(ISD::OR, MVT::v8i8, Promote);
634 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
635 setOperationAction(ISD::OR, MVT::v4i16, Promote);
636 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
637 setOperationAction(ISD::OR, MVT::v2i32, Promote);
638 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
639 setOperationAction(ISD::OR, MVT::v1i64, Legal);
641 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
642 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
643 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
644 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
645 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
646 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
647 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
649 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
650 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
651 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
652 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
653 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
654 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
655 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
656 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
657 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
659 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
660 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
661 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
662 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
663 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
665 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
666 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
667 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
668 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
670 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
671 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
672 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
673 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
675 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
677 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
678 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Expand);
679 setOperationAction(ISD::SELECT, MVT::v8i8, Promote);
680 setOperationAction(ISD::SELECT, MVT::v4i16, Promote);
681 setOperationAction(ISD::SELECT, MVT::v2i32, Promote);
682 setOperationAction(ISD::SELECT, MVT::v1i64, Custom);
683 setOperationAction(ISD::VSETCC, MVT::v8i8, Custom);
684 setOperationAction(ISD::VSETCC, MVT::v4i16, Custom);
685 setOperationAction(ISD::VSETCC, MVT::v2i32, Custom);
688 if (!UseSoftFloat && Subtarget->hasSSE1()) {
689 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
691 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
692 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
693 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
694 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
695 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
696 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
697 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
698 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
699 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
700 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
701 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
702 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
705 if (!UseSoftFloat && Subtarget->hasSSE2()) {
706 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
708 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
709 // registers cannot be used even for integer operations.
710 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
711 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
712 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
713 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
715 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
716 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
717 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
718 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
719 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
720 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
721 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
722 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
723 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
724 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
725 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
726 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
727 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
728 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
729 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
730 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
732 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
733 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
734 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
735 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
737 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
738 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
739 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
740 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
741 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
743 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
744 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
745 EVT VT = (MVT::SimpleValueType)i;
746 // Do not attempt to custom lower non-power-of-2 vectors
747 if (!isPowerOf2_32(VT.getVectorNumElements()))
749 // Do not attempt to custom lower non-128-bit vectors
750 if (!VT.is128BitVector())
752 setOperationAction(ISD::BUILD_VECTOR,
753 VT.getSimpleVT().SimpleTy, Custom);
754 setOperationAction(ISD::VECTOR_SHUFFLE,
755 VT.getSimpleVT().SimpleTy, Custom);
756 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
757 VT.getSimpleVT().SimpleTy, Custom);
760 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
761 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
762 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
763 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
764 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
765 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
767 if (Subtarget->is64Bit()) {
768 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
769 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
772 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
773 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
774 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
777 // Do not attempt to promote non-128-bit vectors
778 if (!VT.is128BitVector()) {
781 setOperationAction(ISD::AND, SVT, Promote);
782 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
783 setOperationAction(ISD::OR, SVT, Promote);
784 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
785 setOperationAction(ISD::XOR, SVT, Promote);
786 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
787 setOperationAction(ISD::LOAD, SVT, Promote);
788 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
789 setOperationAction(ISD::SELECT, SVT, Promote);
790 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
793 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
795 // Custom lower v2i64 and v2f64 selects.
796 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
797 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
798 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
799 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
801 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
802 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
803 if (!DisableMMX && Subtarget->hasMMX()) {
804 setOperationAction(ISD::FP_TO_SINT, MVT::v2i32, Custom);
805 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
809 if (Subtarget->hasSSE41()) {
810 // FIXME: Do we need to handle scalar-to-vector here?
811 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
813 // i8 and i16 vectors are custom , because the source register and source
814 // source memory operand types are not the same width. f32 vectors are
815 // custom since the immediate controlling the insert encodes additional
817 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
818 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
819 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
820 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
822 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
823 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
824 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
825 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
827 if (Subtarget->is64Bit()) {
828 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
829 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
833 if (Subtarget->hasSSE42()) {
834 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
837 if (!UseSoftFloat && Subtarget->hasAVX()) {
838 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
839 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
840 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
841 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
843 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
844 setOperationAction(ISD::LOAD, MVT::v8i32, Legal);
845 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
846 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
847 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
848 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
849 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
850 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
851 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
852 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
853 //setOperationAction(ISD::BUILD_VECTOR, MVT::v8f32, Custom);
854 //setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Custom);
855 //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
856 //setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
857 //setOperationAction(ISD::VSETCC, MVT::v8f32, Custom);
859 // Operations to consider commented out -v16i16 v32i8
860 //setOperationAction(ISD::ADD, MVT::v16i16, Legal);
861 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
862 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
863 //setOperationAction(ISD::SUB, MVT::v32i8, Legal);
864 //setOperationAction(ISD::SUB, MVT::v16i16, Legal);
865 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
866 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
867 //setOperationAction(ISD::MUL, MVT::v16i16, Legal);
868 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
869 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
870 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
871 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
872 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
873 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
875 setOperationAction(ISD::VSETCC, MVT::v4f64, Custom);
876 // setOperationAction(ISD::VSETCC, MVT::v32i8, Custom);
877 // setOperationAction(ISD::VSETCC, MVT::v16i16, Custom);
878 setOperationAction(ISD::VSETCC, MVT::v8i32, Custom);
880 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v32i8, Custom);
881 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i16, Custom);
882 // setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i16, Custom);
883 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i32, Custom);
884 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8f32, Custom);
886 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
887 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i64, Custom);
888 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f64, Custom);
889 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i64, Custom);
890 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f64, Custom);
891 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
894 // Not sure we want to do this since there are no 256-bit integer
897 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
898 // This includes 256-bit vectors
899 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
900 EVT VT = (MVT::SimpleValueType)i;
902 // Do not attempt to custom lower non-power-of-2 vectors
903 if (!isPowerOf2_32(VT.getVectorNumElements()))
906 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
907 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
908 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
911 if (Subtarget->is64Bit()) {
912 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i64, Custom);
913 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
918 // Not sure we want to do this since there are no 256-bit integer
921 // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
922 // Including 256-bit vectors
923 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
924 EVT VT = (MVT::SimpleValueType)i;
926 if (!VT.is256BitVector()) {
929 setOperationAction(ISD::AND, VT, Promote);
930 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
931 setOperationAction(ISD::OR, VT, Promote);
932 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
933 setOperationAction(ISD::XOR, VT, Promote);
934 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
935 setOperationAction(ISD::LOAD, VT, Promote);
936 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
937 setOperationAction(ISD::SELECT, VT, Promote);
938 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
941 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
945 // We want to custom lower some of our intrinsics.
946 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
948 // Add/Sub/Mul with overflow operations are custom lowered.
949 setOperationAction(ISD::SADDO, MVT::i32, Custom);
950 setOperationAction(ISD::SADDO, MVT::i64, Custom);
951 setOperationAction(ISD::UADDO, MVT::i32, Custom);
952 setOperationAction(ISD::UADDO, MVT::i64, Custom);
953 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
954 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
955 setOperationAction(ISD::USUBO, MVT::i32, Custom);
956 setOperationAction(ISD::USUBO, MVT::i64, Custom);
957 setOperationAction(ISD::SMULO, MVT::i32, Custom);
958 setOperationAction(ISD::SMULO, MVT::i64, Custom);
960 if (!Subtarget->is64Bit()) {
961 // These libcalls are not available in 32-bit.
962 setLibcallName(RTLIB::SHL_I128, 0);
963 setLibcallName(RTLIB::SRL_I128, 0);
964 setLibcallName(RTLIB::SRA_I128, 0);
967 // We have target-specific dag combine patterns for the following nodes:
968 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
969 setTargetDAGCombine(ISD::BUILD_VECTOR);
970 setTargetDAGCombine(ISD::SELECT);
971 setTargetDAGCombine(ISD::SHL);
972 setTargetDAGCombine(ISD::SRA);
973 setTargetDAGCombine(ISD::SRL);
974 setTargetDAGCombine(ISD::STORE);
975 setTargetDAGCombine(ISD::MEMBARRIER);
976 if (Subtarget->is64Bit())
977 setTargetDAGCombine(ISD::MUL);
979 computeRegisterProperties();
981 // FIXME: These should be based on subtarget info. Plus, the values should
982 // be smaller when we are in optimizing for size mode.
983 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
984 maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
985 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
986 setPrefLoopAlignment(16);
987 benefitFromCodePlacementOpt = true;
991 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
996 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
997 /// the desired ByVal argument alignment.
998 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1001 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1002 if (VTy->getBitWidth() == 128)
1004 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1005 unsigned EltAlign = 0;
1006 getMaxByValAlign(ATy->getElementType(), EltAlign);
1007 if (EltAlign > MaxAlign)
1008 MaxAlign = EltAlign;
1009 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1010 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1011 unsigned EltAlign = 0;
1012 getMaxByValAlign(STy->getElementType(i), EltAlign);
1013 if (EltAlign > MaxAlign)
1014 MaxAlign = EltAlign;
1022 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1023 /// function arguments in the caller parameter area. For X86, aggregates
1024 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1025 /// are at 4-byte boundaries.
1026 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1027 if (Subtarget->is64Bit()) {
1028 // Max of 8 and alignment of type.
1029 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1036 if (Subtarget->hasSSE1())
1037 getMaxByValAlign(Ty, Align);
1041 /// getOptimalMemOpType - Returns the target specific optimal type for load
1042 /// and store operations as a result of memset, memcpy, and memmove
1043 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
1046 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
1047 bool isSrcConst, bool isSrcStr,
1048 SelectionDAG &DAG) const {
1049 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1050 // linux. This is because the stack realignment code can't handle certain
1051 // cases like PR2962. This should be removed when PR2962 is fixed.
1052 const Function *F = DAG.getMachineFunction().getFunction();
1053 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
1054 if (!NoImplicitFloatOps && Subtarget->getStackAlignment() >= 16) {
1055 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
1057 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
1060 if (Subtarget->is64Bit() && Size >= 8)
1065 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1067 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1068 SelectionDAG &DAG) const {
1069 if (usesGlobalOffsetTable())
1070 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy());
1071 if (!Subtarget->is64Bit())
1072 // This doesn't have DebugLoc associated with it, but is not really the
1073 // same as a Register.
1074 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc::getUnknownLoc(),
1079 /// getFunctionAlignment - Return the Log2 alignment of this function.
1080 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1081 return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1084 //===----------------------------------------------------------------------===//
1085 // Return Value Calling Convention Implementation
1086 //===----------------------------------------------------------------------===//
1088 #include "X86GenCallingConv.inc"
1091 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1092 const SmallVectorImpl<EVT> &OutTys,
1093 const SmallVectorImpl<ISD::ArgFlagsTy> &ArgsFlags,
1094 SelectionDAG &DAG) {
1095 SmallVector<CCValAssign, 16> RVLocs;
1096 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1097 RVLocs, *DAG.getContext());
1098 return CCInfo.CheckReturn(OutTys, ArgsFlags, RetCC_X86);
1102 X86TargetLowering::LowerReturn(SDValue Chain,
1103 CallingConv::ID CallConv, bool isVarArg,
1104 const SmallVectorImpl<ISD::OutputArg> &Outs,
1105 DebugLoc dl, SelectionDAG &DAG) {
1107 SmallVector<CCValAssign, 16> RVLocs;
1108 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1109 RVLocs, *DAG.getContext());
1110 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1112 // If this is the first return lowered for this function, add the regs to the
1113 // liveout set for the function.
1114 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1115 for (unsigned i = 0; i != RVLocs.size(); ++i)
1116 if (RVLocs[i].isRegLoc())
1117 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1122 SmallVector<SDValue, 6> RetOps;
1123 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1124 // Operand #1 = Bytes To Pop
1125 RetOps.push_back(DAG.getTargetConstant(getBytesToPopOnReturn(), MVT::i16));
1127 // Copy the result values into the output registers.
1128 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1129 CCValAssign &VA = RVLocs[i];
1130 assert(VA.isRegLoc() && "Can only return in registers!");
1131 SDValue ValToCopy = Outs[i].Val;
1133 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1134 // the RET instruction and handled by the FP Stackifier.
1135 if (VA.getLocReg() == X86::ST0 ||
1136 VA.getLocReg() == X86::ST1) {
1137 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1138 // change the value to the FP stack register class.
1139 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1140 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1141 RetOps.push_back(ValToCopy);
1142 // Don't emit a copytoreg.
1146 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1147 // which is returned in RAX / RDX.
1148 if (Subtarget->is64Bit()) {
1149 EVT ValVT = ValToCopy.getValueType();
1150 if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1151 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1152 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1153 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1157 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1158 Flag = Chain.getValue(1);
1161 // The x86-64 ABI for returning structs by value requires that we copy
1162 // the sret argument into %rax for the return. We saved the argument into
1163 // a virtual register in the entry block, so now we copy the value out
1165 if (Subtarget->is64Bit() &&
1166 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1167 MachineFunction &MF = DAG.getMachineFunction();
1168 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1169 unsigned Reg = FuncInfo->getSRetReturnReg();
1171 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1172 FuncInfo->setSRetReturnReg(Reg);
1174 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1176 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1177 Flag = Chain.getValue(1);
1179 // RAX now acts like a return value.
1180 MF.getRegInfo().addLiveOut(X86::RAX);
1183 RetOps[0] = Chain; // Update chain.
1185 // Add the flag if we have it.
1187 RetOps.push_back(Flag);
1189 return DAG.getNode(X86ISD::RET_FLAG, dl,
1190 MVT::Other, &RetOps[0], RetOps.size());
1193 /// LowerCallResult - Lower the result values of a call into the
1194 /// appropriate copies out of appropriate physical registers.
1197 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1198 CallingConv::ID CallConv, bool isVarArg,
1199 const SmallVectorImpl<ISD::InputArg> &Ins,
1200 DebugLoc dl, SelectionDAG &DAG,
1201 SmallVectorImpl<SDValue> &InVals) {
1203 // Assign locations to each value returned by this call.
1204 SmallVector<CCValAssign, 16> RVLocs;
1205 bool Is64Bit = Subtarget->is64Bit();
1206 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1207 RVLocs, *DAG.getContext());
1208 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1210 // Copy all of the result registers out of their specified physreg.
1211 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1212 CCValAssign &VA = RVLocs[i];
1213 EVT CopyVT = VA.getValVT();
1215 // If this is x86-64, and we disabled SSE, we can't return FP values
1216 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1217 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1218 llvm_report_error("SSE register return with SSE disabled");
1221 // If this is a call to a function that returns an fp value on the floating
1222 // point stack, but where we prefer to use the value in xmm registers, copy
1223 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1224 if ((VA.getLocReg() == X86::ST0 ||
1225 VA.getLocReg() == X86::ST1) &&
1226 isScalarFPTypeInSSEReg(VA.getValVT())) {
1231 if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1232 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1233 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1234 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1235 MVT::v2i64, InFlag).getValue(1);
1236 Val = Chain.getValue(0);
1237 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1238 Val, DAG.getConstant(0, MVT::i64));
1240 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1241 MVT::i64, InFlag).getValue(1);
1242 Val = Chain.getValue(0);
1244 Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1246 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1247 CopyVT, InFlag).getValue(1);
1248 Val = Chain.getValue(0);
1250 InFlag = Chain.getValue(2);
1252 if (CopyVT != VA.getValVT()) {
1253 // Round the F80 the right size, which also moves to the appropriate xmm
1255 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1256 // This truncation won't change the value.
1257 DAG.getIntPtrConstant(1));
1260 InVals.push_back(Val);
1267 //===----------------------------------------------------------------------===//
1268 // C & StdCall & Fast Calling Convention implementation
1269 //===----------------------------------------------------------------------===//
1270 // StdCall calling convention seems to be standard for many Windows' API
1271 // routines and around. It differs from C calling convention just a little:
1272 // callee should clean up the stack, not caller. Symbols should be also
1273 // decorated in some fancy way :) It doesn't support any vector arguments.
1274 // For info on fast calling convention see Fast Calling Convention (tail call)
1275 // implementation LowerX86_32FastCCCallTo.
1277 /// CallIsStructReturn - Determines whether a call uses struct return
1279 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1283 return Outs[0].Flags.isSRet();
1286 /// ArgsAreStructReturn - Determines whether a function uses struct
1287 /// return semantics.
1289 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1293 return Ins[0].Flags.isSRet();
1296 /// IsCalleePop - Determines whether the callee is required to pop its
1297 /// own arguments. Callee pop is necessary to support tail calls.
1298 bool X86TargetLowering::IsCalleePop(bool IsVarArg, CallingConv::ID CallingConv){
1302 switch (CallingConv) {
1305 case CallingConv::X86_StdCall:
1306 return !Subtarget->is64Bit();
1307 case CallingConv::X86_FastCall:
1308 return !Subtarget->is64Bit();
1309 case CallingConv::Fast:
1310 return PerformTailCallOpt;
1314 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1315 /// given CallingConvention value.
1316 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1317 if (Subtarget->is64Bit()) {
1318 if (Subtarget->isTargetWin64())
1319 return CC_X86_Win64_C;
1324 if (CC == CallingConv::X86_FastCall)
1325 return CC_X86_32_FastCall;
1326 else if (CC == CallingConv::Fast)
1327 return CC_X86_32_FastCC;
1332 /// NameDecorationForCallConv - Selects the appropriate decoration to
1333 /// apply to a MachineFunction containing a given calling convention.
1335 X86TargetLowering::NameDecorationForCallConv(CallingConv::ID CallConv) {
1336 if (CallConv == CallingConv::X86_FastCall)
1338 else if (CallConv == CallingConv::X86_StdCall)
1344 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1345 /// by "Src" to address "Dst" with size and alignment information specified by
1346 /// the specific parameter attribute. The copy will be passed as a byval
1347 /// function parameter.
1349 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1350 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1352 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1353 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1354 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1358 X86TargetLowering::LowerMemArgument(SDValue Chain,
1359 CallingConv::ID CallConv,
1360 const SmallVectorImpl<ISD::InputArg> &Ins,
1361 DebugLoc dl, SelectionDAG &DAG,
1362 const CCValAssign &VA,
1363 MachineFrameInfo *MFI,
1366 // Create the nodes corresponding to a load from this parameter slot.
1367 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1368 bool AlwaysUseMutable = (CallConv==CallingConv::Fast) && PerformTailCallOpt;
1369 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1372 // If value is passed by pointer we have address passed instead of the value
1374 if (VA.getLocInfo() == CCValAssign::Indirect)
1375 ValVT = VA.getLocVT();
1377 ValVT = VA.getValVT();
1379 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1380 // changed with more analysis.
1381 // In case of tail call optimization mark all arguments mutable. Since they
1382 // could be overwritten by lowering of arguments in case of a tail call.
1383 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1384 VA.getLocMemOffset(), isImmutable);
1385 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1386 if (Flags.isByVal())
1388 return DAG.getLoad(ValVT, dl, Chain, FIN,
1389 PseudoSourceValue::getFixedStack(FI), 0);
1393 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1394 CallingConv::ID CallConv,
1396 const SmallVectorImpl<ISD::InputArg> &Ins,
1399 SmallVectorImpl<SDValue> &InVals) {
1401 MachineFunction &MF = DAG.getMachineFunction();
1402 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1404 const Function* Fn = MF.getFunction();
1405 if (Fn->hasExternalLinkage() &&
1406 Subtarget->isTargetCygMing() &&
1407 Fn->getName() == "main")
1408 FuncInfo->setForceFramePointer(true);
1410 // Decorate the function name.
1411 FuncInfo->setDecorationStyle(NameDecorationForCallConv(CallConv));
1413 MachineFrameInfo *MFI = MF.getFrameInfo();
1414 bool Is64Bit = Subtarget->is64Bit();
1415 bool IsWin64 = Subtarget->isTargetWin64();
1417 assert(!(isVarArg && CallConv == CallingConv::Fast) &&
1418 "Var args not supported with calling convention fastcc");
1420 // Assign locations to all of the incoming arguments.
1421 SmallVector<CCValAssign, 16> ArgLocs;
1422 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1423 ArgLocs, *DAG.getContext());
1424 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1426 unsigned LastVal = ~0U;
1428 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1429 CCValAssign &VA = ArgLocs[i];
1430 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1432 assert(VA.getValNo() != LastVal &&
1433 "Don't support value assigned to multiple locs yet");
1434 LastVal = VA.getValNo();
1436 if (VA.isRegLoc()) {
1437 EVT RegVT = VA.getLocVT();
1438 TargetRegisterClass *RC = NULL;
1439 if (RegVT == MVT::i32)
1440 RC = X86::GR32RegisterClass;
1441 else if (Is64Bit && RegVT == MVT::i64)
1442 RC = X86::GR64RegisterClass;
1443 else if (RegVT == MVT::f32)
1444 RC = X86::FR32RegisterClass;
1445 else if (RegVT == MVT::f64)
1446 RC = X86::FR64RegisterClass;
1447 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1448 RC = X86::VR128RegisterClass;
1449 else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1450 RC = X86::VR64RegisterClass;
1452 llvm_unreachable("Unknown argument type!");
1454 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1455 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1457 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1458 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1460 if (VA.getLocInfo() == CCValAssign::SExt)
1461 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1462 DAG.getValueType(VA.getValVT()));
1463 else if (VA.getLocInfo() == CCValAssign::ZExt)
1464 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1465 DAG.getValueType(VA.getValVT()));
1466 else if (VA.getLocInfo() == CCValAssign::BCvt)
1467 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1469 if (VA.isExtInLoc()) {
1470 // Handle MMX values passed in XMM regs.
1471 if (RegVT.isVector()) {
1472 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1473 ArgValue, DAG.getConstant(0, MVT::i64));
1474 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1476 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1479 assert(VA.isMemLoc());
1480 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1483 // If value is passed via pointer - do a load.
1484 if (VA.getLocInfo() == CCValAssign::Indirect)
1485 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0);
1487 InVals.push_back(ArgValue);
1490 // The x86-64 ABI for returning structs by value requires that we copy
1491 // the sret argument into %rax for the return. Save the argument into
1492 // a virtual register so that we can access it from the return points.
1493 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1494 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1495 unsigned Reg = FuncInfo->getSRetReturnReg();
1497 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1498 FuncInfo->setSRetReturnReg(Reg);
1500 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1501 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1504 unsigned StackSize = CCInfo.getNextStackOffset();
1505 // align stack specially for tail calls
1506 if (PerformTailCallOpt && CallConv == CallingConv::Fast)
1507 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1509 // If the function takes variable number of arguments, make a frame index for
1510 // the start of the first vararg value... for expansion of llvm.va_start.
1512 if (Is64Bit || CallConv != CallingConv::X86_FastCall) {
1513 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize);
1516 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1518 // FIXME: We should really autogenerate these arrays
1519 static const unsigned GPR64ArgRegsWin64[] = {
1520 X86::RCX, X86::RDX, X86::R8, X86::R9
1522 static const unsigned XMMArgRegsWin64[] = {
1523 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1525 static const unsigned GPR64ArgRegs64Bit[] = {
1526 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1528 static const unsigned XMMArgRegs64Bit[] = {
1529 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1530 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1532 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1535 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1536 GPR64ArgRegs = GPR64ArgRegsWin64;
1537 XMMArgRegs = XMMArgRegsWin64;
1539 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1540 GPR64ArgRegs = GPR64ArgRegs64Bit;
1541 XMMArgRegs = XMMArgRegs64Bit;
1543 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1545 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1548 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1549 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1550 "SSE register cannot be used when SSE is disabled!");
1551 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1552 "SSE register cannot be used when SSE is disabled!");
1553 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1554 // Kernel mode asks for SSE to be disabled, so don't push them
1556 TotalNumXMMRegs = 0;
1558 // For X86-64, if there are vararg parameters that are passed via
1559 // registers, then we must store them to their spots on the stack so they
1560 // may be loaded by deferencing the result of va_next.
1561 VarArgsGPOffset = NumIntRegs * 8;
1562 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1563 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1564 TotalNumXMMRegs * 16, 16);
1566 // Store the integer parameter registers.
1567 SmallVector<SDValue, 8> MemOps;
1568 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1569 unsigned Offset = VarArgsGPOffset;
1570 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1571 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1572 DAG.getIntPtrConstant(Offset));
1573 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1574 X86::GR64RegisterClass);
1575 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1577 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1578 PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
1580 MemOps.push_back(Store);
1584 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1585 // Now store the XMM (fp + vector) parameter registers.
1586 SmallVector<SDValue, 11> SaveXMMOps;
1587 SaveXMMOps.push_back(Chain);
1589 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1590 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1591 SaveXMMOps.push_back(ALVal);
1593 SaveXMMOps.push_back(DAG.getIntPtrConstant(RegSaveFrameIndex));
1594 SaveXMMOps.push_back(DAG.getIntPtrConstant(VarArgsFPOffset));
1596 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1597 unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1598 X86::VR128RegisterClass);
1599 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1600 SaveXMMOps.push_back(Val);
1602 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1604 &SaveXMMOps[0], SaveXMMOps.size()));
1607 if (!MemOps.empty())
1608 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1609 &MemOps[0], MemOps.size());
1613 // Some CCs need callee pop.
1614 if (IsCalleePop(isVarArg, CallConv)) {
1615 BytesToPopOnReturn = StackSize; // Callee pops everything.
1616 BytesCallerReserves = 0;
1618 BytesToPopOnReturn = 0; // Callee pops nothing.
1619 // If this is an sret function, the return should pop the hidden pointer.
1620 if (!Is64Bit && CallConv != CallingConv::Fast && ArgsAreStructReturn(Ins))
1621 BytesToPopOnReturn = 4;
1622 BytesCallerReserves = StackSize;
1626 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1627 if (CallConv == CallingConv::X86_FastCall)
1628 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1631 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1637 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1638 SDValue StackPtr, SDValue Arg,
1639 DebugLoc dl, SelectionDAG &DAG,
1640 const CCValAssign &VA,
1641 ISD::ArgFlagsTy Flags) {
1642 const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1643 unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1644 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1645 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1646 if (Flags.isByVal()) {
1647 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1649 return DAG.getStore(Chain, dl, Arg, PtrOff,
1650 PseudoSourceValue::getStack(), LocMemOffset);
1653 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1654 /// optimization is performed and it is required.
1656 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1657 SDValue &OutRetAddr,
1663 if (!IsTailCall || FPDiff==0) return Chain;
1665 // Adjust the Return address stack slot.
1666 EVT VT = getPointerTy();
1667 OutRetAddr = getReturnAddressFrameIndex(DAG);
1669 // Load the "old" Return address.
1670 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0);
1671 return SDValue(OutRetAddr.getNode(), 1);
1674 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1675 /// optimization is performed and it is required (FPDiff!=0).
1677 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1678 SDValue Chain, SDValue RetAddrFrIdx,
1679 bool Is64Bit, int FPDiff, DebugLoc dl) {
1680 // Store the return address to the appropriate stack slot.
1681 if (!FPDiff) return Chain;
1682 // Calculate the new stack slot for the return address.
1683 int SlotSize = Is64Bit ? 8 : 4;
1684 int NewReturnAddrFI =
1685 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize);
1686 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1687 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1688 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1689 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1694 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1695 CallingConv::ID CallConv, bool isVarArg,
1697 const SmallVectorImpl<ISD::OutputArg> &Outs,
1698 const SmallVectorImpl<ISD::InputArg> &Ins,
1699 DebugLoc dl, SelectionDAG &DAG,
1700 SmallVectorImpl<SDValue> &InVals) {
1702 MachineFunction &MF = DAG.getMachineFunction();
1703 bool Is64Bit = Subtarget->is64Bit();
1704 bool IsStructRet = CallIsStructReturn(Outs);
1706 assert((!isTailCall ||
1707 (CallConv == CallingConv::Fast && PerformTailCallOpt)) &&
1708 "IsEligibleForTailCallOptimization missed a case!");
1709 assert(!(isVarArg && CallConv == CallingConv::Fast) &&
1710 "Var args not supported with calling convention fastcc");
1712 // Analyze operands of the call, assigning locations to each operand.
1713 SmallVector<CCValAssign, 16> ArgLocs;
1714 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1715 ArgLocs, *DAG.getContext());
1716 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1718 // Get a count of how many bytes are to be pushed on the stack.
1719 unsigned NumBytes = CCInfo.getNextStackOffset();
1720 if (PerformTailCallOpt && CallConv == CallingConv::Fast)
1721 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1725 // Lower arguments at fp - stackoffset + fpdiff.
1726 unsigned NumBytesCallerPushed =
1727 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1728 FPDiff = NumBytesCallerPushed - NumBytes;
1730 // Set the delta of movement of the returnaddr stackslot.
1731 // But only set if delta is greater than previous delta.
1732 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1733 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1736 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1738 SDValue RetAddrFrIdx;
1739 // Load return adress for tail calls.
1740 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall, Is64Bit,
1743 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1744 SmallVector<SDValue, 8> MemOpChains;
1747 // Walk the register/memloc assignments, inserting copies/loads. In the case
1748 // of tail call optimization arguments are handle later.
1749 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1750 CCValAssign &VA = ArgLocs[i];
1751 EVT RegVT = VA.getLocVT();
1752 SDValue Arg = Outs[i].Val;
1753 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1754 bool isByVal = Flags.isByVal();
1756 // Promote the value if needed.
1757 switch (VA.getLocInfo()) {
1758 default: llvm_unreachable("Unknown loc info!");
1759 case CCValAssign::Full: break;
1760 case CCValAssign::SExt:
1761 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1763 case CCValAssign::ZExt:
1764 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1766 case CCValAssign::AExt:
1767 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1768 // Special case: passing MMX values in XMM registers.
1769 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1770 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1771 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1773 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1775 case CCValAssign::BCvt:
1776 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1778 case CCValAssign::Indirect: {
1779 // Store the argument.
1780 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1781 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1782 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1783 PseudoSourceValue::getFixedStack(FI), 0);
1789 if (VA.isRegLoc()) {
1790 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1792 if (!isTailCall || (isTailCall && isByVal)) {
1793 assert(VA.isMemLoc());
1794 if (StackPtr.getNode() == 0)
1795 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1797 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1798 dl, DAG, VA, Flags));
1803 if (!MemOpChains.empty())
1804 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1805 &MemOpChains[0], MemOpChains.size());
1807 // Build a sequence of copy-to-reg nodes chained together with token chain
1808 // and flag operands which copy the outgoing args into registers.
1810 // Tail call byval lowering might overwrite argument registers so in case of
1811 // tail call optimization the copies to registers are lowered later.
1813 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1814 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1815 RegsToPass[i].second, InFlag);
1816 InFlag = Chain.getValue(1);
1820 if (Subtarget->isPICStyleGOT()) {
1821 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1824 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1825 DAG.getNode(X86ISD::GlobalBaseReg,
1826 DebugLoc::getUnknownLoc(),
1829 InFlag = Chain.getValue(1);
1831 // If we are tail calling and generating PIC/GOT style code load the
1832 // address of the callee into ECX. The value in ecx is used as target of
1833 // the tail jump. This is done to circumvent the ebx/callee-saved problem
1834 // for tail calls on PIC/GOT architectures. Normally we would just put the
1835 // address of GOT into ebx and then call target@PLT. But for tail calls
1836 // ebx would be restored (since ebx is callee saved) before jumping to the
1839 // Note: The actual moving to ECX is done further down.
1840 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1841 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1842 !G->getGlobal()->hasProtectedVisibility())
1843 Callee = LowerGlobalAddress(Callee, DAG);
1844 else if (isa<ExternalSymbolSDNode>(Callee))
1845 Callee = LowerExternalSymbol(Callee, DAG);
1849 if (Is64Bit && isVarArg) {
1850 // From AMD64 ABI document:
1851 // For calls that may call functions that use varargs or stdargs
1852 // (prototype-less calls or calls to functions containing ellipsis (...) in
1853 // the declaration) %al is used as hidden argument to specify the number
1854 // of SSE registers used. The contents of %al do not need to match exactly
1855 // the number of registers, but must be an ubound on the number of SSE
1856 // registers used and is in the range 0 - 8 inclusive.
1858 // FIXME: Verify this on Win64
1859 // Count the number of XMM registers allocated.
1860 static const unsigned XMMArgRegs[] = {
1861 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1862 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1864 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1865 assert((Subtarget->hasSSE1() || !NumXMMRegs)
1866 && "SSE registers cannot be used when SSE is disabled");
1868 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1869 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1870 InFlag = Chain.getValue(1);
1874 // For tail calls lower the arguments to the 'real' stack slot.
1876 // Force all the incoming stack arguments to be loaded from the stack
1877 // before any new outgoing arguments are stored to the stack, because the
1878 // outgoing stack slots may alias the incoming argument stack slots, and
1879 // the alias isn't otherwise explicit. This is slightly more conservative
1880 // than necessary, because it means that each store effectively depends
1881 // on every argument instead of just those arguments it would clobber.
1882 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
1884 SmallVector<SDValue, 8> MemOpChains2;
1887 // Do not flag preceeding copytoreg stuff together with the following stuff.
1889 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1890 CCValAssign &VA = ArgLocs[i];
1891 if (!VA.isRegLoc()) {
1892 assert(VA.isMemLoc());
1893 SDValue Arg = Outs[i].Val;
1894 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1895 // Create frame index.
1896 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1897 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1898 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset);
1899 FIN = DAG.getFrameIndex(FI, getPointerTy());
1901 if (Flags.isByVal()) {
1902 // Copy relative to framepointer.
1903 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1904 if (StackPtr.getNode() == 0)
1905 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
1907 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
1909 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
1913 // Store relative to framepointer.
1914 MemOpChains2.push_back(
1915 DAG.getStore(ArgChain, dl, Arg, FIN,
1916 PseudoSourceValue::getFixedStack(FI), 0));
1921 if (!MemOpChains2.empty())
1922 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1923 &MemOpChains2[0], MemOpChains2.size());
1925 // Copy arguments to their registers.
1926 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1927 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1928 RegsToPass[i].second, InFlag);
1929 InFlag = Chain.getValue(1);
1933 // Store the return address to the appropriate stack slot.
1934 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1938 // If the callee is a GlobalAddress node (quite common, every direct call is)
1939 // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1940 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1941 // We should use extra load for direct calls to dllimported functions in
1943 GlobalValue *GV = G->getGlobal();
1944 if (!GV->hasDLLImportLinkage()) {
1945 unsigned char OpFlags = 0;
1947 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
1948 // external symbols most go through the PLT in PIC mode. If the symbol
1949 // has hidden or protected visibility, or if it is static or local, then
1950 // we don't need to use the PLT - we can directly call it.
1951 if (Subtarget->isTargetELF() &&
1952 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1953 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
1954 OpFlags = X86II::MO_PLT;
1955 } else if (Subtarget->isPICStyleStubAny() &&
1956 (GV->isDeclaration() || GV->isWeakForLinker()) &&
1957 Subtarget->getDarwinVers() < 9) {
1958 // PC-relative references to external symbols should go through $stub,
1959 // unless we're building with the leopard linker or later, which
1960 // automatically synthesizes these stubs.
1961 OpFlags = X86II::MO_DARWIN_STUB;
1964 Callee = DAG.getTargetGlobalAddress(GV, getPointerTy(),
1965 G->getOffset(), OpFlags);
1967 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1968 unsigned char OpFlags = 0;
1970 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
1971 // symbols should go through the PLT.
1972 if (Subtarget->isTargetELF() &&
1973 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1974 OpFlags = X86II::MO_PLT;
1975 } else if (Subtarget->isPICStyleStubAny() &&
1976 Subtarget->getDarwinVers() < 9) {
1977 // PC-relative references to external symbols should go through $stub,
1978 // unless we're building with the leopard linker or later, which
1979 // automatically synthesizes these stubs.
1980 OpFlags = X86II::MO_DARWIN_STUB;
1983 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
1985 } else if (isTailCall) {
1986 unsigned Opc = Is64Bit ? X86::R11 : X86::EAX;
1988 Chain = DAG.getCopyToReg(Chain, dl,
1989 DAG.getRegister(Opc, getPointerTy()),
1991 Callee = DAG.getRegister(Opc, getPointerTy());
1992 // Add register as live out.
1993 MF.getRegInfo().addLiveOut(Opc);
1996 // Returns a chain & a flag for retval copy to use.
1997 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
1998 SmallVector<SDValue, 8> Ops;
2001 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2002 DAG.getIntPtrConstant(0, true), InFlag);
2003 InFlag = Chain.getValue(1);
2006 Ops.push_back(Chain);
2007 Ops.push_back(Callee);
2010 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2012 // Add argument registers to the end of the list so that they are known live
2014 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2015 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2016 RegsToPass[i].second.getValueType()));
2018 // Add an implicit use GOT pointer in EBX.
2019 if (!isTailCall && Subtarget->isPICStyleGOT())
2020 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2022 // Add an implicit use of AL for x86 vararg functions.
2023 if (Is64Bit && isVarArg)
2024 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2026 if (InFlag.getNode())
2027 Ops.push_back(InFlag);
2030 // If this is the first return lowered for this function, add the regs
2031 // to the liveout set for the function.
2032 if (MF.getRegInfo().liveout_empty()) {
2033 SmallVector<CCValAssign, 16> RVLocs;
2034 CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
2036 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2037 for (unsigned i = 0; i != RVLocs.size(); ++i)
2038 if (RVLocs[i].isRegLoc())
2039 MF.getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2042 assert(((Callee.getOpcode() == ISD::Register &&
2043 (cast<RegisterSDNode>(Callee)->getReg() == X86::EAX ||
2044 cast<RegisterSDNode>(Callee)->getReg() == X86::R9)) ||
2045 Callee.getOpcode() == ISD::TargetExternalSymbol ||
2046 Callee.getOpcode() == ISD::TargetGlobalAddress) &&
2047 "Expecting an global address, external symbol, or register");
2049 return DAG.getNode(X86ISD::TC_RETURN, dl,
2050 NodeTys, &Ops[0], Ops.size());
2053 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2054 InFlag = Chain.getValue(1);
2056 // Create the CALLSEQ_END node.
2057 unsigned NumBytesForCalleeToPush;
2058 if (IsCalleePop(isVarArg, CallConv))
2059 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2060 else if (!Is64Bit && CallConv != CallingConv::Fast && IsStructRet)
2061 // If this is is a call to a struct-return function, the callee
2062 // pops the hidden struct pointer, so we have to push it back.
2063 // This is common for Darwin/X86, Linux & Mingw32 targets.
2064 NumBytesForCalleeToPush = 4;
2066 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2068 // Returns a flag for retval copy to use.
2069 Chain = DAG.getCALLSEQ_END(Chain,
2070 DAG.getIntPtrConstant(NumBytes, true),
2071 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2074 InFlag = Chain.getValue(1);
2076 // Handle result values, copying them out of physregs into vregs that we
2078 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2079 Ins, dl, DAG, InVals);
2083 //===----------------------------------------------------------------------===//
2084 // Fast Calling Convention (tail call) implementation
2085 //===----------------------------------------------------------------------===//
2087 // Like std call, callee cleans arguments, convention except that ECX is
2088 // reserved for storing the tail called function address. Only 2 registers are
2089 // free for argument passing (inreg). Tail call optimization is performed
2091 // * tailcallopt is enabled
2092 // * caller/callee are fastcc
2093 // On X86_64 architecture with GOT-style position independent code only local
2094 // (within module) calls are supported at the moment.
2095 // To keep the stack aligned according to platform abi the function
2096 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2097 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2098 // If a tail called function callee has more arguments than the caller the
2099 // caller needs to make sure that there is room to move the RETADDR to. This is
2100 // achieved by reserving an area the size of the argument delta right after the
2101 // original REtADDR, but before the saved framepointer or the spilled registers
2102 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2114 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2115 /// for a 16 byte align requirement.
2116 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2117 SelectionDAG& DAG) {
2118 MachineFunction &MF = DAG.getMachineFunction();
2119 const TargetMachine &TM = MF.getTarget();
2120 const TargetFrameInfo &TFI = *TM.getFrameInfo();
2121 unsigned StackAlignment = TFI.getStackAlignment();
2122 uint64_t AlignMask = StackAlignment - 1;
2123 int64_t Offset = StackSize;
2124 uint64_t SlotSize = TD->getPointerSize();
2125 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2126 // Number smaller than 12 so just add the difference.
2127 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2129 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2130 Offset = ((~AlignMask) & Offset) + StackAlignment +
2131 (StackAlignment-SlotSize);
2136 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2137 /// for tail call optimization. Targets which want to do tail call
2138 /// optimization should implement this function.
2140 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2141 CallingConv::ID CalleeCC,
2143 const SmallVectorImpl<ISD::InputArg> &Ins,
2144 SelectionDAG& DAG) const {
2145 MachineFunction &MF = DAG.getMachineFunction();
2146 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
2147 return CalleeCC == CallingConv::Fast && CallerCC == CalleeCC;
2151 X86TargetLowering::createFastISel(MachineFunction &mf,
2152 MachineModuleInfo *mmo,
2154 DenseMap<const Value *, unsigned> &vm,
2155 DenseMap<const BasicBlock *,
2156 MachineBasicBlock *> &bm,
2157 DenseMap<const AllocaInst *, int> &am
2159 , SmallSet<Instruction*, 8> &cil
2162 return X86::createFastISel(mf, mmo, dw, vm, bm, am
2170 //===----------------------------------------------------------------------===//
2171 // Other Lowering Hooks
2172 //===----------------------------------------------------------------------===//
2175 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2176 MachineFunction &MF = DAG.getMachineFunction();
2177 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2178 int ReturnAddrIndex = FuncInfo->getRAIndex();
2180 if (ReturnAddrIndex == 0) {
2181 // Set up a frame object for the return address.
2182 uint64_t SlotSize = TD->getPointerSize();
2183 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize);
2184 FuncInfo->setRAIndex(ReturnAddrIndex);
2187 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2191 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2192 bool hasSymbolicDisplacement) {
2193 // Offset should fit into 32 bit immediate field.
2194 if (!isInt32(Offset))
2197 // If we don't have a symbolic displacement - we don't have any extra
2199 if (!hasSymbolicDisplacement)
2202 // FIXME: Some tweaks might be needed for medium code model.
2203 if (M != CodeModel::Small && M != CodeModel::Kernel)
2206 // For small code model we assume that latest object is 16MB before end of 31
2207 // bits boundary. We may also accept pretty large negative constants knowing
2208 // that all objects are in the positive half of address space.
2209 if (M == CodeModel::Small && Offset < 16*1024*1024)
2212 // For kernel code model we know that all object resist in the negative half
2213 // of 32bits address space. We may not accept negative offsets, since they may
2214 // be just off and we may accept pretty large positive ones.
2215 if (M == CodeModel::Kernel && Offset > 0)
2221 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2222 /// specific condition code, returning the condition code and the LHS/RHS of the
2223 /// comparison to make.
2224 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2225 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2227 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2228 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2229 // X > -1 -> X == 0, jump !sign.
2230 RHS = DAG.getConstant(0, RHS.getValueType());
2231 return X86::COND_NS;
2232 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2233 // X < 0 -> X == 0, jump on sign.
2235 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2237 RHS = DAG.getConstant(0, RHS.getValueType());
2238 return X86::COND_LE;
2242 switch (SetCCOpcode) {
2243 default: llvm_unreachable("Invalid integer condition!");
2244 case ISD::SETEQ: return X86::COND_E;
2245 case ISD::SETGT: return X86::COND_G;
2246 case ISD::SETGE: return X86::COND_GE;
2247 case ISD::SETLT: return X86::COND_L;
2248 case ISD::SETLE: return X86::COND_LE;
2249 case ISD::SETNE: return X86::COND_NE;
2250 case ISD::SETULT: return X86::COND_B;
2251 case ISD::SETUGT: return X86::COND_A;
2252 case ISD::SETULE: return X86::COND_BE;
2253 case ISD::SETUGE: return X86::COND_AE;
2257 // First determine if it is required or is profitable to flip the operands.
2259 // If LHS is a foldable load, but RHS is not, flip the condition.
2260 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2261 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2262 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2263 std::swap(LHS, RHS);
2266 switch (SetCCOpcode) {
2272 std::swap(LHS, RHS);
2276 // On a floating point condition, the flags are set as follows:
2278 // 0 | 0 | 0 | X > Y
2279 // 0 | 0 | 1 | X < Y
2280 // 1 | 0 | 0 | X == Y
2281 // 1 | 1 | 1 | unordered
2282 switch (SetCCOpcode) {
2283 default: llvm_unreachable("Condcode should be pre-legalized away");
2285 case ISD::SETEQ: return X86::COND_E;
2286 case ISD::SETOLT: // flipped
2288 case ISD::SETGT: return X86::COND_A;
2289 case ISD::SETOLE: // flipped
2291 case ISD::SETGE: return X86::COND_AE;
2292 case ISD::SETUGT: // flipped
2294 case ISD::SETLT: return X86::COND_B;
2295 case ISD::SETUGE: // flipped
2297 case ISD::SETLE: return X86::COND_BE;
2299 case ISD::SETNE: return X86::COND_NE;
2300 case ISD::SETUO: return X86::COND_P;
2301 case ISD::SETO: return X86::COND_NP;
2303 case ISD::SETUNE: return X86::COND_INVALID;
2307 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2308 /// code. Current x86 isa includes the following FP cmov instructions:
2309 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2310 static bool hasFPCMov(unsigned X86CC) {
2326 /// isFPImmLegal - Returns true if the target can instruction select the
2327 /// specified FP immediate natively. If false, the legalizer will
2328 /// materialize the FP immediate as a load from a constant pool.
2329 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2330 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2331 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2337 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2338 /// the specified range (L, H].
2339 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2340 return (Val < 0) || (Val >= Low && Val < Hi);
2343 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2344 /// specified value.
2345 static bool isUndefOrEqual(int Val, int CmpVal) {
2346 if (Val < 0 || Val == CmpVal)
2351 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2352 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2353 /// the second operand.
2354 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2355 if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2356 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2357 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2358 return (Mask[0] < 2 && Mask[1] < 2);
2362 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2363 SmallVector<int, 8> M;
2365 return ::isPSHUFDMask(M, N->getValueType(0));
2368 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2369 /// is suitable for input to PSHUFHW.
2370 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2371 if (VT != MVT::v8i16)
2374 // Lower quadword copied in order or undef.
2375 for (int i = 0; i != 4; ++i)
2376 if (Mask[i] >= 0 && Mask[i] != i)
2379 // Upper quadword shuffled.
2380 for (int i = 4; i != 8; ++i)
2381 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2387 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2388 SmallVector<int, 8> M;
2390 return ::isPSHUFHWMask(M, N->getValueType(0));
2393 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2394 /// is suitable for input to PSHUFLW.
2395 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2396 if (VT != MVT::v8i16)
2399 // Upper quadword copied in order.
2400 for (int i = 4; i != 8; ++i)
2401 if (Mask[i] >= 0 && Mask[i] != i)
2404 // Lower quadword shuffled.
2405 for (int i = 0; i != 4; ++i)
2412 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2413 SmallVector<int, 8> M;
2415 return ::isPSHUFLWMask(M, N->getValueType(0));
2418 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2419 /// is suitable for input to PALIGNR.
2420 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2422 int i, e = VT.getVectorNumElements();
2424 // Do not handle v2i64 / v2f64 shuffles with palignr.
2425 if (e < 4 || !hasSSSE3)
2428 for (i = 0; i != e; ++i)
2432 // All undef, not a palignr.
2436 // Determine if it's ok to perform a palignr with only the LHS, since we
2437 // don't have access to the actual shuffle elements to see if RHS is undef.
2438 bool Unary = Mask[i] < (int)e;
2439 bool NeedsUnary = false;
2441 int s = Mask[i] - i;
2443 // Check the rest of the elements to see if they are consecutive.
2444 for (++i; i != e; ++i) {
2449 Unary = Unary && (m < (int)e);
2450 NeedsUnary = NeedsUnary || (m < s);
2452 if (NeedsUnary && !Unary)
2454 if (Unary && m != ((s+i) & (e-1)))
2456 if (!Unary && m != (s+i))
2462 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2463 SmallVector<int, 8> M;
2465 return ::isPALIGNRMask(M, N->getValueType(0), true);
2468 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2469 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2470 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2471 int NumElems = VT.getVectorNumElements();
2472 if (NumElems != 2 && NumElems != 4)
2475 int Half = NumElems / 2;
2476 for (int i = 0; i < Half; ++i)
2477 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2479 for (int i = Half; i < NumElems; ++i)
2480 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2486 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2487 SmallVector<int, 8> M;
2489 return ::isSHUFPMask(M, N->getValueType(0));
2492 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2493 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2494 /// half elements to come from vector 1 (which would equal the dest.) and
2495 /// the upper half to come from vector 2.
2496 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2497 int NumElems = VT.getVectorNumElements();
2499 if (NumElems != 2 && NumElems != 4)
2502 int Half = NumElems / 2;
2503 for (int i = 0; i < Half; ++i)
2504 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2506 for (int i = Half; i < NumElems; ++i)
2507 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2512 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2513 SmallVector<int, 8> M;
2515 return isCommutedSHUFPMask(M, N->getValueType(0));
2518 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2519 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2520 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2521 if (N->getValueType(0).getVectorNumElements() != 4)
2524 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2525 return isUndefOrEqual(N->getMaskElt(0), 6) &&
2526 isUndefOrEqual(N->getMaskElt(1), 7) &&
2527 isUndefOrEqual(N->getMaskElt(2), 2) &&
2528 isUndefOrEqual(N->getMaskElt(3), 3);
2531 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2532 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2534 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2535 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2540 return isUndefOrEqual(N->getMaskElt(0), 2) &&
2541 isUndefOrEqual(N->getMaskElt(1), 3) &&
2542 isUndefOrEqual(N->getMaskElt(2), 2) &&
2543 isUndefOrEqual(N->getMaskElt(3), 3);
2546 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2547 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2548 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2549 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2551 if (NumElems != 2 && NumElems != 4)
2554 for (unsigned i = 0; i < NumElems/2; ++i)
2555 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2558 for (unsigned i = NumElems/2; i < NumElems; ++i)
2559 if (!isUndefOrEqual(N->getMaskElt(i), i))
2565 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
2566 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
2567 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
2568 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2570 if (NumElems != 2 && NumElems != 4)
2573 for (unsigned i = 0; i < NumElems/2; ++i)
2574 if (!isUndefOrEqual(N->getMaskElt(i), i))
2577 for (unsigned i = 0; i < NumElems/2; ++i)
2578 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2584 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2585 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2586 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2587 bool V2IsSplat = false) {
2588 int NumElts = VT.getVectorNumElements();
2589 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2592 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2594 int BitI1 = Mask[i+1];
2595 if (!isUndefOrEqual(BitI, j))
2598 if (!isUndefOrEqual(BitI1, NumElts))
2601 if (!isUndefOrEqual(BitI1, j + NumElts))
2608 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2609 SmallVector<int, 8> M;
2611 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2614 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2615 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2616 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
2617 bool V2IsSplat = false) {
2618 int NumElts = VT.getVectorNumElements();
2619 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2622 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2624 int BitI1 = Mask[i+1];
2625 if (!isUndefOrEqual(BitI, j + NumElts/2))
2628 if (isUndefOrEqual(BitI1, NumElts))
2631 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2638 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2639 SmallVector<int, 8> M;
2641 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2644 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2645 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2647 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2648 int NumElems = VT.getVectorNumElements();
2649 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2652 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2654 int BitI1 = Mask[i+1];
2655 if (!isUndefOrEqual(BitI, j))
2657 if (!isUndefOrEqual(BitI1, j))
2663 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2664 SmallVector<int, 8> M;
2666 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2669 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2670 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2672 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2673 int NumElems = VT.getVectorNumElements();
2674 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2677 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2679 int BitI1 = Mask[i+1];
2680 if (!isUndefOrEqual(BitI, j))
2682 if (!isUndefOrEqual(BitI1, j))
2688 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2689 SmallVector<int, 8> M;
2691 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2694 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2695 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2696 /// MOVSD, and MOVD, i.e. setting the lowest element.
2697 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2698 if (VT.getVectorElementType().getSizeInBits() < 32)
2701 int NumElts = VT.getVectorNumElements();
2703 if (!isUndefOrEqual(Mask[0], NumElts))
2706 for (int i = 1; i < NumElts; ++i)
2707 if (!isUndefOrEqual(Mask[i], i))
2713 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2714 SmallVector<int, 8> M;
2716 return ::isMOVLMask(M, N->getValueType(0));
2719 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2720 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2721 /// element of vector 2 and the other elements to come from vector 1 in order.
2722 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2723 bool V2IsSplat = false, bool V2IsUndef = false) {
2724 int NumOps = VT.getVectorNumElements();
2725 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2728 if (!isUndefOrEqual(Mask[0], 0))
2731 for (int i = 1; i < NumOps; ++i)
2732 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
2733 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
2734 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
2740 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
2741 bool V2IsUndef = false) {
2742 SmallVector<int, 8> M;
2744 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
2747 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2748 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2749 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
2750 if (N->getValueType(0).getVectorNumElements() != 4)
2753 // Expect 1, 1, 3, 3
2754 for (unsigned i = 0; i < 2; ++i) {
2755 int Elt = N->getMaskElt(i);
2756 if (Elt >= 0 && Elt != 1)
2761 for (unsigned i = 2; i < 4; ++i) {
2762 int Elt = N->getMaskElt(i);
2763 if (Elt >= 0 && Elt != 3)
2768 // Don't use movshdup if it can be done with a shufps.
2769 // FIXME: verify that matching u, u, 3, 3 is what we want.
2773 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2774 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2775 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
2776 if (N->getValueType(0).getVectorNumElements() != 4)
2779 // Expect 0, 0, 2, 2
2780 for (unsigned i = 0; i < 2; ++i)
2781 if (N->getMaskElt(i) > 0)
2785 for (unsigned i = 2; i < 4; ++i) {
2786 int Elt = N->getMaskElt(i);
2787 if (Elt >= 0 && Elt != 2)
2792 // Don't use movsldup if it can be done with a shufps.
2796 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2797 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2798 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
2799 int e = N->getValueType(0).getVectorNumElements() / 2;
2801 for (int i = 0; i < e; ++i)
2802 if (!isUndefOrEqual(N->getMaskElt(i), i))
2804 for (int i = 0; i < e; ++i)
2805 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
2810 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2811 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
2812 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2813 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2814 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
2816 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2818 for (int i = 0; i < NumOperands; ++i) {
2819 int Val = SVOp->getMaskElt(NumOperands-i-1);
2820 if (Val < 0) Val = 0;
2821 if (Val >= NumOperands) Val -= NumOperands;
2823 if (i != NumOperands - 1)
2829 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2830 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
2831 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2832 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2834 // 8 nodes, but we only care about the last 4.
2835 for (unsigned i = 7; i >= 4; --i) {
2836 int Val = SVOp->getMaskElt(i);
2845 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2846 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
2847 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2848 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2850 // 8 nodes, but we only care about the first 4.
2851 for (int i = 3; i >= 0; --i) {
2852 int Val = SVOp->getMaskElt(i);
2861 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
2862 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
2863 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
2864 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2865 EVT VVT = N->getValueType(0);
2866 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
2870 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
2871 Val = SVOp->getMaskElt(i);
2875 return (Val - i) * EltSize;
2878 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2880 bool X86::isZeroNode(SDValue Elt) {
2881 return ((isa<ConstantSDNode>(Elt) &&
2882 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2883 (isa<ConstantFPSDNode>(Elt) &&
2884 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2887 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
2888 /// their permute mask.
2889 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
2890 SelectionDAG &DAG) {
2891 EVT VT = SVOp->getValueType(0);
2892 unsigned NumElems = VT.getVectorNumElements();
2893 SmallVector<int, 8> MaskVec;
2895 for (unsigned i = 0; i != NumElems; ++i) {
2896 int idx = SVOp->getMaskElt(i);
2898 MaskVec.push_back(idx);
2899 else if (idx < (int)NumElems)
2900 MaskVec.push_back(idx + NumElems);
2902 MaskVec.push_back(idx - NumElems);
2904 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
2905 SVOp->getOperand(0), &MaskVec[0]);
2908 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2909 /// the two vector operands have swapped position.
2910 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
2911 unsigned NumElems = VT.getVectorNumElements();
2912 for (unsigned i = 0; i != NumElems; ++i) {
2916 else if (idx < (int)NumElems)
2917 Mask[i] = idx + NumElems;
2919 Mask[i] = idx - NumElems;
2923 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2924 /// match movhlps. The lower half elements should come from upper half of
2925 /// V1 (and in order), and the upper half elements should come from the upper
2926 /// half of V2 (and in order).
2927 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
2928 if (Op->getValueType(0).getVectorNumElements() != 4)
2930 for (unsigned i = 0, e = 2; i != e; ++i)
2931 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
2933 for (unsigned i = 2; i != 4; ++i)
2934 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
2939 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2940 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2942 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2943 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
2945 N = N->getOperand(0).getNode();
2946 if (!ISD::isNON_EXTLoad(N))
2949 *LD = cast<LoadSDNode>(N);
2953 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2954 /// match movlp{s|d}. The lower half elements should come from lower half of
2955 /// V1 (and in order), and the upper half elements should come from the upper
2956 /// half of V2 (and in order). And since V1 will become the source of the
2957 /// MOVLP, it must be either a vector load or a scalar load to vector.
2958 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
2959 ShuffleVectorSDNode *Op) {
2960 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2962 // Is V2 is a vector load, don't do this transformation. We will try to use
2963 // load folding shufps op.
2964 if (ISD::isNON_EXTLoad(V2))
2967 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
2969 if (NumElems != 2 && NumElems != 4)
2971 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2972 if (!isUndefOrEqual(Op->getMaskElt(i), i))
2974 for (unsigned i = NumElems/2; i != NumElems; ++i)
2975 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
2980 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2982 static bool isSplatVector(SDNode *N) {
2983 if (N->getOpcode() != ISD::BUILD_VECTOR)
2986 SDValue SplatValue = N->getOperand(0);
2987 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
2988 if (N->getOperand(i) != SplatValue)
2993 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
2994 /// to an zero vector.
2995 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
2996 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
2997 SDValue V1 = N->getOperand(0);
2998 SDValue V2 = N->getOperand(1);
2999 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3000 for (unsigned i = 0; i != NumElems; ++i) {
3001 int Idx = N->getMaskElt(i);
3002 if (Idx >= (int)NumElems) {
3003 unsigned Opc = V2.getOpcode();
3004 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3006 if (Opc != ISD::BUILD_VECTOR ||
3007 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3009 } else if (Idx >= 0) {
3010 unsigned Opc = V1.getOpcode();
3011 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3013 if (Opc != ISD::BUILD_VECTOR ||
3014 !X86::isZeroNode(V1.getOperand(Idx)))
3021 /// getZeroVector - Returns a vector of specified type with all zero elements.
3023 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3025 assert(VT.isVector() && "Expected a vector type");
3027 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3028 // type. This ensures they get CSE'd.
3030 if (VT.getSizeInBits() == 64) { // MMX
3031 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3032 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3033 } else if (HasSSE2) { // SSE2
3034 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3035 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3037 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3038 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3040 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3043 /// getOnesVector - Returns a vector of specified type with all bits set.
3045 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3046 assert(VT.isVector() && "Expected a vector type");
3048 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3049 // type. This ensures they get CSE'd.
3050 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3052 if (VT.getSizeInBits() == 64) // MMX
3053 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3055 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3056 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3060 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3061 /// that point to V2 points to its first element.
3062 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3063 EVT VT = SVOp->getValueType(0);
3064 unsigned NumElems = VT.getVectorNumElements();
3066 bool Changed = false;
3067 SmallVector<int, 8> MaskVec;
3068 SVOp->getMask(MaskVec);
3070 for (unsigned i = 0; i != NumElems; ++i) {
3071 if (MaskVec[i] > (int)NumElems) {
3072 MaskVec[i] = NumElems;
3077 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3078 SVOp->getOperand(1), &MaskVec[0]);
3079 return SDValue(SVOp, 0);
3082 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3083 /// operation of specified width.
3084 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3086 unsigned NumElems = VT.getVectorNumElements();
3087 SmallVector<int, 8> Mask;
3088 Mask.push_back(NumElems);
3089 for (unsigned i = 1; i != NumElems; ++i)
3091 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3094 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3095 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3097 unsigned NumElems = VT.getVectorNumElements();
3098 SmallVector<int, 8> Mask;
3099 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3101 Mask.push_back(i + NumElems);
3103 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3106 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3107 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3109 unsigned NumElems = VT.getVectorNumElements();
3110 unsigned Half = NumElems/2;
3111 SmallVector<int, 8> Mask;
3112 for (unsigned i = 0; i != Half; ++i) {
3113 Mask.push_back(i + Half);
3114 Mask.push_back(i + NumElems + Half);
3116 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3119 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3120 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3122 if (SV->getValueType(0).getVectorNumElements() <= 4)
3123 return SDValue(SV, 0);
3125 EVT PVT = MVT::v4f32;
3126 EVT VT = SV->getValueType(0);
3127 DebugLoc dl = SV->getDebugLoc();
3128 SDValue V1 = SV->getOperand(0);
3129 int NumElems = VT.getVectorNumElements();
3130 int EltNo = SV->getSplatIndex();
3132 // unpack elements to the correct location
3133 while (NumElems > 4) {
3134 if (EltNo < NumElems/2) {
3135 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3137 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3138 EltNo -= NumElems/2;
3143 // Perform the splat.
3144 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3145 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3146 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3147 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3150 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3151 /// vector of zero or undef vector. This produces a shuffle where the low
3152 /// element of V2 is swizzled into the zero/undef vector, landing at element
3153 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3154 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3155 bool isZero, bool HasSSE2,
3156 SelectionDAG &DAG) {
3157 EVT VT = V2.getValueType();
3159 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3160 unsigned NumElems = VT.getVectorNumElements();
3161 SmallVector<int, 16> MaskVec;
3162 for (unsigned i = 0; i != NumElems; ++i)
3163 // If this is the insertion idx, put the low elt of V2 here.
3164 MaskVec.push_back(i == Idx ? NumElems : i);
3165 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3168 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3169 /// a shuffle that is zero.
3171 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3172 bool Low, SelectionDAG &DAG) {
3173 unsigned NumZeros = 0;
3174 for (int i = 0; i < NumElems; ++i) {
3175 unsigned Index = Low ? i : NumElems-i-1;
3176 int Idx = SVOp->getMaskElt(Index);
3181 SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3182 if (Elt.getNode() && X86::isZeroNode(Elt))
3190 /// isVectorShift - Returns true if the shuffle can be implemented as a
3191 /// logical left or right shift of a vector.
3192 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3193 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3194 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3195 int NumElems = SVOp->getValueType(0).getVectorNumElements();
3198 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3201 NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3205 bool SeenV1 = false;
3206 bool SeenV2 = false;
3207 for (int i = NumZeros; i < NumElems; ++i) {
3208 int Val = isLeft ? (i - NumZeros) : i;
3209 int Idx = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3221 if (SeenV1 && SeenV2)
3224 ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3230 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3232 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3233 unsigned NumNonZero, unsigned NumZero,
3234 SelectionDAG &DAG, TargetLowering &TLI) {
3238 DebugLoc dl = Op.getDebugLoc();
3241 for (unsigned i = 0; i < 16; ++i) {
3242 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3243 if (ThisIsNonZero && First) {
3245 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3247 V = DAG.getUNDEF(MVT::v8i16);
3252 SDValue ThisElt(0, 0), LastElt(0, 0);
3253 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3254 if (LastIsNonZero) {
3255 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3256 MVT::i16, Op.getOperand(i-1));
3258 if (ThisIsNonZero) {
3259 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3260 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3261 ThisElt, DAG.getConstant(8, MVT::i8));
3263 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3267 if (ThisElt.getNode())
3268 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3269 DAG.getIntPtrConstant(i/2));
3273 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3276 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3278 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3279 unsigned NumNonZero, unsigned NumZero,
3280 SelectionDAG &DAG, TargetLowering &TLI) {
3284 DebugLoc dl = Op.getDebugLoc();
3287 for (unsigned i = 0; i < 8; ++i) {
3288 bool isNonZero = (NonZeros & (1 << i)) != 0;
3292 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3294 V = DAG.getUNDEF(MVT::v8i16);
3297 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3298 MVT::v8i16, V, Op.getOperand(i),
3299 DAG.getIntPtrConstant(i));
3306 /// getVShift - Return a vector logical shift node.
3308 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3309 unsigned NumBits, SelectionDAG &DAG,
3310 const TargetLowering &TLI, DebugLoc dl) {
3311 bool isMMX = VT.getSizeInBits() == 64;
3312 EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3313 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3314 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3315 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3316 DAG.getNode(Opc, dl, ShVT, SrcOp,
3317 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3321 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3322 DebugLoc dl = Op.getDebugLoc();
3323 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3324 if (ISD::isBuildVectorAllZeros(Op.getNode())
3325 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3326 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3327 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3328 // eliminated on x86-32 hosts.
3329 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3332 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3333 return getOnesVector(Op.getValueType(), DAG, dl);
3334 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3337 EVT VT = Op.getValueType();
3338 EVT ExtVT = VT.getVectorElementType();
3339 unsigned EVTBits = ExtVT.getSizeInBits();
3341 unsigned NumElems = Op.getNumOperands();
3342 unsigned NumZero = 0;
3343 unsigned NumNonZero = 0;
3344 unsigned NonZeros = 0;
3345 bool IsAllConstants = true;
3346 SmallSet<SDValue, 8> Values;
3347 for (unsigned i = 0; i < NumElems; ++i) {
3348 SDValue Elt = Op.getOperand(i);
3349 if (Elt.getOpcode() == ISD::UNDEF)
3352 if (Elt.getOpcode() != ISD::Constant &&
3353 Elt.getOpcode() != ISD::ConstantFP)
3354 IsAllConstants = false;
3355 if (X86::isZeroNode(Elt))
3358 NonZeros |= (1 << i);
3363 if (NumNonZero == 0) {
3364 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3365 return DAG.getUNDEF(VT);
3368 // Special case for single non-zero, non-undef, element.
3369 if (NumNonZero == 1) {
3370 unsigned Idx = CountTrailingZeros_32(NonZeros);
3371 SDValue Item = Op.getOperand(Idx);
3373 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3374 // the value are obviously zero, truncate the value to i32 and do the
3375 // insertion that way. Only do this if the value is non-constant or if the
3376 // value is a constant being inserted into element 0. It is cheaper to do
3377 // a constant pool load than it is to do a movd + shuffle.
3378 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3379 (!IsAllConstants || Idx == 0)) {
3380 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3381 // Handle MMX and SSE both.
3382 EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3383 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3385 // Truncate the value (which may itself be a constant) to i32, and
3386 // convert it to a vector with movd (S2V+shuffle to zero extend).
3387 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3388 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3389 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3390 Subtarget->hasSSE2(), DAG);
3392 // Now we have our 32-bit value zero extended in the low element of
3393 // a vector. If Idx != 0, swizzle it into place.
3395 SmallVector<int, 4> Mask;
3396 Mask.push_back(Idx);
3397 for (unsigned i = 1; i != VecElts; ++i)
3399 Item = DAG.getVectorShuffle(VecVT, dl, Item,
3400 DAG.getUNDEF(Item.getValueType()),
3403 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3407 // If we have a constant or non-constant insertion into the low element of
3408 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3409 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3410 // depending on what the source datatype is.
3413 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3414 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3415 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3416 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3417 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3418 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3420 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3421 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3422 EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3423 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3424 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3425 Subtarget->hasSSE2(), DAG);
3426 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3430 // Is it a vector logical left shift?
3431 if (NumElems == 2 && Idx == 1 &&
3432 X86::isZeroNode(Op.getOperand(0)) &&
3433 !X86::isZeroNode(Op.getOperand(1))) {
3434 unsigned NumBits = VT.getSizeInBits();
3435 return getVShift(true, VT,
3436 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3437 VT, Op.getOperand(1)),
3438 NumBits/2, DAG, *this, dl);
3441 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3444 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3445 // is a non-constant being inserted into an element other than the low one,
3446 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3447 // movd/movss) to move this into the low element, then shuffle it into
3449 if (EVTBits == 32) {
3450 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3452 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3453 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3454 Subtarget->hasSSE2(), DAG);
3455 SmallVector<int, 8> MaskVec;
3456 for (unsigned i = 0; i < NumElems; i++)
3457 MaskVec.push_back(i == Idx ? 0 : 1);
3458 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3462 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3463 if (Values.size() == 1)
3466 // A vector full of immediates; various special cases are already
3467 // handled, so this is best done with a single constant-pool load.
3471 // Let legalizer expand 2-wide build_vectors.
3472 if (EVTBits == 64) {
3473 if (NumNonZero == 1) {
3474 // One half is zero or undef.
3475 unsigned Idx = CountTrailingZeros_32(NonZeros);
3476 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3477 Op.getOperand(Idx));
3478 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3479 Subtarget->hasSSE2(), DAG);
3484 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3485 if (EVTBits == 8 && NumElems == 16) {
3486 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3488 if (V.getNode()) return V;
3491 if (EVTBits == 16 && NumElems == 8) {
3492 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3494 if (V.getNode()) return V;
3497 // If element VT is == 32 bits, turn it into a number of shuffles.
3498 SmallVector<SDValue, 8> V;
3500 if (NumElems == 4 && NumZero > 0) {
3501 for (unsigned i = 0; i < 4; ++i) {
3502 bool isZero = !(NonZeros & (1 << i));
3504 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3506 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3509 for (unsigned i = 0; i < 2; ++i) {
3510 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3513 V[i] = V[i*2]; // Must be a zero vector.
3516 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3519 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3522 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3527 SmallVector<int, 8> MaskVec;
3528 bool Reverse = (NonZeros & 0x3) == 2;
3529 for (unsigned i = 0; i < 2; ++i)
3530 MaskVec.push_back(Reverse ? 1-i : i);
3531 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3532 for (unsigned i = 0; i < 2; ++i)
3533 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3534 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3537 if (Values.size() > 2) {
3538 // If we have SSE 4.1, Expand into a number of inserts unless the number of
3539 // values to be inserted is equal to the number of elements, in which case
3540 // use the unpack code below in the hopes of matching the consecutive elts
3541 // load merge pattern for shuffles.
3542 // FIXME: We could probably just check that here directly.
3543 if (Values.size() < NumElems && VT.getSizeInBits() == 128 &&
3544 getSubtarget()->hasSSE41()) {
3545 V[0] = DAG.getUNDEF(VT);
3546 for (unsigned i = 0; i < NumElems; ++i)
3547 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3548 V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3549 Op.getOperand(i), DAG.getIntPtrConstant(i));
3552 // Expand into a number of unpckl*.
3554 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3555 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3556 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3557 for (unsigned i = 0; i < NumElems; ++i)
3558 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3560 while (NumElems != 0) {
3561 for (unsigned i = 0; i < NumElems; ++i)
3562 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3571 // v8i16 shuffles - Prefer shuffles in the following order:
3572 // 1. [all] pshuflw, pshufhw, optional move
3573 // 2. [ssse3] 1 x pshufb
3574 // 3. [ssse3] 2 x pshufb + 1 x por
3575 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
3577 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
3578 SelectionDAG &DAG, X86TargetLowering &TLI) {
3579 SDValue V1 = SVOp->getOperand(0);
3580 SDValue V2 = SVOp->getOperand(1);
3581 DebugLoc dl = SVOp->getDebugLoc();
3582 SmallVector<int, 8> MaskVals;
3584 // Determine if more than 1 of the words in each of the low and high quadwords
3585 // of the result come from the same quadword of one of the two inputs. Undef
3586 // mask values count as coming from any quadword, for better codegen.
3587 SmallVector<unsigned, 4> LoQuad(4);
3588 SmallVector<unsigned, 4> HiQuad(4);
3589 BitVector InputQuads(4);
3590 for (unsigned i = 0; i < 8; ++i) {
3591 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
3592 int EltIdx = SVOp->getMaskElt(i);
3593 MaskVals.push_back(EltIdx);
3602 InputQuads.set(EltIdx / 4);
3605 int BestLoQuad = -1;
3606 unsigned MaxQuad = 1;
3607 for (unsigned i = 0; i < 4; ++i) {
3608 if (LoQuad[i] > MaxQuad) {
3610 MaxQuad = LoQuad[i];
3614 int BestHiQuad = -1;
3616 for (unsigned i = 0; i < 4; ++i) {
3617 if (HiQuad[i] > MaxQuad) {
3619 MaxQuad = HiQuad[i];
3623 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
3624 // of the two input vectors, shuffle them into one input vector so only a
3625 // single pshufb instruction is necessary. If There are more than 2 input
3626 // quads, disable the next transformation since it does not help SSSE3.
3627 bool V1Used = InputQuads[0] || InputQuads[1];
3628 bool V2Used = InputQuads[2] || InputQuads[3];
3629 if (TLI.getSubtarget()->hasSSSE3()) {
3630 if (InputQuads.count() == 2 && V1Used && V2Used) {
3631 BestLoQuad = InputQuads.find_first();
3632 BestHiQuad = InputQuads.find_next(BestLoQuad);
3634 if (InputQuads.count() > 2) {
3640 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
3641 // the shuffle mask. If a quad is scored as -1, that means that it contains
3642 // words from all 4 input quadwords.
3644 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
3645 SmallVector<int, 8> MaskV;
3646 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
3647 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
3648 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
3649 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
3650 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
3651 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
3653 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
3654 // source words for the shuffle, to aid later transformations.
3655 bool AllWordsInNewV = true;
3656 bool InOrder[2] = { true, true };
3657 for (unsigned i = 0; i != 8; ++i) {
3658 int idx = MaskVals[i];
3660 InOrder[i/4] = false;
3661 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
3663 AllWordsInNewV = false;
3667 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
3668 if (AllWordsInNewV) {
3669 for (int i = 0; i != 8; ++i) {
3670 int idx = MaskVals[i];
3673 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
3674 if ((idx != i) && idx < 4)
3676 if ((idx != i) && idx > 3)
3685 // If we've eliminated the use of V2, and the new mask is a pshuflw or
3686 // pshufhw, that's as cheap as it gets. Return the new shuffle.
3687 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
3688 return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
3689 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
3693 // If we have SSSE3, and all words of the result are from 1 input vector,
3694 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
3695 // is present, fall back to case 4.
3696 if (TLI.getSubtarget()->hasSSSE3()) {
3697 SmallVector<SDValue,16> pshufbMask;
3699 // If we have elements from both input vectors, set the high bit of the
3700 // shuffle mask element to zero out elements that come from V2 in the V1
3701 // mask, and elements that come from V1 in the V2 mask, so that the two
3702 // results can be OR'd together.
3703 bool TwoInputs = V1Used && V2Used;
3704 for (unsigned i = 0; i != 8; ++i) {
3705 int EltIdx = MaskVals[i] * 2;
3706 if (TwoInputs && (EltIdx >= 16)) {
3707 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3708 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3711 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3712 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
3714 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
3715 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3716 DAG.getNode(ISD::BUILD_VECTOR, dl,
3717 MVT::v16i8, &pshufbMask[0], 16));
3719 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3721 // Calculate the shuffle mask for the second input, shuffle it, and
3722 // OR it with the first shuffled input.
3724 for (unsigned i = 0; i != 8; ++i) {
3725 int EltIdx = MaskVals[i] * 2;
3727 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3728 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3731 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3732 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
3734 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
3735 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3736 DAG.getNode(ISD::BUILD_VECTOR, dl,
3737 MVT::v16i8, &pshufbMask[0], 16));
3738 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3739 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3742 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
3743 // and update MaskVals with new element order.
3744 BitVector InOrder(8);
3745 if (BestLoQuad >= 0) {
3746 SmallVector<int, 8> MaskV;
3747 for (int i = 0; i != 4; ++i) {
3748 int idx = MaskVals[i];
3750 MaskV.push_back(-1);
3752 } else if ((idx / 4) == BestLoQuad) {
3753 MaskV.push_back(idx & 3);
3756 MaskV.push_back(-1);
3759 for (unsigned i = 4; i != 8; ++i)
3761 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3765 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
3766 // and update MaskVals with the new element order.
3767 if (BestHiQuad >= 0) {
3768 SmallVector<int, 8> MaskV;
3769 for (unsigned i = 0; i != 4; ++i)
3771 for (unsigned i = 4; i != 8; ++i) {
3772 int idx = MaskVals[i];
3774 MaskV.push_back(-1);
3776 } else if ((idx / 4) == BestHiQuad) {
3777 MaskV.push_back((idx & 3) + 4);
3780 MaskV.push_back(-1);
3783 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3787 // In case BestHi & BestLo were both -1, which means each quadword has a word
3788 // from each of the four input quadwords, calculate the InOrder bitvector now
3789 // before falling through to the insert/extract cleanup.
3790 if (BestLoQuad == -1 && BestHiQuad == -1) {
3792 for (int i = 0; i != 8; ++i)
3793 if (MaskVals[i] < 0 || MaskVals[i] == i)
3797 // The other elements are put in the right place using pextrw and pinsrw.
3798 for (unsigned i = 0; i != 8; ++i) {
3801 int EltIdx = MaskVals[i];
3804 SDValue ExtOp = (EltIdx < 8)
3805 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
3806 DAG.getIntPtrConstant(EltIdx))
3807 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
3808 DAG.getIntPtrConstant(EltIdx - 8));
3809 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3810 DAG.getIntPtrConstant(i));
3815 // v16i8 shuffles - Prefer shuffles in the following order:
3816 // 1. [ssse3] 1 x pshufb
3817 // 2. [ssse3] 2 x pshufb + 1 x por
3818 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
3820 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
3821 SelectionDAG &DAG, X86TargetLowering &TLI) {
3822 SDValue V1 = SVOp->getOperand(0);
3823 SDValue V2 = SVOp->getOperand(1);
3824 DebugLoc dl = SVOp->getDebugLoc();
3825 SmallVector<int, 16> MaskVals;
3826 SVOp->getMask(MaskVals);
3828 // If we have SSSE3, case 1 is generated when all result bytes come from
3829 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
3830 // present, fall back to case 3.
3831 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
3834 for (unsigned i = 0; i < 16; ++i) {
3835 int EltIdx = MaskVals[i];
3844 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
3845 if (TLI.getSubtarget()->hasSSSE3()) {
3846 SmallVector<SDValue,16> pshufbMask;
3848 // If all result elements are from one input vector, then only translate
3849 // undef mask values to 0x80 (zero out result) in the pshufb mask.
3851 // Otherwise, we have elements from both input vectors, and must zero out
3852 // elements that come from V2 in the first mask, and V1 in the second mask
3853 // so that we can OR them together.
3854 bool TwoInputs = !(V1Only || V2Only);
3855 for (unsigned i = 0; i != 16; ++i) {
3856 int EltIdx = MaskVals[i];
3857 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
3858 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3861 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3863 // If all the elements are from V2, assign it to V1 and return after
3864 // building the first pshufb.
3867 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3868 DAG.getNode(ISD::BUILD_VECTOR, dl,
3869 MVT::v16i8, &pshufbMask[0], 16));
3873 // Calculate the shuffle mask for the second input, shuffle it, and
3874 // OR it with the first shuffled input.
3876 for (unsigned i = 0; i != 16; ++i) {
3877 int EltIdx = MaskVals[i];
3879 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3882 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3884 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3885 DAG.getNode(ISD::BUILD_VECTOR, dl,
3886 MVT::v16i8, &pshufbMask[0], 16));
3887 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3890 // No SSSE3 - Calculate in place words and then fix all out of place words
3891 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
3892 // the 16 different words that comprise the two doublequadword input vectors.
3893 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3894 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
3895 SDValue NewV = V2Only ? V2 : V1;
3896 for (int i = 0; i != 8; ++i) {
3897 int Elt0 = MaskVals[i*2];
3898 int Elt1 = MaskVals[i*2+1];
3900 // This word of the result is all undef, skip it.
3901 if (Elt0 < 0 && Elt1 < 0)
3904 // This word of the result is already in the correct place, skip it.
3905 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
3907 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
3910 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
3911 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
3914 // If Elt0 and Elt1 are defined, are consecutive, and can be load
3915 // using a single extract together, load it and store it.
3916 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
3917 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3918 DAG.getIntPtrConstant(Elt1 / 2));
3919 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3920 DAG.getIntPtrConstant(i));
3924 // If Elt1 is defined, extract it from the appropriate source. If the
3925 // source byte is not also odd, shift the extracted word left 8 bits
3926 // otherwise clear the bottom 8 bits if we need to do an or.
3928 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3929 DAG.getIntPtrConstant(Elt1 / 2));
3930 if ((Elt1 & 1) == 0)
3931 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
3932 DAG.getConstant(8, TLI.getShiftAmountTy()));
3934 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
3935 DAG.getConstant(0xFF00, MVT::i16));
3937 // If Elt0 is defined, extract it from the appropriate source. If the
3938 // source byte is not also even, shift the extracted word right 8 bits. If
3939 // Elt1 was also defined, OR the extracted values together before
3940 // inserting them in the result.
3942 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
3943 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
3944 if ((Elt0 & 1) != 0)
3945 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
3946 DAG.getConstant(8, TLI.getShiftAmountTy()));
3948 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
3949 DAG.getConstant(0x00FF, MVT::i16));
3950 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
3953 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3954 DAG.getIntPtrConstant(i));
3956 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
3959 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3960 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3961 /// done when every pair / quad of shuffle mask elements point to elements in
3962 /// the right sequence. e.g.
3963 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3965 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
3967 TargetLowering &TLI, DebugLoc dl) {
3968 EVT VT = SVOp->getValueType(0);
3969 SDValue V1 = SVOp->getOperand(0);
3970 SDValue V2 = SVOp->getOperand(1);
3971 unsigned NumElems = VT.getVectorNumElements();
3972 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3973 EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3974 EVT MaskEltVT = MaskVT.getVectorElementType();
3976 switch (VT.getSimpleVT().SimpleTy) {
3977 default: assert(false && "Unexpected!");
3978 case MVT::v4f32: NewVT = MVT::v2f64; break;
3979 case MVT::v4i32: NewVT = MVT::v2i64; break;
3980 case MVT::v8i16: NewVT = MVT::v4i32; break;
3981 case MVT::v16i8: NewVT = MVT::v4i32; break;
3984 if (NewWidth == 2) {
3990 int Scale = NumElems / NewWidth;
3991 SmallVector<int, 8> MaskVec;
3992 for (unsigned i = 0; i < NumElems; i += Scale) {
3994 for (int j = 0; j < Scale; ++j) {
3995 int EltIdx = SVOp->getMaskElt(i+j);
3999 StartIdx = EltIdx - (EltIdx % Scale);
4000 if (EltIdx != StartIdx + j)
4004 MaskVec.push_back(-1);
4006 MaskVec.push_back(StartIdx / Scale);
4009 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4010 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4011 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4014 /// getVZextMovL - Return a zero-extending vector move low node.
4016 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4017 SDValue SrcOp, SelectionDAG &DAG,
4018 const X86Subtarget *Subtarget, DebugLoc dl) {
4019 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4020 LoadSDNode *LD = NULL;
4021 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4022 LD = dyn_cast<LoadSDNode>(SrcOp);
4024 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4026 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4027 if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4028 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4029 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4030 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4032 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4033 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4034 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4035 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4043 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4044 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4045 DAG.getNode(ISD::BIT_CONVERT, dl,
4049 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4052 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4053 SDValue V1 = SVOp->getOperand(0);
4054 SDValue V2 = SVOp->getOperand(1);
4055 DebugLoc dl = SVOp->getDebugLoc();
4056 EVT VT = SVOp->getValueType(0);
4058 SmallVector<std::pair<int, int>, 8> Locs;
4060 SmallVector<int, 8> Mask1(4U, -1);
4061 SmallVector<int, 8> PermMask;
4062 SVOp->getMask(PermMask);
4066 for (unsigned i = 0; i != 4; ++i) {
4067 int Idx = PermMask[i];
4069 Locs[i] = std::make_pair(-1, -1);
4071 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4073 Locs[i] = std::make_pair(0, NumLo);
4077 Locs[i] = std::make_pair(1, NumHi);
4079 Mask1[2+NumHi] = Idx;
4085 if (NumLo <= 2 && NumHi <= 2) {
4086 // If no more than two elements come from either vector. This can be
4087 // implemented with two shuffles. First shuffle gather the elements.
4088 // The second shuffle, which takes the first shuffle as both of its
4089 // vector operands, put the elements into the right order.
4090 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4092 SmallVector<int, 8> Mask2(4U, -1);
4094 for (unsigned i = 0; i != 4; ++i) {
4095 if (Locs[i].first == -1)
4098 unsigned Idx = (i < 2) ? 0 : 4;
4099 Idx += Locs[i].first * 2 + Locs[i].second;
4104 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4105 } else if (NumLo == 3 || NumHi == 3) {
4106 // Otherwise, we must have three elements from one vector, call it X, and
4107 // one element from the other, call it Y. First, use a shufps to build an
4108 // intermediate vector with the one element from Y and the element from X
4109 // that will be in the same half in the final destination (the indexes don't
4110 // matter). Then, use a shufps to build the final vector, taking the half
4111 // containing the element from Y from the intermediate, and the other half
4114 // Normalize it so the 3 elements come from V1.
4115 CommuteVectorShuffleMask(PermMask, VT);
4119 // Find the element from V2.
4121 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4122 int Val = PermMask[HiIndex];
4129 Mask1[0] = PermMask[HiIndex];
4131 Mask1[2] = PermMask[HiIndex^1];
4133 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4136 Mask1[0] = PermMask[0];
4137 Mask1[1] = PermMask[1];
4138 Mask1[2] = HiIndex & 1 ? 6 : 4;
4139 Mask1[3] = HiIndex & 1 ? 4 : 6;
4140 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4142 Mask1[0] = HiIndex & 1 ? 2 : 0;
4143 Mask1[1] = HiIndex & 1 ? 0 : 2;
4144 Mask1[2] = PermMask[2];
4145 Mask1[3] = PermMask[3];
4150 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4154 // Break it into (shuffle shuffle_hi, shuffle_lo).
4156 SmallVector<int,8> LoMask(4U, -1);
4157 SmallVector<int,8> HiMask(4U, -1);
4159 SmallVector<int,8> *MaskPtr = &LoMask;
4160 unsigned MaskIdx = 0;
4163 for (unsigned i = 0; i != 4; ++i) {
4170 int Idx = PermMask[i];
4172 Locs[i] = std::make_pair(-1, -1);
4173 } else if (Idx < 4) {
4174 Locs[i] = std::make_pair(MaskIdx, LoIdx);
4175 (*MaskPtr)[LoIdx] = Idx;
4178 Locs[i] = std::make_pair(MaskIdx, HiIdx);
4179 (*MaskPtr)[HiIdx] = Idx;
4184 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4185 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4186 SmallVector<int, 8> MaskOps;
4187 for (unsigned i = 0; i != 4; ++i) {
4188 if (Locs[i].first == -1) {
4189 MaskOps.push_back(-1);
4191 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4192 MaskOps.push_back(Idx);
4195 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4199 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4200 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4201 SDValue V1 = Op.getOperand(0);
4202 SDValue V2 = Op.getOperand(1);
4203 EVT VT = Op.getValueType();
4204 DebugLoc dl = Op.getDebugLoc();
4205 unsigned NumElems = VT.getVectorNumElements();
4206 bool isMMX = VT.getSizeInBits() == 64;
4207 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4208 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4209 bool V1IsSplat = false;
4210 bool V2IsSplat = false;
4212 if (isZeroShuffle(SVOp))
4213 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4215 // Promote splats to v4f32.
4216 if (SVOp->isSplat()) {
4217 if (isMMX || NumElems < 4)
4219 return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4222 // If the shuffle can be profitably rewritten as a narrower shuffle, then
4224 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4225 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4226 if (NewOp.getNode())
4227 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4228 LowerVECTOR_SHUFFLE(NewOp, DAG));
4229 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4230 // FIXME: Figure out a cleaner way to do this.
4231 // Try to make use of movq to zero out the top part.
4232 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4233 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4234 if (NewOp.getNode()) {
4235 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4236 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4237 DAG, Subtarget, dl);
4239 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4240 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4241 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4242 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4243 DAG, Subtarget, dl);
4247 if (X86::isPSHUFDMask(SVOp))
4250 // Check if this can be converted into a logical shift.
4251 bool isLeft = false;
4254 bool isShift = getSubtarget()->hasSSE2() &&
4255 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4256 if (isShift && ShVal.hasOneUse()) {
4257 // If the shifted value has multiple uses, it may be cheaper to use
4258 // v_set0 + movlhps or movhlps, etc.
4259 EVT EltVT = VT.getVectorElementType();
4260 ShAmt *= EltVT.getSizeInBits();
4261 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4264 if (X86::isMOVLMask(SVOp)) {
4267 if (ISD::isBuildVectorAllZeros(V1.getNode()))
4268 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4273 // FIXME: fold these into legal mask.
4274 if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4275 X86::isMOVSLDUPMask(SVOp) ||
4276 X86::isMOVHLPSMask(SVOp) ||
4277 X86::isMOVLHPSMask(SVOp) ||
4278 X86::isMOVLPMask(SVOp)))
4281 if (ShouldXformToMOVHLPS(SVOp) ||
4282 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4283 return CommuteVectorShuffle(SVOp, DAG);
4286 // No better options. Use a vshl / vsrl.
4287 EVT EltVT = VT.getVectorElementType();
4288 ShAmt *= EltVT.getSizeInBits();
4289 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4292 bool Commuted = false;
4293 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4294 // 1,1,1,1 -> v8i16 though.
4295 V1IsSplat = isSplatVector(V1.getNode());
4296 V2IsSplat = isSplatVector(V2.getNode());
4298 // Canonicalize the splat or undef, if present, to be on the RHS.
4299 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4300 Op = CommuteVectorShuffle(SVOp, DAG);
4301 SVOp = cast<ShuffleVectorSDNode>(Op);
4302 V1 = SVOp->getOperand(0);
4303 V2 = SVOp->getOperand(1);
4304 std::swap(V1IsSplat, V2IsSplat);
4305 std::swap(V1IsUndef, V2IsUndef);
4309 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4310 // Shuffling low element of v1 into undef, just return v1.
4313 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4314 // the instruction selector will not match, so get a canonical MOVL with
4315 // swapped operands to undo the commute.
4316 return getMOVL(DAG, dl, VT, V2, V1);
4319 if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4320 X86::isUNPCKH_v_undef_Mask(SVOp) ||
4321 X86::isUNPCKLMask(SVOp) ||
4322 X86::isUNPCKHMask(SVOp))
4326 // Normalize mask so all entries that point to V2 points to its first
4327 // element then try to match unpck{h|l} again. If match, return a
4328 // new vector_shuffle with the corrected mask.
4329 SDValue NewMask = NormalizeMask(SVOp, DAG);
4330 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4331 if (NSVOp != SVOp) {
4332 if (X86::isUNPCKLMask(NSVOp, true)) {
4334 } else if (X86::isUNPCKHMask(NSVOp, true)) {
4341 // Commute is back and try unpck* again.
4342 // FIXME: this seems wrong.
4343 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4344 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4345 if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4346 X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4347 X86::isUNPCKLMask(NewSVOp) ||
4348 X86::isUNPCKHMask(NewSVOp))
4352 // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4354 // Normalize the node to match x86 shuffle ops if needed
4355 if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4356 return CommuteVectorShuffle(SVOp, DAG);
4358 // Check for legal shuffle and return?
4359 SmallVector<int, 16> PermMask;
4360 SVOp->getMask(PermMask);
4361 if (isShuffleMaskLegal(PermMask, VT))
4364 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4365 if (VT == MVT::v8i16) {
4366 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4367 if (NewOp.getNode())
4371 if (VT == MVT::v16i8) {
4372 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4373 if (NewOp.getNode())
4377 // Handle all 4 wide cases with a number of shuffles except for MMX.
4378 if (NumElems == 4 && !isMMX)
4379 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4385 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4386 SelectionDAG &DAG) {
4387 EVT VT = Op.getValueType();
4388 DebugLoc dl = Op.getDebugLoc();
4389 if (VT.getSizeInBits() == 8) {
4390 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4391 Op.getOperand(0), Op.getOperand(1));
4392 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4393 DAG.getValueType(VT));
4394 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4395 } else if (VT.getSizeInBits() == 16) {
4396 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4397 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4399 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4400 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4401 DAG.getNode(ISD::BIT_CONVERT, dl,
4405 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4406 Op.getOperand(0), Op.getOperand(1));
4407 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4408 DAG.getValueType(VT));
4409 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4410 } else if (VT == MVT::f32) {
4411 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4412 // the result back to FR32 register. It's only worth matching if the
4413 // result has a single use which is a store or a bitcast to i32. And in
4414 // the case of a store, it's not worth it if the index is a constant 0,
4415 // because a MOVSSmr can be used instead, which is smaller and faster.
4416 if (!Op.hasOneUse())
4418 SDNode *User = *Op.getNode()->use_begin();
4419 if ((User->getOpcode() != ISD::STORE ||
4420 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4421 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4422 (User->getOpcode() != ISD::BIT_CONVERT ||
4423 User->getValueType(0) != MVT::i32))
4425 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4426 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4429 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4430 } else if (VT == MVT::i32) {
4431 // ExtractPS works with constant index.
4432 if (isa<ConstantSDNode>(Op.getOperand(1)))
4440 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4441 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4444 if (Subtarget->hasSSE41()) {
4445 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4450 EVT VT = Op.getValueType();
4451 DebugLoc dl = Op.getDebugLoc();
4452 // TODO: handle v16i8.
4453 if (VT.getSizeInBits() == 16) {
4454 SDValue Vec = Op.getOperand(0);
4455 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4457 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4458 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4459 DAG.getNode(ISD::BIT_CONVERT, dl,
4462 // Transform it so it match pextrw which produces a 32-bit result.
4463 EVT EltVT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy+1);
4464 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
4465 Op.getOperand(0), Op.getOperand(1));
4466 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
4467 DAG.getValueType(VT));
4468 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4469 } else if (VT.getSizeInBits() == 32) {
4470 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4474 // SHUFPS the element to the lowest double word, then movss.
4475 int Mask[4] = { Idx, -1, -1, -1 };
4476 EVT VVT = Op.getOperand(0).getValueType();
4477 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4478 DAG.getUNDEF(VVT), Mask);
4479 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4480 DAG.getIntPtrConstant(0));
4481 } else if (VT.getSizeInBits() == 64) {
4482 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4483 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4484 // to match extract_elt for f64.
4485 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4489 // UNPCKHPD the element to the lowest double word, then movsd.
4490 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4491 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4492 int Mask[2] = { 1, -1 };
4493 EVT VVT = Op.getOperand(0).getValueType();
4494 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4495 DAG.getUNDEF(VVT), Mask);
4496 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4497 DAG.getIntPtrConstant(0));
4504 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4505 EVT VT = Op.getValueType();
4506 EVT EltVT = VT.getVectorElementType();
4507 DebugLoc dl = Op.getDebugLoc();
4509 SDValue N0 = Op.getOperand(0);
4510 SDValue N1 = Op.getOperand(1);
4511 SDValue N2 = Op.getOperand(2);
4513 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
4514 isa<ConstantSDNode>(N2)) {
4515 unsigned Opc = (EltVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4517 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4519 if (N1.getValueType() != MVT::i32)
4520 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4521 if (N2.getValueType() != MVT::i32)
4522 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4523 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4524 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4525 // Bits [7:6] of the constant are the source select. This will always be
4526 // zero here. The DAG Combiner may combine an extract_elt index into these
4527 // bits. For example (insert (extract, 3), 2) could be matched by putting
4528 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4529 // Bits [5:4] of the constant are the destination select. This is the
4530 // value of the incoming immediate.
4531 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4532 // combine either bitwise AND or insert of float 0.0 to set these bits.
4533 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4534 // Create this as a scalar to vector..
4535 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
4536 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4537 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
4538 // PINSR* works with constant index.
4545 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4546 EVT VT = Op.getValueType();
4547 EVT EltVT = VT.getVectorElementType();
4549 if (Subtarget->hasSSE41())
4550 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4552 if (EltVT == MVT::i8)
4555 DebugLoc dl = Op.getDebugLoc();
4556 SDValue N0 = Op.getOperand(0);
4557 SDValue N1 = Op.getOperand(1);
4558 SDValue N2 = Op.getOperand(2);
4560 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
4561 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4562 // as its second argument.
4563 if (N1.getValueType() != MVT::i32)
4564 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4565 if (N2.getValueType() != MVT::i32)
4566 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4567 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
4573 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4574 DebugLoc dl = Op.getDebugLoc();
4575 if (Op.getValueType() == MVT::v2f32)
4576 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4577 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4578 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4579 Op.getOperand(0))));
4581 if (Op.getValueType() == MVT::v1i64 && Op.getOperand(0).getValueType() == MVT::i64)
4582 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
4584 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4585 EVT VT = MVT::v2i32;
4586 switch (Op.getValueType().getSimpleVT().SimpleTy) {
4593 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4594 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4597 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4598 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4599 // one of the above mentioned nodes. It has to be wrapped because otherwise
4600 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4601 // be used to form addressing mode. These wrapped nodes will be selected
4604 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4605 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4607 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4609 unsigned char OpFlag = 0;
4610 unsigned WrapperKind = X86ISD::Wrapper;
4611 CodeModel::Model M = getTargetMachine().getCodeModel();
4613 if (Subtarget->isPICStyleRIPRel() &&
4614 (M == CodeModel::Small || M == CodeModel::Kernel))
4615 WrapperKind = X86ISD::WrapperRIP;
4616 else if (Subtarget->isPICStyleGOT())
4617 OpFlag = X86II::MO_GOTOFF;
4618 else if (Subtarget->isPICStyleStubPIC())
4619 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4621 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
4623 CP->getOffset(), OpFlag);
4624 DebugLoc DL = CP->getDebugLoc();
4625 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4626 // With PIC, the address is actually $g + Offset.
4628 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4629 DAG.getNode(X86ISD::GlobalBaseReg,
4630 DebugLoc::getUnknownLoc(), getPointerTy()),
4637 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4638 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4640 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4642 unsigned char OpFlag = 0;
4643 unsigned WrapperKind = X86ISD::Wrapper;
4644 CodeModel::Model M = getTargetMachine().getCodeModel();
4646 if (Subtarget->isPICStyleRIPRel() &&
4647 (M == CodeModel::Small || M == CodeModel::Kernel))
4648 WrapperKind = X86ISD::WrapperRIP;
4649 else if (Subtarget->isPICStyleGOT())
4650 OpFlag = X86II::MO_GOTOFF;
4651 else if (Subtarget->isPICStyleStubPIC())
4652 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4654 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
4656 DebugLoc DL = JT->getDebugLoc();
4657 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4659 // With PIC, the address is actually $g + Offset.
4661 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4662 DAG.getNode(X86ISD::GlobalBaseReg,
4663 DebugLoc::getUnknownLoc(), getPointerTy()),
4671 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4672 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4674 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4676 unsigned char OpFlag = 0;
4677 unsigned WrapperKind = X86ISD::Wrapper;
4678 CodeModel::Model M = getTargetMachine().getCodeModel();
4680 if (Subtarget->isPICStyleRIPRel() &&
4681 (M == CodeModel::Small || M == CodeModel::Kernel))
4682 WrapperKind = X86ISD::WrapperRIP;
4683 else if (Subtarget->isPICStyleGOT())
4684 OpFlag = X86II::MO_GOTOFF;
4685 else if (Subtarget->isPICStyleStubPIC())
4686 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4688 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
4690 DebugLoc DL = Op.getDebugLoc();
4691 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4694 // With PIC, the address is actually $g + Offset.
4695 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4696 !Subtarget->is64Bit()) {
4697 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4698 DAG.getNode(X86ISD::GlobalBaseReg,
4699 DebugLoc::getUnknownLoc(),
4708 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) {
4709 unsigned WrapperKind = X86ISD::Wrapper;
4710 CodeModel::Model M = getTargetMachine().getCodeModel();
4711 if (Subtarget->isPICStyleRIPRel() &&
4712 (M == CodeModel::Small || M == CodeModel::Kernel))
4713 WrapperKind = X86ISD::WrapperRIP;
4715 DebugLoc DL = Op.getDebugLoc();
4717 BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
4718 SDValue Result = DAG.getBlockAddress(BA, DL, /*isTarget=*/true);
4720 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4726 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
4728 SelectionDAG &DAG) const {
4729 // Create the TargetGlobalAddress node, folding in the constant
4730 // offset if it is legal.
4731 unsigned char OpFlags =
4732 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
4733 CodeModel::Model M = getTargetMachine().getCodeModel();
4735 if (OpFlags == X86II::MO_NO_FLAG &&
4736 X86::isOffsetSuitableForCodeModel(Offset, M)) {
4737 // A direct static reference to a global.
4738 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4741 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
4744 if (Subtarget->isPICStyleRIPRel() &&
4745 (M == CodeModel::Small || M == CodeModel::Kernel))
4746 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
4748 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4750 // With PIC, the address is actually $g + Offset.
4751 if (isGlobalRelativeToPICBase(OpFlags)) {
4752 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4753 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4757 // For globals that require a load from a stub to get the address, emit the
4759 if (isGlobalStubReference(OpFlags))
4760 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
4761 PseudoSourceValue::getGOT(), 0);
4763 // If there was a non-zero offset that we didn't fold, create an explicit
4766 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
4767 DAG.getConstant(Offset, getPointerTy()));
4773 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4774 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4775 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4776 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
4780 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
4781 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
4782 unsigned char OperandFlags) {
4783 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4784 DebugLoc dl = GA->getDebugLoc();
4785 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4786 GA->getValueType(0),
4790 SDValue Ops[] = { Chain, TGA, *InFlag };
4791 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
4793 SDValue Ops[] = { Chain, TGA };
4794 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
4796 SDValue Flag = Chain.getValue(1);
4797 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
4800 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4802 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4805 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
4806 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
4807 DAG.getNode(X86ISD::GlobalBaseReg,
4808 DebugLoc::getUnknownLoc(),
4810 InFlag = Chain.getValue(1);
4812 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
4815 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4817 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4819 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
4820 X86::RAX, X86II::MO_TLSGD);
4823 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4824 // "local exec" model.
4825 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4826 const EVT PtrVT, TLSModel::Model model,
4828 DebugLoc dl = GA->getDebugLoc();
4829 // Get the Thread Pointer
4830 SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
4831 DebugLoc::getUnknownLoc(), PtrVT,
4832 DAG.getRegister(is64Bit? X86::FS : X86::GS,
4835 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
4838 unsigned char OperandFlags = 0;
4839 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
4841 unsigned WrapperKind = X86ISD::Wrapper;
4842 if (model == TLSModel::LocalExec) {
4843 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
4844 } else if (is64Bit) {
4845 assert(model == TLSModel::InitialExec);
4846 OperandFlags = X86II::MO_GOTTPOFF;
4847 WrapperKind = X86ISD::WrapperRIP;
4849 assert(model == TLSModel::InitialExec);
4850 OperandFlags = X86II::MO_INDNTPOFF;
4853 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4855 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
4856 GA->getOffset(), OperandFlags);
4857 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
4859 if (model == TLSModel::InitialExec)
4860 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
4861 PseudoSourceValue::getGOT(), 0);
4863 // The address of the thread local variable is the add of the thread
4864 // pointer with the offset of the variable.
4865 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
4869 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4870 // TODO: implement the "local dynamic" model
4871 // TODO: implement the "initial exec"model for pic executables
4872 assert(Subtarget->isTargetELF() &&
4873 "TLS not implemented for non-ELF targets");
4874 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4875 const GlobalValue *GV = GA->getGlobal();
4877 // If GV is an alias then use the aliasee for determining
4878 // thread-localness.
4879 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
4880 GV = GA->resolveAliasedGlobal(false);
4882 TLSModel::Model model = getTLSModel(GV,
4883 getTargetMachine().getRelocationModel());
4886 case TLSModel::GeneralDynamic:
4887 case TLSModel::LocalDynamic: // not implemented
4888 if (Subtarget->is64Bit())
4889 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4890 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4892 case TLSModel::InitialExec:
4893 case TLSModel::LocalExec:
4894 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
4895 Subtarget->is64Bit());
4898 llvm_unreachable("Unreachable");
4903 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4904 /// take a 2 x i32 value to shift plus a shift amount.
4905 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4906 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4907 EVT VT = Op.getValueType();
4908 unsigned VTBits = VT.getSizeInBits();
4909 DebugLoc dl = Op.getDebugLoc();
4910 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4911 SDValue ShOpLo = Op.getOperand(0);
4912 SDValue ShOpHi = Op.getOperand(1);
4913 SDValue ShAmt = Op.getOperand(2);
4914 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
4915 DAG.getConstant(VTBits - 1, MVT::i8))
4916 : DAG.getConstant(0, VT);
4919 if (Op.getOpcode() == ISD::SHL_PARTS) {
4920 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
4921 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4923 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
4924 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
4927 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
4928 DAG.getConstant(VTBits, MVT::i8));
4929 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, VT,
4930 AndNode, DAG.getConstant(0, MVT::i8));
4933 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4934 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4935 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4937 if (Op.getOpcode() == ISD::SHL_PARTS) {
4938 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4939 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4941 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4942 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4945 SDValue Ops[2] = { Lo, Hi };
4946 return DAG.getMergeValues(Ops, 2, dl);
4949 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4950 EVT SrcVT = Op.getOperand(0).getValueType();
4952 if (SrcVT.isVector()) {
4953 if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
4959 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4960 "Unknown SINT_TO_FP to lower!");
4962 // These are really Legal; return the operand so the caller accepts it as
4964 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4966 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
4967 Subtarget->is64Bit()) {
4971 DebugLoc dl = Op.getDebugLoc();
4972 unsigned Size = SrcVT.getSizeInBits()/8;
4973 MachineFunction &MF = DAG.getMachineFunction();
4974 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size);
4975 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4976 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
4978 PseudoSourceValue::getFixedStack(SSFI), 0);
4979 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
4982 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
4984 SelectionDAG &DAG) {
4986 DebugLoc dl = Op.getDebugLoc();
4988 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
4990 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
4992 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
4993 SmallVector<SDValue, 8> Ops;
4994 Ops.push_back(Chain);
4995 Ops.push_back(StackSlot);
4996 Ops.push_back(DAG.getValueType(SrcVT));
4997 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
4998 Tys, &Ops[0], Ops.size());
5001 Chain = Result.getValue(1);
5002 SDValue InFlag = Result.getValue(2);
5004 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5005 // shouldn't be necessary except that RFP cannot be live across
5006 // multiple blocks. When stackifier is fixed, they can be uncoupled.
5007 MachineFunction &MF = DAG.getMachineFunction();
5008 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
5009 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5010 Tys = DAG.getVTList(MVT::Other);
5011 SmallVector<SDValue, 8> Ops;
5012 Ops.push_back(Chain);
5013 Ops.push_back(Result);
5014 Ops.push_back(StackSlot);
5015 Ops.push_back(DAG.getValueType(Op.getValueType()));
5016 Ops.push_back(InFlag);
5017 Chain = DAG.getNode(X86ISD::FST, dl, Tys, &Ops[0], Ops.size());
5018 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5019 PseudoSourceValue::getFixedStack(SSFI), 0);
5025 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5026 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
5027 // This algorithm is not obvious. Here it is in C code, more or less:
5029 double uint64_to_double( uint32_t hi, uint32_t lo ) {
5030 static const __m128i exp = { 0x4330000045300000ULL, 0 };
5031 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5033 // Copy ints to xmm registers.
5034 __m128i xh = _mm_cvtsi32_si128( hi );
5035 __m128i xl = _mm_cvtsi32_si128( lo );
5037 // Combine into low half of a single xmm register.
5038 __m128i x = _mm_unpacklo_epi32( xh, xl );
5042 // Merge in appropriate exponents to give the integer bits the right
5044 x = _mm_unpacklo_epi32( x, exp );
5046 // Subtract away the biases to deal with the IEEE-754 double precision
5048 d = _mm_sub_pd( (__m128d) x, bias );
5050 // All conversions up to here are exact. The correctly rounded result is
5051 // calculated using the current rounding mode using the following
5053 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5054 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
5055 // store doesn't really need to be here (except
5056 // maybe to zero the other double)
5061 DebugLoc dl = Op.getDebugLoc();
5062 LLVMContext *Context = DAG.getContext();
5064 // Build some magic constants.
5065 std::vector<Constant*> CV0;
5066 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
5067 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
5068 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5069 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5070 Constant *C0 = ConstantVector::get(CV0);
5071 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5073 std::vector<Constant*> CV1;
5075 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
5077 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
5078 Constant *C1 = ConstantVector::get(CV1);
5079 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5081 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5082 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5084 DAG.getIntPtrConstant(1)));
5085 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5086 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5088 DAG.getIntPtrConstant(0)));
5089 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
5090 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5091 PseudoSourceValue::getConstantPool(), 0,
5093 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
5094 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5095 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5096 PseudoSourceValue::getConstantPool(), 0,
5098 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5100 // Add the halves; easiest way is to swap them into another reg first.
5101 int ShufMask[2] = { 1, -1 };
5102 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
5103 DAG.getUNDEF(MVT::v2f64), ShufMask);
5104 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5105 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5106 DAG.getIntPtrConstant(0));
5109 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5110 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
5111 DebugLoc dl = Op.getDebugLoc();
5112 // FP constant to bias correct the final result.
5113 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5116 // Load the 32-bit value into an XMM register.
5117 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5118 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5120 DAG.getIntPtrConstant(0)));
5122 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5123 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5124 DAG.getIntPtrConstant(0));
5126 // Or the load with the bias.
5127 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5128 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5129 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5131 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5132 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5133 MVT::v2f64, Bias)));
5134 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5135 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5136 DAG.getIntPtrConstant(0));
5138 // Subtract the bias.
5139 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5141 // Handle final rounding.
5142 EVT DestVT = Op.getValueType();
5144 if (DestVT.bitsLT(MVT::f64)) {
5145 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5146 DAG.getIntPtrConstant(0));
5147 } else if (DestVT.bitsGT(MVT::f64)) {
5148 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5151 // Handle final rounding.
5155 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5156 SDValue N0 = Op.getOperand(0);
5157 DebugLoc dl = Op.getDebugLoc();
5159 // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
5160 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5161 // the optimization here.
5162 if (DAG.SignBitIsZero(N0))
5163 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5165 EVT SrcVT = N0.getValueType();
5166 if (SrcVT == MVT::i64) {
5167 // We only handle SSE2 f64 target here; caller can expand the rest.
5168 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
5171 return LowerUINT_TO_FP_i64(Op, DAG);
5172 } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
5173 return LowerUINT_TO_FP_i32(Op, DAG);
5176 assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
5178 // Make a 64-bit buffer, and use it to build an FILD.
5179 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5180 SDValue WordOff = DAG.getConstant(4, getPointerTy());
5181 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5182 getPointerTy(), StackSlot, WordOff);
5183 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5184 StackSlot, NULL, 0);
5185 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5186 OffsetSlot, NULL, 0);
5187 return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5190 std::pair<SDValue,SDValue> X86TargetLowering::
5191 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) {
5192 DebugLoc dl = Op.getDebugLoc();
5194 EVT DstTy = Op.getValueType();
5197 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5201 assert(DstTy.getSimpleVT() <= MVT::i64 &&
5202 DstTy.getSimpleVT() >= MVT::i16 &&
5203 "Unknown FP_TO_SINT to lower!");
5205 // These are really Legal.
5206 if (DstTy == MVT::i32 &&
5207 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5208 return std::make_pair(SDValue(), SDValue());
5209 if (Subtarget->is64Bit() &&
5210 DstTy == MVT::i64 &&
5211 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5212 return std::make_pair(SDValue(), SDValue());
5214 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5216 MachineFunction &MF = DAG.getMachineFunction();
5217 unsigned MemSize = DstTy.getSizeInBits()/8;
5218 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
5219 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5222 switch (DstTy.getSimpleVT().SimpleTy) {
5223 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5224 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5225 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5226 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5229 SDValue Chain = DAG.getEntryNode();
5230 SDValue Value = Op.getOperand(0);
5231 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5232 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5233 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5234 PseudoSourceValue::getFixedStack(SSFI), 0);
5235 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5237 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5239 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5240 Chain = Value.getValue(1);
5241 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize);
5242 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5245 // Build the FP_TO_INT*_IN_MEM
5246 SDValue Ops[] = { Chain, Value, StackSlot };
5247 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5249 return std::make_pair(FIST, StackSlot);
5252 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
5253 if (Op.getValueType().isVector()) {
5254 if (Op.getValueType() == MVT::v2i32 &&
5255 Op.getOperand(0).getValueType() == MVT::v2f64) {
5261 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5262 SDValue FIST = Vals.first, StackSlot = Vals.second;
5263 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5264 if (FIST.getNode() == 0) return Op;
5267 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5268 FIST, StackSlot, NULL, 0);
5271 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG) {
5272 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5273 SDValue FIST = Vals.first, StackSlot = Vals.second;
5274 assert(FIST.getNode() && "Unexpected failure");
5277 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5278 FIST, StackSlot, NULL, 0);
5281 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
5282 LLVMContext *Context = DAG.getContext();
5283 DebugLoc dl = Op.getDebugLoc();
5284 EVT VT = Op.getValueType();
5287 EltVT = VT.getVectorElementType();
5288 std::vector<Constant*> CV;
5289 if (EltVT == MVT::f64) {
5290 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5294 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5300 Constant *C = ConstantVector::get(CV);
5301 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5302 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5303 PseudoSourceValue::getConstantPool(), 0,
5305 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5308 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
5309 LLVMContext *Context = DAG.getContext();
5310 DebugLoc dl = Op.getDebugLoc();
5311 EVT VT = Op.getValueType();
5314 EltVT = VT.getVectorElementType();
5315 std::vector<Constant*> CV;
5316 if (EltVT == MVT::f64) {
5317 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5321 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5327 Constant *C = ConstantVector::get(CV);
5328 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5329 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5330 PseudoSourceValue::getConstantPool(), 0,
5332 if (VT.isVector()) {
5333 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5334 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5335 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5337 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5339 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5343 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5344 LLVMContext *Context = DAG.getContext();
5345 SDValue Op0 = Op.getOperand(0);
5346 SDValue Op1 = Op.getOperand(1);
5347 DebugLoc dl = Op.getDebugLoc();
5348 EVT VT = Op.getValueType();
5349 EVT SrcVT = Op1.getValueType();
5351 // If second operand is smaller, extend it first.
5352 if (SrcVT.bitsLT(VT)) {
5353 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5356 // And if it is bigger, shrink it first.
5357 if (SrcVT.bitsGT(VT)) {
5358 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5362 // At this point the operands and the result should have the same
5363 // type, and that won't be f80 since that is not custom lowered.
5365 // First get the sign bit of second operand.
5366 std::vector<Constant*> CV;
5367 if (SrcVT == MVT::f64) {
5368 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
5369 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5371 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
5372 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5373 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5374 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5376 Constant *C = ConstantVector::get(CV);
5377 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5378 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5379 PseudoSourceValue::getConstantPool(), 0,
5381 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5383 // Shift sign bit right or left if the two operands have different types.
5384 if (SrcVT.bitsGT(VT)) {
5385 // Op0 is MVT::f32, Op1 is MVT::f64.
5386 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5387 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5388 DAG.getConstant(32, MVT::i32));
5389 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5390 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5391 DAG.getIntPtrConstant(0));
5394 // Clear first operand sign bit.
5396 if (VT == MVT::f64) {
5397 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
5398 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5400 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
5401 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5402 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5403 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5405 C = ConstantVector::get(CV);
5406 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5407 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5408 PseudoSourceValue::getConstantPool(), 0,
5410 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5412 // Or the value with the sign bit.
5413 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5416 /// Emit nodes that will be selected as "test Op0,Op0", or something
5418 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5419 SelectionDAG &DAG) {
5420 DebugLoc dl = Op.getDebugLoc();
5422 // CF and OF aren't always set the way we want. Determine which
5423 // of these we need.
5424 bool NeedCF = false;
5425 bool NeedOF = false;
5427 case X86::COND_A: case X86::COND_AE:
5428 case X86::COND_B: case X86::COND_BE:
5431 case X86::COND_G: case X86::COND_GE:
5432 case X86::COND_L: case X86::COND_LE:
5433 case X86::COND_O: case X86::COND_NO:
5439 // See if we can use the EFLAGS value from the operand instead of
5440 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5441 // we prove that the arithmetic won't overflow, we can't use OF or CF.
5442 if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5443 unsigned Opcode = 0;
5444 unsigned NumOperands = 0;
5445 switch (Op.getNode()->getOpcode()) {
5447 // Due to an isel shortcoming, be conservative if this add is likely to
5448 // be selected as part of a load-modify-store instruction. When the root
5449 // node in a match is a store, isel doesn't know how to remap non-chain
5450 // non-flag uses of other nodes in the match, such as the ADD in this
5451 // case. This leads to the ADD being left around and reselected, with
5452 // the result being two adds in the output.
5453 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5454 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5455 if (UI->getOpcode() == ISD::STORE)
5457 if (ConstantSDNode *C =
5458 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5459 // An add of one will be selected as an INC.
5460 if (C->getAPIntValue() == 1) {
5461 Opcode = X86ISD::INC;
5465 // An add of negative one (subtract of one) will be selected as a DEC.
5466 if (C->getAPIntValue().isAllOnesValue()) {
5467 Opcode = X86ISD::DEC;
5472 // Otherwise use a regular EFLAGS-setting add.
5473 Opcode = X86ISD::ADD;
5477 // If the primary and result isn't used, don't bother using X86ISD::AND,
5478 // because a TEST instruction will be better.
5479 bool NonFlagUse = false;
5480 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5481 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5482 if (UI->getOpcode() != ISD::BRCOND &&
5483 UI->getOpcode() != ISD::SELECT &&
5484 UI->getOpcode() != ISD::SETCC) {
5495 // Due to the ISEL shortcoming noted above, be conservative if this op is
5496 // likely to be selected as part of a load-modify-store instruction.
5497 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5498 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5499 if (UI->getOpcode() == ISD::STORE)
5501 // Otherwise use a regular EFLAGS-setting instruction.
5502 switch (Op.getNode()->getOpcode()) {
5503 case ISD::SUB: Opcode = X86ISD::SUB; break;
5504 case ISD::OR: Opcode = X86ISD::OR; break;
5505 case ISD::XOR: Opcode = X86ISD::XOR; break;
5506 case ISD::AND: Opcode = X86ISD::AND; break;
5507 default: llvm_unreachable("unexpected operator!");
5518 return SDValue(Op.getNode(), 1);
5524 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
5525 SmallVector<SDValue, 4> Ops;
5526 for (unsigned i = 0; i != NumOperands; ++i)
5527 Ops.push_back(Op.getOperand(i));
5528 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
5529 DAG.ReplaceAllUsesWith(Op, New);
5530 return SDValue(New.getNode(), 1);
5534 // Otherwise just emit a CMP with 0, which is the TEST pattern.
5535 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5536 DAG.getConstant(0, Op.getValueType()));
5539 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
5541 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5542 SelectionDAG &DAG) {
5543 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5544 if (C->getAPIntValue() == 0)
5545 return EmitTest(Op0, X86CC, DAG);
5547 DebugLoc dl = Op0.getDebugLoc();
5548 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5551 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5552 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5553 SDValue Op0 = Op.getOperand(0);
5554 SDValue Op1 = Op.getOperand(1);
5555 DebugLoc dl = Op.getDebugLoc();
5556 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5558 // Lower (X & (1 << N)) == 0 to BT(X, N).
5559 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5560 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5561 if (Op0.getOpcode() == ISD::AND &&
5563 Op1.getOpcode() == ISD::Constant &&
5564 cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5565 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5567 if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
5568 if (ConstantSDNode *Op010C =
5569 dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
5570 if (Op010C->getZExtValue() == 1) {
5571 LHS = Op0.getOperand(0);
5572 RHS = Op0.getOperand(1).getOperand(1);
5574 } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
5575 if (ConstantSDNode *Op000C =
5576 dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
5577 if (Op000C->getZExtValue() == 1) {
5578 LHS = Op0.getOperand(1);
5579 RHS = Op0.getOperand(0).getOperand(1);
5581 } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
5582 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5583 SDValue AndLHS = Op0.getOperand(0);
5584 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5585 LHS = AndLHS.getOperand(0);
5586 RHS = AndLHS.getOperand(1);
5590 if (LHS.getNode()) {
5591 // If LHS is i8, promote it to i16 with any_extend. There is no i8 BT
5592 // instruction. Since the shift amount is in-range-or-undefined, we know
5593 // that doing a bittest on the i16 value is ok. We extend to i32 because
5594 // the encoding for the i16 version is larger than the i32 version.
5595 if (LHS.getValueType() == MVT::i8)
5596 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5598 // If the operand types disagree, extend the shift amount to match. Since
5599 // BT ignores high bits (like shifts) we can use anyextend.
5600 if (LHS.getValueType() != RHS.getValueType())
5601 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5603 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5604 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5605 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5606 DAG.getConstant(Cond, MVT::i8), BT);
5610 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5611 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5612 if (X86CC == X86::COND_INVALID)
5615 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
5616 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5617 DAG.getConstant(X86CC, MVT::i8), Cond);
5620 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5622 SDValue Op0 = Op.getOperand(0);
5623 SDValue Op1 = Op.getOperand(1);
5624 SDValue CC = Op.getOperand(2);
5625 EVT VT = Op.getValueType();
5626 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5627 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5628 DebugLoc dl = Op.getDebugLoc();
5632 EVT VT0 = Op0.getValueType();
5633 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5634 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5637 switch (SetCCOpcode) {
5640 case ISD::SETEQ: SSECC = 0; break;
5642 case ISD::SETGT: Swap = true; // Fallthrough
5644 case ISD::SETOLT: SSECC = 1; break;
5646 case ISD::SETGE: Swap = true; // Fallthrough
5648 case ISD::SETOLE: SSECC = 2; break;
5649 case ISD::SETUO: SSECC = 3; break;
5651 case ISD::SETNE: SSECC = 4; break;
5652 case ISD::SETULE: Swap = true;
5653 case ISD::SETUGE: SSECC = 5; break;
5654 case ISD::SETULT: Swap = true;
5655 case ISD::SETUGT: SSECC = 6; break;
5656 case ISD::SETO: SSECC = 7; break;
5659 std::swap(Op0, Op1);
5661 // In the two special cases we can't handle, emit two comparisons.
5663 if (SetCCOpcode == ISD::SETUEQ) {
5665 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5666 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5667 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
5669 else if (SetCCOpcode == ISD::SETONE) {
5671 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5672 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5673 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
5675 llvm_unreachable("Illegal FP comparison");
5677 // Handle all other FP comparisons here.
5678 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5681 // We are handling one of the integer comparisons here. Since SSE only has
5682 // GT and EQ comparisons for integer, swapping operands and multiple
5683 // operations may be required for some comparisons.
5684 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5685 bool Swap = false, Invert = false, FlipSigns = false;
5687 switch (VT.getSimpleVT().SimpleTy) {
5690 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5692 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5694 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5695 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5698 switch (SetCCOpcode) {
5700 case ISD::SETNE: Invert = true;
5701 case ISD::SETEQ: Opc = EQOpc; break;
5702 case ISD::SETLT: Swap = true;
5703 case ISD::SETGT: Opc = GTOpc; break;
5704 case ISD::SETGE: Swap = true;
5705 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
5706 case ISD::SETULT: Swap = true;
5707 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5708 case ISD::SETUGE: Swap = true;
5709 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5712 std::swap(Op0, Op1);
5714 // Since SSE has no unsigned integer comparisons, we need to flip the sign
5715 // bits of the inputs before performing those operations.
5717 EVT EltVT = VT.getVectorElementType();
5718 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
5720 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5721 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
5723 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
5724 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
5727 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
5729 // If the logical-not of the result is required, perform that now.
5731 Result = DAG.getNOT(dl, Result, VT);
5736 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5737 static bool isX86LogicalCmp(SDValue Op) {
5738 unsigned Opc = Op.getNode()->getOpcode();
5739 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
5741 if (Op.getResNo() == 1 &&
5742 (Opc == X86ISD::ADD ||
5743 Opc == X86ISD::SUB ||
5744 Opc == X86ISD::SMUL ||
5745 Opc == X86ISD::UMUL ||
5746 Opc == X86ISD::INC ||
5747 Opc == X86ISD::DEC ||
5748 Opc == X86ISD::OR ||
5749 Opc == X86ISD::XOR ||
5750 Opc == X86ISD::AND))
5756 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5757 bool addTest = true;
5758 SDValue Cond = Op.getOperand(0);
5759 DebugLoc dl = Op.getDebugLoc();
5762 if (Cond.getOpcode() == ISD::SETCC) {
5763 SDValue NewCond = LowerSETCC(Cond, DAG);
5764 if (NewCond.getNode())
5768 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5769 // setting operand in place of the X86ISD::SETCC.
5770 if (Cond.getOpcode() == X86ISD::SETCC) {
5771 CC = Cond.getOperand(0);
5773 SDValue Cmp = Cond.getOperand(1);
5774 unsigned Opc = Cmp.getOpcode();
5775 EVT VT = Op.getValueType();
5777 bool IllegalFPCMov = false;
5778 if (VT.isFloatingPoint() && !VT.isVector() &&
5779 !isScalarFPTypeInSSEReg(VT)) // FPStack?
5780 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
5782 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
5783 Opc == X86ISD::BT) { // FIXME
5790 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5791 Cond = EmitTest(Cond, X86::COND_NE, DAG);
5794 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
5795 SmallVector<SDValue, 4> Ops;
5796 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
5797 // condition is true.
5798 Ops.push_back(Op.getOperand(2));
5799 Ops.push_back(Op.getOperand(1));
5801 Ops.push_back(Cond);
5802 return DAG.getNode(X86ISD::CMOV, dl, VTs, &Ops[0], Ops.size());
5805 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
5806 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
5807 // from the AND / OR.
5808 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
5809 Opc = Op.getOpcode();
5810 if (Opc != ISD::OR && Opc != ISD::AND)
5812 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5813 Op.getOperand(0).hasOneUse() &&
5814 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
5815 Op.getOperand(1).hasOneUse());
5818 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
5819 // 1 and that the SETCC node has a single use.
5820 static bool isXor1OfSetCC(SDValue Op) {
5821 if (Op.getOpcode() != ISD::XOR)
5823 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5824 if (N1C && N1C->getAPIntValue() == 1) {
5825 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5826 Op.getOperand(0).hasOneUse();
5831 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
5832 bool addTest = true;
5833 SDValue Chain = Op.getOperand(0);
5834 SDValue Cond = Op.getOperand(1);
5835 SDValue Dest = Op.getOperand(2);
5836 DebugLoc dl = Op.getDebugLoc();
5839 if (Cond.getOpcode() == ISD::SETCC) {
5840 SDValue NewCond = LowerSETCC(Cond, DAG);
5841 if (NewCond.getNode())
5845 // FIXME: LowerXALUO doesn't handle these!!
5846 else if (Cond.getOpcode() == X86ISD::ADD ||
5847 Cond.getOpcode() == X86ISD::SUB ||
5848 Cond.getOpcode() == X86ISD::SMUL ||
5849 Cond.getOpcode() == X86ISD::UMUL)
5850 Cond = LowerXALUO(Cond, DAG);
5853 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5854 // setting operand in place of the X86ISD::SETCC.
5855 if (Cond.getOpcode() == X86ISD::SETCC) {
5856 CC = Cond.getOperand(0);
5858 SDValue Cmp = Cond.getOperand(1);
5859 unsigned Opc = Cmp.getOpcode();
5860 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
5861 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
5865 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
5869 // These can only come from an arithmetic instruction with overflow,
5870 // e.g. SADDO, UADDO.
5871 Cond = Cond.getNode()->getOperand(1);
5878 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
5879 SDValue Cmp = Cond.getOperand(0).getOperand(1);
5880 if (CondOpc == ISD::OR) {
5881 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
5882 // two branches instead of an explicit OR instruction with a
5884 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5885 isX86LogicalCmp(Cmp)) {
5886 CC = Cond.getOperand(0).getOperand(0);
5887 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5888 Chain, Dest, CC, Cmp);
5889 CC = Cond.getOperand(1).getOperand(0);
5893 } else { // ISD::AND
5894 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
5895 // two branches instead of an explicit AND instruction with a
5896 // separate test. However, we only do this if this block doesn't
5897 // have a fall-through edge, because this requires an explicit
5898 // jmp when the condition is false.
5899 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5900 isX86LogicalCmp(Cmp) &&
5901 Op.getNode()->hasOneUse()) {
5902 X86::CondCode CCode =
5903 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5904 CCode = X86::GetOppositeBranchCondition(CCode);
5905 CC = DAG.getConstant(CCode, MVT::i8);
5906 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
5907 // Look for an unconditional branch following this conditional branch.
5908 // We need this because we need to reverse the successors in order
5909 // to implement FCMP_OEQ.
5910 if (User.getOpcode() == ISD::BR) {
5911 SDValue FalseBB = User.getOperand(1);
5913 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
5914 assert(NewBR == User);
5917 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5918 Chain, Dest, CC, Cmp);
5919 X86::CondCode CCode =
5920 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
5921 CCode = X86::GetOppositeBranchCondition(CCode);
5922 CC = DAG.getConstant(CCode, MVT::i8);
5928 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
5929 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
5930 // It should be transformed during dag combiner except when the condition
5931 // is set by a arithmetics with overflow node.
5932 X86::CondCode CCode =
5933 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5934 CCode = X86::GetOppositeBranchCondition(CCode);
5935 CC = DAG.getConstant(CCode, MVT::i8);
5936 Cond = Cond.getOperand(0).getOperand(1);
5942 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5943 Cond = EmitTest(Cond, X86::COND_NE, DAG);
5945 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5946 Chain, Dest, CC, Cond);
5950 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
5951 // Calls to _alloca is needed to probe the stack when allocating more than 4k
5952 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
5953 // that the guard pages used by the OS virtual memory manager are allocated in
5954 // correct sequence.
5956 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5957 SelectionDAG &DAG) {
5958 assert(Subtarget->isTargetCygMing() &&
5959 "This should be used only on Cygwin/Mingw targets");
5960 DebugLoc dl = Op.getDebugLoc();
5963 SDValue Chain = Op.getOperand(0);
5964 SDValue Size = Op.getOperand(1);
5965 // FIXME: Ensure alignment here
5969 EVT IntPtr = getPointerTy();
5970 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
5972 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
5974 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
5975 Flag = Chain.getValue(1);
5977 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5978 SDValue Ops[] = { Chain,
5979 DAG.getTargetExternalSymbol("_alloca", IntPtr),
5980 DAG.getRegister(X86::EAX, IntPtr),
5981 DAG.getRegister(X86StackPtr, SPTy),
5983 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops, 5);
5984 Flag = Chain.getValue(1);
5986 Chain = DAG.getCALLSEQ_END(Chain,
5987 DAG.getIntPtrConstant(0, true),
5988 DAG.getIntPtrConstant(0, true),
5991 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
5993 SDValue Ops1[2] = { Chain.getValue(0), Chain };
5994 return DAG.getMergeValues(Ops1, 2, dl);
5998 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
6000 SDValue Dst, SDValue Src,
6001 SDValue Size, unsigned Align,
6003 uint64_t DstSVOff) {
6004 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6006 // If not DWORD aligned or size is more than the threshold, call the library.
6007 // The libc version is likely to be faster for these cases. It can use the
6008 // address value and run time information about the CPU.
6009 if ((Align & 3) != 0 ||
6011 ConstantSize->getZExtValue() >
6012 getSubtarget()->getMaxInlineSizeThreshold()) {
6013 SDValue InFlag(0, 0);
6015 // Check to see if there is a specialized entry-point for memory zeroing.
6016 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
6018 if (const char *bzeroEntry = V &&
6019 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
6020 EVT IntPtr = getPointerTy();
6021 const Type *IntPtrTy = TD->getIntPtrType(*DAG.getContext());
6022 TargetLowering::ArgListTy Args;
6023 TargetLowering::ArgListEntry Entry;
6025 Entry.Ty = IntPtrTy;
6026 Args.push_back(Entry);
6028 Args.push_back(Entry);
6029 std::pair<SDValue,SDValue> CallResult =
6030 LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()),
6031 false, false, false, false,
6032 0, CallingConv::C, false, /*isReturnValueUsed=*/false,
6033 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl);
6034 return CallResult.second;
6037 // Otherwise have the target-independent code call memset.
6041 uint64_t SizeVal = ConstantSize->getZExtValue();
6042 SDValue InFlag(0, 0);
6045 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
6046 unsigned BytesLeft = 0;
6047 bool TwoRepStos = false;
6050 uint64_t Val = ValC->getZExtValue() & 255;
6052 // If the value is a constant, then we can potentially use larger sets.
6053 switch (Align & 3) {
6054 case 2: // WORD aligned
6057 Val = (Val << 8) | Val;
6059 case 0: // DWORD aligned
6062 Val = (Val << 8) | Val;
6063 Val = (Val << 16) | Val;
6064 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
6067 Val = (Val << 32) | Val;
6070 default: // Byte aligned
6073 Count = DAG.getIntPtrConstant(SizeVal);
6077 if (AVT.bitsGT(MVT::i8)) {
6078 unsigned UBytes = AVT.getSizeInBits() / 8;
6079 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
6080 BytesLeft = SizeVal % UBytes;
6083 Chain = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
6085 InFlag = Chain.getValue(1);
6088 Count = DAG.getIntPtrConstant(SizeVal);
6089 Chain = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
6090 InFlag = Chain.getValue(1);
6093 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6096 InFlag = Chain.getValue(1);
6097 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6100 InFlag = Chain.getValue(1);
6102 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6103 SmallVector<SDValue, 8> Ops;
6104 Ops.push_back(Chain);
6105 Ops.push_back(DAG.getValueType(AVT));
6106 Ops.push_back(InFlag);
6107 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
6110 InFlag = Chain.getValue(1);
6112 EVT CVT = Count.getValueType();
6113 SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
6114 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
6115 Chain = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
6118 InFlag = Chain.getValue(1);
6119 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6121 Ops.push_back(Chain);
6122 Ops.push_back(DAG.getValueType(MVT::i8));
6123 Ops.push_back(InFlag);
6124 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
6125 } else if (BytesLeft) {
6126 // Handle the last 1 - 7 bytes.
6127 unsigned Offset = SizeVal - BytesLeft;
6128 EVT AddrVT = Dst.getValueType();
6129 EVT SizeVT = Size.getValueType();
6131 Chain = DAG.getMemset(Chain, dl,
6132 DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
6133 DAG.getConstant(Offset, AddrVT)),
6135 DAG.getConstant(BytesLeft, SizeVT),
6136 Align, DstSV, DstSVOff + Offset);
6139 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
6144 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
6145 SDValue Chain, SDValue Dst, SDValue Src,
6146 SDValue Size, unsigned Align,
6148 const Value *DstSV, uint64_t DstSVOff,
6149 const Value *SrcSV, uint64_t SrcSVOff) {
6150 // This requires the copy size to be a constant, preferrably
6151 // within a subtarget-specific limit.
6152 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6155 uint64_t SizeVal = ConstantSize->getZExtValue();
6156 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
6159 /// If not DWORD aligned, call the library.
6160 if ((Align & 3) != 0)
6165 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
6168 unsigned UBytes = AVT.getSizeInBits() / 8;
6169 unsigned CountVal = SizeVal / UBytes;
6170 SDValue Count = DAG.getIntPtrConstant(CountVal);
6171 unsigned BytesLeft = SizeVal % UBytes;
6173 SDValue InFlag(0, 0);
6174 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6177 InFlag = Chain.getValue(1);
6178 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6181 InFlag = Chain.getValue(1);
6182 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
6185 InFlag = Chain.getValue(1);
6187 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6188 SmallVector<SDValue, 8> Ops;
6189 Ops.push_back(Chain);
6190 Ops.push_back(DAG.getValueType(AVT));
6191 Ops.push_back(InFlag);
6192 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, &Ops[0], Ops.size());
6194 SmallVector<SDValue, 4> Results;
6195 Results.push_back(RepMovs);
6197 // Handle the last 1 - 7 bytes.
6198 unsigned Offset = SizeVal - BytesLeft;
6199 EVT DstVT = Dst.getValueType();
6200 EVT SrcVT = Src.getValueType();
6201 EVT SizeVT = Size.getValueType();
6202 Results.push_back(DAG.getMemcpy(Chain, dl,
6203 DAG.getNode(ISD::ADD, dl, DstVT, Dst,
6204 DAG.getConstant(Offset, DstVT)),
6205 DAG.getNode(ISD::ADD, dl, SrcVT, Src,
6206 DAG.getConstant(Offset, SrcVT)),
6207 DAG.getConstant(BytesLeft, SizeVT),
6208 Align, AlwaysInline,
6209 DstSV, DstSVOff + Offset,
6210 SrcSV, SrcSVOff + Offset));
6213 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6214 &Results[0], Results.size());
6217 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
6218 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6219 DebugLoc dl = Op.getDebugLoc();
6221 if (!Subtarget->is64Bit()) {
6222 // vastart just stores the address of the VarArgsFrameIndex slot into the
6223 // memory location argument.
6224 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6225 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
6229 // gp_offset (0 - 6 * 8)
6230 // fp_offset (48 - 48 + 8 * 16)
6231 // overflow_arg_area (point to parameters coming in memory).
6233 SmallVector<SDValue, 8> MemOps;
6234 SDValue FIN = Op.getOperand(1);
6236 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6237 DAG.getConstant(VarArgsGPOffset, MVT::i32),
6239 MemOps.push_back(Store);
6242 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6243 FIN, DAG.getIntPtrConstant(4));
6244 Store = DAG.getStore(Op.getOperand(0), dl,
6245 DAG.getConstant(VarArgsFPOffset, MVT::i32),
6247 MemOps.push_back(Store);
6249 // Store ptr to overflow_arg_area
6250 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6251 FIN, DAG.getIntPtrConstant(4));
6252 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6253 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0);
6254 MemOps.push_back(Store);
6256 // Store ptr to reg_save_area.
6257 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6258 FIN, DAG.getIntPtrConstant(8));
6259 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
6260 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0);
6261 MemOps.push_back(Store);
6262 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6263 &MemOps[0], MemOps.size());
6266 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
6267 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6268 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6269 SDValue Chain = Op.getOperand(0);
6270 SDValue SrcPtr = Op.getOperand(1);
6271 SDValue SrcSV = Op.getOperand(2);
6273 llvm_report_error("VAArgInst is not yet implemented for x86-64!");
6277 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
6278 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6279 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6280 SDValue Chain = Op.getOperand(0);
6281 SDValue DstPtr = Op.getOperand(1);
6282 SDValue SrcPtr = Op.getOperand(2);
6283 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6284 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6285 DebugLoc dl = Op.getDebugLoc();
6287 return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6288 DAG.getIntPtrConstant(24), 8, false,
6289 DstSV, 0, SrcSV, 0);
6293 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
6294 DebugLoc dl = Op.getDebugLoc();
6295 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6297 default: return SDValue(); // Don't custom lower most intrinsics.
6298 // Comparison intrinsics.
6299 case Intrinsic::x86_sse_comieq_ss:
6300 case Intrinsic::x86_sse_comilt_ss:
6301 case Intrinsic::x86_sse_comile_ss:
6302 case Intrinsic::x86_sse_comigt_ss:
6303 case Intrinsic::x86_sse_comige_ss:
6304 case Intrinsic::x86_sse_comineq_ss:
6305 case Intrinsic::x86_sse_ucomieq_ss:
6306 case Intrinsic::x86_sse_ucomilt_ss:
6307 case Intrinsic::x86_sse_ucomile_ss:
6308 case Intrinsic::x86_sse_ucomigt_ss:
6309 case Intrinsic::x86_sse_ucomige_ss:
6310 case Intrinsic::x86_sse_ucomineq_ss:
6311 case Intrinsic::x86_sse2_comieq_sd:
6312 case Intrinsic::x86_sse2_comilt_sd:
6313 case Intrinsic::x86_sse2_comile_sd:
6314 case Intrinsic::x86_sse2_comigt_sd:
6315 case Intrinsic::x86_sse2_comige_sd:
6316 case Intrinsic::x86_sse2_comineq_sd:
6317 case Intrinsic::x86_sse2_ucomieq_sd:
6318 case Intrinsic::x86_sse2_ucomilt_sd:
6319 case Intrinsic::x86_sse2_ucomile_sd:
6320 case Intrinsic::x86_sse2_ucomigt_sd:
6321 case Intrinsic::x86_sse2_ucomige_sd:
6322 case Intrinsic::x86_sse2_ucomineq_sd: {
6324 ISD::CondCode CC = ISD::SETCC_INVALID;
6327 case Intrinsic::x86_sse_comieq_ss:
6328 case Intrinsic::x86_sse2_comieq_sd:
6332 case Intrinsic::x86_sse_comilt_ss:
6333 case Intrinsic::x86_sse2_comilt_sd:
6337 case Intrinsic::x86_sse_comile_ss:
6338 case Intrinsic::x86_sse2_comile_sd:
6342 case Intrinsic::x86_sse_comigt_ss:
6343 case Intrinsic::x86_sse2_comigt_sd:
6347 case Intrinsic::x86_sse_comige_ss:
6348 case Intrinsic::x86_sse2_comige_sd:
6352 case Intrinsic::x86_sse_comineq_ss:
6353 case Intrinsic::x86_sse2_comineq_sd:
6357 case Intrinsic::x86_sse_ucomieq_ss:
6358 case Intrinsic::x86_sse2_ucomieq_sd:
6359 Opc = X86ISD::UCOMI;
6362 case Intrinsic::x86_sse_ucomilt_ss:
6363 case Intrinsic::x86_sse2_ucomilt_sd:
6364 Opc = X86ISD::UCOMI;
6367 case Intrinsic::x86_sse_ucomile_ss:
6368 case Intrinsic::x86_sse2_ucomile_sd:
6369 Opc = X86ISD::UCOMI;
6372 case Intrinsic::x86_sse_ucomigt_ss:
6373 case Intrinsic::x86_sse2_ucomigt_sd:
6374 Opc = X86ISD::UCOMI;
6377 case Intrinsic::x86_sse_ucomige_ss:
6378 case Intrinsic::x86_sse2_ucomige_sd:
6379 Opc = X86ISD::UCOMI;
6382 case Intrinsic::x86_sse_ucomineq_ss:
6383 case Intrinsic::x86_sse2_ucomineq_sd:
6384 Opc = X86ISD::UCOMI;
6389 SDValue LHS = Op.getOperand(1);
6390 SDValue RHS = Op.getOperand(2);
6391 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6392 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
6393 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6394 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6395 DAG.getConstant(X86CC, MVT::i8), Cond);
6396 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6398 // ptest intrinsics. The intrinsic these come from are designed to return
6399 // an integer value, not just an instruction so lower it to the ptest
6400 // pattern and a setcc for the result.
6401 case Intrinsic::x86_sse41_ptestz:
6402 case Intrinsic::x86_sse41_ptestc:
6403 case Intrinsic::x86_sse41_ptestnzc:{
6406 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
6407 case Intrinsic::x86_sse41_ptestz:
6409 X86CC = X86::COND_E;
6411 case Intrinsic::x86_sse41_ptestc:
6413 X86CC = X86::COND_B;
6415 case Intrinsic::x86_sse41_ptestnzc:
6417 X86CC = X86::COND_A;
6421 SDValue LHS = Op.getOperand(1);
6422 SDValue RHS = Op.getOperand(2);
6423 SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
6424 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
6425 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
6426 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6429 // Fix vector shift instructions where the last operand is a non-immediate
6431 case Intrinsic::x86_sse2_pslli_w:
6432 case Intrinsic::x86_sse2_pslli_d:
6433 case Intrinsic::x86_sse2_pslli_q:
6434 case Intrinsic::x86_sse2_psrli_w:
6435 case Intrinsic::x86_sse2_psrli_d:
6436 case Intrinsic::x86_sse2_psrli_q:
6437 case Intrinsic::x86_sse2_psrai_w:
6438 case Intrinsic::x86_sse2_psrai_d:
6439 case Intrinsic::x86_mmx_pslli_w:
6440 case Intrinsic::x86_mmx_pslli_d:
6441 case Intrinsic::x86_mmx_pslli_q:
6442 case Intrinsic::x86_mmx_psrli_w:
6443 case Intrinsic::x86_mmx_psrli_d:
6444 case Intrinsic::x86_mmx_psrli_q:
6445 case Intrinsic::x86_mmx_psrai_w:
6446 case Intrinsic::x86_mmx_psrai_d: {
6447 SDValue ShAmt = Op.getOperand(2);
6448 if (isa<ConstantSDNode>(ShAmt))
6451 unsigned NewIntNo = 0;
6452 EVT ShAmtVT = MVT::v4i32;
6454 case Intrinsic::x86_sse2_pslli_w:
6455 NewIntNo = Intrinsic::x86_sse2_psll_w;
6457 case Intrinsic::x86_sse2_pslli_d:
6458 NewIntNo = Intrinsic::x86_sse2_psll_d;
6460 case Intrinsic::x86_sse2_pslli_q:
6461 NewIntNo = Intrinsic::x86_sse2_psll_q;
6463 case Intrinsic::x86_sse2_psrli_w:
6464 NewIntNo = Intrinsic::x86_sse2_psrl_w;
6466 case Intrinsic::x86_sse2_psrli_d:
6467 NewIntNo = Intrinsic::x86_sse2_psrl_d;
6469 case Intrinsic::x86_sse2_psrli_q:
6470 NewIntNo = Intrinsic::x86_sse2_psrl_q;
6472 case Intrinsic::x86_sse2_psrai_w:
6473 NewIntNo = Intrinsic::x86_sse2_psra_w;
6475 case Intrinsic::x86_sse2_psrai_d:
6476 NewIntNo = Intrinsic::x86_sse2_psra_d;
6479 ShAmtVT = MVT::v2i32;
6481 case Intrinsic::x86_mmx_pslli_w:
6482 NewIntNo = Intrinsic::x86_mmx_psll_w;
6484 case Intrinsic::x86_mmx_pslli_d:
6485 NewIntNo = Intrinsic::x86_mmx_psll_d;
6487 case Intrinsic::x86_mmx_pslli_q:
6488 NewIntNo = Intrinsic::x86_mmx_psll_q;
6490 case Intrinsic::x86_mmx_psrli_w:
6491 NewIntNo = Intrinsic::x86_mmx_psrl_w;
6493 case Intrinsic::x86_mmx_psrli_d:
6494 NewIntNo = Intrinsic::x86_mmx_psrl_d;
6496 case Intrinsic::x86_mmx_psrli_q:
6497 NewIntNo = Intrinsic::x86_mmx_psrl_q;
6499 case Intrinsic::x86_mmx_psrai_w:
6500 NewIntNo = Intrinsic::x86_mmx_psra_w;
6502 case Intrinsic::x86_mmx_psrai_d:
6503 NewIntNo = Intrinsic::x86_mmx_psra_d;
6505 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
6511 // The vector shift intrinsics with scalars uses 32b shift amounts but
6512 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
6516 ShOps[1] = DAG.getConstant(0, MVT::i32);
6517 if (ShAmtVT == MVT::v4i32) {
6518 ShOps[2] = DAG.getUNDEF(MVT::i32);
6519 ShOps[3] = DAG.getUNDEF(MVT::i32);
6520 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
6522 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
6525 EVT VT = Op.getValueType();
6526 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
6527 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6528 DAG.getConstant(NewIntNo, MVT::i32),
6529 Op.getOperand(1), ShAmt);
6534 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
6535 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6536 DebugLoc dl = Op.getDebugLoc();
6539 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6541 DAG.getConstant(TD->getPointerSize(),
6542 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6543 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6544 DAG.getNode(ISD::ADD, dl, getPointerTy(),
6549 // Just load the return address.
6550 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6551 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6552 RetAddrFI, NULL, 0);
6555 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
6556 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6557 MFI->setFrameAddressIsTaken(true);
6558 EVT VT = Op.getValueType();
6559 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
6560 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6561 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6562 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6564 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
6568 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6569 SelectionDAG &DAG) {
6570 return DAG.getIntPtrConstant(2*TD->getPointerSize());
6573 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
6575 MachineFunction &MF = DAG.getMachineFunction();
6576 SDValue Chain = Op.getOperand(0);
6577 SDValue Offset = Op.getOperand(1);
6578 SDValue Handler = Op.getOperand(2);
6579 DebugLoc dl = Op.getDebugLoc();
6581 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6583 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6585 SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
6586 DAG.getIntPtrConstant(-TD->getPointerSize()));
6587 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
6588 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0);
6589 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
6590 MF.getRegInfo().addLiveOut(StoreAddrReg);
6592 return DAG.getNode(X86ISD::EH_RETURN, dl,
6594 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6597 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6598 SelectionDAG &DAG) {
6599 SDValue Root = Op.getOperand(0);
6600 SDValue Trmp = Op.getOperand(1); // trampoline
6601 SDValue FPtr = Op.getOperand(2); // nested function
6602 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6603 DebugLoc dl = Op.getDebugLoc();
6605 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6607 const X86InstrInfo *TII =
6608 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
6610 if (Subtarget->is64Bit()) {
6611 SDValue OutChains[6];
6613 // Large code-model.
6615 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
6616 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
6618 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
6619 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
6621 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
6623 // Load the pointer to the nested function into R11.
6624 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
6625 SDValue Addr = Trmp;
6626 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6629 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6630 DAG.getConstant(2, MVT::i64));
6631 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2, false, 2);
6633 // Load the 'nest' parameter value into R10.
6634 // R10 is specified in X86CallingConv.td
6635 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
6636 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6637 DAG.getConstant(10, MVT::i64));
6638 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6639 Addr, TrmpAddr, 10);
6641 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6642 DAG.getConstant(12, MVT::i64));
6643 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12, false, 2);
6645 // Jump to the nested function.
6646 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
6647 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6648 DAG.getConstant(20, MVT::i64));
6649 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6650 Addr, TrmpAddr, 20);
6652 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
6653 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6654 DAG.getConstant(22, MVT::i64));
6655 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
6659 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
6660 return DAG.getMergeValues(Ops, 2, dl);
6662 const Function *Func =
6663 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
6664 CallingConv::ID CC = Func->getCallingConv();
6669 llvm_unreachable("Unsupported calling convention");
6670 case CallingConv::C:
6671 case CallingConv::X86_StdCall: {
6672 // Pass 'nest' parameter in ECX.
6673 // Must be kept in sync with X86CallingConv.td
6676 // Check that ECX wasn't needed by an 'inreg' parameter.
6677 const FunctionType *FTy = Func->getFunctionType();
6678 const AttrListPtr &Attrs = Func->getAttributes();
6680 if (!Attrs.isEmpty() && !Func->isVarArg()) {
6681 unsigned InRegCount = 0;
6684 for (FunctionType::param_iterator I = FTy->param_begin(),
6685 E = FTy->param_end(); I != E; ++I, ++Idx)
6686 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6687 // FIXME: should only count parameters that are lowered to integers.
6688 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6690 if (InRegCount > 2) {
6691 llvm_report_error("Nest register in use - reduce number of inreg parameters!");
6696 case CallingConv::X86_FastCall:
6697 case CallingConv::Fast:
6698 // Pass 'nest' parameter in EAX.
6699 // Must be kept in sync with X86CallingConv.td
6704 SDValue OutChains[4];
6707 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6708 DAG.getConstant(10, MVT::i32));
6709 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
6711 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
6712 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
6713 OutChains[0] = DAG.getStore(Root, dl,
6714 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
6717 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6718 DAG.getConstant(1, MVT::i32));
6719 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1, false, 1);
6721 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
6722 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6723 DAG.getConstant(5, MVT::i32));
6724 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
6725 TrmpAddr, 5, false, 1);
6727 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6728 DAG.getConstant(6, MVT::i32));
6729 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6, false, 1);
6732 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
6733 return DAG.getMergeValues(Ops, 2, dl);
6737 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
6739 The rounding mode is in bits 11:10 of FPSR, and has the following
6746 FLT_ROUNDS, on the other hand, expects the following:
6753 To perform the conversion, we do:
6754 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
6757 MachineFunction &MF = DAG.getMachineFunction();
6758 const TargetMachine &TM = MF.getTarget();
6759 const TargetFrameInfo &TFI = *TM.getFrameInfo();
6760 unsigned StackAlignment = TFI.getStackAlignment();
6761 EVT VT = Op.getValueType();
6762 DebugLoc dl = Op.getDebugLoc();
6764 // Save FP Control Word to stack slot
6765 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment);
6766 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6768 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
6769 DAG.getEntryNode(), StackSlot);
6771 // Load FP Control Word from stack slot
6772 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0);
6774 // Transform as necessary
6776 DAG.getNode(ISD::SRL, dl, MVT::i16,
6777 DAG.getNode(ISD::AND, dl, MVT::i16,
6778 CWD, DAG.getConstant(0x800, MVT::i16)),
6779 DAG.getConstant(11, MVT::i8));
6781 DAG.getNode(ISD::SRL, dl, MVT::i16,
6782 DAG.getNode(ISD::AND, dl, MVT::i16,
6783 CWD, DAG.getConstant(0x400, MVT::i16)),
6784 DAG.getConstant(9, MVT::i8));
6787 DAG.getNode(ISD::AND, dl, MVT::i16,
6788 DAG.getNode(ISD::ADD, dl, MVT::i16,
6789 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
6790 DAG.getConstant(1, MVT::i16)),
6791 DAG.getConstant(3, MVT::i16));
6794 return DAG.getNode((VT.getSizeInBits() < 16 ?
6795 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6798 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
6799 EVT VT = Op.getValueType();
6801 unsigned NumBits = VT.getSizeInBits();
6802 DebugLoc dl = Op.getDebugLoc();
6804 Op = Op.getOperand(0);
6805 if (VT == MVT::i8) {
6806 // Zero extend to i32 since there is not an i8 bsr.
6808 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6811 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
6812 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6813 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
6815 // If src is zero (i.e. bsr sets ZF), returns NumBits.
6816 SmallVector<SDValue, 4> Ops;
6818 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
6819 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6820 Ops.push_back(Op.getValue(1));
6821 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6823 // Finally xor with NumBits-1.
6824 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
6827 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6831 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
6832 EVT VT = Op.getValueType();
6834 unsigned NumBits = VT.getSizeInBits();
6835 DebugLoc dl = Op.getDebugLoc();
6837 Op = Op.getOperand(0);
6838 if (VT == MVT::i8) {
6840 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6843 // Issue a bsf (scan bits forward) which also sets EFLAGS.
6844 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6845 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
6847 // If src is zero (i.e. bsf sets ZF), returns NumBits.
6848 SmallVector<SDValue, 4> Ops;
6850 Ops.push_back(DAG.getConstant(NumBits, OpVT));
6851 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6852 Ops.push_back(Op.getValue(1));
6853 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6856 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6860 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
6861 EVT VT = Op.getValueType();
6862 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
6863 DebugLoc dl = Op.getDebugLoc();
6865 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
6866 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
6867 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
6868 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
6869 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
6871 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
6872 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
6873 // return AloBlo + AloBhi + AhiBlo;
6875 SDValue A = Op.getOperand(0);
6876 SDValue B = Op.getOperand(1);
6878 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6879 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6880 A, DAG.getConstant(32, MVT::i32));
6881 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6882 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6883 B, DAG.getConstant(32, MVT::i32));
6884 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6885 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6887 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6888 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6890 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6891 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6893 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6894 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6895 AloBhi, DAG.getConstant(32, MVT::i32));
6896 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6897 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6898 AhiBlo, DAG.getConstant(32, MVT::i32));
6899 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
6900 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
6905 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
6906 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
6907 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
6908 // looks for this combo and may remove the "setcc" instruction if the "setcc"
6909 // has only one use.
6910 SDNode *N = Op.getNode();
6911 SDValue LHS = N->getOperand(0);
6912 SDValue RHS = N->getOperand(1);
6913 unsigned BaseOp = 0;
6915 DebugLoc dl = Op.getDebugLoc();
6917 switch (Op.getOpcode()) {
6918 default: llvm_unreachable("Unknown ovf instruction!");
6920 // A subtract of one will be selected as a INC. Note that INC doesn't
6921 // set CF, so we can't do this for UADDO.
6922 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6923 if (C->getAPIntValue() == 1) {
6924 BaseOp = X86ISD::INC;
6928 BaseOp = X86ISD::ADD;
6932 BaseOp = X86ISD::ADD;
6936 // A subtract of one will be selected as a DEC. Note that DEC doesn't
6937 // set CF, so we can't do this for USUBO.
6938 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6939 if (C->getAPIntValue() == 1) {
6940 BaseOp = X86ISD::DEC;
6944 BaseOp = X86ISD::SUB;
6948 BaseOp = X86ISD::SUB;
6952 BaseOp = X86ISD::SMUL;
6956 BaseOp = X86ISD::UMUL;
6961 // Also sets EFLAGS.
6962 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
6963 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
6966 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
6967 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
6969 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
6973 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
6974 EVT T = Op.getValueType();
6975 DebugLoc dl = Op.getDebugLoc();
6978 switch(T.getSimpleVT().SimpleTy) {
6980 assert(false && "Invalid value type!");
6981 case MVT::i8: Reg = X86::AL; size = 1; break;
6982 case MVT::i16: Reg = X86::AX; size = 2; break;
6983 case MVT::i32: Reg = X86::EAX; size = 4; break;
6985 assert(Subtarget->is64Bit() && "Node not type legal!");
6986 Reg = X86::RAX; size = 8;
6989 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
6990 Op.getOperand(2), SDValue());
6991 SDValue Ops[] = { cpIn.getValue(0),
6994 DAG.getTargetConstant(size, MVT::i8),
6996 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6997 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
6999 DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
7003 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
7004 SelectionDAG &DAG) {
7005 assert(Subtarget->is64Bit() && "Result not type legalized?");
7006 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7007 SDValue TheChain = Op.getOperand(0);
7008 DebugLoc dl = Op.getDebugLoc();
7009 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7010 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
7011 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
7013 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
7014 DAG.getConstant(32, MVT::i8));
7016 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
7019 return DAG.getMergeValues(Ops, 2, dl);
7022 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
7023 SDNode *Node = Op.getNode();
7024 DebugLoc dl = Node->getDebugLoc();
7025 EVT T = Node->getValueType(0);
7026 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
7027 DAG.getConstant(0, T), Node->getOperand(2));
7028 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
7029 cast<AtomicSDNode>(Node)->getMemoryVT(),
7030 Node->getOperand(0),
7031 Node->getOperand(1), negOp,
7032 cast<AtomicSDNode>(Node)->getSrcValue(),
7033 cast<AtomicSDNode>(Node)->getAlignment());
7036 /// LowerOperation - Provide custom lowering hooks for some operations.
7038 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
7039 switch (Op.getOpcode()) {
7040 default: llvm_unreachable("Should not custom lower this!");
7041 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
7042 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
7043 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
7044 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7045 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7046 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7047 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
7048 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
7049 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
7050 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7051 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
7052 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
7053 case ISD::SHL_PARTS:
7054 case ISD::SRA_PARTS:
7055 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
7056 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
7057 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
7058 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
7059 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
7060 case ISD::FABS: return LowerFABS(Op, DAG);
7061 case ISD::FNEG: return LowerFNEG(Op, DAG);
7062 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
7063 case ISD::SETCC: return LowerSETCC(Op, DAG);
7064 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
7065 case ISD::SELECT: return LowerSELECT(Op, DAG);
7066 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
7067 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
7068 case ISD::VASTART: return LowerVASTART(Op, DAG);
7069 case ISD::VAARG: return LowerVAARG(Op, DAG);
7070 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
7071 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7072 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
7073 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
7074 case ISD::FRAME_TO_ARGS_OFFSET:
7075 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
7076 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
7077 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
7078 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
7079 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
7080 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
7081 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
7082 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
7088 case ISD::UMULO: return LowerXALUO(Op, DAG);
7089 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
7093 void X86TargetLowering::
7094 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
7095 SelectionDAG &DAG, unsigned NewOp) {
7096 EVT T = Node->getValueType(0);
7097 DebugLoc dl = Node->getDebugLoc();
7098 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
7100 SDValue Chain = Node->getOperand(0);
7101 SDValue In1 = Node->getOperand(1);
7102 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7103 Node->getOperand(2), DAG.getIntPtrConstant(0));
7104 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7105 Node->getOperand(2), DAG.getIntPtrConstant(1));
7106 SDValue Ops[] = { Chain, In1, In2L, In2H };
7107 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7109 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
7110 cast<MemSDNode>(Node)->getMemOperand());
7111 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7112 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7113 Results.push_back(Result.getValue(2));
7116 /// ReplaceNodeResults - Replace a node with an illegal result type
7117 /// with a new node built out of custom code.
7118 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7119 SmallVectorImpl<SDValue>&Results,
7120 SelectionDAG &DAG) {
7121 DebugLoc dl = N->getDebugLoc();
7122 switch (N->getOpcode()) {
7124 assert(false && "Do not know how to custom type legalize this operation!");
7126 case ISD::FP_TO_SINT: {
7127 std::pair<SDValue,SDValue> Vals =
7128 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
7129 SDValue FIST = Vals.first, StackSlot = Vals.second;
7130 if (FIST.getNode() != 0) {
7131 EVT VT = N->getValueType(0);
7132 // Return a load from the stack slot.
7133 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0));
7137 case ISD::READCYCLECOUNTER: {
7138 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7139 SDValue TheChain = N->getOperand(0);
7140 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7141 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7143 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7145 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7146 SDValue Ops[] = { eax, edx };
7147 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7148 Results.push_back(edx.getValue(1));
7151 case ISD::ATOMIC_CMP_SWAP: {
7152 EVT T = N->getValueType(0);
7153 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7154 SDValue cpInL, cpInH;
7155 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7156 DAG.getConstant(0, MVT::i32));
7157 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7158 DAG.getConstant(1, MVT::i32));
7159 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7160 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7162 SDValue swapInL, swapInH;
7163 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7164 DAG.getConstant(0, MVT::i32));
7165 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7166 DAG.getConstant(1, MVT::i32));
7167 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7169 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7170 swapInL.getValue(1));
7171 SDValue Ops[] = { swapInH.getValue(0),
7173 swapInH.getValue(1) };
7174 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7175 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7176 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7177 MVT::i32, Result.getValue(1));
7178 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7179 MVT::i32, cpOutL.getValue(2));
7180 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7181 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7182 Results.push_back(cpOutH.getValue(1));
7185 case ISD::ATOMIC_LOAD_ADD:
7186 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7188 case ISD::ATOMIC_LOAD_AND:
7189 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7191 case ISD::ATOMIC_LOAD_NAND:
7192 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7194 case ISD::ATOMIC_LOAD_OR:
7195 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7197 case ISD::ATOMIC_LOAD_SUB:
7198 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7200 case ISD::ATOMIC_LOAD_XOR:
7201 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7203 case ISD::ATOMIC_SWAP:
7204 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7209 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7211 default: return NULL;
7212 case X86ISD::BSF: return "X86ISD::BSF";
7213 case X86ISD::BSR: return "X86ISD::BSR";
7214 case X86ISD::SHLD: return "X86ISD::SHLD";
7215 case X86ISD::SHRD: return "X86ISD::SHRD";
7216 case X86ISD::FAND: return "X86ISD::FAND";
7217 case X86ISD::FOR: return "X86ISD::FOR";
7218 case X86ISD::FXOR: return "X86ISD::FXOR";
7219 case X86ISD::FSRL: return "X86ISD::FSRL";
7220 case X86ISD::FILD: return "X86ISD::FILD";
7221 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
7222 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7223 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7224 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7225 case X86ISD::FLD: return "X86ISD::FLD";
7226 case X86ISD::FST: return "X86ISD::FST";
7227 case X86ISD::CALL: return "X86ISD::CALL";
7228 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
7229 case X86ISD::BT: return "X86ISD::BT";
7230 case X86ISD::CMP: return "X86ISD::CMP";
7231 case X86ISD::COMI: return "X86ISD::COMI";
7232 case X86ISD::UCOMI: return "X86ISD::UCOMI";
7233 case X86ISD::SETCC: return "X86ISD::SETCC";
7234 case X86ISD::CMOV: return "X86ISD::CMOV";
7235 case X86ISD::BRCOND: return "X86ISD::BRCOND";
7236 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
7237 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
7238 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
7239 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
7240 case X86ISD::Wrapper: return "X86ISD::Wrapper";
7241 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
7242 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
7243 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
7244 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
7245 case X86ISD::PINSRB: return "X86ISD::PINSRB";
7246 case X86ISD::PINSRW: return "X86ISD::PINSRW";
7247 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
7248 case X86ISD::FMAX: return "X86ISD::FMAX";
7249 case X86ISD::FMIN: return "X86ISD::FMIN";
7250 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
7251 case X86ISD::FRCP: return "X86ISD::FRCP";
7252 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
7253 case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7254 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
7255 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
7256 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
7257 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
7258 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
7259 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
7260 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
7261 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
7262 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
7263 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
7264 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
7265 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
7266 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
7267 case X86ISD::VSHL: return "X86ISD::VSHL";
7268 case X86ISD::VSRL: return "X86ISD::VSRL";
7269 case X86ISD::CMPPD: return "X86ISD::CMPPD";
7270 case X86ISD::CMPPS: return "X86ISD::CMPPS";
7271 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
7272 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
7273 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
7274 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
7275 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
7276 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
7277 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
7278 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
7279 case X86ISD::ADD: return "X86ISD::ADD";
7280 case X86ISD::SUB: return "X86ISD::SUB";
7281 case X86ISD::SMUL: return "X86ISD::SMUL";
7282 case X86ISD::UMUL: return "X86ISD::UMUL";
7283 case X86ISD::INC: return "X86ISD::INC";
7284 case X86ISD::DEC: return "X86ISD::DEC";
7285 case X86ISD::OR: return "X86ISD::OR";
7286 case X86ISD::XOR: return "X86ISD::XOR";
7287 case X86ISD::AND: return "X86ISD::AND";
7288 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
7289 case X86ISD::PTEST: return "X86ISD::PTEST";
7290 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
7294 // isLegalAddressingMode - Return true if the addressing mode represented
7295 // by AM is legal for this target, for a load/store of the specified type.
7296 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7297 const Type *Ty) const {
7298 // X86 supports extremely general addressing modes.
7299 CodeModel::Model M = getTargetMachine().getCodeModel();
7301 // X86 allows a sign-extended 32-bit immediate field as a displacement.
7302 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
7307 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7309 // If a reference to this global requires an extra load, we can't fold it.
7310 if (isGlobalStubReference(GVFlags))
7313 // If BaseGV requires a register for the PIC base, we cannot also have a
7314 // BaseReg specified.
7315 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
7318 // If lower 4G is not available, then we must use rip-relative addressing.
7319 if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
7329 // These scales always work.
7334 // These scales are formed with basereg+scalereg. Only accept if there is
7339 default: // Other stuff never works.
7347 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7348 if (!Ty1->isInteger() || !Ty2->isInteger())
7350 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7351 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7352 if (NumBits1 <= NumBits2)
7354 return Subtarget->is64Bit() || NumBits1 < 64;
7357 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7358 if (!VT1.isInteger() || !VT2.isInteger())
7360 unsigned NumBits1 = VT1.getSizeInBits();
7361 unsigned NumBits2 = VT2.getSizeInBits();
7362 if (NumBits1 <= NumBits2)
7364 return Subtarget->is64Bit() || NumBits1 < 64;
7367 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7368 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7369 return Ty1 == Type::getInt32Ty(Ty1->getContext()) &&
7370 Ty2 == Type::getInt64Ty(Ty1->getContext()) && Subtarget->is64Bit();
7373 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7374 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7375 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7378 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
7379 // i16 instructions are longer (0x66 prefix) and potentially slower.
7380 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7383 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7384 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7385 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7386 /// are assumed to be legal.
7388 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
7390 // Only do shuffles on 128-bit vector types for now.
7391 if (VT.getSizeInBits() == 64)
7394 // FIXME: pshufb, blends, shifts.
7395 return (VT.getVectorNumElements() == 2 ||
7396 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7397 isMOVLMask(M, VT) ||
7398 isSHUFPMask(M, VT) ||
7399 isPSHUFDMask(M, VT) ||
7400 isPSHUFHWMask(M, VT) ||
7401 isPSHUFLWMask(M, VT) ||
7402 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
7403 isUNPCKLMask(M, VT) ||
7404 isUNPCKHMask(M, VT) ||
7405 isUNPCKL_v_undef_Mask(M, VT) ||
7406 isUNPCKH_v_undef_Mask(M, VT));
7410 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
7412 unsigned NumElts = VT.getVectorNumElements();
7413 // FIXME: This collection of masks seems suspect.
7416 if (NumElts == 4 && VT.getSizeInBits() == 128) {
7417 return (isMOVLMask(Mask, VT) ||
7418 isCommutedMOVLMask(Mask, VT, true) ||
7419 isSHUFPMask(Mask, VT) ||
7420 isCommutedSHUFPMask(Mask, VT));
7425 //===----------------------------------------------------------------------===//
7426 // X86 Scheduler Hooks
7427 //===----------------------------------------------------------------------===//
7429 // private utility function
7431 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7432 MachineBasicBlock *MBB,
7440 TargetRegisterClass *RC,
7441 bool invSrc) const {
7442 // For the atomic bitwise operator, we generate
7445 // ld t1 = [bitinstr.addr]
7446 // op t2 = t1, [bitinstr.val]
7448 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7450 // fallthrough -->nextMBB
7451 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7452 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7453 MachineFunction::iterator MBBIter = MBB;
7456 /// First build the CFG
7457 MachineFunction *F = MBB->getParent();
7458 MachineBasicBlock *thisMBB = MBB;
7459 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7460 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7461 F->insert(MBBIter, newMBB);
7462 F->insert(MBBIter, nextMBB);
7464 // Move all successors to thisMBB to nextMBB
7465 nextMBB->transferSuccessors(thisMBB);
7467 // Update thisMBB to fall through to newMBB
7468 thisMBB->addSuccessor(newMBB);
7470 // newMBB jumps to itself and fall through to nextMBB
7471 newMBB->addSuccessor(nextMBB);
7472 newMBB->addSuccessor(newMBB);
7474 // Insert instructions into newMBB based on incoming instruction
7475 assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7476 "unexpected number of operands");
7477 DebugLoc dl = bInstr->getDebugLoc();
7478 MachineOperand& destOper = bInstr->getOperand(0);
7479 MachineOperand* argOpers[2 + X86AddrNumOperands];
7480 int numArgs = bInstr->getNumOperands() - 1;
7481 for (int i=0; i < numArgs; ++i)
7482 argOpers[i] = &bInstr->getOperand(i+1);
7484 // x86 address has 4 operands: base, index, scale, and displacement
7485 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7486 int valArgIndx = lastAddrIndx + 1;
7488 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7489 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7490 for (int i=0; i <= lastAddrIndx; ++i)
7491 (*MIB).addOperand(*argOpers[i]);
7493 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7495 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7500 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7501 assert((argOpers[valArgIndx]->isReg() ||
7502 argOpers[valArgIndx]->isImm()) &&
7504 if (argOpers[valArgIndx]->isReg())
7505 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7507 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7509 (*MIB).addOperand(*argOpers[valArgIndx]);
7511 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7514 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7515 for (int i=0; i <= lastAddrIndx; ++i)
7516 (*MIB).addOperand(*argOpers[i]);
7518 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7519 (*MIB).setMemRefs(bInstr->memoperands_begin(),
7520 bInstr->memoperands_end());
7522 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7526 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7528 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7532 // private utility function: 64 bit atomics on 32 bit host.
7534 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7535 MachineBasicBlock *MBB,
7540 bool invSrc) const {
7541 // For the atomic bitwise operator, we generate
7542 // thisMBB (instructions are in pairs, except cmpxchg8b)
7543 // ld t1,t2 = [bitinstr.addr]
7545 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7546 // op t5, t6 <- out1, out2, [bitinstr.val]
7547 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
7548 // mov ECX, EBX <- t5, t6
7549 // mov EAX, EDX <- t1, t2
7550 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
7551 // mov t3, t4 <- EAX, EDX
7553 // result in out1, out2
7554 // fallthrough -->nextMBB
7556 const TargetRegisterClass *RC = X86::GR32RegisterClass;
7557 const unsigned LoadOpc = X86::MOV32rm;
7558 const unsigned copyOpc = X86::MOV32rr;
7559 const unsigned NotOpc = X86::NOT32r;
7560 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7561 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7562 MachineFunction::iterator MBBIter = MBB;
7565 /// First build the CFG
7566 MachineFunction *F = MBB->getParent();
7567 MachineBasicBlock *thisMBB = MBB;
7568 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7569 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7570 F->insert(MBBIter, newMBB);
7571 F->insert(MBBIter, nextMBB);
7573 // Move all successors to thisMBB to nextMBB
7574 nextMBB->transferSuccessors(thisMBB);
7576 // Update thisMBB to fall through to newMBB
7577 thisMBB->addSuccessor(newMBB);
7579 // newMBB jumps to itself and fall through to nextMBB
7580 newMBB->addSuccessor(nextMBB);
7581 newMBB->addSuccessor(newMBB);
7583 DebugLoc dl = bInstr->getDebugLoc();
7584 // Insert instructions into newMBB based on incoming instruction
7585 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7586 assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
7587 "unexpected number of operands");
7588 MachineOperand& dest1Oper = bInstr->getOperand(0);
7589 MachineOperand& dest2Oper = bInstr->getOperand(1);
7590 MachineOperand* argOpers[2 + X86AddrNumOperands];
7591 for (int i=0; i < 2 + X86AddrNumOperands; ++i)
7592 argOpers[i] = &bInstr->getOperand(i+2);
7594 // x86 address has 4 operands: base, index, scale, and displacement
7595 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7597 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7598 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
7599 for (int i=0; i <= lastAddrIndx; ++i)
7600 (*MIB).addOperand(*argOpers[i]);
7601 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7602 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
7603 // add 4 to displacement.
7604 for (int i=0; i <= lastAddrIndx-2; ++i)
7605 (*MIB).addOperand(*argOpers[i]);
7606 MachineOperand newOp3 = *(argOpers[3]);
7608 newOp3.setImm(newOp3.getImm()+4);
7610 newOp3.setOffset(newOp3.getOffset()+4);
7611 (*MIB).addOperand(newOp3);
7612 (*MIB).addOperand(*argOpers[lastAddrIndx]);
7614 // t3/4 are defined later, at the bottom of the loop
7615 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
7616 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
7617 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
7618 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
7619 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
7620 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
7622 unsigned tt1 = F->getRegInfo().createVirtualRegister(RC);
7623 unsigned tt2 = F->getRegInfo().createVirtualRegister(RC);
7625 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt1).addReg(t1);
7626 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt2).addReg(t2);
7632 int valArgIndx = lastAddrIndx + 1;
7633 assert((argOpers[valArgIndx]->isReg() ||
7634 argOpers[valArgIndx]->isImm()) &&
7636 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
7637 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
7638 if (argOpers[valArgIndx]->isReg())
7639 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
7641 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
7642 if (regOpcL != X86::MOV32rr)
7644 (*MIB).addOperand(*argOpers[valArgIndx]);
7645 assert(argOpers[valArgIndx + 1]->isReg() ==
7646 argOpers[valArgIndx]->isReg());
7647 assert(argOpers[valArgIndx + 1]->isImm() ==
7648 argOpers[valArgIndx]->isImm());
7649 if (argOpers[valArgIndx + 1]->isReg())
7650 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
7652 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
7653 if (regOpcH != X86::MOV32rr)
7655 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
7657 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
7659 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
7662 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
7664 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
7667 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
7668 for (int i=0; i <= lastAddrIndx; ++i)
7669 (*MIB).addOperand(*argOpers[i]);
7671 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7672 (*MIB).setMemRefs(bInstr->memoperands_begin(),
7673 bInstr->memoperands_end());
7675 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
7676 MIB.addReg(X86::EAX);
7677 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
7678 MIB.addReg(X86::EDX);
7681 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7683 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7687 // private utility function
7689 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
7690 MachineBasicBlock *MBB,
7691 unsigned cmovOpc) const {
7692 // For the atomic min/max operator, we generate
7695 // ld t1 = [min/max.addr]
7696 // mov t2 = [min/max.val]
7698 // cmov[cond] t2 = t1
7700 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7702 // fallthrough -->nextMBB
7704 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7705 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7706 MachineFunction::iterator MBBIter = MBB;
7709 /// First build the CFG
7710 MachineFunction *F = MBB->getParent();
7711 MachineBasicBlock *thisMBB = MBB;
7712 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7713 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7714 F->insert(MBBIter, newMBB);
7715 F->insert(MBBIter, nextMBB);
7717 // Move all successors of thisMBB to nextMBB
7718 nextMBB->transferSuccessors(thisMBB);
7720 // Update thisMBB to fall through to newMBB
7721 thisMBB->addSuccessor(newMBB);
7723 // newMBB jumps to newMBB and fall through to nextMBB
7724 newMBB->addSuccessor(nextMBB);
7725 newMBB->addSuccessor(newMBB);
7727 DebugLoc dl = mInstr->getDebugLoc();
7728 // Insert instructions into newMBB based on incoming instruction
7729 assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7730 "unexpected number of operands");
7731 MachineOperand& destOper = mInstr->getOperand(0);
7732 MachineOperand* argOpers[2 + X86AddrNumOperands];
7733 int numArgs = mInstr->getNumOperands() - 1;
7734 for (int i=0; i < numArgs; ++i)
7735 argOpers[i] = &mInstr->getOperand(i+1);
7737 // x86 address has 4 operands: base, index, scale, and displacement
7738 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7739 int valArgIndx = lastAddrIndx + 1;
7741 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7742 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
7743 for (int i=0; i <= lastAddrIndx; ++i)
7744 (*MIB).addOperand(*argOpers[i]);
7746 // We only support register and immediate values
7747 assert((argOpers[valArgIndx]->isReg() ||
7748 argOpers[valArgIndx]->isImm()) &&
7751 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7752 if (argOpers[valArgIndx]->isReg())
7753 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7755 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7756 (*MIB).addOperand(*argOpers[valArgIndx]);
7758 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
7761 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
7766 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7767 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
7771 // Cmp and exchange if none has modified the memory location
7772 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
7773 for (int i=0; i <= lastAddrIndx; ++i)
7774 (*MIB).addOperand(*argOpers[i]);
7776 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7777 (*MIB).setMemRefs(mInstr->memoperands_begin(),
7778 mInstr->memoperands_end());
7780 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
7781 MIB.addReg(X86::EAX);
7784 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7786 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
7790 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
7791 // all of this code can be replaced with that in the .td file.
7793 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
7794 unsigned numArgs, bool memArg) const {
7796 MachineFunction *F = BB->getParent();
7797 DebugLoc dl = MI->getDebugLoc();
7798 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7802 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
7804 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
7806 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
7808 for (unsigned i = 0; i < numArgs; ++i) {
7809 MachineOperand &Op = MI->getOperand(i+1);
7811 if (!(Op.isReg() && Op.isImplicit()))
7815 BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
7818 F->DeleteMachineInstr(MI);
7824 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
7826 MachineBasicBlock *MBB) const {
7827 // Emit code to save XMM registers to the stack. The ABI says that the
7828 // number of registers to save is given in %al, so it's theoretically
7829 // possible to do an indirect jump trick to avoid saving all of them,
7830 // however this code takes a simpler approach and just executes all
7831 // of the stores if %al is non-zero. It's less code, and it's probably
7832 // easier on the hardware branch predictor, and stores aren't all that
7833 // expensive anyway.
7835 // Create the new basic blocks. One block contains all the XMM stores,
7836 // and one block is the final destination regardless of whether any
7837 // stores were performed.
7838 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7839 MachineFunction *F = MBB->getParent();
7840 MachineFunction::iterator MBBIter = MBB;
7842 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
7843 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
7844 F->insert(MBBIter, XMMSaveMBB);
7845 F->insert(MBBIter, EndMBB);
7848 // Move any original successors of MBB to the end block.
7849 EndMBB->transferSuccessors(MBB);
7850 // The original block will now fall through to the XMM save block.
7851 MBB->addSuccessor(XMMSaveMBB);
7852 // The XMMSaveMBB will fall through to the end block.
7853 XMMSaveMBB->addSuccessor(EndMBB);
7855 // Now add the instructions.
7856 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7857 DebugLoc DL = MI->getDebugLoc();
7859 unsigned CountReg = MI->getOperand(0).getReg();
7860 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
7861 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
7863 if (!Subtarget->isTargetWin64()) {
7864 // If %al is 0, branch around the XMM save block.
7865 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
7866 BuildMI(MBB, DL, TII->get(X86::JE)).addMBB(EndMBB);
7867 MBB->addSuccessor(EndMBB);
7870 // In the XMM save block, save all the XMM argument registers.
7871 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
7872 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
7873 MachineMemOperand *MMO =
7874 F->getMachineMemOperand(
7875 PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
7876 MachineMemOperand::MOStore, Offset,
7877 /*Size=*/16, /*Align=*/16);
7878 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
7879 .addFrameIndex(RegSaveFrameIndex)
7880 .addImm(/*Scale=*/1)
7881 .addReg(/*IndexReg=*/0)
7882 .addImm(/*Disp=*/Offset)
7883 .addReg(/*Segment=*/0)
7884 .addReg(MI->getOperand(i).getReg())
7885 .addMemOperand(MMO);
7888 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7894 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
7895 MachineBasicBlock *BB,
7896 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
7897 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7898 DebugLoc DL = MI->getDebugLoc();
7900 // To "insert" a SELECT_CC instruction, we actually have to insert the
7901 // diamond control-flow pattern. The incoming instruction knows the
7902 // destination vreg to set, the condition code register to branch on, the
7903 // true/false values to select between, and a branch opcode to use.
7904 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7905 MachineFunction::iterator It = BB;
7911 // cmpTY ccX, r1, r2
7913 // fallthrough --> copy0MBB
7914 MachineBasicBlock *thisMBB = BB;
7915 MachineFunction *F = BB->getParent();
7916 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7917 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7919 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
7920 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
7921 F->insert(It, copy0MBB);
7922 F->insert(It, sinkMBB);
7923 // Update machine-CFG edges by first adding all successors of the current
7924 // block to the new block which will contain the Phi node for the select.
7925 // Also inform sdisel of the edge changes.
7926 for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
7927 E = BB->succ_end(); I != E; ++I) {
7928 EM->insert(std::make_pair(*I, sinkMBB));
7929 sinkMBB->addSuccessor(*I);
7931 // Next, remove all successors of the current block, and add the true
7932 // and fallthrough blocks as its successors.
7933 while (!BB->succ_empty())
7934 BB->removeSuccessor(BB->succ_begin());
7935 // Add the true and fallthrough blocks as its successors.
7936 BB->addSuccessor(copy0MBB);
7937 BB->addSuccessor(sinkMBB);
7940 // %FalseValue = ...
7941 // # fallthrough to sinkMBB
7944 // Update machine-CFG edges
7945 BB->addSuccessor(sinkMBB);
7948 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7951 BuildMI(BB, DL, TII->get(X86::PHI), MI->getOperand(0).getReg())
7952 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7953 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7955 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7961 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7962 MachineBasicBlock *BB,
7963 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
7964 switch (MI->getOpcode()) {
7965 default: assert(false && "Unexpected instr type to insert");
7967 case X86::CMOV_V1I64:
7968 case X86::CMOV_FR32:
7969 case X86::CMOV_FR64:
7970 case X86::CMOV_V4F32:
7971 case X86::CMOV_V2F64:
7972 case X86::CMOV_V2I64:
7973 return EmitLoweredSelect(MI, BB, EM);
7975 case X86::FP32_TO_INT16_IN_MEM:
7976 case X86::FP32_TO_INT32_IN_MEM:
7977 case X86::FP32_TO_INT64_IN_MEM:
7978 case X86::FP64_TO_INT16_IN_MEM:
7979 case X86::FP64_TO_INT32_IN_MEM:
7980 case X86::FP64_TO_INT64_IN_MEM:
7981 case X86::FP80_TO_INT16_IN_MEM:
7982 case X86::FP80_TO_INT32_IN_MEM:
7983 case X86::FP80_TO_INT64_IN_MEM: {
7984 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7985 DebugLoc DL = MI->getDebugLoc();
7987 // Change the floating point control register to use "round towards zero"
7988 // mode when truncating to an integer value.
7989 MachineFunction *F = BB->getParent();
7990 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
7991 addFrameReference(BuildMI(BB, DL, TII->get(X86::FNSTCW16m)), CWFrameIdx);
7993 // Load the old value of the high byte of the control word...
7995 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
7996 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16rm), OldCW),
7999 // Set the high part to be round to zero...
8000 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
8003 // Reload the modified control word now...
8004 addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8006 // Restore the memory image of control word to original value
8007 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
8010 // Get the X86 opcode to use.
8012 switch (MI->getOpcode()) {
8013 default: llvm_unreachable("illegal opcode!");
8014 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
8015 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
8016 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
8017 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
8018 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
8019 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
8020 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
8021 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
8022 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
8026 MachineOperand &Op = MI->getOperand(0);
8028 AM.BaseType = X86AddressMode::RegBase;
8029 AM.Base.Reg = Op.getReg();
8031 AM.BaseType = X86AddressMode::FrameIndexBase;
8032 AM.Base.FrameIndex = Op.getIndex();
8034 Op = MI->getOperand(1);
8036 AM.Scale = Op.getImm();
8037 Op = MI->getOperand(2);
8039 AM.IndexReg = Op.getImm();
8040 Op = MI->getOperand(3);
8041 if (Op.isGlobal()) {
8042 AM.GV = Op.getGlobal();
8044 AM.Disp = Op.getImm();
8046 addFullAddress(BuildMI(BB, DL, TII->get(Opc)), AM)
8047 .addReg(MI->getOperand(X86AddrNumOperands).getReg());
8049 // Reload the original control word now.
8050 addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8052 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8055 // String/text processing lowering.
8056 case X86::PCMPISTRM128REG:
8057 return EmitPCMP(MI, BB, 3, false /* in-mem */);
8058 case X86::PCMPISTRM128MEM:
8059 return EmitPCMP(MI, BB, 3, true /* in-mem */);
8060 case X86::PCMPESTRM128REG:
8061 return EmitPCMP(MI, BB, 5, false /* in mem */);
8062 case X86::PCMPESTRM128MEM:
8063 return EmitPCMP(MI, BB, 5, true /* in mem */);
8066 case X86::ATOMAND32:
8067 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8068 X86::AND32ri, X86::MOV32rm,
8069 X86::LCMPXCHG32, X86::MOV32rr,
8070 X86::NOT32r, X86::EAX,
8071 X86::GR32RegisterClass);
8073 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
8074 X86::OR32ri, X86::MOV32rm,
8075 X86::LCMPXCHG32, X86::MOV32rr,
8076 X86::NOT32r, X86::EAX,
8077 X86::GR32RegisterClass);
8078 case X86::ATOMXOR32:
8079 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
8080 X86::XOR32ri, X86::MOV32rm,
8081 X86::LCMPXCHG32, X86::MOV32rr,
8082 X86::NOT32r, X86::EAX,
8083 X86::GR32RegisterClass);
8084 case X86::ATOMNAND32:
8085 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8086 X86::AND32ri, X86::MOV32rm,
8087 X86::LCMPXCHG32, X86::MOV32rr,
8088 X86::NOT32r, X86::EAX,
8089 X86::GR32RegisterClass, true);
8090 case X86::ATOMMIN32:
8091 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
8092 case X86::ATOMMAX32:
8093 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
8094 case X86::ATOMUMIN32:
8095 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
8096 case X86::ATOMUMAX32:
8097 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
8099 case X86::ATOMAND16:
8100 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8101 X86::AND16ri, X86::MOV16rm,
8102 X86::LCMPXCHG16, X86::MOV16rr,
8103 X86::NOT16r, X86::AX,
8104 X86::GR16RegisterClass);
8106 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
8107 X86::OR16ri, X86::MOV16rm,
8108 X86::LCMPXCHG16, X86::MOV16rr,
8109 X86::NOT16r, X86::AX,
8110 X86::GR16RegisterClass);
8111 case X86::ATOMXOR16:
8112 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
8113 X86::XOR16ri, X86::MOV16rm,
8114 X86::LCMPXCHG16, X86::MOV16rr,
8115 X86::NOT16r, X86::AX,
8116 X86::GR16RegisterClass);
8117 case X86::ATOMNAND16:
8118 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8119 X86::AND16ri, X86::MOV16rm,
8120 X86::LCMPXCHG16, X86::MOV16rr,
8121 X86::NOT16r, X86::AX,
8122 X86::GR16RegisterClass, true);
8123 case X86::ATOMMIN16:
8124 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
8125 case X86::ATOMMAX16:
8126 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
8127 case X86::ATOMUMIN16:
8128 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
8129 case X86::ATOMUMAX16:
8130 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
8133 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8134 X86::AND8ri, X86::MOV8rm,
8135 X86::LCMPXCHG8, X86::MOV8rr,
8136 X86::NOT8r, X86::AL,
8137 X86::GR8RegisterClass);
8139 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
8140 X86::OR8ri, X86::MOV8rm,
8141 X86::LCMPXCHG8, X86::MOV8rr,
8142 X86::NOT8r, X86::AL,
8143 X86::GR8RegisterClass);
8145 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
8146 X86::XOR8ri, X86::MOV8rm,
8147 X86::LCMPXCHG8, X86::MOV8rr,
8148 X86::NOT8r, X86::AL,
8149 X86::GR8RegisterClass);
8150 case X86::ATOMNAND8:
8151 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8152 X86::AND8ri, X86::MOV8rm,
8153 X86::LCMPXCHG8, X86::MOV8rr,
8154 X86::NOT8r, X86::AL,
8155 X86::GR8RegisterClass, true);
8156 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
8157 // This group is for 64-bit host.
8158 case X86::ATOMAND64:
8159 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8160 X86::AND64ri32, X86::MOV64rm,
8161 X86::LCMPXCHG64, X86::MOV64rr,
8162 X86::NOT64r, X86::RAX,
8163 X86::GR64RegisterClass);
8165 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
8166 X86::OR64ri32, X86::MOV64rm,
8167 X86::LCMPXCHG64, X86::MOV64rr,
8168 X86::NOT64r, X86::RAX,
8169 X86::GR64RegisterClass);
8170 case X86::ATOMXOR64:
8171 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
8172 X86::XOR64ri32, X86::MOV64rm,
8173 X86::LCMPXCHG64, X86::MOV64rr,
8174 X86::NOT64r, X86::RAX,
8175 X86::GR64RegisterClass);
8176 case X86::ATOMNAND64:
8177 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8178 X86::AND64ri32, X86::MOV64rm,
8179 X86::LCMPXCHG64, X86::MOV64rr,
8180 X86::NOT64r, X86::RAX,
8181 X86::GR64RegisterClass, true);
8182 case X86::ATOMMIN64:
8183 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
8184 case X86::ATOMMAX64:
8185 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
8186 case X86::ATOMUMIN64:
8187 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
8188 case X86::ATOMUMAX64:
8189 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
8191 // This group does 64-bit operations on a 32-bit host.
8192 case X86::ATOMAND6432:
8193 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8194 X86::AND32rr, X86::AND32rr,
8195 X86::AND32ri, X86::AND32ri,
8197 case X86::ATOMOR6432:
8198 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8199 X86::OR32rr, X86::OR32rr,
8200 X86::OR32ri, X86::OR32ri,
8202 case X86::ATOMXOR6432:
8203 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8204 X86::XOR32rr, X86::XOR32rr,
8205 X86::XOR32ri, X86::XOR32ri,
8207 case X86::ATOMNAND6432:
8208 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8209 X86::AND32rr, X86::AND32rr,
8210 X86::AND32ri, X86::AND32ri,
8212 case X86::ATOMADD6432:
8213 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8214 X86::ADD32rr, X86::ADC32rr,
8215 X86::ADD32ri, X86::ADC32ri,
8217 case X86::ATOMSUB6432:
8218 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8219 X86::SUB32rr, X86::SBB32rr,
8220 X86::SUB32ri, X86::SBB32ri,
8222 case X86::ATOMSWAP6432:
8223 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8224 X86::MOV32rr, X86::MOV32rr,
8225 X86::MOV32ri, X86::MOV32ri,
8227 case X86::VASTART_SAVE_XMM_REGS:
8228 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
8232 //===----------------------------------------------------------------------===//
8233 // X86 Optimization Hooks
8234 //===----------------------------------------------------------------------===//
8236 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8240 const SelectionDAG &DAG,
8241 unsigned Depth) const {
8242 unsigned Opc = Op.getOpcode();
8243 assert((Opc >= ISD::BUILTIN_OP_END ||
8244 Opc == ISD::INTRINSIC_WO_CHAIN ||
8245 Opc == ISD::INTRINSIC_W_CHAIN ||
8246 Opc == ISD::INTRINSIC_VOID) &&
8247 "Should use MaskedValueIsZero if you don't know whether Op"
8248 " is a target node!");
8250 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
8262 // These nodes' second result is a boolean.
8263 if (Op.getResNo() == 0)
8267 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
8268 Mask.getBitWidth() - 1);
8273 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
8274 /// node is a GlobalAddress + offset.
8275 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
8276 GlobalValue* &GA, int64_t &Offset) const{
8277 if (N->getOpcode() == X86ISD::Wrapper) {
8278 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
8279 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
8280 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
8284 return TargetLowering::isGAPlusOffset(N, GA, Offset);
8287 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
8288 const TargetLowering &TLI) {
8291 if (TLI.isGAPlusOffset(Base, GV, Offset))
8292 return (GV->getAlignment() >= N && (Offset % N) == 0);
8293 // DAG combine handles the stack object case.
8297 static bool EltsFromConsecutiveLoads(ShuffleVectorSDNode *N, unsigned NumElems,
8298 EVT EltVT, LoadSDNode *&LDBase,
8299 unsigned &LastLoadedElt,
8300 SelectionDAG &DAG, MachineFrameInfo *MFI,
8301 const TargetLowering &TLI) {
8303 LastLoadedElt = -1U;
8304 for (unsigned i = 0; i < NumElems; ++i) {
8305 if (N->getMaskElt(i) < 0) {
8311 SDValue Elt = DAG.getShuffleScalarElt(N, i);
8312 if (!Elt.getNode() ||
8313 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
8316 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
8318 LDBase = cast<LoadSDNode>(Elt.getNode());
8322 if (Elt.getOpcode() == ISD::UNDEF)
8325 LoadSDNode *LD = cast<LoadSDNode>(Elt);
8326 if (!TLI.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i, MFI))
8333 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8334 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8335 /// if the load addresses are consecutive, non-overlapping, and in the right
8336 /// order. In the case of v2i64, it will see if it can rewrite the
8337 /// shuffle to be an appropriate build vector so it can take advantage of
8338 // performBuildVectorCombine.
8339 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8340 const TargetLowering &TLI) {
8341 DebugLoc dl = N->getDebugLoc();
8342 EVT VT = N->getValueType(0);
8343 EVT EltVT = VT.getVectorElementType();
8344 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8345 unsigned NumElems = VT.getVectorNumElements();
8347 if (VT.getSizeInBits() != 128)
8350 // Try to combine a vector_shuffle into a 128-bit load.
8351 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8352 LoadSDNode *LD = NULL;
8353 unsigned LastLoadedElt;
8354 if (!EltsFromConsecutiveLoads(SVN, NumElems, EltVT, LD, LastLoadedElt, DAG,
8358 if (LastLoadedElt == NumElems - 1) {
8359 if (isBaseAlignmentOfN(16, LD->getBasePtr().getNode(), TLI))
8360 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8361 LD->getSrcValue(), LD->getSrcValueOffset(),
8363 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8364 LD->getSrcValue(), LD->getSrcValueOffset(),
8365 LD->isVolatile(), LD->getAlignment());
8366 } else if (NumElems == 4 && LastLoadedElt == 1) {
8367 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
8368 SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
8369 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
8370 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
8375 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
8376 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
8377 const X86Subtarget *Subtarget) {
8378 DebugLoc DL = N->getDebugLoc();
8379 SDValue Cond = N->getOperand(0);
8380 // Get the LHS/RHS of the select.
8381 SDValue LHS = N->getOperand(1);
8382 SDValue RHS = N->getOperand(2);
8384 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
8385 // instructions have the peculiarity that if either operand is a NaN,
8386 // they chose what we call the RHS operand (and as such are not symmetric).
8387 // It happens that this matches the semantics of the common C idiom
8388 // x<y?x:y and related forms, so we can recognize these cases.
8389 if (Subtarget->hasSSE2() &&
8390 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
8391 Cond.getOpcode() == ISD::SETCC) {
8392 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
8394 unsigned Opcode = 0;
8395 // Check for x CC y ? x : y.
8396 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
8400 // This can be a min if we can prove that at least one of the operands
8402 if (!FiniteOnlyFPMath()) {
8403 if (DAG.isKnownNeverNaN(RHS)) {
8404 // Put the potential NaN in the RHS so that SSE will preserve it.
8405 std::swap(LHS, RHS);
8406 } else if (!DAG.isKnownNeverNaN(LHS))
8409 Opcode = X86ISD::FMIN;
8412 // This can be a min if we can prove that at least one of the operands
8414 if (!FiniteOnlyFPMath()) {
8415 if (DAG.isKnownNeverNaN(LHS)) {
8416 // Put the potential NaN in the RHS so that SSE will preserve it.
8417 std::swap(LHS, RHS);
8418 } else if (!DAG.isKnownNeverNaN(RHS))
8421 Opcode = X86ISD::FMIN;
8424 // This can be a min, but if either operand is a NaN we need it to
8425 // preserve the original LHS.
8426 std::swap(LHS, RHS);
8430 Opcode = X86ISD::FMIN;
8434 // This can be a max if we can prove that at least one of the operands
8436 if (!FiniteOnlyFPMath()) {
8437 if (DAG.isKnownNeverNaN(LHS)) {
8438 // Put the potential NaN in the RHS so that SSE will preserve it.
8439 std::swap(LHS, RHS);
8440 } else if (!DAG.isKnownNeverNaN(RHS))
8443 Opcode = X86ISD::FMAX;
8446 // This can be a max if we can prove that at least one of the operands
8448 if (!FiniteOnlyFPMath()) {
8449 if (DAG.isKnownNeverNaN(RHS)) {
8450 // Put the potential NaN in the RHS so that SSE will preserve it.
8451 std::swap(LHS, RHS);
8452 } else if (!DAG.isKnownNeverNaN(LHS))
8455 Opcode = X86ISD::FMAX;
8458 // This can be a max, but if either operand is a NaN we need it to
8459 // preserve the original LHS.
8460 std::swap(LHS, RHS);
8464 Opcode = X86ISD::FMAX;
8467 // Check for x CC y ? y : x -- a min/max with reversed arms.
8468 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
8472 // This can be a min if we can prove that at least one of the operands
8474 if (!FiniteOnlyFPMath()) {
8475 if (DAG.isKnownNeverNaN(RHS)) {
8476 // Put the potential NaN in the RHS so that SSE will preserve it.
8477 std::swap(LHS, RHS);
8478 } else if (!DAG.isKnownNeverNaN(LHS))
8481 Opcode = X86ISD::FMIN;
8484 // This can be a min if we can prove that at least one of the operands
8486 if (!FiniteOnlyFPMath()) {
8487 if (DAG.isKnownNeverNaN(LHS)) {
8488 // Put the potential NaN in the RHS so that SSE will preserve it.
8489 std::swap(LHS, RHS);
8490 } else if (!DAG.isKnownNeverNaN(RHS))
8493 Opcode = X86ISD::FMIN;
8496 // This can be a min, but if either operand is a NaN we need it to
8497 // preserve the original LHS.
8498 std::swap(LHS, RHS);
8502 Opcode = X86ISD::FMIN;
8506 // This can be a max if we can prove that at least one of the operands
8508 if (!FiniteOnlyFPMath()) {
8509 if (DAG.isKnownNeverNaN(LHS)) {
8510 // Put the potential NaN in the RHS so that SSE will preserve it.
8511 std::swap(LHS, RHS);
8512 } else if (!DAG.isKnownNeverNaN(RHS))
8515 Opcode = X86ISD::FMAX;
8518 // This can be a max if we can prove that at least one of the operands
8520 if (!FiniteOnlyFPMath()) {
8521 if (DAG.isKnownNeverNaN(RHS)) {
8522 // Put the potential NaN in the RHS so that SSE will preserve it.
8523 std::swap(LHS, RHS);
8524 } else if (!DAG.isKnownNeverNaN(LHS))
8527 Opcode = X86ISD::FMAX;
8530 // This can be a max, but if either operand is a NaN we need it to
8531 // preserve the original LHS.
8532 std::swap(LHS, RHS);
8536 Opcode = X86ISD::FMAX;
8542 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
8545 // If this is a select between two integer constants, try to do some
8547 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
8548 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
8549 // Don't do this for crazy integer types.
8550 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
8551 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
8552 // so that TrueC (the true value) is larger than FalseC.
8553 bool NeedsCondInvert = false;
8555 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
8556 // Efficiently invertible.
8557 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
8558 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
8559 isa<ConstantSDNode>(Cond.getOperand(1))))) {
8560 NeedsCondInvert = true;
8561 std::swap(TrueC, FalseC);
8564 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
8565 if (FalseC->getAPIntValue() == 0 &&
8566 TrueC->getAPIntValue().isPowerOf2()) {
8567 if (NeedsCondInvert) // Invert the condition if needed.
8568 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8569 DAG.getConstant(1, Cond.getValueType()));
8571 // Zero extend the condition if needed.
8572 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
8574 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8575 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
8576 DAG.getConstant(ShAmt, MVT::i8));
8579 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
8580 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8581 if (NeedsCondInvert) // Invert the condition if needed.
8582 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8583 DAG.getConstant(1, Cond.getValueType()));
8585 // Zero extend the condition if needed.
8586 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8587 FalseC->getValueType(0), Cond);
8588 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8589 SDValue(FalseC, 0));
8592 // Optimize cases that will turn into an LEA instruction. This requires
8593 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8594 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8595 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8596 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8598 bool isFastMultiplier = false;
8600 switch ((unsigned char)Diff) {
8602 case 1: // result = add base, cond
8603 case 2: // result = lea base( , cond*2)
8604 case 3: // result = lea base(cond, cond*2)
8605 case 4: // result = lea base( , cond*4)
8606 case 5: // result = lea base(cond, cond*4)
8607 case 8: // result = lea base( , cond*8)
8608 case 9: // result = lea base(cond, cond*8)
8609 isFastMultiplier = true;
8614 if (isFastMultiplier) {
8615 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8616 if (NeedsCondInvert) // Invert the condition if needed.
8617 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8618 DAG.getConstant(1, Cond.getValueType()));
8620 // Zero extend the condition if needed.
8621 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8623 // Scale the condition by the difference.
8625 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8626 DAG.getConstant(Diff, Cond.getValueType()));
8628 // Add the base if non-zero.
8629 if (FalseC->getAPIntValue() != 0)
8630 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8631 SDValue(FalseC, 0));
8641 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
8642 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
8643 TargetLowering::DAGCombinerInfo &DCI) {
8644 DebugLoc DL = N->getDebugLoc();
8646 // If the flag operand isn't dead, don't touch this CMOV.
8647 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
8650 // If this is a select between two integer constants, try to do some
8651 // optimizations. Note that the operands are ordered the opposite of SELECT
8653 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
8654 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8655 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
8656 // larger than FalseC (the false value).
8657 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
8659 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
8660 CC = X86::GetOppositeBranchCondition(CC);
8661 std::swap(TrueC, FalseC);
8664 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
8665 // This is efficient for any integer data type (including i8/i16) and
8667 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
8668 SDValue Cond = N->getOperand(3);
8669 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8670 DAG.getConstant(CC, MVT::i8), Cond);
8672 // Zero extend the condition if needed.
8673 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
8675 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8676 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
8677 DAG.getConstant(ShAmt, MVT::i8));
8678 if (N->getNumValues() == 2) // Dead flag value?
8679 return DCI.CombineTo(N, Cond, SDValue());
8683 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
8684 // for any integer data type, including i8/i16.
8685 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8686 SDValue Cond = N->getOperand(3);
8687 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8688 DAG.getConstant(CC, MVT::i8), Cond);
8690 // Zero extend the condition if needed.
8691 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8692 FalseC->getValueType(0), Cond);
8693 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8694 SDValue(FalseC, 0));
8696 if (N->getNumValues() == 2) // Dead flag value?
8697 return DCI.CombineTo(N, Cond, SDValue());
8701 // Optimize cases that will turn into an LEA instruction. This requires
8702 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8703 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8704 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8705 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8707 bool isFastMultiplier = false;
8709 switch ((unsigned char)Diff) {
8711 case 1: // result = add base, cond
8712 case 2: // result = lea base( , cond*2)
8713 case 3: // result = lea base(cond, cond*2)
8714 case 4: // result = lea base( , cond*4)
8715 case 5: // result = lea base(cond, cond*4)
8716 case 8: // result = lea base( , cond*8)
8717 case 9: // result = lea base(cond, cond*8)
8718 isFastMultiplier = true;
8723 if (isFastMultiplier) {
8724 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8725 SDValue Cond = N->getOperand(3);
8726 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8727 DAG.getConstant(CC, MVT::i8), Cond);
8728 // Zero extend the condition if needed.
8729 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8731 // Scale the condition by the difference.
8733 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8734 DAG.getConstant(Diff, Cond.getValueType()));
8736 // Add the base if non-zero.
8737 if (FalseC->getAPIntValue() != 0)
8738 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8739 SDValue(FalseC, 0));
8740 if (N->getNumValues() == 2) // Dead flag value?
8741 return DCI.CombineTo(N, Cond, SDValue());
8751 /// PerformMulCombine - Optimize a single multiply with constant into two
8752 /// in order to implement it with two cheaper instructions, e.g.
8753 /// LEA + SHL, LEA + LEA.
8754 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
8755 TargetLowering::DAGCombinerInfo &DCI) {
8756 if (DAG.getMachineFunction().
8757 getFunction()->hasFnAttr(Attribute::OptimizeForSize))
8760 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8763 EVT VT = N->getValueType(0);
8767 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8770 uint64_t MulAmt = C->getZExtValue();
8771 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
8774 uint64_t MulAmt1 = 0;
8775 uint64_t MulAmt2 = 0;
8776 if ((MulAmt % 9) == 0) {
8778 MulAmt2 = MulAmt / 9;
8779 } else if ((MulAmt % 5) == 0) {
8781 MulAmt2 = MulAmt / 5;
8782 } else if ((MulAmt % 3) == 0) {
8784 MulAmt2 = MulAmt / 3;
8787 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
8788 DebugLoc DL = N->getDebugLoc();
8790 if (isPowerOf2_64(MulAmt2) &&
8791 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
8792 // If second multiplifer is pow2, issue it first. We want the multiply by
8793 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
8795 std::swap(MulAmt1, MulAmt2);
8798 if (isPowerOf2_64(MulAmt1))
8799 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
8800 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
8802 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
8803 DAG.getConstant(MulAmt1, VT));
8805 if (isPowerOf2_64(MulAmt2))
8806 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
8807 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
8809 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
8810 DAG.getConstant(MulAmt2, VT));
8812 // Do not add new nodes to DAG combiner worklist.
8813 DCI.CombineTo(N, NewMul, false);
8819 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
8821 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
8822 const X86Subtarget *Subtarget) {
8823 // On X86 with SSE2 support, we can transform this to a vector shift if
8824 // all elements are shifted by the same amount. We can't do this in legalize
8825 // because the a constant vector is typically transformed to a constant pool
8826 // so we have no knowledge of the shift amount.
8827 if (!Subtarget->hasSSE2())
8830 EVT VT = N->getValueType(0);
8831 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
8834 SDValue ShAmtOp = N->getOperand(1);
8835 EVT EltVT = VT.getVectorElementType();
8836 DebugLoc DL = N->getDebugLoc();
8837 SDValue BaseShAmt = SDValue();
8838 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
8839 unsigned NumElts = VT.getVectorNumElements();
8841 for (; i != NumElts; ++i) {
8842 SDValue Arg = ShAmtOp.getOperand(i);
8843 if (Arg.getOpcode() == ISD::UNDEF) continue;
8847 for (; i != NumElts; ++i) {
8848 SDValue Arg = ShAmtOp.getOperand(i);
8849 if (Arg.getOpcode() == ISD::UNDEF) continue;
8850 if (Arg != BaseShAmt) {
8854 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
8855 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
8856 SDValue InVec = ShAmtOp.getOperand(0);
8857 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
8858 unsigned NumElts = InVec.getValueType().getVectorNumElements();
8860 for (; i != NumElts; ++i) {
8861 SDValue Arg = InVec.getOperand(i);
8862 if (Arg.getOpcode() == ISD::UNDEF) continue;
8866 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
8867 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
8868 unsigned SplatIdx = cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
8869 if (C->getZExtValue() == SplatIdx)
8870 BaseShAmt = InVec.getOperand(1);
8873 if (BaseShAmt.getNode() == 0)
8874 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
8875 DAG.getIntPtrConstant(0));
8879 // The shift amount is an i32.
8880 if (EltVT.bitsGT(MVT::i32))
8881 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
8882 else if (EltVT.bitsLT(MVT::i32))
8883 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
8885 // The shift amount is identical so we can do a vector shift.
8886 SDValue ValOp = N->getOperand(0);
8887 switch (N->getOpcode()) {
8889 llvm_unreachable("Unknown shift opcode!");
8892 if (VT == MVT::v2i64)
8893 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8894 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8896 if (VT == MVT::v4i32)
8897 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8898 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8900 if (VT == MVT::v8i16)
8901 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8902 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8906 if (VT == MVT::v4i32)
8907 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8908 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8910 if (VT == MVT::v8i16)
8911 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8912 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8916 if (VT == MVT::v2i64)
8917 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8918 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8920 if (VT == MVT::v4i32)
8921 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8922 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8924 if (VT == MVT::v8i16)
8925 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8926 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8933 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
8934 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
8935 const X86Subtarget *Subtarget) {
8936 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
8937 // the FP state in cases where an emms may be missing.
8938 // A preferable solution to the general problem is to figure out the right
8939 // places to insert EMMS. This qualifies as a quick hack.
8941 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
8942 StoreSDNode *St = cast<StoreSDNode>(N);
8943 EVT VT = St->getValue().getValueType();
8944 if (VT.getSizeInBits() != 64)
8947 const Function *F = DAG.getMachineFunction().getFunction();
8948 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
8949 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
8950 && Subtarget->hasSSE2();
8951 if ((VT.isVector() ||
8952 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
8953 isa<LoadSDNode>(St->getValue()) &&
8954 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
8955 St->getChain().hasOneUse() && !St->isVolatile()) {
8956 SDNode* LdVal = St->getValue().getNode();
8958 int TokenFactorIndex = -1;
8959 SmallVector<SDValue, 8> Ops;
8960 SDNode* ChainVal = St->getChain().getNode();
8961 // Must be a store of a load. We currently handle two cases: the load
8962 // is a direct child, and it's under an intervening TokenFactor. It is
8963 // possible to dig deeper under nested TokenFactors.
8964 if (ChainVal == LdVal)
8965 Ld = cast<LoadSDNode>(St->getChain());
8966 else if (St->getValue().hasOneUse() &&
8967 ChainVal->getOpcode() == ISD::TokenFactor) {
8968 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
8969 if (ChainVal->getOperand(i).getNode() == LdVal) {
8970 TokenFactorIndex = i;
8971 Ld = cast<LoadSDNode>(St->getValue());
8973 Ops.push_back(ChainVal->getOperand(i));
8977 if (!Ld || !ISD::isNormalLoad(Ld))
8980 // If this is not the MMX case, i.e. we are just turning i64 load/store
8981 // into f64 load/store, avoid the transformation if there are multiple
8982 // uses of the loaded value.
8983 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
8986 DebugLoc LdDL = Ld->getDebugLoc();
8987 DebugLoc StDL = N->getDebugLoc();
8988 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
8989 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
8991 if (Subtarget->is64Bit() || F64IsLegal) {
8992 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
8993 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
8994 Ld->getBasePtr(), Ld->getSrcValue(),
8995 Ld->getSrcValueOffset(), Ld->isVolatile(),
8996 Ld->getAlignment());
8997 SDValue NewChain = NewLd.getValue(1);
8998 if (TokenFactorIndex != -1) {
8999 Ops.push_back(NewChain);
9000 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9003 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
9004 St->getSrcValue(), St->getSrcValueOffset(),
9005 St->isVolatile(), St->getAlignment());
9008 // Otherwise, lower to two pairs of 32-bit loads / stores.
9009 SDValue LoAddr = Ld->getBasePtr();
9010 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
9011 DAG.getConstant(4, MVT::i32));
9013 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
9014 Ld->getSrcValue(), Ld->getSrcValueOffset(),
9015 Ld->isVolatile(), Ld->getAlignment());
9016 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
9017 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
9019 MinAlign(Ld->getAlignment(), 4));
9021 SDValue NewChain = LoLd.getValue(1);
9022 if (TokenFactorIndex != -1) {
9023 Ops.push_back(LoLd);
9024 Ops.push_back(HiLd);
9025 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9029 LoAddr = St->getBasePtr();
9030 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
9031 DAG.getConstant(4, MVT::i32));
9033 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
9034 St->getSrcValue(), St->getSrcValueOffset(),
9035 St->isVolatile(), St->getAlignment());
9036 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
9038 St->getSrcValueOffset() + 4,
9040 MinAlign(St->getAlignment(), 4));
9041 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
9046 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
9047 /// X86ISD::FXOR nodes.
9048 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
9049 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
9050 // F[X]OR(0.0, x) -> x
9051 // F[X]OR(x, 0.0) -> x
9052 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9053 if (C->getValueAPF().isPosZero())
9054 return N->getOperand(1);
9055 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9056 if (C->getValueAPF().isPosZero())
9057 return N->getOperand(0);
9061 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
9062 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
9063 // FAND(0.0, x) -> 0.0
9064 // FAND(x, 0.0) -> 0.0
9065 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9066 if (C->getValueAPF().isPosZero())
9067 return N->getOperand(0);
9068 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9069 if (C->getValueAPF().isPosZero())
9070 return N->getOperand(1);
9074 static SDValue PerformBTCombine(SDNode *N,
9076 TargetLowering::DAGCombinerInfo &DCI) {
9077 // BT ignores high bits in the bit index operand.
9078 SDValue Op1 = N->getOperand(1);
9079 if (Op1.hasOneUse()) {
9080 unsigned BitWidth = Op1.getValueSizeInBits();
9081 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
9082 APInt KnownZero, KnownOne;
9083 TargetLowering::TargetLoweringOpt TLO(DAG);
9084 TargetLowering &TLI = DAG.getTargetLoweringInfo();
9085 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
9086 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
9087 DCI.CommitTargetLoweringOpt(TLO);
9092 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
9093 SDValue Op = N->getOperand(0);
9094 if (Op.getOpcode() == ISD::BIT_CONVERT)
9095 Op = Op.getOperand(0);
9096 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
9097 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
9098 VT.getVectorElementType().getSizeInBits() ==
9099 OpVT.getVectorElementType().getSizeInBits()) {
9100 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
9105 // On X86 and X86-64, atomic operations are lowered to locked instructions.
9106 // Locked instructions, in turn, have implicit fence semantics (all memory
9107 // operations are flushed before issuing the locked instruction, and the
9108 // are not buffered), so we can fold away the common pattern of
9109 // fence-atomic-fence.
9110 static SDValue PerformMEMBARRIERCombine(SDNode* N, SelectionDAG &DAG) {
9111 SDValue atomic = N->getOperand(0);
9112 switch (atomic.getOpcode()) {
9113 case ISD::ATOMIC_CMP_SWAP:
9114 case ISD::ATOMIC_SWAP:
9115 case ISD::ATOMIC_LOAD_ADD:
9116 case ISD::ATOMIC_LOAD_SUB:
9117 case ISD::ATOMIC_LOAD_AND:
9118 case ISD::ATOMIC_LOAD_OR:
9119 case ISD::ATOMIC_LOAD_XOR:
9120 case ISD::ATOMIC_LOAD_NAND:
9121 case ISD::ATOMIC_LOAD_MIN:
9122 case ISD::ATOMIC_LOAD_MAX:
9123 case ISD::ATOMIC_LOAD_UMIN:
9124 case ISD::ATOMIC_LOAD_UMAX:
9130 SDValue fence = atomic.getOperand(0);
9131 if (fence.getOpcode() != ISD::MEMBARRIER)
9134 switch (atomic.getOpcode()) {
9135 case ISD::ATOMIC_CMP_SWAP:
9136 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9137 atomic.getOperand(1), atomic.getOperand(2),
9138 atomic.getOperand(3));
9139 case ISD::ATOMIC_SWAP:
9140 case ISD::ATOMIC_LOAD_ADD:
9141 case ISD::ATOMIC_LOAD_SUB:
9142 case ISD::ATOMIC_LOAD_AND:
9143 case ISD::ATOMIC_LOAD_OR:
9144 case ISD::ATOMIC_LOAD_XOR:
9145 case ISD::ATOMIC_LOAD_NAND:
9146 case ISD::ATOMIC_LOAD_MIN:
9147 case ISD::ATOMIC_LOAD_MAX:
9148 case ISD::ATOMIC_LOAD_UMIN:
9149 case ISD::ATOMIC_LOAD_UMAX:
9150 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9151 atomic.getOperand(1), atomic.getOperand(2));
9157 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
9158 DAGCombinerInfo &DCI) const {
9159 SelectionDAG &DAG = DCI.DAG;
9160 switch (N->getOpcode()) {
9162 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
9163 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
9164 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
9165 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
9168 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
9169 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
9171 case X86ISD::FOR: return PerformFORCombine(N, DAG);
9172 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
9173 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
9174 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
9175 case ISD::MEMBARRIER: return PerformMEMBARRIERCombine(N, DAG);
9181 //===----------------------------------------------------------------------===//
9182 // X86 Inline Assembly Support
9183 //===----------------------------------------------------------------------===//
9185 static bool LowerToBSwap(CallInst *CI) {
9186 // FIXME: this should verify that we are targetting a 486 or better. If not,
9187 // we will turn this bswap into something that will be lowered to logical ops
9188 // instead of emitting the bswap asm. For now, we don't support 486 or lower
9189 // so don't worry about this.
9191 // Verify this is a simple bswap.
9192 if (CI->getNumOperands() != 2 ||
9193 CI->getType() != CI->getOperand(1)->getType() ||
9194 !CI->getType()->isInteger())
9197 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9198 if (!Ty || Ty->getBitWidth() % 16 != 0)
9201 // Okay, we can do this xform, do so now.
9202 const Type *Tys[] = { Ty };
9203 Module *M = CI->getParent()->getParent()->getParent();
9204 Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
9206 Value *Op = CI->getOperand(1);
9207 Op = CallInst::Create(Int, Op, CI->getName(), CI);
9209 CI->replaceAllUsesWith(Op);
9210 CI->eraseFromParent();
9214 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
9215 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9216 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
9218 std::string AsmStr = IA->getAsmString();
9220 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
9221 std::vector<std::string> AsmPieces;
9222 SplitString(AsmStr, AsmPieces, "\n"); // ; as separator?
9224 switch (AsmPieces.size()) {
9225 default: return false;
9227 AsmStr = AsmPieces[0];
9229 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
9232 if (AsmPieces.size() == 2 &&
9233 (AsmPieces[0] == "bswap" ||
9234 AsmPieces[0] == "bswapq" ||
9235 AsmPieces[0] == "bswapl") &&
9236 (AsmPieces[1] == "$0" ||
9237 AsmPieces[1] == "${0:q}")) {
9238 // No need to check constraints, nothing other than the equivalent of
9239 // "=r,0" would be valid here.
9240 return LowerToBSwap(CI);
9242 // rorw $$8, ${0:w} --> llvm.bswap.i16
9243 if (CI->getType() == Type::getInt16Ty(CI->getContext()) &&
9244 AsmPieces.size() == 3 &&
9245 AsmPieces[0] == "rorw" &&
9246 AsmPieces[1] == "$$8," &&
9247 AsmPieces[2] == "${0:w}" &&
9248 IA->getConstraintString() == "=r,0,~{dirflag},~{fpsr},~{flags},~{cc}") {
9249 return LowerToBSwap(CI);
9253 if (CI->getType() == Type::getInt64Ty(CI->getContext()) &&
9254 Constraints.size() >= 2 &&
9255 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
9256 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
9257 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
9258 std::vector<std::string> Words;
9259 SplitString(AsmPieces[0], Words, " \t");
9260 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
9262 SplitString(AsmPieces[1], Words, " \t");
9263 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
9265 SplitString(AsmPieces[2], Words, " \t,");
9266 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
9267 Words[2] == "%edx") {
9268 return LowerToBSwap(CI);
9280 /// getConstraintType - Given a constraint letter, return the type of
9281 /// constraint it is for this target.
9282 X86TargetLowering::ConstraintType
9283 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
9284 if (Constraint.size() == 1) {
9285 switch (Constraint[0]) {
9297 return C_RegisterClass;
9305 return TargetLowering::getConstraintType(Constraint);
9308 /// LowerXConstraint - try to replace an X constraint, which matches anything,
9309 /// with another that has more specific requirements based on the type of the
9310 /// corresponding operand.
9311 const char *X86TargetLowering::
9312 LowerXConstraint(EVT ConstraintVT) const {
9313 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
9314 // 'f' like normal targets.
9315 if (ConstraintVT.isFloatingPoint()) {
9316 if (Subtarget->hasSSE2())
9318 if (Subtarget->hasSSE1())
9322 return TargetLowering::LowerXConstraint(ConstraintVT);
9325 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9326 /// vector. If it is invalid, don't add anything to Ops.
9327 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9330 std::vector<SDValue>&Ops,
9331 SelectionDAG &DAG) const {
9332 SDValue Result(0, 0);
9334 switch (Constraint) {
9337 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9338 if (C->getZExtValue() <= 31) {
9339 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9345 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9346 if (C->getZExtValue() <= 63) {
9347 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9353 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9354 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
9355 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9361 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9362 if (C->getZExtValue() <= 255) {
9363 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9369 // 32-bit signed value
9370 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9371 const ConstantInt *CI = C->getConstantIntValue();
9372 if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
9373 C->getSExtValue())) {
9374 // Widen to 64 bits here to get it sign extended.
9375 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
9378 // FIXME gcc accepts some relocatable values here too, but only in certain
9379 // memory models; it's complicated.
9384 // 32-bit unsigned value
9385 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9386 const ConstantInt *CI = C->getConstantIntValue();
9387 if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
9388 C->getZExtValue())) {
9389 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9393 // FIXME gcc accepts some relocatable values here too, but only in certain
9394 // memory models; it's complicated.
9398 // Literal immediates are always ok.
9399 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
9400 // Widen to 64 bits here to get it sign extended.
9401 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
9405 // If we are in non-pic codegen mode, we allow the address of a global (with
9406 // an optional displacement) to be used with 'i'.
9407 GlobalAddressSDNode *GA = 0;
9410 // Match either (GA), (GA+C), (GA+C1+C2), etc.
9412 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
9413 Offset += GA->getOffset();
9415 } else if (Op.getOpcode() == ISD::ADD) {
9416 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9417 Offset += C->getZExtValue();
9418 Op = Op.getOperand(0);
9421 } else if (Op.getOpcode() == ISD::SUB) {
9422 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9423 Offset += -C->getZExtValue();
9424 Op = Op.getOperand(0);
9429 // Otherwise, this isn't something we can handle, reject it.
9433 GlobalValue *GV = GA->getGlobal();
9434 // If we require an extra load to get this address, as in PIC mode, we
9436 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
9437 getTargetMachine())))
9441 Op = LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
9443 Op = DAG.getTargetGlobalAddress(GV, GA->getValueType(0), Offset);
9449 if (Result.getNode()) {
9450 Ops.push_back(Result);
9453 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
9457 std::vector<unsigned> X86TargetLowering::
9458 getRegClassForInlineAsmConstraint(const std::string &Constraint,
9460 if (Constraint.size() == 1) {
9461 // FIXME: not handling fp-stack yet!
9462 switch (Constraint[0]) { // GCC X86 Constraint Letters
9463 default: break; // Unknown constraint letter
9464 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
9465 if (Subtarget->is64Bit()) {
9467 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
9468 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
9469 X86::R10D,X86::R11D,X86::R12D,
9470 X86::R13D,X86::R14D,X86::R15D,
9471 X86::EBP, X86::ESP, 0);
9472 else if (VT == MVT::i16)
9473 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
9474 X86::SI, X86::DI, X86::R8W,X86::R9W,
9475 X86::R10W,X86::R11W,X86::R12W,
9476 X86::R13W,X86::R14W,X86::R15W,
9477 X86::BP, X86::SP, 0);
9478 else if (VT == MVT::i8)
9479 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
9480 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
9481 X86::R10B,X86::R11B,X86::R12B,
9482 X86::R13B,X86::R14B,X86::R15B,
9483 X86::BPL, X86::SPL, 0);
9485 else if (VT == MVT::i64)
9486 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
9487 X86::RSI, X86::RDI, X86::R8, X86::R9,
9488 X86::R10, X86::R11, X86::R12,
9489 X86::R13, X86::R14, X86::R15,
9490 X86::RBP, X86::RSP, 0);
9494 // 32-bit fallthrough
9497 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
9498 else if (VT == MVT::i16)
9499 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
9500 else if (VT == MVT::i8)
9501 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
9502 else if (VT == MVT::i64)
9503 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
9508 return std::vector<unsigned>();
9511 std::pair<unsigned, const TargetRegisterClass*>
9512 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9514 // First, see if this is a constraint that directly corresponds to an LLVM
9516 if (Constraint.size() == 1) {
9517 // GCC Constraint Letters
9518 switch (Constraint[0]) {
9520 case 'r': // GENERAL_REGS
9521 case 'l': // INDEX_REGS
9523 return std::make_pair(0U, X86::GR8RegisterClass);
9525 return std::make_pair(0U, X86::GR16RegisterClass);
9526 if (VT == MVT::i32 || !Subtarget->is64Bit())
9527 return std::make_pair(0U, X86::GR32RegisterClass);
9528 return std::make_pair(0U, X86::GR64RegisterClass);
9529 case 'R': // LEGACY_REGS
9531 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
9533 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
9534 if (VT == MVT::i32 || !Subtarget->is64Bit())
9535 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
9536 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
9537 case 'f': // FP Stack registers.
9538 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
9539 // value to the correct fpstack register class.
9540 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
9541 return std::make_pair(0U, X86::RFP32RegisterClass);
9542 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
9543 return std::make_pair(0U, X86::RFP64RegisterClass);
9544 return std::make_pair(0U, X86::RFP80RegisterClass);
9545 case 'y': // MMX_REGS if MMX allowed.
9546 if (!Subtarget->hasMMX()) break;
9547 return std::make_pair(0U, X86::VR64RegisterClass);
9548 case 'Y': // SSE_REGS if SSE2 allowed
9549 if (!Subtarget->hasSSE2()) break;
9551 case 'x': // SSE_REGS if SSE1 allowed
9552 if (!Subtarget->hasSSE1()) break;
9554 switch (VT.getSimpleVT().SimpleTy) {
9556 // Scalar SSE types.
9559 return std::make_pair(0U, X86::FR32RegisterClass);
9562 return std::make_pair(0U, X86::FR64RegisterClass);
9570 return std::make_pair(0U, X86::VR128RegisterClass);
9576 // Use the default implementation in TargetLowering to convert the register
9577 // constraint into a member of a register class.
9578 std::pair<unsigned, const TargetRegisterClass*> Res;
9579 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9581 // Not found as a standard register?
9582 if (Res.second == 0) {
9583 // Map st(0) -> st(7) -> ST0
9584 if (Constraint.size() == 7 && Constraint[0] == '{' &&
9585 tolower(Constraint[1]) == 's' &&
9586 tolower(Constraint[2]) == 't' &&
9587 Constraint[3] == '(' &&
9588 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
9589 Constraint[5] == ')' &&
9590 Constraint[6] == '}') {
9592 Res.first = X86::ST0+Constraint[4]-'0';
9593 Res.second = X86::RFP80RegisterClass;
9597 // GCC allows "st(0)" to be called just plain "st".
9598 if (StringsEqualNoCase("{st}", Constraint)) {
9599 Res.first = X86::ST0;
9600 Res.second = X86::RFP80RegisterClass;
9605 if (StringsEqualNoCase("{flags}", Constraint)) {
9606 Res.first = X86::EFLAGS;
9607 Res.second = X86::CCRRegisterClass;
9611 // 'A' means EAX + EDX.
9612 if (Constraint == "A") {
9613 Res.first = X86::EAX;
9614 Res.second = X86::GR32_ADRegisterClass;
9620 // Otherwise, check to see if this is a register class of the wrong value
9621 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
9622 // turn into {ax},{dx}.
9623 if (Res.second->hasType(VT))
9624 return Res; // Correct type already, nothing to do.
9626 // All of the single-register GCC register classes map their values onto
9627 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
9628 // really want an 8-bit or 32-bit register, map to the appropriate register
9629 // class and return the appropriate register.
9630 if (Res.second == X86::GR16RegisterClass) {
9631 if (VT == MVT::i8) {
9632 unsigned DestReg = 0;
9633 switch (Res.first) {
9635 case X86::AX: DestReg = X86::AL; break;
9636 case X86::DX: DestReg = X86::DL; break;
9637 case X86::CX: DestReg = X86::CL; break;
9638 case X86::BX: DestReg = X86::BL; break;
9641 Res.first = DestReg;
9642 Res.second = X86::GR8RegisterClass;
9644 } else if (VT == MVT::i32) {
9645 unsigned DestReg = 0;
9646 switch (Res.first) {
9648 case X86::AX: DestReg = X86::EAX; break;
9649 case X86::DX: DestReg = X86::EDX; break;
9650 case X86::CX: DestReg = X86::ECX; break;
9651 case X86::BX: DestReg = X86::EBX; break;
9652 case X86::SI: DestReg = X86::ESI; break;
9653 case X86::DI: DestReg = X86::EDI; break;
9654 case X86::BP: DestReg = X86::EBP; break;
9655 case X86::SP: DestReg = X86::ESP; break;
9658 Res.first = DestReg;
9659 Res.second = X86::GR32RegisterClass;
9661 } else if (VT == MVT::i64) {
9662 unsigned DestReg = 0;
9663 switch (Res.first) {
9665 case X86::AX: DestReg = X86::RAX; break;
9666 case X86::DX: DestReg = X86::RDX; break;
9667 case X86::CX: DestReg = X86::RCX; break;
9668 case X86::BX: DestReg = X86::RBX; break;
9669 case X86::SI: DestReg = X86::RSI; break;
9670 case X86::DI: DestReg = X86::RDI; break;
9671 case X86::BP: DestReg = X86::RBP; break;
9672 case X86::SP: DestReg = X86::RSP; break;
9675 Res.first = DestReg;
9676 Res.second = X86::GR64RegisterClass;
9679 } else if (Res.second == X86::FR32RegisterClass ||
9680 Res.second == X86::FR64RegisterClass ||
9681 Res.second == X86::VR128RegisterClass) {
9682 // Handle references to XMM physical registers that got mapped into the
9683 // wrong class. This can happen with constraints like {xmm0} where the
9684 // target independent register mapper will just pick the first match it can
9685 // find, ignoring the required type.
9687 Res.second = X86::FR32RegisterClass;
9688 else if (VT == MVT::f64)
9689 Res.second = X86::FR64RegisterClass;
9690 else if (X86::VR128RegisterClass->hasType(VT))
9691 Res.second = X86::VR128RegisterClass;
9697 //===----------------------------------------------------------------------===//
9698 // X86 Widen vector type
9699 //===----------------------------------------------------------------------===//
9701 /// getWidenVectorType: given a vector type, returns the type to widen
9702 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
9703 /// If there is no vector type that we want to widen to, returns MVT::Other
9704 /// When and where to widen is target dependent based on the cost of
9705 /// scalarizing vs using the wider vector type.
9707 EVT X86TargetLowering::getWidenVectorType(EVT VT) const {
9708 assert(VT.isVector());
9709 if (isTypeLegal(VT))
9712 // TODO: In computeRegisterProperty, we can compute the list of legal vector
9713 // type based on element type. This would speed up our search (though
9714 // it may not be worth it since the size of the list is relatively
9716 EVT EltVT = VT.getVectorElementType();
9717 unsigned NElts = VT.getVectorNumElements();
9719 // On X86, it make sense to widen any vector wider than 1
9723 for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
9724 nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
9725 EVT SVT = (MVT::SimpleValueType)nVT;
9727 if (isTypeLegal(SVT) &&
9728 SVT.getVectorElementType() == EltVT &&
9729 SVT.getVectorNumElements() > NElts)