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 // FIXME - use subtarget debug flags
377 if (!Subtarget->isTargetDarwin() &&
378 !Subtarget->isTargetELF() &&
379 !Subtarget->isTargetCygMing()) {
380 setOperationAction(ISD::DBG_LABEL, MVT::Other, Expand);
381 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
384 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
385 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
386 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
387 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
388 if (Subtarget->is64Bit()) {
389 setExceptionPointerRegister(X86::RAX);
390 setExceptionSelectorRegister(X86::RDX);
392 setExceptionPointerRegister(X86::EAX);
393 setExceptionSelectorRegister(X86::EDX);
395 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
396 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
398 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
400 setOperationAction(ISD::TRAP, MVT::Other, Legal);
402 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
403 setOperationAction(ISD::VASTART , MVT::Other, Custom);
404 setOperationAction(ISD::VAEND , MVT::Other, Expand);
405 if (Subtarget->is64Bit()) {
406 setOperationAction(ISD::VAARG , MVT::Other, Custom);
407 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
409 setOperationAction(ISD::VAARG , MVT::Other, Expand);
410 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
413 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
414 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
415 if (Subtarget->is64Bit())
416 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
417 if (Subtarget->isTargetCygMing())
418 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
420 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
422 if (!UseSoftFloat && X86ScalarSSEf64) {
423 // f32 and f64 use SSE.
424 // Set up the FP register classes.
425 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
426 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
428 // Use ANDPD to simulate FABS.
429 setOperationAction(ISD::FABS , MVT::f64, Custom);
430 setOperationAction(ISD::FABS , MVT::f32, Custom);
432 // Use XORP to simulate FNEG.
433 setOperationAction(ISD::FNEG , MVT::f64, Custom);
434 setOperationAction(ISD::FNEG , MVT::f32, Custom);
436 // Use ANDPD and ORPD to simulate FCOPYSIGN.
437 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
438 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
440 // We don't support sin/cos/fmod
441 setOperationAction(ISD::FSIN , MVT::f64, Expand);
442 setOperationAction(ISD::FCOS , MVT::f64, Expand);
443 setOperationAction(ISD::FSIN , MVT::f32, Expand);
444 setOperationAction(ISD::FCOS , MVT::f32, Expand);
446 // Expand FP immediates into loads from the stack, except for the special
448 addLegalFPImmediate(APFloat(+0.0)); // xorpd
449 addLegalFPImmediate(APFloat(+0.0f)); // xorps
450 } else if (!UseSoftFloat && X86ScalarSSEf32) {
451 // Use SSE for f32, x87 for f64.
452 // Set up the FP register classes.
453 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
454 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
456 // Use ANDPS to simulate FABS.
457 setOperationAction(ISD::FABS , MVT::f32, Custom);
459 // Use XORP to simulate FNEG.
460 setOperationAction(ISD::FNEG , MVT::f32, Custom);
462 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
464 // Use ANDPS and ORPS to simulate FCOPYSIGN.
465 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
466 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
468 // We don't support sin/cos/fmod
469 setOperationAction(ISD::FSIN , MVT::f32, Expand);
470 setOperationAction(ISD::FCOS , MVT::f32, Expand);
472 // Special cases we handle for FP constants.
473 addLegalFPImmediate(APFloat(+0.0f)); // xorps
474 addLegalFPImmediate(APFloat(+0.0)); // FLD0
475 addLegalFPImmediate(APFloat(+1.0)); // FLD1
476 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
477 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
480 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
481 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
483 } else if (!UseSoftFloat) {
484 // f32 and f64 in x87.
485 // Set up the FP register classes.
486 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
487 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
489 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
490 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
491 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
492 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
495 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
496 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
498 addLegalFPImmediate(APFloat(+0.0)); // FLD0
499 addLegalFPImmediate(APFloat(+1.0)); // FLD1
500 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
501 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
502 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
503 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
504 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
505 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
508 // Long double always uses X87.
510 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
511 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
512 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
515 APFloat TmpFlt(+0.0);
516 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
518 addLegalFPImmediate(TmpFlt); // FLD0
520 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
521 APFloat TmpFlt2(+1.0);
522 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
524 addLegalFPImmediate(TmpFlt2); // FLD1
525 TmpFlt2.changeSign();
526 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
530 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
531 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
535 // Always use a library call for pow.
536 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
537 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
538 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
540 setOperationAction(ISD::FLOG, MVT::f80, Expand);
541 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
542 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
543 setOperationAction(ISD::FEXP, MVT::f80, Expand);
544 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
546 // First set operation action for all vector types to either promote
547 // (for widening) or expand (for scalarization). Then we will selectively
548 // turn on ones that can be effectively codegen'd.
549 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
550 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
551 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
552 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
553 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
554 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
555 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
556 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
557 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
558 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
559 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
560 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
561 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
562 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
563 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
564 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
565 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
566 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
567 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
568 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
569 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
570 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
571 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
572 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
573 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
574 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
575 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
576 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
577 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
578 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
579 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
580 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
581 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
582 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
583 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
584 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
585 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
586 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
587 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
588 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
589 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
590 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
591 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
592 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
593 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
594 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
595 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
596 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
597 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
598 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
601 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
602 // with -msoft-float, disable use of MMX as well.
603 if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
604 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
605 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
606 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
607 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
608 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
610 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
611 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
612 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
613 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
615 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
616 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
617 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
618 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
620 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
621 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
623 setOperationAction(ISD::AND, MVT::v8i8, Promote);
624 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
625 setOperationAction(ISD::AND, MVT::v4i16, Promote);
626 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
627 setOperationAction(ISD::AND, MVT::v2i32, Promote);
628 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
629 setOperationAction(ISD::AND, MVT::v1i64, Legal);
631 setOperationAction(ISD::OR, MVT::v8i8, Promote);
632 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
633 setOperationAction(ISD::OR, MVT::v4i16, Promote);
634 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
635 setOperationAction(ISD::OR, MVT::v2i32, Promote);
636 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
637 setOperationAction(ISD::OR, MVT::v1i64, Legal);
639 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
640 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
641 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
642 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
643 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
644 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
645 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
647 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
648 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
649 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
650 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
651 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
652 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
653 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
654 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
655 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
657 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
658 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
659 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
660 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
661 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
663 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
664 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
665 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
666 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
668 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
669 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
670 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
671 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
673 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
675 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
676 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Expand);
677 setOperationAction(ISD::SELECT, MVT::v8i8, Promote);
678 setOperationAction(ISD::SELECT, MVT::v4i16, Promote);
679 setOperationAction(ISD::SELECT, MVT::v2i32, Promote);
680 setOperationAction(ISD::SELECT, MVT::v1i64, Custom);
681 setOperationAction(ISD::VSETCC, MVT::v8i8, Custom);
682 setOperationAction(ISD::VSETCC, MVT::v4i16, Custom);
683 setOperationAction(ISD::VSETCC, MVT::v2i32, Custom);
686 if (!UseSoftFloat && Subtarget->hasSSE1()) {
687 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
689 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
690 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
691 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
692 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
693 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
694 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
695 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
696 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
697 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
698 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
699 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
700 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
703 if (!UseSoftFloat && Subtarget->hasSSE2()) {
704 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
706 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
707 // registers cannot be used even for integer operations.
708 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
709 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
710 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
711 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
713 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
714 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
715 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
716 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
717 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
718 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
719 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
720 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
721 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
722 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
723 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
724 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
725 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
726 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
727 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
728 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
730 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
731 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
732 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
733 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
735 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
736 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
737 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
738 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
739 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
741 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
742 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
743 EVT VT = (MVT::SimpleValueType)i;
744 // Do not attempt to custom lower non-power-of-2 vectors
745 if (!isPowerOf2_32(VT.getVectorNumElements()))
747 // Do not attempt to custom lower non-128-bit vectors
748 if (!VT.is128BitVector())
750 setOperationAction(ISD::BUILD_VECTOR,
751 VT.getSimpleVT().SimpleTy, Custom);
752 setOperationAction(ISD::VECTOR_SHUFFLE,
753 VT.getSimpleVT().SimpleTy, Custom);
754 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
755 VT.getSimpleVT().SimpleTy, Custom);
758 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
759 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
760 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
761 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
762 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
763 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
765 if (Subtarget->is64Bit()) {
766 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
767 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
770 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
771 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
772 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
775 // Do not attempt to promote non-128-bit vectors
776 if (!VT.is128BitVector()) {
779 setOperationAction(ISD::AND, SVT, Promote);
780 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
781 setOperationAction(ISD::OR, SVT, Promote);
782 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
783 setOperationAction(ISD::XOR, SVT, Promote);
784 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
785 setOperationAction(ISD::LOAD, SVT, Promote);
786 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
787 setOperationAction(ISD::SELECT, SVT, Promote);
788 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
791 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
793 // Custom lower v2i64 and v2f64 selects.
794 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
795 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
796 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
797 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
799 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
800 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
801 if (!DisableMMX && Subtarget->hasMMX()) {
802 setOperationAction(ISD::FP_TO_SINT, MVT::v2i32, Custom);
803 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
807 if (Subtarget->hasSSE41()) {
808 // FIXME: Do we need to handle scalar-to-vector here?
809 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
811 // i8 and i16 vectors are custom , because the source register and source
812 // source memory operand types are not the same width. f32 vectors are
813 // custom since the immediate controlling the insert encodes additional
815 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
816 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
817 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
818 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
820 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
821 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
822 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
823 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
825 if (Subtarget->is64Bit()) {
826 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
827 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
831 if (Subtarget->hasSSE42()) {
832 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
835 if (!UseSoftFloat && Subtarget->hasAVX()) {
836 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
837 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
838 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
839 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
841 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
842 setOperationAction(ISD::LOAD, MVT::v8i32, Legal);
843 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
844 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
845 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
846 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
847 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
848 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
849 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
850 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
851 //setOperationAction(ISD::BUILD_VECTOR, MVT::v8f32, Custom);
852 //setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Custom);
853 //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
854 //setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
855 //setOperationAction(ISD::VSETCC, MVT::v8f32, Custom);
857 // Operations to consider commented out -v16i16 v32i8
858 //setOperationAction(ISD::ADD, MVT::v16i16, Legal);
859 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
860 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
861 //setOperationAction(ISD::SUB, MVT::v32i8, Legal);
862 //setOperationAction(ISD::SUB, MVT::v16i16, Legal);
863 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
864 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
865 //setOperationAction(ISD::MUL, MVT::v16i16, Legal);
866 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
867 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
868 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
869 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
870 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
871 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
873 setOperationAction(ISD::VSETCC, MVT::v4f64, Custom);
874 // setOperationAction(ISD::VSETCC, MVT::v32i8, Custom);
875 // setOperationAction(ISD::VSETCC, MVT::v16i16, Custom);
876 setOperationAction(ISD::VSETCC, MVT::v8i32, Custom);
878 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v32i8, Custom);
879 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i16, Custom);
880 // setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i16, Custom);
881 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i32, Custom);
882 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8f32, Custom);
884 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
885 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i64, Custom);
886 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f64, Custom);
887 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i64, Custom);
888 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f64, Custom);
889 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
892 // Not sure we want to do this since there are no 256-bit integer
895 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
896 // This includes 256-bit vectors
897 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
898 EVT VT = (MVT::SimpleValueType)i;
900 // Do not attempt to custom lower non-power-of-2 vectors
901 if (!isPowerOf2_32(VT.getVectorNumElements()))
904 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
905 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
906 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
909 if (Subtarget->is64Bit()) {
910 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i64, Custom);
911 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
916 // Not sure we want to do this since there are no 256-bit integer
919 // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
920 // Including 256-bit vectors
921 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
922 EVT VT = (MVT::SimpleValueType)i;
924 if (!VT.is256BitVector()) {
927 setOperationAction(ISD::AND, VT, Promote);
928 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
929 setOperationAction(ISD::OR, VT, Promote);
930 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
931 setOperationAction(ISD::XOR, VT, Promote);
932 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
933 setOperationAction(ISD::LOAD, VT, Promote);
934 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
935 setOperationAction(ISD::SELECT, VT, Promote);
936 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
939 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
943 // We want to custom lower some of our intrinsics.
944 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
946 // Add/Sub/Mul with overflow operations are custom lowered.
947 setOperationAction(ISD::SADDO, MVT::i32, Custom);
948 setOperationAction(ISD::SADDO, MVT::i64, Custom);
949 setOperationAction(ISD::UADDO, MVT::i32, Custom);
950 setOperationAction(ISD::UADDO, MVT::i64, Custom);
951 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
952 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
953 setOperationAction(ISD::USUBO, MVT::i32, Custom);
954 setOperationAction(ISD::USUBO, MVT::i64, Custom);
955 setOperationAction(ISD::SMULO, MVT::i32, Custom);
956 setOperationAction(ISD::SMULO, MVT::i64, Custom);
958 if (!Subtarget->is64Bit()) {
959 // These libcalls are not available in 32-bit.
960 setLibcallName(RTLIB::SHL_I128, 0);
961 setLibcallName(RTLIB::SRL_I128, 0);
962 setLibcallName(RTLIB::SRA_I128, 0);
965 // We have target-specific dag combine patterns for the following nodes:
966 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
967 setTargetDAGCombine(ISD::BUILD_VECTOR);
968 setTargetDAGCombine(ISD::SELECT);
969 setTargetDAGCombine(ISD::SHL);
970 setTargetDAGCombine(ISD::SRA);
971 setTargetDAGCombine(ISD::SRL);
972 setTargetDAGCombine(ISD::STORE);
973 setTargetDAGCombine(ISD::MEMBARRIER);
974 if (Subtarget->is64Bit())
975 setTargetDAGCombine(ISD::MUL);
977 computeRegisterProperties();
979 // FIXME: These should be based on subtarget info. Plus, the values should
980 // be smaller when we are in optimizing for size mode.
981 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
982 maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
983 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
984 setPrefLoopAlignment(16);
985 benefitFromCodePlacementOpt = true;
989 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
994 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
995 /// the desired ByVal argument alignment.
996 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
999 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1000 if (VTy->getBitWidth() == 128)
1002 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1003 unsigned EltAlign = 0;
1004 getMaxByValAlign(ATy->getElementType(), EltAlign);
1005 if (EltAlign > MaxAlign)
1006 MaxAlign = EltAlign;
1007 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1008 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1009 unsigned EltAlign = 0;
1010 getMaxByValAlign(STy->getElementType(i), EltAlign);
1011 if (EltAlign > MaxAlign)
1012 MaxAlign = EltAlign;
1020 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1021 /// function arguments in the caller parameter area. For X86, aggregates
1022 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1023 /// are at 4-byte boundaries.
1024 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1025 if (Subtarget->is64Bit()) {
1026 // Max of 8 and alignment of type.
1027 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1034 if (Subtarget->hasSSE1())
1035 getMaxByValAlign(Ty, Align);
1039 /// getOptimalMemOpType - Returns the target specific optimal type for load
1040 /// and store operations as a result of memset, memcpy, and memmove
1041 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
1044 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
1045 bool isSrcConst, bool isSrcStr,
1046 SelectionDAG &DAG) const {
1047 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1048 // linux. This is because the stack realignment code can't handle certain
1049 // cases like PR2962. This should be removed when PR2962 is fixed.
1050 const Function *F = DAG.getMachineFunction().getFunction();
1051 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
1052 if (!NoImplicitFloatOps && Subtarget->getStackAlignment() >= 16) {
1053 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
1055 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
1058 if (Subtarget->is64Bit() && Size >= 8)
1063 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1065 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1066 SelectionDAG &DAG) const {
1067 if (usesGlobalOffsetTable())
1068 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy());
1069 if (!Subtarget->is64Bit())
1070 // This doesn't have DebugLoc associated with it, but is not really the
1071 // same as a Register.
1072 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc::getUnknownLoc(),
1077 /// getFunctionAlignment - Return the Log2 alignment of this function.
1078 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1079 return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1082 //===----------------------------------------------------------------------===//
1083 // Return Value Calling Convention Implementation
1084 //===----------------------------------------------------------------------===//
1086 #include "X86GenCallingConv.inc"
1089 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1090 const SmallVectorImpl<EVT> &OutTys,
1091 const SmallVectorImpl<ISD::ArgFlagsTy> &ArgsFlags,
1092 SelectionDAG &DAG) {
1093 SmallVector<CCValAssign, 16> RVLocs;
1094 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1095 RVLocs, *DAG.getContext());
1096 return CCInfo.CheckReturn(OutTys, ArgsFlags, RetCC_X86);
1100 X86TargetLowering::LowerReturn(SDValue Chain,
1101 CallingConv::ID CallConv, bool isVarArg,
1102 const SmallVectorImpl<ISD::OutputArg> &Outs,
1103 DebugLoc dl, SelectionDAG &DAG) {
1105 SmallVector<CCValAssign, 16> RVLocs;
1106 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1107 RVLocs, *DAG.getContext());
1108 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1110 // If this is the first return lowered for this function, add the regs to the
1111 // liveout set for the function.
1112 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1113 for (unsigned i = 0; i != RVLocs.size(); ++i)
1114 if (RVLocs[i].isRegLoc())
1115 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1120 SmallVector<SDValue, 6> RetOps;
1121 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1122 // Operand #1 = Bytes To Pop
1123 RetOps.push_back(DAG.getTargetConstant(getBytesToPopOnReturn(), MVT::i16));
1125 // Copy the result values into the output registers.
1126 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1127 CCValAssign &VA = RVLocs[i];
1128 assert(VA.isRegLoc() && "Can only return in registers!");
1129 SDValue ValToCopy = Outs[i].Val;
1131 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1132 // the RET instruction and handled by the FP Stackifier.
1133 if (VA.getLocReg() == X86::ST0 ||
1134 VA.getLocReg() == X86::ST1) {
1135 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1136 // change the value to the FP stack register class.
1137 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1138 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1139 RetOps.push_back(ValToCopy);
1140 // Don't emit a copytoreg.
1144 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1145 // which is returned in RAX / RDX.
1146 if (Subtarget->is64Bit()) {
1147 EVT ValVT = ValToCopy.getValueType();
1148 if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1149 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1150 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1151 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1155 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1156 Flag = Chain.getValue(1);
1159 // The x86-64 ABI for returning structs by value requires that we copy
1160 // the sret argument into %rax for the return. We saved the argument into
1161 // a virtual register in the entry block, so now we copy the value out
1163 if (Subtarget->is64Bit() &&
1164 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1165 MachineFunction &MF = DAG.getMachineFunction();
1166 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1167 unsigned Reg = FuncInfo->getSRetReturnReg();
1169 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1170 FuncInfo->setSRetReturnReg(Reg);
1172 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1174 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1175 Flag = Chain.getValue(1);
1177 // RAX now acts like a return value.
1178 MF.getRegInfo().addLiveOut(X86::RAX);
1181 RetOps[0] = Chain; // Update chain.
1183 // Add the flag if we have it.
1185 RetOps.push_back(Flag);
1187 return DAG.getNode(X86ISD::RET_FLAG, dl,
1188 MVT::Other, &RetOps[0], RetOps.size());
1191 /// LowerCallResult - Lower the result values of a call into the
1192 /// appropriate copies out of appropriate physical registers.
1195 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1196 CallingConv::ID CallConv, bool isVarArg,
1197 const SmallVectorImpl<ISD::InputArg> &Ins,
1198 DebugLoc dl, SelectionDAG &DAG,
1199 SmallVectorImpl<SDValue> &InVals) {
1201 // Assign locations to each value returned by this call.
1202 SmallVector<CCValAssign, 16> RVLocs;
1203 bool Is64Bit = Subtarget->is64Bit();
1204 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1205 RVLocs, *DAG.getContext());
1206 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1208 // Copy all of the result registers out of their specified physreg.
1209 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1210 CCValAssign &VA = RVLocs[i];
1211 EVT CopyVT = VA.getValVT();
1213 // If this is x86-64, and we disabled SSE, we can't return FP values
1214 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1215 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1216 llvm_report_error("SSE register return with SSE disabled");
1219 // If this is a call to a function that returns an fp value on the floating
1220 // point stack, but where we prefer to use the value in xmm registers, copy
1221 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1222 if ((VA.getLocReg() == X86::ST0 ||
1223 VA.getLocReg() == X86::ST1) &&
1224 isScalarFPTypeInSSEReg(VA.getValVT())) {
1229 if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1230 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1231 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1232 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1233 MVT::v2i64, InFlag).getValue(1);
1234 Val = Chain.getValue(0);
1235 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1236 Val, DAG.getConstant(0, MVT::i64));
1238 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1239 MVT::i64, InFlag).getValue(1);
1240 Val = Chain.getValue(0);
1242 Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1244 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1245 CopyVT, InFlag).getValue(1);
1246 Val = Chain.getValue(0);
1248 InFlag = Chain.getValue(2);
1250 if (CopyVT != VA.getValVT()) {
1251 // Round the F80 the right size, which also moves to the appropriate xmm
1253 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1254 // This truncation won't change the value.
1255 DAG.getIntPtrConstant(1));
1258 InVals.push_back(Val);
1265 //===----------------------------------------------------------------------===//
1266 // C & StdCall & Fast Calling Convention implementation
1267 //===----------------------------------------------------------------------===//
1268 // StdCall calling convention seems to be standard for many Windows' API
1269 // routines and around. It differs from C calling convention just a little:
1270 // callee should clean up the stack, not caller. Symbols should be also
1271 // decorated in some fancy way :) It doesn't support any vector arguments.
1272 // For info on fast calling convention see Fast Calling Convention (tail call)
1273 // implementation LowerX86_32FastCCCallTo.
1275 /// CallIsStructReturn - Determines whether a call uses struct return
1277 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1281 return Outs[0].Flags.isSRet();
1284 /// ArgsAreStructReturn - Determines whether a function uses struct
1285 /// return semantics.
1287 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1291 return Ins[0].Flags.isSRet();
1294 /// IsCalleePop - Determines whether the callee is required to pop its
1295 /// own arguments. Callee pop is necessary to support tail calls.
1296 bool X86TargetLowering::IsCalleePop(bool IsVarArg, CallingConv::ID CallingConv){
1300 switch (CallingConv) {
1303 case CallingConv::X86_StdCall:
1304 return !Subtarget->is64Bit();
1305 case CallingConv::X86_FastCall:
1306 return !Subtarget->is64Bit();
1307 case CallingConv::Fast:
1308 return PerformTailCallOpt;
1312 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1313 /// given CallingConvention value.
1314 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1315 if (Subtarget->is64Bit()) {
1316 if (Subtarget->isTargetWin64())
1317 return CC_X86_Win64_C;
1322 if (CC == CallingConv::X86_FastCall)
1323 return CC_X86_32_FastCall;
1324 else if (CC == CallingConv::Fast)
1325 return CC_X86_32_FastCC;
1330 /// NameDecorationForCallConv - Selects the appropriate decoration to
1331 /// apply to a MachineFunction containing a given calling convention.
1333 X86TargetLowering::NameDecorationForCallConv(CallingConv::ID CallConv) {
1334 if (CallConv == CallingConv::X86_FastCall)
1336 else if (CallConv == CallingConv::X86_StdCall)
1342 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1343 /// by "Src" to address "Dst" with size and alignment information specified by
1344 /// the specific parameter attribute. The copy will be passed as a byval
1345 /// function parameter.
1347 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1348 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1350 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1351 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1352 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1356 X86TargetLowering::LowerMemArgument(SDValue Chain,
1357 CallingConv::ID CallConv,
1358 const SmallVectorImpl<ISD::InputArg> &Ins,
1359 DebugLoc dl, SelectionDAG &DAG,
1360 const CCValAssign &VA,
1361 MachineFrameInfo *MFI,
1364 // Create the nodes corresponding to a load from this parameter slot.
1365 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1366 bool AlwaysUseMutable = (CallConv==CallingConv::Fast) && PerformTailCallOpt;
1367 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1370 // If value is passed by pointer we have address passed instead of the value
1372 if (VA.getLocInfo() == CCValAssign::Indirect)
1373 ValVT = VA.getLocVT();
1375 ValVT = VA.getValVT();
1377 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1378 // changed with more analysis.
1379 // In case of tail call optimization mark all arguments mutable. Since they
1380 // could be overwritten by lowering of arguments in case of a tail call.
1381 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1382 VA.getLocMemOffset(), isImmutable, false);
1383 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1384 if (Flags.isByVal())
1386 return DAG.getLoad(ValVT, dl, Chain, FIN,
1387 PseudoSourceValue::getFixedStack(FI), 0);
1391 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1392 CallingConv::ID CallConv,
1394 const SmallVectorImpl<ISD::InputArg> &Ins,
1397 SmallVectorImpl<SDValue> &InVals) {
1399 MachineFunction &MF = DAG.getMachineFunction();
1400 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1402 const Function* Fn = MF.getFunction();
1403 if (Fn->hasExternalLinkage() &&
1404 Subtarget->isTargetCygMing() &&
1405 Fn->getName() == "main")
1406 FuncInfo->setForceFramePointer(true);
1408 // Decorate the function name.
1409 FuncInfo->setDecorationStyle(NameDecorationForCallConv(CallConv));
1411 MachineFrameInfo *MFI = MF.getFrameInfo();
1412 bool Is64Bit = Subtarget->is64Bit();
1413 bool IsWin64 = Subtarget->isTargetWin64();
1415 assert(!(isVarArg && CallConv == CallingConv::Fast) &&
1416 "Var args not supported with calling convention fastcc");
1418 // Assign locations to all of the incoming arguments.
1419 SmallVector<CCValAssign, 16> ArgLocs;
1420 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1421 ArgLocs, *DAG.getContext());
1422 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1424 unsigned LastVal = ~0U;
1426 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1427 CCValAssign &VA = ArgLocs[i];
1428 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1430 assert(VA.getValNo() != LastVal &&
1431 "Don't support value assigned to multiple locs yet");
1432 LastVal = VA.getValNo();
1434 if (VA.isRegLoc()) {
1435 EVT RegVT = VA.getLocVT();
1436 TargetRegisterClass *RC = NULL;
1437 if (RegVT == MVT::i32)
1438 RC = X86::GR32RegisterClass;
1439 else if (Is64Bit && RegVT == MVT::i64)
1440 RC = X86::GR64RegisterClass;
1441 else if (RegVT == MVT::f32)
1442 RC = X86::FR32RegisterClass;
1443 else if (RegVT == MVT::f64)
1444 RC = X86::FR64RegisterClass;
1445 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1446 RC = X86::VR128RegisterClass;
1447 else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1448 RC = X86::VR64RegisterClass;
1450 llvm_unreachable("Unknown argument type!");
1452 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1453 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1455 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1456 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1458 if (VA.getLocInfo() == CCValAssign::SExt)
1459 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1460 DAG.getValueType(VA.getValVT()));
1461 else if (VA.getLocInfo() == CCValAssign::ZExt)
1462 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1463 DAG.getValueType(VA.getValVT()));
1464 else if (VA.getLocInfo() == CCValAssign::BCvt)
1465 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1467 if (VA.isExtInLoc()) {
1468 // Handle MMX values passed in XMM regs.
1469 if (RegVT.isVector()) {
1470 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1471 ArgValue, DAG.getConstant(0, MVT::i64));
1472 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1474 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1477 assert(VA.isMemLoc());
1478 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1481 // If value is passed via pointer - do a load.
1482 if (VA.getLocInfo() == CCValAssign::Indirect)
1483 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0);
1485 InVals.push_back(ArgValue);
1488 // The x86-64 ABI for returning structs by value requires that we copy
1489 // the sret argument into %rax for the return. Save the argument into
1490 // a virtual register so that we can access it from the return points.
1491 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1492 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1493 unsigned Reg = FuncInfo->getSRetReturnReg();
1495 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1496 FuncInfo->setSRetReturnReg(Reg);
1498 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1499 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1502 unsigned StackSize = CCInfo.getNextStackOffset();
1503 // align stack specially for tail calls
1504 if (PerformTailCallOpt && CallConv == CallingConv::Fast)
1505 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1507 // If the function takes variable number of arguments, make a frame index for
1508 // the start of the first vararg value... for expansion of llvm.va_start.
1510 if (Is64Bit || CallConv != CallingConv::X86_FastCall) {
1511 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize, true, false);
1514 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1516 // FIXME: We should really autogenerate these arrays
1517 static const unsigned GPR64ArgRegsWin64[] = {
1518 X86::RCX, X86::RDX, X86::R8, X86::R9
1520 static const unsigned XMMArgRegsWin64[] = {
1521 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1523 static const unsigned GPR64ArgRegs64Bit[] = {
1524 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1526 static const unsigned XMMArgRegs64Bit[] = {
1527 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1528 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1530 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1533 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1534 GPR64ArgRegs = GPR64ArgRegsWin64;
1535 XMMArgRegs = XMMArgRegsWin64;
1537 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1538 GPR64ArgRegs = GPR64ArgRegs64Bit;
1539 XMMArgRegs = XMMArgRegs64Bit;
1541 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1543 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1546 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1547 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1548 "SSE register cannot be used when SSE is disabled!");
1549 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1550 "SSE register cannot be used when SSE is disabled!");
1551 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1552 // Kernel mode asks for SSE to be disabled, so don't push them
1554 TotalNumXMMRegs = 0;
1556 // For X86-64, if there are vararg parameters that are passed via
1557 // registers, then we must store them to their spots on the stack so they
1558 // may be loaded by deferencing the result of va_next.
1559 VarArgsGPOffset = NumIntRegs * 8;
1560 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1561 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1562 TotalNumXMMRegs * 16, 16,
1565 // Store the integer parameter registers.
1566 SmallVector<SDValue, 8> MemOps;
1567 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1568 unsigned Offset = VarArgsGPOffset;
1569 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1570 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1571 DAG.getIntPtrConstant(Offset));
1572 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1573 X86::GR64RegisterClass);
1574 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1576 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1577 PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
1579 MemOps.push_back(Store);
1583 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1584 // Now store the XMM (fp + vector) parameter registers.
1585 SmallVector<SDValue, 11> SaveXMMOps;
1586 SaveXMMOps.push_back(Chain);
1588 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1589 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1590 SaveXMMOps.push_back(ALVal);
1592 SaveXMMOps.push_back(DAG.getIntPtrConstant(RegSaveFrameIndex));
1593 SaveXMMOps.push_back(DAG.getIntPtrConstant(VarArgsFPOffset));
1595 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1596 unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1597 X86::VR128RegisterClass);
1598 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1599 SaveXMMOps.push_back(Val);
1601 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1603 &SaveXMMOps[0], SaveXMMOps.size()));
1606 if (!MemOps.empty())
1607 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1608 &MemOps[0], MemOps.size());
1612 // Some CCs need callee pop.
1613 if (IsCalleePop(isVarArg, CallConv)) {
1614 BytesToPopOnReturn = StackSize; // Callee pops everything.
1615 BytesCallerReserves = 0;
1617 BytesToPopOnReturn = 0; // Callee pops nothing.
1618 // If this is an sret function, the return should pop the hidden pointer.
1619 if (!Is64Bit && CallConv != CallingConv::Fast && ArgsAreStructReturn(Ins))
1620 BytesToPopOnReturn = 4;
1621 BytesCallerReserves = StackSize;
1625 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1626 if (CallConv == CallingConv::X86_FastCall)
1627 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1630 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1636 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1637 SDValue StackPtr, SDValue Arg,
1638 DebugLoc dl, SelectionDAG &DAG,
1639 const CCValAssign &VA,
1640 ISD::ArgFlagsTy Flags) {
1641 const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1642 unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1643 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1644 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1645 if (Flags.isByVal()) {
1646 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1648 return DAG.getStore(Chain, dl, Arg, PtrOff,
1649 PseudoSourceValue::getStack(), LocMemOffset);
1652 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1653 /// optimization is performed and it is required.
1655 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1656 SDValue &OutRetAddr,
1662 if (!IsTailCall || FPDiff==0) return Chain;
1664 // Adjust the Return address stack slot.
1665 EVT VT = getPointerTy();
1666 OutRetAddr = getReturnAddressFrameIndex(DAG);
1668 // Load the "old" Return address.
1669 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0);
1670 return SDValue(OutRetAddr.getNode(), 1);
1673 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1674 /// optimization is performed and it is required (FPDiff!=0).
1676 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1677 SDValue Chain, SDValue RetAddrFrIdx,
1678 bool Is64Bit, int FPDiff, DebugLoc dl) {
1679 // Store the return address to the appropriate stack slot.
1680 if (!FPDiff) return Chain;
1681 // Calculate the new stack slot for the return address.
1682 int SlotSize = Is64Bit ? 8 : 4;
1683 int NewReturnAddrFI =
1684 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, true, false);
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 bool WasGlobalOrExternal = false;
1939 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
1940 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
1941 // In the 64-bit large code model, we have to make all calls
1942 // through a register, since the call instruction's 32-bit
1943 // pc-relative offset may not be large enough to hold the whole
1945 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1946 WasGlobalOrExternal = true;
1947 // If the callee is a GlobalAddress node (quite common, every direct call
1948 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
1951 // We should use extra load for direct calls to dllimported functions in
1953 GlobalValue *GV = G->getGlobal();
1954 if (!GV->hasDLLImportLinkage()) {
1955 unsigned char OpFlags = 0;
1957 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
1958 // external symbols most go through the PLT in PIC mode. If the symbol
1959 // has hidden or protected visibility, or if it is static or local, then
1960 // we don't need to use the PLT - we can directly call it.
1961 if (Subtarget->isTargetELF() &&
1962 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1963 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
1964 OpFlags = X86II::MO_PLT;
1965 } else if (Subtarget->isPICStyleStubAny() &&
1966 (GV->isDeclaration() || GV->isWeakForLinker()) &&
1967 Subtarget->getDarwinVers() < 9) {
1968 // PC-relative references to external symbols should go through $stub,
1969 // unless we're building with the leopard linker or later, which
1970 // automatically synthesizes these stubs.
1971 OpFlags = X86II::MO_DARWIN_STUB;
1974 Callee = DAG.getTargetGlobalAddress(GV, getPointerTy(),
1975 G->getOffset(), OpFlags);
1977 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1978 WasGlobalOrExternal = true;
1979 unsigned char OpFlags = 0;
1981 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
1982 // symbols should go through the PLT.
1983 if (Subtarget->isTargetELF() &&
1984 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1985 OpFlags = X86II::MO_PLT;
1986 } else if (Subtarget->isPICStyleStubAny() &&
1987 Subtarget->getDarwinVers() < 9) {
1988 // PC-relative references to external symbols should go through $stub,
1989 // unless we're building with the leopard linker or later, which
1990 // automatically synthesizes these stubs.
1991 OpFlags = X86II::MO_DARWIN_STUB;
1994 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
1998 if (isTailCall && !WasGlobalOrExternal) {
1999 unsigned Opc = Is64Bit ? X86::R11 : X86::EAX;
2001 Chain = DAG.getCopyToReg(Chain, dl,
2002 DAG.getRegister(Opc, getPointerTy()),
2004 Callee = DAG.getRegister(Opc, getPointerTy());
2005 // Add register as live out.
2006 MF.getRegInfo().addLiveOut(Opc);
2009 // Returns a chain & a flag for retval copy to use.
2010 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2011 SmallVector<SDValue, 8> Ops;
2014 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2015 DAG.getIntPtrConstant(0, true), InFlag);
2016 InFlag = Chain.getValue(1);
2019 Ops.push_back(Chain);
2020 Ops.push_back(Callee);
2023 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2025 // Add argument registers to the end of the list so that they are known live
2027 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2028 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2029 RegsToPass[i].second.getValueType()));
2031 // Add an implicit use GOT pointer in EBX.
2032 if (!isTailCall && Subtarget->isPICStyleGOT())
2033 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2035 // Add an implicit use of AL for x86 vararg functions.
2036 if (Is64Bit && isVarArg)
2037 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2039 if (InFlag.getNode())
2040 Ops.push_back(InFlag);
2043 // If this is the first return lowered for this function, add the regs
2044 // to the liveout set for the function.
2045 if (MF.getRegInfo().liveout_empty()) {
2046 SmallVector<CCValAssign, 16> RVLocs;
2047 CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
2049 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2050 for (unsigned i = 0; i != RVLocs.size(); ++i)
2051 if (RVLocs[i].isRegLoc())
2052 MF.getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2055 assert(((Callee.getOpcode() == ISD::Register &&
2056 (cast<RegisterSDNode>(Callee)->getReg() == X86::EAX ||
2057 cast<RegisterSDNode>(Callee)->getReg() == X86::R9)) ||
2058 Callee.getOpcode() == ISD::TargetExternalSymbol ||
2059 Callee.getOpcode() == ISD::TargetGlobalAddress) &&
2060 "Expecting an global address, external symbol, or register");
2062 return DAG.getNode(X86ISD::TC_RETURN, dl,
2063 NodeTys, &Ops[0], Ops.size());
2066 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2067 InFlag = Chain.getValue(1);
2069 // Create the CALLSEQ_END node.
2070 unsigned NumBytesForCalleeToPush;
2071 if (IsCalleePop(isVarArg, CallConv))
2072 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2073 else if (!Is64Bit && CallConv != CallingConv::Fast && IsStructRet)
2074 // If this is is a call to a struct-return function, the callee
2075 // pops the hidden struct pointer, so we have to push it back.
2076 // This is common for Darwin/X86, Linux & Mingw32 targets.
2077 NumBytesForCalleeToPush = 4;
2079 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2081 // Returns a flag for retval copy to use.
2082 Chain = DAG.getCALLSEQ_END(Chain,
2083 DAG.getIntPtrConstant(NumBytes, true),
2084 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2087 InFlag = Chain.getValue(1);
2089 // Handle result values, copying them out of physregs into vregs that we
2091 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2092 Ins, dl, DAG, InVals);
2096 //===----------------------------------------------------------------------===//
2097 // Fast Calling Convention (tail call) implementation
2098 //===----------------------------------------------------------------------===//
2100 // Like std call, callee cleans arguments, convention except that ECX is
2101 // reserved for storing the tail called function address. Only 2 registers are
2102 // free for argument passing (inreg). Tail call optimization is performed
2104 // * tailcallopt is enabled
2105 // * caller/callee are fastcc
2106 // On X86_64 architecture with GOT-style position independent code only local
2107 // (within module) calls are supported at the moment.
2108 // To keep the stack aligned according to platform abi the function
2109 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2110 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2111 // If a tail called function callee has more arguments than the caller the
2112 // caller needs to make sure that there is room to move the RETADDR to. This is
2113 // achieved by reserving an area the size of the argument delta right after the
2114 // original REtADDR, but before the saved framepointer or the spilled registers
2115 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2127 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2128 /// for a 16 byte align requirement.
2129 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2130 SelectionDAG& DAG) {
2131 MachineFunction &MF = DAG.getMachineFunction();
2132 const TargetMachine &TM = MF.getTarget();
2133 const TargetFrameInfo &TFI = *TM.getFrameInfo();
2134 unsigned StackAlignment = TFI.getStackAlignment();
2135 uint64_t AlignMask = StackAlignment - 1;
2136 int64_t Offset = StackSize;
2137 uint64_t SlotSize = TD->getPointerSize();
2138 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2139 // Number smaller than 12 so just add the difference.
2140 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2142 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2143 Offset = ((~AlignMask) & Offset) + StackAlignment +
2144 (StackAlignment-SlotSize);
2149 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2150 /// for tail call optimization. Targets which want to do tail call
2151 /// optimization should implement this function.
2153 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2154 CallingConv::ID CalleeCC,
2156 const SmallVectorImpl<ISD::InputArg> &Ins,
2157 SelectionDAG& DAG) const {
2158 MachineFunction &MF = DAG.getMachineFunction();
2159 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
2160 return CalleeCC == CallingConv::Fast && CallerCC == CalleeCC;
2164 X86TargetLowering::createFastISel(MachineFunction &mf,
2165 MachineModuleInfo *mmo,
2167 DenseMap<const Value *, unsigned> &vm,
2168 DenseMap<const BasicBlock *,
2169 MachineBasicBlock *> &bm,
2170 DenseMap<const AllocaInst *, int> &am
2172 , SmallSet<Instruction*, 8> &cil
2175 return X86::createFastISel(mf, mmo, dw, vm, bm, am
2183 //===----------------------------------------------------------------------===//
2184 // Other Lowering Hooks
2185 //===----------------------------------------------------------------------===//
2188 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2189 MachineFunction &MF = DAG.getMachineFunction();
2190 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2191 int ReturnAddrIndex = FuncInfo->getRAIndex();
2193 if (ReturnAddrIndex == 0) {
2194 // Set up a frame object for the return address.
2195 uint64_t SlotSize = TD->getPointerSize();
2196 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2198 FuncInfo->setRAIndex(ReturnAddrIndex);
2201 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2205 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2206 bool hasSymbolicDisplacement) {
2207 // Offset should fit into 32 bit immediate field.
2208 if (!isInt32(Offset))
2211 // If we don't have a symbolic displacement - we don't have any extra
2213 if (!hasSymbolicDisplacement)
2216 // FIXME: Some tweaks might be needed for medium code model.
2217 if (M != CodeModel::Small && M != CodeModel::Kernel)
2220 // For small code model we assume that latest object is 16MB before end of 31
2221 // bits boundary. We may also accept pretty large negative constants knowing
2222 // that all objects are in the positive half of address space.
2223 if (M == CodeModel::Small && Offset < 16*1024*1024)
2226 // For kernel code model we know that all object resist in the negative half
2227 // of 32bits address space. We may not accept negative offsets, since they may
2228 // be just off and we may accept pretty large positive ones.
2229 if (M == CodeModel::Kernel && Offset > 0)
2235 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2236 /// specific condition code, returning the condition code and the LHS/RHS of the
2237 /// comparison to make.
2238 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2239 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2241 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2242 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2243 // X > -1 -> X == 0, jump !sign.
2244 RHS = DAG.getConstant(0, RHS.getValueType());
2245 return X86::COND_NS;
2246 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2247 // X < 0 -> X == 0, jump on sign.
2249 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2251 RHS = DAG.getConstant(0, RHS.getValueType());
2252 return X86::COND_LE;
2256 switch (SetCCOpcode) {
2257 default: llvm_unreachable("Invalid integer condition!");
2258 case ISD::SETEQ: return X86::COND_E;
2259 case ISD::SETGT: return X86::COND_G;
2260 case ISD::SETGE: return X86::COND_GE;
2261 case ISD::SETLT: return X86::COND_L;
2262 case ISD::SETLE: return X86::COND_LE;
2263 case ISD::SETNE: return X86::COND_NE;
2264 case ISD::SETULT: return X86::COND_B;
2265 case ISD::SETUGT: return X86::COND_A;
2266 case ISD::SETULE: return X86::COND_BE;
2267 case ISD::SETUGE: return X86::COND_AE;
2271 // First determine if it is required or is profitable to flip the operands.
2273 // If LHS is a foldable load, but RHS is not, flip the condition.
2274 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2275 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2276 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2277 std::swap(LHS, RHS);
2280 switch (SetCCOpcode) {
2286 std::swap(LHS, RHS);
2290 // On a floating point condition, the flags are set as follows:
2292 // 0 | 0 | 0 | X > Y
2293 // 0 | 0 | 1 | X < Y
2294 // 1 | 0 | 0 | X == Y
2295 // 1 | 1 | 1 | unordered
2296 switch (SetCCOpcode) {
2297 default: llvm_unreachable("Condcode should be pre-legalized away");
2299 case ISD::SETEQ: return X86::COND_E;
2300 case ISD::SETOLT: // flipped
2302 case ISD::SETGT: return X86::COND_A;
2303 case ISD::SETOLE: // flipped
2305 case ISD::SETGE: return X86::COND_AE;
2306 case ISD::SETUGT: // flipped
2308 case ISD::SETLT: return X86::COND_B;
2309 case ISD::SETUGE: // flipped
2311 case ISD::SETLE: return X86::COND_BE;
2313 case ISD::SETNE: return X86::COND_NE;
2314 case ISD::SETUO: return X86::COND_P;
2315 case ISD::SETO: return X86::COND_NP;
2317 case ISD::SETUNE: return X86::COND_INVALID;
2321 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2322 /// code. Current x86 isa includes the following FP cmov instructions:
2323 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2324 static bool hasFPCMov(unsigned X86CC) {
2340 /// isFPImmLegal - Returns true if the target can instruction select the
2341 /// specified FP immediate natively. If false, the legalizer will
2342 /// materialize the FP immediate as a load from a constant pool.
2343 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2344 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2345 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2351 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2352 /// the specified range (L, H].
2353 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2354 return (Val < 0) || (Val >= Low && Val < Hi);
2357 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2358 /// specified value.
2359 static bool isUndefOrEqual(int Val, int CmpVal) {
2360 if (Val < 0 || Val == CmpVal)
2365 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2366 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2367 /// the second operand.
2368 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2369 if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2370 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2371 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2372 return (Mask[0] < 2 && Mask[1] < 2);
2376 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2377 SmallVector<int, 8> M;
2379 return ::isPSHUFDMask(M, N->getValueType(0));
2382 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2383 /// is suitable for input to PSHUFHW.
2384 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2385 if (VT != MVT::v8i16)
2388 // Lower quadword copied in order or undef.
2389 for (int i = 0; i != 4; ++i)
2390 if (Mask[i] >= 0 && Mask[i] != i)
2393 // Upper quadword shuffled.
2394 for (int i = 4; i != 8; ++i)
2395 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2401 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2402 SmallVector<int, 8> M;
2404 return ::isPSHUFHWMask(M, N->getValueType(0));
2407 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2408 /// is suitable for input to PSHUFLW.
2409 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2410 if (VT != MVT::v8i16)
2413 // Upper quadword copied in order.
2414 for (int i = 4; i != 8; ++i)
2415 if (Mask[i] >= 0 && Mask[i] != i)
2418 // Lower quadword shuffled.
2419 for (int i = 0; i != 4; ++i)
2426 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2427 SmallVector<int, 8> M;
2429 return ::isPSHUFLWMask(M, N->getValueType(0));
2432 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2433 /// is suitable for input to PALIGNR.
2434 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2436 int i, e = VT.getVectorNumElements();
2438 // Do not handle v2i64 / v2f64 shuffles with palignr.
2439 if (e < 4 || !hasSSSE3)
2442 for (i = 0; i != e; ++i)
2446 // All undef, not a palignr.
2450 // Determine if it's ok to perform a palignr with only the LHS, since we
2451 // don't have access to the actual shuffle elements to see if RHS is undef.
2452 bool Unary = Mask[i] < (int)e;
2453 bool NeedsUnary = false;
2455 int s = Mask[i] - i;
2457 // Check the rest of the elements to see if they are consecutive.
2458 for (++i; i != e; ++i) {
2463 Unary = Unary && (m < (int)e);
2464 NeedsUnary = NeedsUnary || (m < s);
2466 if (NeedsUnary && !Unary)
2468 if (Unary && m != ((s+i) & (e-1)))
2470 if (!Unary && m != (s+i))
2476 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2477 SmallVector<int, 8> M;
2479 return ::isPALIGNRMask(M, N->getValueType(0), true);
2482 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2483 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2484 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2485 int NumElems = VT.getVectorNumElements();
2486 if (NumElems != 2 && NumElems != 4)
2489 int Half = NumElems / 2;
2490 for (int i = 0; i < Half; ++i)
2491 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2493 for (int i = Half; i < NumElems; ++i)
2494 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2500 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2501 SmallVector<int, 8> M;
2503 return ::isSHUFPMask(M, N->getValueType(0));
2506 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2507 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2508 /// half elements to come from vector 1 (which would equal the dest.) and
2509 /// the upper half to come from vector 2.
2510 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2511 int NumElems = VT.getVectorNumElements();
2513 if (NumElems != 2 && NumElems != 4)
2516 int Half = NumElems / 2;
2517 for (int i = 0; i < Half; ++i)
2518 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2520 for (int i = Half; i < NumElems; ++i)
2521 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2526 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2527 SmallVector<int, 8> M;
2529 return isCommutedSHUFPMask(M, N->getValueType(0));
2532 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2533 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2534 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2535 if (N->getValueType(0).getVectorNumElements() != 4)
2538 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2539 return isUndefOrEqual(N->getMaskElt(0), 6) &&
2540 isUndefOrEqual(N->getMaskElt(1), 7) &&
2541 isUndefOrEqual(N->getMaskElt(2), 2) &&
2542 isUndefOrEqual(N->getMaskElt(3), 3);
2545 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2546 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2548 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2549 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2554 return isUndefOrEqual(N->getMaskElt(0), 2) &&
2555 isUndefOrEqual(N->getMaskElt(1), 3) &&
2556 isUndefOrEqual(N->getMaskElt(2), 2) &&
2557 isUndefOrEqual(N->getMaskElt(3), 3);
2560 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2561 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2562 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2563 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2565 if (NumElems != 2 && NumElems != 4)
2568 for (unsigned i = 0; i < NumElems/2; ++i)
2569 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2572 for (unsigned i = NumElems/2; i < NumElems; ++i)
2573 if (!isUndefOrEqual(N->getMaskElt(i), i))
2579 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
2580 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
2581 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
2582 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2584 if (NumElems != 2 && NumElems != 4)
2587 for (unsigned i = 0; i < NumElems/2; ++i)
2588 if (!isUndefOrEqual(N->getMaskElt(i), i))
2591 for (unsigned i = 0; i < NumElems/2; ++i)
2592 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2598 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2599 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2600 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2601 bool V2IsSplat = false) {
2602 int NumElts = VT.getVectorNumElements();
2603 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2606 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2608 int BitI1 = Mask[i+1];
2609 if (!isUndefOrEqual(BitI, j))
2612 if (!isUndefOrEqual(BitI1, NumElts))
2615 if (!isUndefOrEqual(BitI1, j + NumElts))
2622 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2623 SmallVector<int, 8> M;
2625 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2628 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2629 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2630 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
2631 bool V2IsSplat = false) {
2632 int NumElts = VT.getVectorNumElements();
2633 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2636 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2638 int BitI1 = Mask[i+1];
2639 if (!isUndefOrEqual(BitI, j + NumElts/2))
2642 if (isUndefOrEqual(BitI1, NumElts))
2645 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2652 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2653 SmallVector<int, 8> M;
2655 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2658 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2659 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2661 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2662 int NumElems = VT.getVectorNumElements();
2663 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2666 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2668 int BitI1 = Mask[i+1];
2669 if (!isUndefOrEqual(BitI, j))
2671 if (!isUndefOrEqual(BitI1, j))
2677 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2678 SmallVector<int, 8> M;
2680 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2683 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2684 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2686 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2687 int NumElems = VT.getVectorNumElements();
2688 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2691 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2693 int BitI1 = Mask[i+1];
2694 if (!isUndefOrEqual(BitI, j))
2696 if (!isUndefOrEqual(BitI1, j))
2702 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2703 SmallVector<int, 8> M;
2705 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2708 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2709 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2710 /// MOVSD, and MOVD, i.e. setting the lowest element.
2711 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2712 if (VT.getVectorElementType().getSizeInBits() < 32)
2715 int NumElts = VT.getVectorNumElements();
2717 if (!isUndefOrEqual(Mask[0], NumElts))
2720 for (int i = 1; i < NumElts; ++i)
2721 if (!isUndefOrEqual(Mask[i], i))
2727 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2728 SmallVector<int, 8> M;
2730 return ::isMOVLMask(M, N->getValueType(0));
2733 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2734 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2735 /// element of vector 2 and the other elements to come from vector 1 in order.
2736 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2737 bool V2IsSplat = false, bool V2IsUndef = false) {
2738 int NumOps = VT.getVectorNumElements();
2739 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2742 if (!isUndefOrEqual(Mask[0], 0))
2745 for (int i = 1; i < NumOps; ++i)
2746 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
2747 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
2748 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
2754 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
2755 bool V2IsUndef = false) {
2756 SmallVector<int, 8> M;
2758 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
2761 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2762 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2763 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
2764 if (N->getValueType(0).getVectorNumElements() != 4)
2767 // Expect 1, 1, 3, 3
2768 for (unsigned i = 0; i < 2; ++i) {
2769 int Elt = N->getMaskElt(i);
2770 if (Elt >= 0 && Elt != 1)
2775 for (unsigned i = 2; i < 4; ++i) {
2776 int Elt = N->getMaskElt(i);
2777 if (Elt >= 0 && Elt != 3)
2782 // Don't use movshdup if it can be done with a shufps.
2783 // FIXME: verify that matching u, u, 3, 3 is what we want.
2787 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2788 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2789 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
2790 if (N->getValueType(0).getVectorNumElements() != 4)
2793 // Expect 0, 0, 2, 2
2794 for (unsigned i = 0; i < 2; ++i)
2795 if (N->getMaskElt(i) > 0)
2799 for (unsigned i = 2; i < 4; ++i) {
2800 int Elt = N->getMaskElt(i);
2801 if (Elt >= 0 && Elt != 2)
2806 // Don't use movsldup if it can be done with a shufps.
2810 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2811 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2812 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
2813 int e = N->getValueType(0).getVectorNumElements() / 2;
2815 for (int i = 0; i < e; ++i)
2816 if (!isUndefOrEqual(N->getMaskElt(i), i))
2818 for (int i = 0; i < e; ++i)
2819 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
2824 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2825 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
2826 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2827 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2828 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
2830 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2832 for (int i = 0; i < NumOperands; ++i) {
2833 int Val = SVOp->getMaskElt(NumOperands-i-1);
2834 if (Val < 0) Val = 0;
2835 if (Val >= NumOperands) Val -= NumOperands;
2837 if (i != NumOperands - 1)
2843 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2844 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
2845 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2846 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2848 // 8 nodes, but we only care about the last 4.
2849 for (unsigned i = 7; i >= 4; --i) {
2850 int Val = SVOp->getMaskElt(i);
2859 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2860 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
2861 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2862 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2864 // 8 nodes, but we only care about the first 4.
2865 for (int i = 3; i >= 0; --i) {
2866 int Val = SVOp->getMaskElt(i);
2875 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
2876 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
2877 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
2878 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2879 EVT VVT = N->getValueType(0);
2880 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
2884 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
2885 Val = SVOp->getMaskElt(i);
2889 return (Val - i) * EltSize;
2892 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2894 bool X86::isZeroNode(SDValue Elt) {
2895 return ((isa<ConstantSDNode>(Elt) &&
2896 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2897 (isa<ConstantFPSDNode>(Elt) &&
2898 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2901 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
2902 /// their permute mask.
2903 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
2904 SelectionDAG &DAG) {
2905 EVT VT = SVOp->getValueType(0);
2906 unsigned NumElems = VT.getVectorNumElements();
2907 SmallVector<int, 8> MaskVec;
2909 for (unsigned i = 0; i != NumElems; ++i) {
2910 int idx = SVOp->getMaskElt(i);
2912 MaskVec.push_back(idx);
2913 else if (idx < (int)NumElems)
2914 MaskVec.push_back(idx + NumElems);
2916 MaskVec.push_back(idx - NumElems);
2918 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
2919 SVOp->getOperand(0), &MaskVec[0]);
2922 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2923 /// the two vector operands have swapped position.
2924 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
2925 unsigned NumElems = VT.getVectorNumElements();
2926 for (unsigned i = 0; i != NumElems; ++i) {
2930 else if (idx < (int)NumElems)
2931 Mask[i] = idx + NumElems;
2933 Mask[i] = idx - NumElems;
2937 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2938 /// match movhlps. The lower half elements should come from upper half of
2939 /// V1 (and in order), and the upper half elements should come from the upper
2940 /// half of V2 (and in order).
2941 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
2942 if (Op->getValueType(0).getVectorNumElements() != 4)
2944 for (unsigned i = 0, e = 2; i != e; ++i)
2945 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
2947 for (unsigned i = 2; i != 4; ++i)
2948 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
2953 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2954 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2956 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2957 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
2959 N = N->getOperand(0).getNode();
2960 if (!ISD::isNON_EXTLoad(N))
2963 *LD = cast<LoadSDNode>(N);
2967 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2968 /// match movlp{s|d}. The lower half elements should come from lower half of
2969 /// V1 (and in order), and the upper half elements should come from the upper
2970 /// half of V2 (and in order). And since V1 will become the source of the
2971 /// MOVLP, it must be either a vector load or a scalar load to vector.
2972 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
2973 ShuffleVectorSDNode *Op) {
2974 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2976 // Is V2 is a vector load, don't do this transformation. We will try to use
2977 // load folding shufps op.
2978 if (ISD::isNON_EXTLoad(V2))
2981 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
2983 if (NumElems != 2 && NumElems != 4)
2985 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2986 if (!isUndefOrEqual(Op->getMaskElt(i), i))
2988 for (unsigned i = NumElems/2; i != NumElems; ++i)
2989 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
2994 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2996 static bool isSplatVector(SDNode *N) {
2997 if (N->getOpcode() != ISD::BUILD_VECTOR)
3000 SDValue SplatValue = N->getOperand(0);
3001 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3002 if (N->getOperand(i) != SplatValue)
3007 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3008 /// to an zero vector.
3009 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3010 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3011 SDValue V1 = N->getOperand(0);
3012 SDValue V2 = N->getOperand(1);
3013 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3014 for (unsigned i = 0; i != NumElems; ++i) {
3015 int Idx = N->getMaskElt(i);
3016 if (Idx >= (int)NumElems) {
3017 unsigned Opc = V2.getOpcode();
3018 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3020 if (Opc != ISD::BUILD_VECTOR ||
3021 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3023 } else if (Idx >= 0) {
3024 unsigned Opc = V1.getOpcode();
3025 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3027 if (Opc != ISD::BUILD_VECTOR ||
3028 !X86::isZeroNode(V1.getOperand(Idx)))
3035 /// getZeroVector - Returns a vector of specified type with all zero elements.
3037 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3039 assert(VT.isVector() && "Expected a vector type");
3041 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3042 // type. This ensures they get CSE'd.
3044 if (VT.getSizeInBits() == 64) { // MMX
3045 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3046 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3047 } else if (HasSSE2) { // SSE2
3048 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3049 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3051 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3052 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3054 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3057 /// getOnesVector - Returns a vector of specified type with all bits set.
3059 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3060 assert(VT.isVector() && "Expected a vector type");
3062 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3063 // type. This ensures they get CSE'd.
3064 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3066 if (VT.getSizeInBits() == 64) // MMX
3067 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3069 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3070 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3074 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3075 /// that point to V2 points to its first element.
3076 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3077 EVT VT = SVOp->getValueType(0);
3078 unsigned NumElems = VT.getVectorNumElements();
3080 bool Changed = false;
3081 SmallVector<int, 8> MaskVec;
3082 SVOp->getMask(MaskVec);
3084 for (unsigned i = 0; i != NumElems; ++i) {
3085 if (MaskVec[i] > (int)NumElems) {
3086 MaskVec[i] = NumElems;
3091 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3092 SVOp->getOperand(1), &MaskVec[0]);
3093 return SDValue(SVOp, 0);
3096 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3097 /// operation of specified width.
3098 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3100 unsigned NumElems = VT.getVectorNumElements();
3101 SmallVector<int, 8> Mask;
3102 Mask.push_back(NumElems);
3103 for (unsigned i = 1; i != NumElems; ++i)
3105 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3108 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3109 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3111 unsigned NumElems = VT.getVectorNumElements();
3112 SmallVector<int, 8> Mask;
3113 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3115 Mask.push_back(i + NumElems);
3117 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3120 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3121 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3123 unsigned NumElems = VT.getVectorNumElements();
3124 unsigned Half = NumElems/2;
3125 SmallVector<int, 8> Mask;
3126 for (unsigned i = 0; i != Half; ++i) {
3127 Mask.push_back(i + Half);
3128 Mask.push_back(i + NumElems + Half);
3130 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3133 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3134 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3136 if (SV->getValueType(0).getVectorNumElements() <= 4)
3137 return SDValue(SV, 0);
3139 EVT PVT = MVT::v4f32;
3140 EVT VT = SV->getValueType(0);
3141 DebugLoc dl = SV->getDebugLoc();
3142 SDValue V1 = SV->getOperand(0);
3143 int NumElems = VT.getVectorNumElements();
3144 int EltNo = SV->getSplatIndex();
3146 // unpack elements to the correct location
3147 while (NumElems > 4) {
3148 if (EltNo < NumElems/2) {
3149 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3151 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3152 EltNo -= NumElems/2;
3157 // Perform the splat.
3158 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3159 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3160 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3161 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3164 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3165 /// vector of zero or undef vector. This produces a shuffle where the low
3166 /// element of V2 is swizzled into the zero/undef vector, landing at element
3167 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3168 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3169 bool isZero, bool HasSSE2,
3170 SelectionDAG &DAG) {
3171 EVT VT = V2.getValueType();
3173 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3174 unsigned NumElems = VT.getVectorNumElements();
3175 SmallVector<int, 16> MaskVec;
3176 for (unsigned i = 0; i != NumElems; ++i)
3177 // If this is the insertion idx, put the low elt of V2 here.
3178 MaskVec.push_back(i == Idx ? NumElems : i);
3179 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3182 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3183 /// a shuffle that is zero.
3185 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3186 bool Low, SelectionDAG &DAG) {
3187 unsigned NumZeros = 0;
3188 for (int i = 0; i < NumElems; ++i) {
3189 unsigned Index = Low ? i : NumElems-i-1;
3190 int Idx = SVOp->getMaskElt(Index);
3195 SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3196 if (Elt.getNode() && X86::isZeroNode(Elt))
3204 /// isVectorShift - Returns true if the shuffle can be implemented as a
3205 /// logical left or right shift of a vector.
3206 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3207 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3208 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3209 int NumElems = SVOp->getValueType(0).getVectorNumElements();
3212 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3215 NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3219 bool SeenV1 = false;
3220 bool SeenV2 = false;
3221 for (int i = NumZeros; i < NumElems; ++i) {
3222 int Val = isLeft ? (i - NumZeros) : i;
3223 int Idx = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3235 if (SeenV1 && SeenV2)
3238 ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3244 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3246 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3247 unsigned NumNonZero, unsigned NumZero,
3248 SelectionDAG &DAG, TargetLowering &TLI) {
3252 DebugLoc dl = Op.getDebugLoc();
3255 for (unsigned i = 0; i < 16; ++i) {
3256 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3257 if (ThisIsNonZero && First) {
3259 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3261 V = DAG.getUNDEF(MVT::v8i16);
3266 SDValue ThisElt(0, 0), LastElt(0, 0);
3267 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3268 if (LastIsNonZero) {
3269 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3270 MVT::i16, Op.getOperand(i-1));
3272 if (ThisIsNonZero) {
3273 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3274 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3275 ThisElt, DAG.getConstant(8, MVT::i8));
3277 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3281 if (ThisElt.getNode())
3282 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3283 DAG.getIntPtrConstant(i/2));
3287 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3290 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3292 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3293 unsigned NumNonZero, unsigned NumZero,
3294 SelectionDAG &DAG, TargetLowering &TLI) {
3298 DebugLoc dl = Op.getDebugLoc();
3301 for (unsigned i = 0; i < 8; ++i) {
3302 bool isNonZero = (NonZeros & (1 << i)) != 0;
3306 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3308 V = DAG.getUNDEF(MVT::v8i16);
3311 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3312 MVT::v8i16, V, Op.getOperand(i),
3313 DAG.getIntPtrConstant(i));
3320 /// getVShift - Return a vector logical shift node.
3322 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3323 unsigned NumBits, SelectionDAG &DAG,
3324 const TargetLowering &TLI, DebugLoc dl) {
3325 bool isMMX = VT.getSizeInBits() == 64;
3326 EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3327 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3328 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3329 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3330 DAG.getNode(Opc, dl, ShVT, SrcOp,
3331 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3335 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3336 DebugLoc dl = Op.getDebugLoc();
3337 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3338 if (ISD::isBuildVectorAllZeros(Op.getNode())
3339 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3340 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3341 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3342 // eliminated on x86-32 hosts.
3343 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3346 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3347 return getOnesVector(Op.getValueType(), DAG, dl);
3348 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3351 EVT VT = Op.getValueType();
3352 EVT ExtVT = VT.getVectorElementType();
3353 unsigned EVTBits = ExtVT.getSizeInBits();
3355 unsigned NumElems = Op.getNumOperands();
3356 unsigned NumZero = 0;
3357 unsigned NumNonZero = 0;
3358 unsigned NonZeros = 0;
3359 bool IsAllConstants = true;
3360 SmallSet<SDValue, 8> Values;
3361 for (unsigned i = 0; i < NumElems; ++i) {
3362 SDValue Elt = Op.getOperand(i);
3363 if (Elt.getOpcode() == ISD::UNDEF)
3366 if (Elt.getOpcode() != ISD::Constant &&
3367 Elt.getOpcode() != ISD::ConstantFP)
3368 IsAllConstants = false;
3369 if (X86::isZeroNode(Elt))
3372 NonZeros |= (1 << i);
3377 if (NumNonZero == 0) {
3378 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3379 return DAG.getUNDEF(VT);
3382 // Special case for single non-zero, non-undef, element.
3383 if (NumNonZero == 1) {
3384 unsigned Idx = CountTrailingZeros_32(NonZeros);
3385 SDValue Item = Op.getOperand(Idx);
3387 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3388 // the value are obviously zero, truncate the value to i32 and do the
3389 // insertion that way. Only do this if the value is non-constant or if the
3390 // value is a constant being inserted into element 0. It is cheaper to do
3391 // a constant pool load than it is to do a movd + shuffle.
3392 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3393 (!IsAllConstants || Idx == 0)) {
3394 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3395 // Handle MMX and SSE both.
3396 EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3397 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3399 // Truncate the value (which may itself be a constant) to i32, and
3400 // convert it to a vector with movd (S2V+shuffle to zero extend).
3401 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3402 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3403 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3404 Subtarget->hasSSE2(), DAG);
3406 // Now we have our 32-bit value zero extended in the low element of
3407 // a vector. If Idx != 0, swizzle it into place.
3409 SmallVector<int, 4> Mask;
3410 Mask.push_back(Idx);
3411 for (unsigned i = 1; i != VecElts; ++i)
3413 Item = DAG.getVectorShuffle(VecVT, dl, Item,
3414 DAG.getUNDEF(Item.getValueType()),
3417 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3421 // If we have a constant or non-constant insertion into the low element of
3422 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3423 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3424 // depending on what the source datatype is.
3427 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3428 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3429 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3430 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3431 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3432 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3434 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3435 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3436 EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3437 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3438 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3439 Subtarget->hasSSE2(), DAG);
3440 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3444 // Is it a vector logical left shift?
3445 if (NumElems == 2 && Idx == 1 &&
3446 X86::isZeroNode(Op.getOperand(0)) &&
3447 !X86::isZeroNode(Op.getOperand(1))) {
3448 unsigned NumBits = VT.getSizeInBits();
3449 return getVShift(true, VT,
3450 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3451 VT, Op.getOperand(1)),
3452 NumBits/2, DAG, *this, dl);
3455 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3458 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3459 // is a non-constant being inserted into an element other than the low one,
3460 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3461 // movd/movss) to move this into the low element, then shuffle it into
3463 if (EVTBits == 32) {
3464 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3466 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3467 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3468 Subtarget->hasSSE2(), DAG);
3469 SmallVector<int, 8> MaskVec;
3470 for (unsigned i = 0; i < NumElems; i++)
3471 MaskVec.push_back(i == Idx ? 0 : 1);
3472 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3476 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3477 if (Values.size() == 1)
3480 // A vector full of immediates; various special cases are already
3481 // handled, so this is best done with a single constant-pool load.
3485 // Let legalizer expand 2-wide build_vectors.
3486 if (EVTBits == 64) {
3487 if (NumNonZero == 1) {
3488 // One half is zero or undef.
3489 unsigned Idx = CountTrailingZeros_32(NonZeros);
3490 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3491 Op.getOperand(Idx));
3492 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3493 Subtarget->hasSSE2(), DAG);
3498 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3499 if (EVTBits == 8 && NumElems == 16) {
3500 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3502 if (V.getNode()) return V;
3505 if (EVTBits == 16 && NumElems == 8) {
3506 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3508 if (V.getNode()) return V;
3511 // If element VT is == 32 bits, turn it into a number of shuffles.
3512 SmallVector<SDValue, 8> V;
3514 if (NumElems == 4 && NumZero > 0) {
3515 for (unsigned i = 0; i < 4; ++i) {
3516 bool isZero = !(NonZeros & (1 << i));
3518 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3520 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3523 for (unsigned i = 0; i < 2; ++i) {
3524 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3527 V[i] = V[i*2]; // Must be a zero vector.
3530 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3533 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3536 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3541 SmallVector<int, 8> MaskVec;
3542 bool Reverse = (NonZeros & 0x3) == 2;
3543 for (unsigned i = 0; i < 2; ++i)
3544 MaskVec.push_back(Reverse ? 1-i : i);
3545 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3546 for (unsigned i = 0; i < 2; ++i)
3547 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3548 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3551 if (Values.size() > 2) {
3552 // If we have SSE 4.1, Expand into a number of inserts unless the number of
3553 // values to be inserted is equal to the number of elements, in which case
3554 // use the unpack code below in the hopes of matching the consecutive elts
3555 // load merge pattern for shuffles.
3556 // FIXME: We could probably just check that here directly.
3557 if (Values.size() < NumElems && VT.getSizeInBits() == 128 &&
3558 getSubtarget()->hasSSE41()) {
3559 V[0] = DAG.getUNDEF(VT);
3560 for (unsigned i = 0; i < NumElems; ++i)
3561 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3562 V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3563 Op.getOperand(i), DAG.getIntPtrConstant(i));
3566 // Expand into a number of unpckl*.
3568 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3569 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3570 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3571 for (unsigned i = 0; i < NumElems; ++i)
3572 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3574 while (NumElems != 0) {
3575 for (unsigned i = 0; i < NumElems; ++i)
3576 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3585 // v8i16 shuffles - Prefer shuffles in the following order:
3586 // 1. [all] pshuflw, pshufhw, optional move
3587 // 2. [ssse3] 1 x pshufb
3588 // 3. [ssse3] 2 x pshufb + 1 x por
3589 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
3591 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
3592 SelectionDAG &DAG, X86TargetLowering &TLI) {
3593 SDValue V1 = SVOp->getOperand(0);
3594 SDValue V2 = SVOp->getOperand(1);
3595 DebugLoc dl = SVOp->getDebugLoc();
3596 SmallVector<int, 8> MaskVals;
3598 // Determine if more than 1 of the words in each of the low and high quadwords
3599 // of the result come from the same quadword of one of the two inputs. Undef
3600 // mask values count as coming from any quadword, for better codegen.
3601 SmallVector<unsigned, 4> LoQuad(4);
3602 SmallVector<unsigned, 4> HiQuad(4);
3603 BitVector InputQuads(4);
3604 for (unsigned i = 0; i < 8; ++i) {
3605 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
3606 int EltIdx = SVOp->getMaskElt(i);
3607 MaskVals.push_back(EltIdx);
3616 InputQuads.set(EltIdx / 4);
3619 int BestLoQuad = -1;
3620 unsigned MaxQuad = 1;
3621 for (unsigned i = 0; i < 4; ++i) {
3622 if (LoQuad[i] > MaxQuad) {
3624 MaxQuad = LoQuad[i];
3628 int BestHiQuad = -1;
3630 for (unsigned i = 0; i < 4; ++i) {
3631 if (HiQuad[i] > MaxQuad) {
3633 MaxQuad = HiQuad[i];
3637 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
3638 // of the two input vectors, shuffle them into one input vector so only a
3639 // single pshufb instruction is necessary. If There are more than 2 input
3640 // quads, disable the next transformation since it does not help SSSE3.
3641 bool V1Used = InputQuads[0] || InputQuads[1];
3642 bool V2Used = InputQuads[2] || InputQuads[3];
3643 if (TLI.getSubtarget()->hasSSSE3()) {
3644 if (InputQuads.count() == 2 && V1Used && V2Used) {
3645 BestLoQuad = InputQuads.find_first();
3646 BestHiQuad = InputQuads.find_next(BestLoQuad);
3648 if (InputQuads.count() > 2) {
3654 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
3655 // the shuffle mask. If a quad is scored as -1, that means that it contains
3656 // words from all 4 input quadwords.
3658 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
3659 SmallVector<int, 8> MaskV;
3660 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
3661 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
3662 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
3663 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
3664 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
3665 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
3667 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
3668 // source words for the shuffle, to aid later transformations.
3669 bool AllWordsInNewV = true;
3670 bool InOrder[2] = { true, true };
3671 for (unsigned i = 0; i != 8; ++i) {
3672 int idx = MaskVals[i];
3674 InOrder[i/4] = false;
3675 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
3677 AllWordsInNewV = false;
3681 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
3682 if (AllWordsInNewV) {
3683 for (int i = 0; i != 8; ++i) {
3684 int idx = MaskVals[i];
3687 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
3688 if ((idx != i) && idx < 4)
3690 if ((idx != i) && idx > 3)
3699 // If we've eliminated the use of V2, and the new mask is a pshuflw or
3700 // pshufhw, that's as cheap as it gets. Return the new shuffle.
3701 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
3702 return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
3703 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
3707 // If we have SSSE3, and all words of the result are from 1 input vector,
3708 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
3709 // is present, fall back to case 4.
3710 if (TLI.getSubtarget()->hasSSSE3()) {
3711 SmallVector<SDValue,16> pshufbMask;
3713 // If we have elements from both input vectors, set the high bit of the
3714 // shuffle mask element to zero out elements that come from V2 in the V1
3715 // mask, and elements that come from V1 in the V2 mask, so that the two
3716 // results can be OR'd together.
3717 bool TwoInputs = V1Used && V2Used;
3718 for (unsigned i = 0; i != 8; ++i) {
3719 int EltIdx = MaskVals[i] * 2;
3720 if (TwoInputs && (EltIdx >= 16)) {
3721 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3722 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3725 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3726 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
3728 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
3729 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3730 DAG.getNode(ISD::BUILD_VECTOR, dl,
3731 MVT::v16i8, &pshufbMask[0], 16));
3733 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3735 // Calculate the shuffle mask for the second input, shuffle it, and
3736 // OR it with the first shuffled input.
3738 for (unsigned i = 0; i != 8; ++i) {
3739 int EltIdx = MaskVals[i] * 2;
3741 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3742 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3745 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3746 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
3748 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
3749 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3750 DAG.getNode(ISD::BUILD_VECTOR, dl,
3751 MVT::v16i8, &pshufbMask[0], 16));
3752 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3753 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3756 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
3757 // and update MaskVals with new element order.
3758 BitVector InOrder(8);
3759 if (BestLoQuad >= 0) {
3760 SmallVector<int, 8> MaskV;
3761 for (int i = 0; i != 4; ++i) {
3762 int idx = MaskVals[i];
3764 MaskV.push_back(-1);
3766 } else if ((idx / 4) == BestLoQuad) {
3767 MaskV.push_back(idx & 3);
3770 MaskV.push_back(-1);
3773 for (unsigned i = 4; i != 8; ++i)
3775 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3779 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
3780 // and update MaskVals with the new element order.
3781 if (BestHiQuad >= 0) {
3782 SmallVector<int, 8> MaskV;
3783 for (unsigned i = 0; i != 4; ++i)
3785 for (unsigned i = 4; i != 8; ++i) {
3786 int idx = MaskVals[i];
3788 MaskV.push_back(-1);
3790 } else if ((idx / 4) == BestHiQuad) {
3791 MaskV.push_back((idx & 3) + 4);
3794 MaskV.push_back(-1);
3797 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3801 // In case BestHi & BestLo were both -1, which means each quadword has a word
3802 // from each of the four input quadwords, calculate the InOrder bitvector now
3803 // before falling through to the insert/extract cleanup.
3804 if (BestLoQuad == -1 && BestHiQuad == -1) {
3806 for (int i = 0; i != 8; ++i)
3807 if (MaskVals[i] < 0 || MaskVals[i] == i)
3811 // The other elements are put in the right place using pextrw and pinsrw.
3812 for (unsigned i = 0; i != 8; ++i) {
3815 int EltIdx = MaskVals[i];
3818 SDValue ExtOp = (EltIdx < 8)
3819 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
3820 DAG.getIntPtrConstant(EltIdx))
3821 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
3822 DAG.getIntPtrConstant(EltIdx - 8));
3823 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3824 DAG.getIntPtrConstant(i));
3829 // v16i8 shuffles - Prefer shuffles in the following order:
3830 // 1. [ssse3] 1 x pshufb
3831 // 2. [ssse3] 2 x pshufb + 1 x por
3832 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
3834 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
3835 SelectionDAG &DAG, X86TargetLowering &TLI) {
3836 SDValue V1 = SVOp->getOperand(0);
3837 SDValue V2 = SVOp->getOperand(1);
3838 DebugLoc dl = SVOp->getDebugLoc();
3839 SmallVector<int, 16> MaskVals;
3840 SVOp->getMask(MaskVals);
3842 // If we have SSSE3, case 1 is generated when all result bytes come from
3843 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
3844 // present, fall back to case 3.
3845 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
3848 for (unsigned i = 0; i < 16; ++i) {
3849 int EltIdx = MaskVals[i];
3858 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
3859 if (TLI.getSubtarget()->hasSSSE3()) {
3860 SmallVector<SDValue,16> pshufbMask;
3862 // If all result elements are from one input vector, then only translate
3863 // undef mask values to 0x80 (zero out result) in the pshufb mask.
3865 // Otherwise, we have elements from both input vectors, and must zero out
3866 // elements that come from V2 in the first mask, and V1 in the second mask
3867 // so that we can OR them together.
3868 bool TwoInputs = !(V1Only || V2Only);
3869 for (unsigned i = 0; i != 16; ++i) {
3870 int EltIdx = MaskVals[i];
3871 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
3872 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3875 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3877 // If all the elements are from V2, assign it to V1 and return after
3878 // building the first pshufb.
3881 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3882 DAG.getNode(ISD::BUILD_VECTOR, dl,
3883 MVT::v16i8, &pshufbMask[0], 16));
3887 // Calculate the shuffle mask for the second input, shuffle it, and
3888 // OR it with the first shuffled input.
3890 for (unsigned i = 0; i != 16; ++i) {
3891 int EltIdx = MaskVals[i];
3893 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3896 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3898 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3899 DAG.getNode(ISD::BUILD_VECTOR, dl,
3900 MVT::v16i8, &pshufbMask[0], 16));
3901 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3904 // No SSSE3 - Calculate in place words and then fix all out of place words
3905 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
3906 // the 16 different words that comprise the two doublequadword input vectors.
3907 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3908 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
3909 SDValue NewV = V2Only ? V2 : V1;
3910 for (int i = 0; i != 8; ++i) {
3911 int Elt0 = MaskVals[i*2];
3912 int Elt1 = MaskVals[i*2+1];
3914 // This word of the result is all undef, skip it.
3915 if (Elt0 < 0 && Elt1 < 0)
3918 // This word of the result is already in the correct place, skip it.
3919 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
3921 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
3924 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
3925 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
3928 // If Elt0 and Elt1 are defined, are consecutive, and can be load
3929 // using a single extract together, load it and store it.
3930 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
3931 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3932 DAG.getIntPtrConstant(Elt1 / 2));
3933 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3934 DAG.getIntPtrConstant(i));
3938 // If Elt1 is defined, extract it from the appropriate source. If the
3939 // source byte is not also odd, shift the extracted word left 8 bits
3940 // otherwise clear the bottom 8 bits if we need to do an or.
3942 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3943 DAG.getIntPtrConstant(Elt1 / 2));
3944 if ((Elt1 & 1) == 0)
3945 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
3946 DAG.getConstant(8, TLI.getShiftAmountTy()));
3948 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
3949 DAG.getConstant(0xFF00, MVT::i16));
3951 // If Elt0 is defined, extract it from the appropriate source. If the
3952 // source byte is not also even, shift the extracted word right 8 bits. If
3953 // Elt1 was also defined, OR the extracted values together before
3954 // inserting them in the result.
3956 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
3957 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
3958 if ((Elt0 & 1) != 0)
3959 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
3960 DAG.getConstant(8, TLI.getShiftAmountTy()));
3962 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
3963 DAG.getConstant(0x00FF, MVT::i16));
3964 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
3967 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3968 DAG.getIntPtrConstant(i));
3970 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
3973 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3974 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3975 /// done when every pair / quad of shuffle mask elements point to elements in
3976 /// the right sequence. e.g.
3977 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3979 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
3981 TargetLowering &TLI, DebugLoc dl) {
3982 EVT VT = SVOp->getValueType(0);
3983 SDValue V1 = SVOp->getOperand(0);
3984 SDValue V2 = SVOp->getOperand(1);
3985 unsigned NumElems = VT.getVectorNumElements();
3986 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3987 EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3988 EVT MaskEltVT = MaskVT.getVectorElementType();
3990 switch (VT.getSimpleVT().SimpleTy) {
3991 default: assert(false && "Unexpected!");
3992 case MVT::v4f32: NewVT = MVT::v2f64; break;
3993 case MVT::v4i32: NewVT = MVT::v2i64; break;
3994 case MVT::v8i16: NewVT = MVT::v4i32; break;
3995 case MVT::v16i8: NewVT = MVT::v4i32; break;
3998 if (NewWidth == 2) {
4004 int Scale = NumElems / NewWidth;
4005 SmallVector<int, 8> MaskVec;
4006 for (unsigned i = 0; i < NumElems; i += Scale) {
4008 for (int j = 0; j < Scale; ++j) {
4009 int EltIdx = SVOp->getMaskElt(i+j);
4013 StartIdx = EltIdx - (EltIdx % Scale);
4014 if (EltIdx != StartIdx + j)
4018 MaskVec.push_back(-1);
4020 MaskVec.push_back(StartIdx / Scale);
4023 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4024 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4025 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4028 /// getVZextMovL - Return a zero-extending vector move low node.
4030 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4031 SDValue SrcOp, SelectionDAG &DAG,
4032 const X86Subtarget *Subtarget, DebugLoc dl) {
4033 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4034 LoadSDNode *LD = NULL;
4035 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4036 LD = dyn_cast<LoadSDNode>(SrcOp);
4038 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4040 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4041 if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4042 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4043 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4044 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4046 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4047 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4048 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4049 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4057 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4058 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4059 DAG.getNode(ISD::BIT_CONVERT, dl,
4063 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4066 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4067 SDValue V1 = SVOp->getOperand(0);
4068 SDValue V2 = SVOp->getOperand(1);
4069 DebugLoc dl = SVOp->getDebugLoc();
4070 EVT VT = SVOp->getValueType(0);
4072 SmallVector<std::pair<int, int>, 8> Locs;
4074 SmallVector<int, 8> Mask1(4U, -1);
4075 SmallVector<int, 8> PermMask;
4076 SVOp->getMask(PermMask);
4080 for (unsigned i = 0; i != 4; ++i) {
4081 int Idx = PermMask[i];
4083 Locs[i] = std::make_pair(-1, -1);
4085 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4087 Locs[i] = std::make_pair(0, NumLo);
4091 Locs[i] = std::make_pair(1, NumHi);
4093 Mask1[2+NumHi] = Idx;
4099 if (NumLo <= 2 && NumHi <= 2) {
4100 // If no more than two elements come from either vector. This can be
4101 // implemented with two shuffles. First shuffle gather the elements.
4102 // The second shuffle, which takes the first shuffle as both of its
4103 // vector operands, put the elements into the right order.
4104 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4106 SmallVector<int, 8> Mask2(4U, -1);
4108 for (unsigned i = 0; i != 4; ++i) {
4109 if (Locs[i].first == -1)
4112 unsigned Idx = (i < 2) ? 0 : 4;
4113 Idx += Locs[i].first * 2 + Locs[i].second;
4118 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4119 } else if (NumLo == 3 || NumHi == 3) {
4120 // Otherwise, we must have three elements from one vector, call it X, and
4121 // one element from the other, call it Y. First, use a shufps to build an
4122 // intermediate vector with the one element from Y and the element from X
4123 // that will be in the same half in the final destination (the indexes don't
4124 // matter). Then, use a shufps to build the final vector, taking the half
4125 // containing the element from Y from the intermediate, and the other half
4128 // Normalize it so the 3 elements come from V1.
4129 CommuteVectorShuffleMask(PermMask, VT);
4133 // Find the element from V2.
4135 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4136 int Val = PermMask[HiIndex];
4143 Mask1[0] = PermMask[HiIndex];
4145 Mask1[2] = PermMask[HiIndex^1];
4147 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4150 Mask1[0] = PermMask[0];
4151 Mask1[1] = PermMask[1];
4152 Mask1[2] = HiIndex & 1 ? 6 : 4;
4153 Mask1[3] = HiIndex & 1 ? 4 : 6;
4154 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4156 Mask1[0] = HiIndex & 1 ? 2 : 0;
4157 Mask1[1] = HiIndex & 1 ? 0 : 2;
4158 Mask1[2] = PermMask[2];
4159 Mask1[3] = PermMask[3];
4164 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4168 // Break it into (shuffle shuffle_hi, shuffle_lo).
4170 SmallVector<int,8> LoMask(4U, -1);
4171 SmallVector<int,8> HiMask(4U, -1);
4173 SmallVector<int,8> *MaskPtr = &LoMask;
4174 unsigned MaskIdx = 0;
4177 for (unsigned i = 0; i != 4; ++i) {
4184 int Idx = PermMask[i];
4186 Locs[i] = std::make_pair(-1, -1);
4187 } else if (Idx < 4) {
4188 Locs[i] = std::make_pair(MaskIdx, LoIdx);
4189 (*MaskPtr)[LoIdx] = Idx;
4192 Locs[i] = std::make_pair(MaskIdx, HiIdx);
4193 (*MaskPtr)[HiIdx] = Idx;
4198 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4199 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4200 SmallVector<int, 8> MaskOps;
4201 for (unsigned i = 0; i != 4; ++i) {
4202 if (Locs[i].first == -1) {
4203 MaskOps.push_back(-1);
4205 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4206 MaskOps.push_back(Idx);
4209 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4213 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4214 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4215 SDValue V1 = Op.getOperand(0);
4216 SDValue V2 = Op.getOperand(1);
4217 EVT VT = Op.getValueType();
4218 DebugLoc dl = Op.getDebugLoc();
4219 unsigned NumElems = VT.getVectorNumElements();
4220 bool isMMX = VT.getSizeInBits() == 64;
4221 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4222 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4223 bool V1IsSplat = false;
4224 bool V2IsSplat = false;
4226 if (isZeroShuffle(SVOp))
4227 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4229 // Promote splats to v4f32.
4230 if (SVOp->isSplat()) {
4231 if (isMMX || NumElems < 4)
4233 return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4236 // If the shuffle can be profitably rewritten as a narrower shuffle, then
4238 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4239 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4240 if (NewOp.getNode())
4241 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4242 LowerVECTOR_SHUFFLE(NewOp, DAG));
4243 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4244 // FIXME: Figure out a cleaner way to do this.
4245 // Try to make use of movq to zero out the top part.
4246 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4247 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4248 if (NewOp.getNode()) {
4249 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4250 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4251 DAG, Subtarget, dl);
4253 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4254 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4255 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4256 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4257 DAG, Subtarget, dl);
4261 if (X86::isPSHUFDMask(SVOp))
4264 // Check if this can be converted into a logical shift.
4265 bool isLeft = false;
4268 bool isShift = getSubtarget()->hasSSE2() &&
4269 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4270 if (isShift && ShVal.hasOneUse()) {
4271 // If the shifted value has multiple uses, it may be cheaper to use
4272 // v_set0 + movlhps or movhlps, etc.
4273 EVT EltVT = VT.getVectorElementType();
4274 ShAmt *= EltVT.getSizeInBits();
4275 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4278 if (X86::isMOVLMask(SVOp)) {
4281 if (ISD::isBuildVectorAllZeros(V1.getNode()))
4282 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4287 // FIXME: fold these into legal mask.
4288 if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4289 X86::isMOVSLDUPMask(SVOp) ||
4290 X86::isMOVHLPSMask(SVOp) ||
4291 X86::isMOVLHPSMask(SVOp) ||
4292 X86::isMOVLPMask(SVOp)))
4295 if (ShouldXformToMOVHLPS(SVOp) ||
4296 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4297 return CommuteVectorShuffle(SVOp, DAG);
4300 // No better options. Use a vshl / vsrl.
4301 EVT EltVT = VT.getVectorElementType();
4302 ShAmt *= EltVT.getSizeInBits();
4303 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4306 bool Commuted = false;
4307 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4308 // 1,1,1,1 -> v8i16 though.
4309 V1IsSplat = isSplatVector(V1.getNode());
4310 V2IsSplat = isSplatVector(V2.getNode());
4312 // Canonicalize the splat or undef, if present, to be on the RHS.
4313 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4314 Op = CommuteVectorShuffle(SVOp, DAG);
4315 SVOp = cast<ShuffleVectorSDNode>(Op);
4316 V1 = SVOp->getOperand(0);
4317 V2 = SVOp->getOperand(1);
4318 std::swap(V1IsSplat, V2IsSplat);
4319 std::swap(V1IsUndef, V2IsUndef);
4323 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4324 // Shuffling low element of v1 into undef, just return v1.
4327 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4328 // the instruction selector will not match, so get a canonical MOVL with
4329 // swapped operands to undo the commute.
4330 return getMOVL(DAG, dl, VT, V2, V1);
4333 if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4334 X86::isUNPCKH_v_undef_Mask(SVOp) ||
4335 X86::isUNPCKLMask(SVOp) ||
4336 X86::isUNPCKHMask(SVOp))
4340 // Normalize mask so all entries that point to V2 points to its first
4341 // element then try to match unpck{h|l} again. If match, return a
4342 // new vector_shuffle with the corrected mask.
4343 SDValue NewMask = NormalizeMask(SVOp, DAG);
4344 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4345 if (NSVOp != SVOp) {
4346 if (X86::isUNPCKLMask(NSVOp, true)) {
4348 } else if (X86::isUNPCKHMask(NSVOp, true)) {
4355 // Commute is back and try unpck* again.
4356 // FIXME: this seems wrong.
4357 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4358 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4359 if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4360 X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4361 X86::isUNPCKLMask(NewSVOp) ||
4362 X86::isUNPCKHMask(NewSVOp))
4366 // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4368 // Normalize the node to match x86 shuffle ops if needed
4369 if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4370 return CommuteVectorShuffle(SVOp, DAG);
4372 // Check for legal shuffle and return?
4373 SmallVector<int, 16> PermMask;
4374 SVOp->getMask(PermMask);
4375 if (isShuffleMaskLegal(PermMask, VT))
4378 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4379 if (VT == MVT::v8i16) {
4380 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4381 if (NewOp.getNode())
4385 if (VT == MVT::v16i8) {
4386 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4387 if (NewOp.getNode())
4391 // Handle all 4 wide cases with a number of shuffles except for MMX.
4392 if (NumElems == 4 && !isMMX)
4393 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4399 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4400 SelectionDAG &DAG) {
4401 EVT VT = Op.getValueType();
4402 DebugLoc dl = Op.getDebugLoc();
4403 if (VT.getSizeInBits() == 8) {
4404 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4405 Op.getOperand(0), Op.getOperand(1));
4406 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4407 DAG.getValueType(VT));
4408 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4409 } else if (VT.getSizeInBits() == 16) {
4410 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4411 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4413 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4414 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4415 DAG.getNode(ISD::BIT_CONVERT, dl,
4419 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4420 Op.getOperand(0), Op.getOperand(1));
4421 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4422 DAG.getValueType(VT));
4423 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4424 } else if (VT == MVT::f32) {
4425 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4426 // the result back to FR32 register. It's only worth matching if the
4427 // result has a single use which is a store or a bitcast to i32. And in
4428 // the case of a store, it's not worth it if the index is a constant 0,
4429 // because a MOVSSmr can be used instead, which is smaller and faster.
4430 if (!Op.hasOneUse())
4432 SDNode *User = *Op.getNode()->use_begin();
4433 if ((User->getOpcode() != ISD::STORE ||
4434 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4435 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4436 (User->getOpcode() != ISD::BIT_CONVERT ||
4437 User->getValueType(0) != MVT::i32))
4439 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4440 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4443 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4444 } else if (VT == MVT::i32) {
4445 // ExtractPS works with constant index.
4446 if (isa<ConstantSDNode>(Op.getOperand(1)))
4454 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4455 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4458 if (Subtarget->hasSSE41()) {
4459 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4464 EVT VT = Op.getValueType();
4465 DebugLoc dl = Op.getDebugLoc();
4466 // TODO: handle v16i8.
4467 if (VT.getSizeInBits() == 16) {
4468 SDValue Vec = Op.getOperand(0);
4469 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4471 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4472 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4473 DAG.getNode(ISD::BIT_CONVERT, dl,
4476 // Transform it so it match pextrw which produces a 32-bit result.
4477 EVT EltVT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy+1);
4478 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
4479 Op.getOperand(0), Op.getOperand(1));
4480 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
4481 DAG.getValueType(VT));
4482 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4483 } else if (VT.getSizeInBits() == 32) {
4484 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4488 // SHUFPS the element to the lowest double word, then movss.
4489 int Mask[4] = { Idx, -1, -1, -1 };
4490 EVT VVT = Op.getOperand(0).getValueType();
4491 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4492 DAG.getUNDEF(VVT), Mask);
4493 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4494 DAG.getIntPtrConstant(0));
4495 } else if (VT.getSizeInBits() == 64) {
4496 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4497 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4498 // to match extract_elt for f64.
4499 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4503 // UNPCKHPD the element to the lowest double word, then movsd.
4504 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4505 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4506 int Mask[2] = { 1, -1 };
4507 EVT VVT = Op.getOperand(0).getValueType();
4508 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4509 DAG.getUNDEF(VVT), Mask);
4510 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4511 DAG.getIntPtrConstant(0));
4518 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4519 EVT VT = Op.getValueType();
4520 EVT EltVT = VT.getVectorElementType();
4521 DebugLoc dl = Op.getDebugLoc();
4523 SDValue N0 = Op.getOperand(0);
4524 SDValue N1 = Op.getOperand(1);
4525 SDValue N2 = Op.getOperand(2);
4527 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
4528 isa<ConstantSDNode>(N2)) {
4529 unsigned Opc = (EltVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4531 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4533 if (N1.getValueType() != MVT::i32)
4534 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4535 if (N2.getValueType() != MVT::i32)
4536 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4537 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4538 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4539 // Bits [7:6] of the constant are the source select. This will always be
4540 // zero here. The DAG Combiner may combine an extract_elt index into these
4541 // bits. For example (insert (extract, 3), 2) could be matched by putting
4542 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4543 // Bits [5:4] of the constant are the destination select. This is the
4544 // value of the incoming immediate.
4545 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4546 // combine either bitwise AND or insert of float 0.0 to set these bits.
4547 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4548 // Create this as a scalar to vector..
4549 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
4550 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4551 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
4552 // PINSR* works with constant index.
4559 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4560 EVT VT = Op.getValueType();
4561 EVT EltVT = VT.getVectorElementType();
4563 if (Subtarget->hasSSE41())
4564 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4566 if (EltVT == MVT::i8)
4569 DebugLoc dl = Op.getDebugLoc();
4570 SDValue N0 = Op.getOperand(0);
4571 SDValue N1 = Op.getOperand(1);
4572 SDValue N2 = Op.getOperand(2);
4574 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
4575 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4576 // as its second argument.
4577 if (N1.getValueType() != MVT::i32)
4578 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4579 if (N2.getValueType() != MVT::i32)
4580 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4581 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
4587 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4588 DebugLoc dl = Op.getDebugLoc();
4589 if (Op.getValueType() == MVT::v2f32)
4590 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4591 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4592 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4593 Op.getOperand(0))));
4595 if (Op.getValueType() == MVT::v1i64 && Op.getOperand(0).getValueType() == MVT::i64)
4596 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
4598 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4599 EVT VT = MVT::v2i32;
4600 switch (Op.getValueType().getSimpleVT().SimpleTy) {
4607 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4608 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4611 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4612 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4613 // one of the above mentioned nodes. It has to be wrapped because otherwise
4614 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4615 // be used to form addressing mode. These wrapped nodes will be selected
4618 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4619 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4621 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4623 unsigned char OpFlag = 0;
4624 unsigned WrapperKind = X86ISD::Wrapper;
4625 CodeModel::Model M = getTargetMachine().getCodeModel();
4627 if (Subtarget->isPICStyleRIPRel() &&
4628 (M == CodeModel::Small || M == CodeModel::Kernel))
4629 WrapperKind = X86ISD::WrapperRIP;
4630 else if (Subtarget->isPICStyleGOT())
4631 OpFlag = X86II::MO_GOTOFF;
4632 else if (Subtarget->isPICStyleStubPIC())
4633 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4635 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
4637 CP->getOffset(), OpFlag);
4638 DebugLoc DL = CP->getDebugLoc();
4639 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4640 // With PIC, the address is actually $g + Offset.
4642 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4643 DAG.getNode(X86ISD::GlobalBaseReg,
4644 DebugLoc::getUnknownLoc(), getPointerTy()),
4651 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4652 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4654 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4656 unsigned char OpFlag = 0;
4657 unsigned WrapperKind = X86ISD::Wrapper;
4658 CodeModel::Model M = getTargetMachine().getCodeModel();
4660 if (Subtarget->isPICStyleRIPRel() &&
4661 (M == CodeModel::Small || M == CodeModel::Kernel))
4662 WrapperKind = X86ISD::WrapperRIP;
4663 else if (Subtarget->isPICStyleGOT())
4664 OpFlag = X86II::MO_GOTOFF;
4665 else if (Subtarget->isPICStyleStubPIC())
4666 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4668 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
4670 DebugLoc DL = JT->getDebugLoc();
4671 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4673 // With PIC, the address is actually $g + Offset.
4675 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4676 DAG.getNode(X86ISD::GlobalBaseReg,
4677 DebugLoc::getUnknownLoc(), getPointerTy()),
4685 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4686 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4688 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4690 unsigned char OpFlag = 0;
4691 unsigned WrapperKind = X86ISD::Wrapper;
4692 CodeModel::Model M = getTargetMachine().getCodeModel();
4694 if (Subtarget->isPICStyleRIPRel() &&
4695 (M == CodeModel::Small || M == CodeModel::Kernel))
4696 WrapperKind = X86ISD::WrapperRIP;
4697 else if (Subtarget->isPICStyleGOT())
4698 OpFlag = X86II::MO_GOTOFF;
4699 else if (Subtarget->isPICStyleStubPIC())
4700 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4702 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
4704 DebugLoc DL = Op.getDebugLoc();
4705 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4708 // With PIC, the address is actually $g + Offset.
4709 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4710 !Subtarget->is64Bit()) {
4711 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4712 DAG.getNode(X86ISD::GlobalBaseReg,
4713 DebugLoc::getUnknownLoc(),
4722 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) {
4723 // Create the TargetBlockAddressAddress node.
4724 unsigned char OpFlags =
4725 Subtarget->ClassifyBlockAddressReference();
4726 CodeModel::Model M = getTargetMachine().getCodeModel();
4727 BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
4728 DebugLoc dl = Op.getDebugLoc();
4729 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
4730 /*isTarget=*/true, OpFlags);
4732 if (Subtarget->isPICStyleRIPRel() &&
4733 (M == CodeModel::Small || M == CodeModel::Kernel))
4734 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
4736 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4738 // With PIC, the address is actually $g + Offset.
4739 if (isGlobalRelativeToPICBase(OpFlags)) {
4740 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4741 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4749 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
4751 SelectionDAG &DAG) const {
4752 // Create the TargetGlobalAddress node, folding in the constant
4753 // offset if it is legal.
4754 unsigned char OpFlags =
4755 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
4756 CodeModel::Model M = getTargetMachine().getCodeModel();
4758 if (OpFlags == X86II::MO_NO_FLAG &&
4759 X86::isOffsetSuitableForCodeModel(Offset, M)) {
4760 // A direct static reference to a global.
4761 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4764 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
4767 if (Subtarget->isPICStyleRIPRel() &&
4768 (M == CodeModel::Small || M == CodeModel::Kernel))
4769 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
4771 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4773 // With PIC, the address is actually $g + Offset.
4774 if (isGlobalRelativeToPICBase(OpFlags)) {
4775 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4776 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4780 // For globals that require a load from a stub to get the address, emit the
4782 if (isGlobalStubReference(OpFlags))
4783 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
4784 PseudoSourceValue::getGOT(), 0);
4786 // If there was a non-zero offset that we didn't fold, create an explicit
4789 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
4790 DAG.getConstant(Offset, getPointerTy()));
4796 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4797 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4798 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4799 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
4803 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
4804 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
4805 unsigned char OperandFlags) {
4806 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4807 DebugLoc dl = GA->getDebugLoc();
4808 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4809 GA->getValueType(0),
4813 SDValue Ops[] = { Chain, TGA, *InFlag };
4814 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
4816 SDValue Ops[] = { Chain, TGA };
4817 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
4819 SDValue Flag = Chain.getValue(1);
4820 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
4823 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4825 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4828 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
4829 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
4830 DAG.getNode(X86ISD::GlobalBaseReg,
4831 DebugLoc::getUnknownLoc(),
4833 InFlag = Chain.getValue(1);
4835 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
4838 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4840 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4842 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
4843 X86::RAX, X86II::MO_TLSGD);
4846 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4847 // "local exec" model.
4848 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4849 const EVT PtrVT, TLSModel::Model model,
4851 DebugLoc dl = GA->getDebugLoc();
4852 // Get the Thread Pointer
4853 SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
4854 DebugLoc::getUnknownLoc(), PtrVT,
4855 DAG.getRegister(is64Bit? X86::FS : X86::GS,
4858 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
4861 unsigned char OperandFlags = 0;
4862 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
4864 unsigned WrapperKind = X86ISD::Wrapper;
4865 if (model == TLSModel::LocalExec) {
4866 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
4867 } else if (is64Bit) {
4868 assert(model == TLSModel::InitialExec);
4869 OperandFlags = X86II::MO_GOTTPOFF;
4870 WrapperKind = X86ISD::WrapperRIP;
4872 assert(model == TLSModel::InitialExec);
4873 OperandFlags = X86II::MO_INDNTPOFF;
4876 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4878 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
4879 GA->getOffset(), OperandFlags);
4880 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
4882 if (model == TLSModel::InitialExec)
4883 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
4884 PseudoSourceValue::getGOT(), 0);
4886 // The address of the thread local variable is the add of the thread
4887 // pointer with the offset of the variable.
4888 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
4892 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4893 // TODO: implement the "local dynamic" model
4894 // TODO: implement the "initial exec"model for pic executables
4895 assert(Subtarget->isTargetELF() &&
4896 "TLS not implemented for non-ELF targets");
4897 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4898 const GlobalValue *GV = GA->getGlobal();
4900 // If GV is an alias then use the aliasee for determining
4901 // thread-localness.
4902 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
4903 GV = GA->resolveAliasedGlobal(false);
4905 TLSModel::Model model = getTLSModel(GV,
4906 getTargetMachine().getRelocationModel());
4909 case TLSModel::GeneralDynamic:
4910 case TLSModel::LocalDynamic: // not implemented
4911 if (Subtarget->is64Bit())
4912 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4913 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4915 case TLSModel::InitialExec:
4916 case TLSModel::LocalExec:
4917 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
4918 Subtarget->is64Bit());
4921 llvm_unreachable("Unreachable");
4926 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4927 /// take a 2 x i32 value to shift plus a shift amount.
4928 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4929 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4930 EVT VT = Op.getValueType();
4931 unsigned VTBits = VT.getSizeInBits();
4932 DebugLoc dl = Op.getDebugLoc();
4933 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4934 SDValue ShOpLo = Op.getOperand(0);
4935 SDValue ShOpHi = Op.getOperand(1);
4936 SDValue ShAmt = Op.getOperand(2);
4937 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
4938 DAG.getConstant(VTBits - 1, MVT::i8))
4939 : DAG.getConstant(0, VT);
4942 if (Op.getOpcode() == ISD::SHL_PARTS) {
4943 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
4944 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4946 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
4947 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
4950 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
4951 DAG.getConstant(VTBits, MVT::i8));
4952 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, VT,
4953 AndNode, DAG.getConstant(0, MVT::i8));
4956 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4957 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4958 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4960 if (Op.getOpcode() == ISD::SHL_PARTS) {
4961 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4962 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4964 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4965 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4968 SDValue Ops[2] = { Lo, Hi };
4969 return DAG.getMergeValues(Ops, 2, dl);
4972 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4973 EVT SrcVT = Op.getOperand(0).getValueType();
4975 if (SrcVT.isVector()) {
4976 if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
4982 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4983 "Unknown SINT_TO_FP to lower!");
4985 // These are really Legal; return the operand so the caller accepts it as
4987 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4989 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
4990 Subtarget->is64Bit()) {
4994 DebugLoc dl = Op.getDebugLoc();
4995 unsigned Size = SrcVT.getSizeInBits()/8;
4996 MachineFunction &MF = DAG.getMachineFunction();
4997 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
4998 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4999 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5001 PseudoSourceValue::getFixedStack(SSFI), 0);
5002 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
5005 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
5007 SelectionDAG &DAG) {
5009 DebugLoc dl = Op.getDebugLoc();
5011 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
5013 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
5015 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
5016 SmallVector<SDValue, 8> Ops;
5017 Ops.push_back(Chain);
5018 Ops.push_back(StackSlot);
5019 Ops.push_back(DAG.getValueType(SrcVT));
5020 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
5021 Tys, &Ops[0], Ops.size());
5024 Chain = Result.getValue(1);
5025 SDValue InFlag = Result.getValue(2);
5027 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5028 // shouldn't be necessary except that RFP cannot be live across
5029 // multiple blocks. When stackifier is fixed, they can be uncoupled.
5030 MachineFunction &MF = DAG.getMachineFunction();
5031 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5032 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5033 Tys = DAG.getVTList(MVT::Other);
5034 SmallVector<SDValue, 8> Ops;
5035 Ops.push_back(Chain);
5036 Ops.push_back(Result);
5037 Ops.push_back(StackSlot);
5038 Ops.push_back(DAG.getValueType(Op.getValueType()));
5039 Ops.push_back(InFlag);
5040 Chain = DAG.getNode(X86ISD::FST, dl, Tys, &Ops[0], Ops.size());
5041 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5042 PseudoSourceValue::getFixedStack(SSFI), 0);
5048 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5049 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
5050 // This algorithm is not obvious. Here it is in C code, more or less:
5052 double uint64_to_double( uint32_t hi, uint32_t lo ) {
5053 static const __m128i exp = { 0x4330000045300000ULL, 0 };
5054 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5056 // Copy ints to xmm registers.
5057 __m128i xh = _mm_cvtsi32_si128( hi );
5058 __m128i xl = _mm_cvtsi32_si128( lo );
5060 // Combine into low half of a single xmm register.
5061 __m128i x = _mm_unpacklo_epi32( xh, xl );
5065 // Merge in appropriate exponents to give the integer bits the right
5067 x = _mm_unpacklo_epi32( x, exp );
5069 // Subtract away the biases to deal with the IEEE-754 double precision
5071 d = _mm_sub_pd( (__m128d) x, bias );
5073 // All conversions up to here are exact. The correctly rounded result is
5074 // calculated using the current rounding mode using the following
5076 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5077 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
5078 // store doesn't really need to be here (except
5079 // maybe to zero the other double)
5084 DebugLoc dl = Op.getDebugLoc();
5085 LLVMContext *Context = DAG.getContext();
5087 // Build some magic constants.
5088 std::vector<Constant*> CV0;
5089 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
5090 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
5091 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5092 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5093 Constant *C0 = ConstantVector::get(CV0);
5094 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5096 std::vector<Constant*> CV1;
5098 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
5100 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
5101 Constant *C1 = ConstantVector::get(CV1);
5102 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5104 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5105 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5107 DAG.getIntPtrConstant(1)));
5108 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5109 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5111 DAG.getIntPtrConstant(0)));
5112 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
5113 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5114 PseudoSourceValue::getConstantPool(), 0,
5116 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
5117 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5118 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5119 PseudoSourceValue::getConstantPool(), 0,
5121 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5123 // Add the halves; easiest way is to swap them into another reg first.
5124 int ShufMask[2] = { 1, -1 };
5125 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
5126 DAG.getUNDEF(MVT::v2f64), ShufMask);
5127 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5128 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5129 DAG.getIntPtrConstant(0));
5132 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5133 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
5134 DebugLoc dl = Op.getDebugLoc();
5135 // FP constant to bias correct the final result.
5136 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5139 // Load the 32-bit value into an XMM register.
5140 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5141 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5143 DAG.getIntPtrConstant(0)));
5145 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5146 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5147 DAG.getIntPtrConstant(0));
5149 // Or the load with the bias.
5150 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5151 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5152 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5154 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5155 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5156 MVT::v2f64, Bias)));
5157 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5158 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5159 DAG.getIntPtrConstant(0));
5161 // Subtract the bias.
5162 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5164 // Handle final rounding.
5165 EVT DestVT = Op.getValueType();
5167 if (DestVT.bitsLT(MVT::f64)) {
5168 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5169 DAG.getIntPtrConstant(0));
5170 } else if (DestVT.bitsGT(MVT::f64)) {
5171 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5174 // Handle final rounding.
5178 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5179 SDValue N0 = Op.getOperand(0);
5180 DebugLoc dl = Op.getDebugLoc();
5182 // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
5183 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5184 // the optimization here.
5185 if (DAG.SignBitIsZero(N0))
5186 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5188 EVT SrcVT = N0.getValueType();
5189 if (SrcVT == MVT::i64) {
5190 // We only handle SSE2 f64 target here; caller can expand the rest.
5191 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
5194 return LowerUINT_TO_FP_i64(Op, DAG);
5195 } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
5196 return LowerUINT_TO_FP_i32(Op, DAG);
5199 assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
5201 // Make a 64-bit buffer, and use it to build an FILD.
5202 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5203 SDValue WordOff = DAG.getConstant(4, getPointerTy());
5204 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5205 getPointerTy(), StackSlot, WordOff);
5206 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5207 StackSlot, NULL, 0);
5208 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5209 OffsetSlot, NULL, 0);
5210 return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5213 std::pair<SDValue,SDValue> X86TargetLowering::
5214 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) {
5215 DebugLoc dl = Op.getDebugLoc();
5217 EVT DstTy = Op.getValueType();
5220 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5224 assert(DstTy.getSimpleVT() <= MVT::i64 &&
5225 DstTy.getSimpleVT() >= MVT::i16 &&
5226 "Unknown FP_TO_SINT to lower!");
5228 // These are really Legal.
5229 if (DstTy == MVT::i32 &&
5230 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5231 return std::make_pair(SDValue(), SDValue());
5232 if (Subtarget->is64Bit() &&
5233 DstTy == MVT::i64 &&
5234 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5235 return std::make_pair(SDValue(), SDValue());
5237 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5239 MachineFunction &MF = DAG.getMachineFunction();
5240 unsigned MemSize = DstTy.getSizeInBits()/8;
5241 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5242 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5245 switch (DstTy.getSimpleVT().SimpleTy) {
5246 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5247 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5248 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5249 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5252 SDValue Chain = DAG.getEntryNode();
5253 SDValue Value = Op.getOperand(0);
5254 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5255 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5256 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5257 PseudoSourceValue::getFixedStack(SSFI), 0);
5258 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5260 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5262 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5263 Chain = Value.getValue(1);
5264 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5265 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5268 // Build the FP_TO_INT*_IN_MEM
5269 SDValue Ops[] = { Chain, Value, StackSlot };
5270 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5272 return std::make_pair(FIST, StackSlot);
5275 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
5276 if (Op.getValueType().isVector()) {
5277 if (Op.getValueType() == MVT::v2i32 &&
5278 Op.getOperand(0).getValueType() == MVT::v2f64) {
5284 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5285 SDValue FIST = Vals.first, StackSlot = Vals.second;
5286 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5287 if (FIST.getNode() == 0) return Op;
5290 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5291 FIST, StackSlot, NULL, 0);
5294 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG) {
5295 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5296 SDValue FIST = Vals.first, StackSlot = Vals.second;
5297 assert(FIST.getNode() && "Unexpected failure");
5300 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5301 FIST, StackSlot, NULL, 0);
5304 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
5305 LLVMContext *Context = DAG.getContext();
5306 DebugLoc dl = Op.getDebugLoc();
5307 EVT VT = Op.getValueType();
5310 EltVT = VT.getVectorElementType();
5311 std::vector<Constant*> CV;
5312 if (EltVT == MVT::f64) {
5313 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5317 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5323 Constant *C = ConstantVector::get(CV);
5324 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5325 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5326 PseudoSourceValue::getConstantPool(), 0,
5328 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5331 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
5332 LLVMContext *Context = DAG.getContext();
5333 DebugLoc dl = Op.getDebugLoc();
5334 EVT VT = Op.getValueType();
5337 EltVT = VT.getVectorElementType();
5338 std::vector<Constant*> CV;
5339 if (EltVT == MVT::f64) {
5340 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5344 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5350 Constant *C = ConstantVector::get(CV);
5351 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5352 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5353 PseudoSourceValue::getConstantPool(), 0,
5355 if (VT.isVector()) {
5356 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5357 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5358 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5360 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5362 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5366 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5367 LLVMContext *Context = DAG.getContext();
5368 SDValue Op0 = Op.getOperand(0);
5369 SDValue Op1 = Op.getOperand(1);
5370 DebugLoc dl = Op.getDebugLoc();
5371 EVT VT = Op.getValueType();
5372 EVT SrcVT = Op1.getValueType();
5374 // If second operand is smaller, extend it first.
5375 if (SrcVT.bitsLT(VT)) {
5376 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5379 // And if it is bigger, shrink it first.
5380 if (SrcVT.bitsGT(VT)) {
5381 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5385 // At this point the operands and the result should have the same
5386 // type, and that won't be f80 since that is not custom lowered.
5388 // First get the sign bit of second operand.
5389 std::vector<Constant*> CV;
5390 if (SrcVT == MVT::f64) {
5391 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
5392 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5394 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
5395 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5396 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5397 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5399 Constant *C = ConstantVector::get(CV);
5400 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5401 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5402 PseudoSourceValue::getConstantPool(), 0,
5404 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5406 // Shift sign bit right or left if the two operands have different types.
5407 if (SrcVT.bitsGT(VT)) {
5408 // Op0 is MVT::f32, Op1 is MVT::f64.
5409 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5410 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5411 DAG.getConstant(32, MVT::i32));
5412 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5413 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5414 DAG.getIntPtrConstant(0));
5417 // Clear first operand sign bit.
5419 if (VT == MVT::f64) {
5420 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
5421 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5423 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
5424 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5425 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5426 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5428 C = ConstantVector::get(CV);
5429 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5430 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5431 PseudoSourceValue::getConstantPool(), 0,
5433 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5435 // Or the value with the sign bit.
5436 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5439 /// Emit nodes that will be selected as "test Op0,Op0", or something
5441 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5442 SelectionDAG &DAG) {
5443 DebugLoc dl = Op.getDebugLoc();
5445 // CF and OF aren't always set the way we want. Determine which
5446 // of these we need.
5447 bool NeedCF = false;
5448 bool NeedOF = false;
5450 case X86::COND_A: case X86::COND_AE:
5451 case X86::COND_B: case X86::COND_BE:
5454 case X86::COND_G: case X86::COND_GE:
5455 case X86::COND_L: case X86::COND_LE:
5456 case X86::COND_O: case X86::COND_NO:
5462 // See if we can use the EFLAGS value from the operand instead of
5463 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5464 // we prove that the arithmetic won't overflow, we can't use OF or CF.
5465 if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5466 unsigned Opcode = 0;
5467 unsigned NumOperands = 0;
5468 switch (Op.getNode()->getOpcode()) {
5470 // Due to an isel shortcoming, be conservative if this add is likely to
5471 // be selected as part of a load-modify-store instruction. When the root
5472 // node in a match is a store, isel doesn't know how to remap non-chain
5473 // non-flag uses of other nodes in the match, such as the ADD in this
5474 // case. This leads to the ADD being left around and reselected, with
5475 // the result being two adds in the output.
5476 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5477 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5478 if (UI->getOpcode() == ISD::STORE)
5480 if (ConstantSDNode *C =
5481 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5482 // An add of one will be selected as an INC.
5483 if (C->getAPIntValue() == 1) {
5484 Opcode = X86ISD::INC;
5488 // An add of negative one (subtract of one) will be selected as a DEC.
5489 if (C->getAPIntValue().isAllOnesValue()) {
5490 Opcode = X86ISD::DEC;
5495 // Otherwise use a regular EFLAGS-setting add.
5496 Opcode = X86ISD::ADD;
5500 // If the primary and result isn't used, don't bother using X86ISD::AND,
5501 // because a TEST instruction will be better.
5502 bool NonFlagUse = false;
5503 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5504 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5505 if (UI->getOpcode() != ISD::BRCOND &&
5506 UI->getOpcode() != ISD::SELECT &&
5507 UI->getOpcode() != ISD::SETCC) {
5518 // Due to the ISEL shortcoming noted above, be conservative if this op is
5519 // likely to be selected as part of a load-modify-store instruction.
5520 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5521 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5522 if (UI->getOpcode() == ISD::STORE)
5524 // Otherwise use a regular EFLAGS-setting instruction.
5525 switch (Op.getNode()->getOpcode()) {
5526 case ISD::SUB: Opcode = X86ISD::SUB; break;
5527 case ISD::OR: Opcode = X86ISD::OR; break;
5528 case ISD::XOR: Opcode = X86ISD::XOR; break;
5529 case ISD::AND: Opcode = X86ISD::AND; break;
5530 default: llvm_unreachable("unexpected operator!");
5541 return SDValue(Op.getNode(), 1);
5547 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
5548 SmallVector<SDValue, 4> Ops;
5549 for (unsigned i = 0; i != NumOperands; ++i)
5550 Ops.push_back(Op.getOperand(i));
5551 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
5552 DAG.ReplaceAllUsesWith(Op, New);
5553 return SDValue(New.getNode(), 1);
5557 // Otherwise just emit a CMP with 0, which is the TEST pattern.
5558 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5559 DAG.getConstant(0, Op.getValueType()));
5562 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
5564 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5565 SelectionDAG &DAG) {
5566 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5567 if (C->getAPIntValue() == 0)
5568 return EmitTest(Op0, X86CC, DAG);
5570 DebugLoc dl = Op0.getDebugLoc();
5571 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5574 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5575 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5576 SDValue Op0 = Op.getOperand(0);
5577 SDValue Op1 = Op.getOperand(1);
5578 DebugLoc dl = Op.getDebugLoc();
5579 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5581 // Lower (X & (1 << N)) == 0 to BT(X, N).
5582 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5583 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5584 if (Op0.getOpcode() == ISD::AND &&
5586 Op1.getOpcode() == ISD::Constant &&
5587 cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5588 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5590 if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
5591 if (ConstantSDNode *Op010C =
5592 dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
5593 if (Op010C->getZExtValue() == 1) {
5594 LHS = Op0.getOperand(0);
5595 RHS = Op0.getOperand(1).getOperand(1);
5597 } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
5598 if (ConstantSDNode *Op000C =
5599 dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
5600 if (Op000C->getZExtValue() == 1) {
5601 LHS = Op0.getOperand(1);
5602 RHS = Op0.getOperand(0).getOperand(1);
5604 } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
5605 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5606 SDValue AndLHS = Op0.getOperand(0);
5607 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5608 LHS = AndLHS.getOperand(0);
5609 RHS = AndLHS.getOperand(1);
5613 if (LHS.getNode()) {
5614 // If LHS is i8, promote it to i16 with any_extend. There is no i8 BT
5615 // instruction. Since the shift amount is in-range-or-undefined, we know
5616 // that doing a bittest on the i16 value is ok. We extend to i32 because
5617 // the encoding for the i16 version is larger than the i32 version.
5618 if (LHS.getValueType() == MVT::i8)
5619 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5621 // If the operand types disagree, extend the shift amount to match. Since
5622 // BT ignores high bits (like shifts) we can use anyextend.
5623 if (LHS.getValueType() != RHS.getValueType())
5624 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5626 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5627 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5628 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5629 DAG.getConstant(Cond, MVT::i8), BT);
5633 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5634 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5635 if (X86CC == X86::COND_INVALID)
5638 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
5639 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5640 DAG.getConstant(X86CC, MVT::i8), Cond);
5643 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5645 SDValue Op0 = Op.getOperand(0);
5646 SDValue Op1 = Op.getOperand(1);
5647 SDValue CC = Op.getOperand(2);
5648 EVT VT = Op.getValueType();
5649 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5650 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5651 DebugLoc dl = Op.getDebugLoc();
5655 EVT VT0 = Op0.getValueType();
5656 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5657 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5660 switch (SetCCOpcode) {
5663 case ISD::SETEQ: SSECC = 0; break;
5665 case ISD::SETGT: Swap = true; // Fallthrough
5667 case ISD::SETOLT: SSECC = 1; break;
5669 case ISD::SETGE: Swap = true; // Fallthrough
5671 case ISD::SETOLE: SSECC = 2; break;
5672 case ISD::SETUO: SSECC = 3; break;
5674 case ISD::SETNE: SSECC = 4; break;
5675 case ISD::SETULE: Swap = true;
5676 case ISD::SETUGE: SSECC = 5; break;
5677 case ISD::SETULT: Swap = true;
5678 case ISD::SETUGT: SSECC = 6; break;
5679 case ISD::SETO: SSECC = 7; break;
5682 std::swap(Op0, Op1);
5684 // In the two special cases we can't handle, emit two comparisons.
5686 if (SetCCOpcode == ISD::SETUEQ) {
5688 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5689 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5690 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
5692 else if (SetCCOpcode == ISD::SETONE) {
5694 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5695 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5696 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
5698 llvm_unreachable("Illegal FP comparison");
5700 // Handle all other FP comparisons here.
5701 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5704 // We are handling one of the integer comparisons here. Since SSE only has
5705 // GT and EQ comparisons for integer, swapping operands and multiple
5706 // operations may be required for some comparisons.
5707 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5708 bool Swap = false, Invert = false, FlipSigns = false;
5710 switch (VT.getSimpleVT().SimpleTy) {
5713 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5715 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5717 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5718 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5721 switch (SetCCOpcode) {
5723 case ISD::SETNE: Invert = true;
5724 case ISD::SETEQ: Opc = EQOpc; break;
5725 case ISD::SETLT: Swap = true;
5726 case ISD::SETGT: Opc = GTOpc; break;
5727 case ISD::SETGE: Swap = true;
5728 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
5729 case ISD::SETULT: Swap = true;
5730 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5731 case ISD::SETUGE: Swap = true;
5732 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5735 std::swap(Op0, Op1);
5737 // Since SSE has no unsigned integer comparisons, we need to flip the sign
5738 // bits of the inputs before performing those operations.
5740 EVT EltVT = VT.getVectorElementType();
5741 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
5743 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5744 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
5746 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
5747 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
5750 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
5752 // If the logical-not of the result is required, perform that now.
5754 Result = DAG.getNOT(dl, Result, VT);
5759 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5760 static bool isX86LogicalCmp(SDValue Op) {
5761 unsigned Opc = Op.getNode()->getOpcode();
5762 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
5764 if (Op.getResNo() == 1 &&
5765 (Opc == X86ISD::ADD ||
5766 Opc == X86ISD::SUB ||
5767 Opc == X86ISD::SMUL ||
5768 Opc == X86ISD::UMUL ||
5769 Opc == X86ISD::INC ||
5770 Opc == X86ISD::DEC ||
5771 Opc == X86ISD::OR ||
5772 Opc == X86ISD::XOR ||
5773 Opc == X86ISD::AND))
5779 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5780 bool addTest = true;
5781 SDValue Cond = Op.getOperand(0);
5782 DebugLoc dl = Op.getDebugLoc();
5785 if (Cond.getOpcode() == ISD::SETCC) {
5786 SDValue NewCond = LowerSETCC(Cond, DAG);
5787 if (NewCond.getNode())
5791 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5792 // setting operand in place of the X86ISD::SETCC.
5793 if (Cond.getOpcode() == X86ISD::SETCC) {
5794 CC = Cond.getOperand(0);
5796 SDValue Cmp = Cond.getOperand(1);
5797 unsigned Opc = Cmp.getOpcode();
5798 EVT VT = Op.getValueType();
5800 bool IllegalFPCMov = false;
5801 if (VT.isFloatingPoint() && !VT.isVector() &&
5802 !isScalarFPTypeInSSEReg(VT)) // FPStack?
5803 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
5805 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
5806 Opc == X86ISD::BT) { // FIXME
5813 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5814 Cond = EmitTest(Cond, X86::COND_NE, DAG);
5817 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
5818 SmallVector<SDValue, 4> Ops;
5819 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
5820 // condition is true.
5821 Ops.push_back(Op.getOperand(2));
5822 Ops.push_back(Op.getOperand(1));
5824 Ops.push_back(Cond);
5825 return DAG.getNode(X86ISD::CMOV, dl, VTs, &Ops[0], Ops.size());
5828 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
5829 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
5830 // from the AND / OR.
5831 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
5832 Opc = Op.getOpcode();
5833 if (Opc != ISD::OR && Opc != ISD::AND)
5835 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5836 Op.getOperand(0).hasOneUse() &&
5837 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
5838 Op.getOperand(1).hasOneUse());
5841 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
5842 // 1 and that the SETCC node has a single use.
5843 static bool isXor1OfSetCC(SDValue Op) {
5844 if (Op.getOpcode() != ISD::XOR)
5846 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5847 if (N1C && N1C->getAPIntValue() == 1) {
5848 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5849 Op.getOperand(0).hasOneUse();
5854 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
5855 bool addTest = true;
5856 SDValue Chain = Op.getOperand(0);
5857 SDValue Cond = Op.getOperand(1);
5858 SDValue Dest = Op.getOperand(2);
5859 DebugLoc dl = Op.getDebugLoc();
5862 if (Cond.getOpcode() == ISD::SETCC) {
5863 SDValue NewCond = LowerSETCC(Cond, DAG);
5864 if (NewCond.getNode())
5868 // FIXME: LowerXALUO doesn't handle these!!
5869 else if (Cond.getOpcode() == X86ISD::ADD ||
5870 Cond.getOpcode() == X86ISD::SUB ||
5871 Cond.getOpcode() == X86ISD::SMUL ||
5872 Cond.getOpcode() == X86ISD::UMUL)
5873 Cond = LowerXALUO(Cond, DAG);
5876 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5877 // setting operand in place of the X86ISD::SETCC.
5878 if (Cond.getOpcode() == X86ISD::SETCC) {
5879 CC = Cond.getOperand(0);
5881 SDValue Cmp = Cond.getOperand(1);
5882 unsigned Opc = Cmp.getOpcode();
5883 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
5884 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
5888 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
5892 // These can only come from an arithmetic instruction with overflow,
5893 // e.g. SADDO, UADDO.
5894 Cond = Cond.getNode()->getOperand(1);
5901 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
5902 SDValue Cmp = Cond.getOperand(0).getOperand(1);
5903 if (CondOpc == ISD::OR) {
5904 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
5905 // two branches instead of an explicit OR instruction with a
5907 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5908 isX86LogicalCmp(Cmp)) {
5909 CC = Cond.getOperand(0).getOperand(0);
5910 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5911 Chain, Dest, CC, Cmp);
5912 CC = Cond.getOperand(1).getOperand(0);
5916 } else { // ISD::AND
5917 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
5918 // two branches instead of an explicit AND instruction with a
5919 // separate test. However, we only do this if this block doesn't
5920 // have a fall-through edge, because this requires an explicit
5921 // jmp when the condition is false.
5922 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5923 isX86LogicalCmp(Cmp) &&
5924 Op.getNode()->hasOneUse()) {
5925 X86::CondCode CCode =
5926 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5927 CCode = X86::GetOppositeBranchCondition(CCode);
5928 CC = DAG.getConstant(CCode, MVT::i8);
5929 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
5930 // Look for an unconditional branch following this conditional branch.
5931 // We need this because we need to reverse the successors in order
5932 // to implement FCMP_OEQ.
5933 if (User.getOpcode() == ISD::BR) {
5934 SDValue FalseBB = User.getOperand(1);
5936 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
5937 assert(NewBR == User);
5940 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5941 Chain, Dest, CC, Cmp);
5942 X86::CondCode CCode =
5943 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
5944 CCode = X86::GetOppositeBranchCondition(CCode);
5945 CC = DAG.getConstant(CCode, MVT::i8);
5951 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
5952 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
5953 // It should be transformed during dag combiner except when the condition
5954 // is set by a arithmetics with overflow node.
5955 X86::CondCode CCode =
5956 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5957 CCode = X86::GetOppositeBranchCondition(CCode);
5958 CC = DAG.getConstant(CCode, MVT::i8);
5959 Cond = Cond.getOperand(0).getOperand(1);
5965 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5966 Cond = EmitTest(Cond, X86::COND_NE, DAG);
5968 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5969 Chain, Dest, CC, Cond);
5973 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
5974 // Calls to _alloca is needed to probe the stack when allocating more than 4k
5975 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
5976 // that the guard pages used by the OS virtual memory manager are allocated in
5977 // correct sequence.
5979 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5980 SelectionDAG &DAG) {
5981 assert(Subtarget->isTargetCygMing() &&
5982 "This should be used only on Cygwin/Mingw targets");
5983 DebugLoc dl = Op.getDebugLoc();
5986 SDValue Chain = Op.getOperand(0);
5987 SDValue Size = Op.getOperand(1);
5988 // FIXME: Ensure alignment here
5992 EVT IntPtr = getPointerTy();
5993 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
5995 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
5997 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
5998 Flag = Chain.getValue(1);
6000 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6001 SDValue Ops[] = { Chain,
6002 DAG.getTargetExternalSymbol("_alloca", IntPtr),
6003 DAG.getRegister(X86::EAX, IntPtr),
6004 DAG.getRegister(X86StackPtr, SPTy),
6006 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops, 5);
6007 Flag = Chain.getValue(1);
6009 Chain = DAG.getCALLSEQ_END(Chain,
6010 DAG.getIntPtrConstant(0, true),
6011 DAG.getIntPtrConstant(0, true),
6014 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
6016 SDValue Ops1[2] = { Chain.getValue(0), Chain };
6017 return DAG.getMergeValues(Ops1, 2, dl);
6021 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
6023 SDValue Dst, SDValue Src,
6024 SDValue Size, unsigned Align,
6026 uint64_t DstSVOff) {
6027 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6029 // If not DWORD aligned or size is more than the threshold, call the library.
6030 // The libc version is likely to be faster for these cases. It can use the
6031 // address value and run time information about the CPU.
6032 if ((Align & 3) != 0 ||
6034 ConstantSize->getZExtValue() >
6035 getSubtarget()->getMaxInlineSizeThreshold()) {
6036 SDValue InFlag(0, 0);
6038 // Check to see if there is a specialized entry-point for memory zeroing.
6039 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
6041 if (const char *bzeroEntry = V &&
6042 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
6043 EVT IntPtr = getPointerTy();
6044 const Type *IntPtrTy = TD->getIntPtrType(*DAG.getContext());
6045 TargetLowering::ArgListTy Args;
6046 TargetLowering::ArgListEntry Entry;
6048 Entry.Ty = IntPtrTy;
6049 Args.push_back(Entry);
6051 Args.push_back(Entry);
6052 std::pair<SDValue,SDValue> CallResult =
6053 LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()),
6054 false, false, false, false,
6055 0, CallingConv::C, false, /*isReturnValueUsed=*/false,
6056 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl);
6057 return CallResult.second;
6060 // Otherwise have the target-independent code call memset.
6064 uint64_t SizeVal = ConstantSize->getZExtValue();
6065 SDValue InFlag(0, 0);
6068 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
6069 unsigned BytesLeft = 0;
6070 bool TwoRepStos = false;
6073 uint64_t Val = ValC->getZExtValue() & 255;
6075 // If the value is a constant, then we can potentially use larger sets.
6076 switch (Align & 3) {
6077 case 2: // WORD aligned
6080 Val = (Val << 8) | Val;
6082 case 0: // DWORD aligned
6085 Val = (Val << 8) | Val;
6086 Val = (Val << 16) | Val;
6087 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
6090 Val = (Val << 32) | Val;
6093 default: // Byte aligned
6096 Count = DAG.getIntPtrConstant(SizeVal);
6100 if (AVT.bitsGT(MVT::i8)) {
6101 unsigned UBytes = AVT.getSizeInBits() / 8;
6102 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
6103 BytesLeft = SizeVal % UBytes;
6106 Chain = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
6108 InFlag = Chain.getValue(1);
6111 Count = DAG.getIntPtrConstant(SizeVal);
6112 Chain = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
6113 InFlag = Chain.getValue(1);
6116 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6119 InFlag = Chain.getValue(1);
6120 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6123 InFlag = Chain.getValue(1);
6125 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6126 SmallVector<SDValue, 8> Ops;
6127 Ops.push_back(Chain);
6128 Ops.push_back(DAG.getValueType(AVT));
6129 Ops.push_back(InFlag);
6130 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
6133 InFlag = Chain.getValue(1);
6135 EVT CVT = Count.getValueType();
6136 SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
6137 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
6138 Chain = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
6141 InFlag = Chain.getValue(1);
6142 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6144 Ops.push_back(Chain);
6145 Ops.push_back(DAG.getValueType(MVT::i8));
6146 Ops.push_back(InFlag);
6147 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
6148 } else if (BytesLeft) {
6149 // Handle the last 1 - 7 bytes.
6150 unsigned Offset = SizeVal - BytesLeft;
6151 EVT AddrVT = Dst.getValueType();
6152 EVT SizeVT = Size.getValueType();
6154 Chain = DAG.getMemset(Chain, dl,
6155 DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
6156 DAG.getConstant(Offset, AddrVT)),
6158 DAG.getConstant(BytesLeft, SizeVT),
6159 Align, DstSV, DstSVOff + Offset);
6162 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
6167 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
6168 SDValue Chain, SDValue Dst, SDValue Src,
6169 SDValue Size, unsigned Align,
6171 const Value *DstSV, uint64_t DstSVOff,
6172 const Value *SrcSV, uint64_t SrcSVOff) {
6173 // This requires the copy size to be a constant, preferrably
6174 // within a subtarget-specific limit.
6175 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6178 uint64_t SizeVal = ConstantSize->getZExtValue();
6179 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
6182 /// If not DWORD aligned, call the library.
6183 if ((Align & 3) != 0)
6188 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
6191 unsigned UBytes = AVT.getSizeInBits() / 8;
6192 unsigned CountVal = SizeVal / UBytes;
6193 SDValue Count = DAG.getIntPtrConstant(CountVal);
6194 unsigned BytesLeft = SizeVal % UBytes;
6196 SDValue InFlag(0, 0);
6197 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6200 InFlag = Chain.getValue(1);
6201 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6204 InFlag = Chain.getValue(1);
6205 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
6208 InFlag = Chain.getValue(1);
6210 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6211 SmallVector<SDValue, 8> Ops;
6212 Ops.push_back(Chain);
6213 Ops.push_back(DAG.getValueType(AVT));
6214 Ops.push_back(InFlag);
6215 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, &Ops[0], Ops.size());
6217 SmallVector<SDValue, 4> Results;
6218 Results.push_back(RepMovs);
6220 // Handle the last 1 - 7 bytes.
6221 unsigned Offset = SizeVal - BytesLeft;
6222 EVT DstVT = Dst.getValueType();
6223 EVT SrcVT = Src.getValueType();
6224 EVT SizeVT = Size.getValueType();
6225 Results.push_back(DAG.getMemcpy(Chain, dl,
6226 DAG.getNode(ISD::ADD, dl, DstVT, Dst,
6227 DAG.getConstant(Offset, DstVT)),
6228 DAG.getNode(ISD::ADD, dl, SrcVT, Src,
6229 DAG.getConstant(Offset, SrcVT)),
6230 DAG.getConstant(BytesLeft, SizeVT),
6231 Align, AlwaysInline,
6232 DstSV, DstSVOff + Offset,
6233 SrcSV, SrcSVOff + Offset));
6236 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6237 &Results[0], Results.size());
6240 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
6241 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6242 DebugLoc dl = Op.getDebugLoc();
6244 if (!Subtarget->is64Bit()) {
6245 // vastart just stores the address of the VarArgsFrameIndex slot into the
6246 // memory location argument.
6247 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6248 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
6252 // gp_offset (0 - 6 * 8)
6253 // fp_offset (48 - 48 + 8 * 16)
6254 // overflow_arg_area (point to parameters coming in memory).
6256 SmallVector<SDValue, 8> MemOps;
6257 SDValue FIN = Op.getOperand(1);
6259 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6260 DAG.getConstant(VarArgsGPOffset, MVT::i32),
6262 MemOps.push_back(Store);
6265 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6266 FIN, DAG.getIntPtrConstant(4));
6267 Store = DAG.getStore(Op.getOperand(0), dl,
6268 DAG.getConstant(VarArgsFPOffset, MVT::i32),
6270 MemOps.push_back(Store);
6272 // Store ptr to overflow_arg_area
6273 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6274 FIN, DAG.getIntPtrConstant(4));
6275 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6276 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0);
6277 MemOps.push_back(Store);
6279 // Store ptr to reg_save_area.
6280 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6281 FIN, DAG.getIntPtrConstant(8));
6282 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
6283 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0);
6284 MemOps.push_back(Store);
6285 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6286 &MemOps[0], MemOps.size());
6289 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
6290 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6291 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6292 SDValue Chain = Op.getOperand(0);
6293 SDValue SrcPtr = Op.getOperand(1);
6294 SDValue SrcSV = Op.getOperand(2);
6296 llvm_report_error("VAArgInst is not yet implemented for x86-64!");
6300 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
6301 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6302 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6303 SDValue Chain = Op.getOperand(0);
6304 SDValue DstPtr = Op.getOperand(1);
6305 SDValue SrcPtr = Op.getOperand(2);
6306 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6307 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6308 DebugLoc dl = Op.getDebugLoc();
6310 return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6311 DAG.getIntPtrConstant(24), 8, false,
6312 DstSV, 0, SrcSV, 0);
6316 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
6317 DebugLoc dl = Op.getDebugLoc();
6318 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6320 default: return SDValue(); // Don't custom lower most intrinsics.
6321 // Comparison intrinsics.
6322 case Intrinsic::x86_sse_comieq_ss:
6323 case Intrinsic::x86_sse_comilt_ss:
6324 case Intrinsic::x86_sse_comile_ss:
6325 case Intrinsic::x86_sse_comigt_ss:
6326 case Intrinsic::x86_sse_comige_ss:
6327 case Intrinsic::x86_sse_comineq_ss:
6328 case Intrinsic::x86_sse_ucomieq_ss:
6329 case Intrinsic::x86_sse_ucomilt_ss:
6330 case Intrinsic::x86_sse_ucomile_ss:
6331 case Intrinsic::x86_sse_ucomigt_ss:
6332 case Intrinsic::x86_sse_ucomige_ss:
6333 case Intrinsic::x86_sse_ucomineq_ss:
6334 case Intrinsic::x86_sse2_comieq_sd:
6335 case Intrinsic::x86_sse2_comilt_sd:
6336 case Intrinsic::x86_sse2_comile_sd:
6337 case Intrinsic::x86_sse2_comigt_sd:
6338 case Intrinsic::x86_sse2_comige_sd:
6339 case Intrinsic::x86_sse2_comineq_sd:
6340 case Intrinsic::x86_sse2_ucomieq_sd:
6341 case Intrinsic::x86_sse2_ucomilt_sd:
6342 case Intrinsic::x86_sse2_ucomile_sd:
6343 case Intrinsic::x86_sse2_ucomigt_sd:
6344 case Intrinsic::x86_sse2_ucomige_sd:
6345 case Intrinsic::x86_sse2_ucomineq_sd: {
6347 ISD::CondCode CC = ISD::SETCC_INVALID;
6350 case Intrinsic::x86_sse_comieq_ss:
6351 case Intrinsic::x86_sse2_comieq_sd:
6355 case Intrinsic::x86_sse_comilt_ss:
6356 case Intrinsic::x86_sse2_comilt_sd:
6360 case Intrinsic::x86_sse_comile_ss:
6361 case Intrinsic::x86_sse2_comile_sd:
6365 case Intrinsic::x86_sse_comigt_ss:
6366 case Intrinsic::x86_sse2_comigt_sd:
6370 case Intrinsic::x86_sse_comige_ss:
6371 case Intrinsic::x86_sse2_comige_sd:
6375 case Intrinsic::x86_sse_comineq_ss:
6376 case Intrinsic::x86_sse2_comineq_sd:
6380 case Intrinsic::x86_sse_ucomieq_ss:
6381 case Intrinsic::x86_sse2_ucomieq_sd:
6382 Opc = X86ISD::UCOMI;
6385 case Intrinsic::x86_sse_ucomilt_ss:
6386 case Intrinsic::x86_sse2_ucomilt_sd:
6387 Opc = X86ISD::UCOMI;
6390 case Intrinsic::x86_sse_ucomile_ss:
6391 case Intrinsic::x86_sse2_ucomile_sd:
6392 Opc = X86ISD::UCOMI;
6395 case Intrinsic::x86_sse_ucomigt_ss:
6396 case Intrinsic::x86_sse2_ucomigt_sd:
6397 Opc = X86ISD::UCOMI;
6400 case Intrinsic::x86_sse_ucomige_ss:
6401 case Intrinsic::x86_sse2_ucomige_sd:
6402 Opc = X86ISD::UCOMI;
6405 case Intrinsic::x86_sse_ucomineq_ss:
6406 case Intrinsic::x86_sse2_ucomineq_sd:
6407 Opc = X86ISD::UCOMI;
6412 SDValue LHS = Op.getOperand(1);
6413 SDValue RHS = Op.getOperand(2);
6414 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6415 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
6416 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6417 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6418 DAG.getConstant(X86CC, MVT::i8), Cond);
6419 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6421 // ptest intrinsics. The intrinsic these come from are designed to return
6422 // an integer value, not just an instruction so lower it to the ptest
6423 // pattern and a setcc for the result.
6424 case Intrinsic::x86_sse41_ptestz:
6425 case Intrinsic::x86_sse41_ptestc:
6426 case Intrinsic::x86_sse41_ptestnzc:{
6429 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
6430 case Intrinsic::x86_sse41_ptestz:
6432 X86CC = X86::COND_E;
6434 case Intrinsic::x86_sse41_ptestc:
6436 X86CC = X86::COND_B;
6438 case Intrinsic::x86_sse41_ptestnzc:
6440 X86CC = X86::COND_A;
6444 SDValue LHS = Op.getOperand(1);
6445 SDValue RHS = Op.getOperand(2);
6446 SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
6447 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
6448 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
6449 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6452 // Fix vector shift instructions where the last operand is a non-immediate
6454 case Intrinsic::x86_sse2_pslli_w:
6455 case Intrinsic::x86_sse2_pslli_d:
6456 case Intrinsic::x86_sse2_pslli_q:
6457 case Intrinsic::x86_sse2_psrli_w:
6458 case Intrinsic::x86_sse2_psrli_d:
6459 case Intrinsic::x86_sse2_psrli_q:
6460 case Intrinsic::x86_sse2_psrai_w:
6461 case Intrinsic::x86_sse2_psrai_d:
6462 case Intrinsic::x86_mmx_pslli_w:
6463 case Intrinsic::x86_mmx_pslli_d:
6464 case Intrinsic::x86_mmx_pslli_q:
6465 case Intrinsic::x86_mmx_psrli_w:
6466 case Intrinsic::x86_mmx_psrli_d:
6467 case Intrinsic::x86_mmx_psrli_q:
6468 case Intrinsic::x86_mmx_psrai_w:
6469 case Intrinsic::x86_mmx_psrai_d: {
6470 SDValue ShAmt = Op.getOperand(2);
6471 if (isa<ConstantSDNode>(ShAmt))
6474 unsigned NewIntNo = 0;
6475 EVT ShAmtVT = MVT::v4i32;
6477 case Intrinsic::x86_sse2_pslli_w:
6478 NewIntNo = Intrinsic::x86_sse2_psll_w;
6480 case Intrinsic::x86_sse2_pslli_d:
6481 NewIntNo = Intrinsic::x86_sse2_psll_d;
6483 case Intrinsic::x86_sse2_pslli_q:
6484 NewIntNo = Intrinsic::x86_sse2_psll_q;
6486 case Intrinsic::x86_sse2_psrli_w:
6487 NewIntNo = Intrinsic::x86_sse2_psrl_w;
6489 case Intrinsic::x86_sse2_psrli_d:
6490 NewIntNo = Intrinsic::x86_sse2_psrl_d;
6492 case Intrinsic::x86_sse2_psrli_q:
6493 NewIntNo = Intrinsic::x86_sse2_psrl_q;
6495 case Intrinsic::x86_sse2_psrai_w:
6496 NewIntNo = Intrinsic::x86_sse2_psra_w;
6498 case Intrinsic::x86_sse2_psrai_d:
6499 NewIntNo = Intrinsic::x86_sse2_psra_d;
6502 ShAmtVT = MVT::v2i32;
6504 case Intrinsic::x86_mmx_pslli_w:
6505 NewIntNo = Intrinsic::x86_mmx_psll_w;
6507 case Intrinsic::x86_mmx_pslli_d:
6508 NewIntNo = Intrinsic::x86_mmx_psll_d;
6510 case Intrinsic::x86_mmx_pslli_q:
6511 NewIntNo = Intrinsic::x86_mmx_psll_q;
6513 case Intrinsic::x86_mmx_psrli_w:
6514 NewIntNo = Intrinsic::x86_mmx_psrl_w;
6516 case Intrinsic::x86_mmx_psrli_d:
6517 NewIntNo = Intrinsic::x86_mmx_psrl_d;
6519 case Intrinsic::x86_mmx_psrli_q:
6520 NewIntNo = Intrinsic::x86_mmx_psrl_q;
6522 case Intrinsic::x86_mmx_psrai_w:
6523 NewIntNo = Intrinsic::x86_mmx_psra_w;
6525 case Intrinsic::x86_mmx_psrai_d:
6526 NewIntNo = Intrinsic::x86_mmx_psra_d;
6528 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
6534 // The vector shift intrinsics with scalars uses 32b shift amounts but
6535 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
6539 ShOps[1] = DAG.getConstant(0, MVT::i32);
6540 if (ShAmtVT == MVT::v4i32) {
6541 ShOps[2] = DAG.getUNDEF(MVT::i32);
6542 ShOps[3] = DAG.getUNDEF(MVT::i32);
6543 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
6545 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
6548 EVT VT = Op.getValueType();
6549 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
6550 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6551 DAG.getConstant(NewIntNo, MVT::i32),
6552 Op.getOperand(1), ShAmt);
6557 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
6558 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6559 DebugLoc dl = Op.getDebugLoc();
6562 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6564 DAG.getConstant(TD->getPointerSize(),
6565 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6566 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6567 DAG.getNode(ISD::ADD, dl, getPointerTy(),
6572 // Just load the return address.
6573 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6574 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6575 RetAddrFI, NULL, 0);
6578 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
6579 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6580 MFI->setFrameAddressIsTaken(true);
6581 EVT VT = Op.getValueType();
6582 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
6583 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6584 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6585 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6587 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
6591 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6592 SelectionDAG &DAG) {
6593 return DAG.getIntPtrConstant(2*TD->getPointerSize());
6596 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
6598 MachineFunction &MF = DAG.getMachineFunction();
6599 SDValue Chain = Op.getOperand(0);
6600 SDValue Offset = Op.getOperand(1);
6601 SDValue Handler = Op.getOperand(2);
6602 DebugLoc dl = Op.getDebugLoc();
6604 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6606 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6608 SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
6609 DAG.getIntPtrConstant(-TD->getPointerSize()));
6610 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
6611 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0);
6612 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
6613 MF.getRegInfo().addLiveOut(StoreAddrReg);
6615 return DAG.getNode(X86ISD::EH_RETURN, dl,
6617 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6620 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6621 SelectionDAG &DAG) {
6622 SDValue Root = Op.getOperand(0);
6623 SDValue Trmp = Op.getOperand(1); // trampoline
6624 SDValue FPtr = Op.getOperand(2); // nested function
6625 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6626 DebugLoc dl = Op.getDebugLoc();
6628 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6630 const X86InstrInfo *TII =
6631 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
6633 if (Subtarget->is64Bit()) {
6634 SDValue OutChains[6];
6636 // Large code-model.
6638 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
6639 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
6641 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
6642 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
6644 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
6646 // Load the pointer to the nested function into R11.
6647 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
6648 SDValue Addr = Trmp;
6649 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6652 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6653 DAG.getConstant(2, MVT::i64));
6654 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2, false, 2);
6656 // Load the 'nest' parameter value into R10.
6657 // R10 is specified in X86CallingConv.td
6658 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
6659 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6660 DAG.getConstant(10, MVT::i64));
6661 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6662 Addr, TrmpAddr, 10);
6664 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6665 DAG.getConstant(12, MVT::i64));
6666 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12, false, 2);
6668 // Jump to the nested function.
6669 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
6670 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6671 DAG.getConstant(20, MVT::i64));
6672 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6673 Addr, TrmpAddr, 20);
6675 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
6676 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6677 DAG.getConstant(22, MVT::i64));
6678 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
6682 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
6683 return DAG.getMergeValues(Ops, 2, dl);
6685 const Function *Func =
6686 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
6687 CallingConv::ID CC = Func->getCallingConv();
6692 llvm_unreachable("Unsupported calling convention");
6693 case CallingConv::C:
6694 case CallingConv::X86_StdCall: {
6695 // Pass 'nest' parameter in ECX.
6696 // Must be kept in sync with X86CallingConv.td
6699 // Check that ECX wasn't needed by an 'inreg' parameter.
6700 const FunctionType *FTy = Func->getFunctionType();
6701 const AttrListPtr &Attrs = Func->getAttributes();
6703 if (!Attrs.isEmpty() && !Func->isVarArg()) {
6704 unsigned InRegCount = 0;
6707 for (FunctionType::param_iterator I = FTy->param_begin(),
6708 E = FTy->param_end(); I != E; ++I, ++Idx)
6709 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6710 // FIXME: should only count parameters that are lowered to integers.
6711 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6713 if (InRegCount > 2) {
6714 llvm_report_error("Nest register in use - reduce number of inreg parameters!");
6719 case CallingConv::X86_FastCall:
6720 case CallingConv::Fast:
6721 // Pass 'nest' parameter in EAX.
6722 // Must be kept in sync with X86CallingConv.td
6727 SDValue OutChains[4];
6730 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6731 DAG.getConstant(10, MVT::i32));
6732 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
6734 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
6735 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
6736 OutChains[0] = DAG.getStore(Root, dl,
6737 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
6740 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6741 DAG.getConstant(1, MVT::i32));
6742 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1, false, 1);
6744 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
6745 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6746 DAG.getConstant(5, MVT::i32));
6747 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
6748 TrmpAddr, 5, false, 1);
6750 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6751 DAG.getConstant(6, MVT::i32));
6752 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6, false, 1);
6755 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
6756 return DAG.getMergeValues(Ops, 2, dl);
6760 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
6762 The rounding mode is in bits 11:10 of FPSR, and has the following
6769 FLT_ROUNDS, on the other hand, expects the following:
6776 To perform the conversion, we do:
6777 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
6780 MachineFunction &MF = DAG.getMachineFunction();
6781 const TargetMachine &TM = MF.getTarget();
6782 const TargetFrameInfo &TFI = *TM.getFrameInfo();
6783 unsigned StackAlignment = TFI.getStackAlignment();
6784 EVT VT = Op.getValueType();
6785 DebugLoc dl = Op.getDebugLoc();
6787 // Save FP Control Word to stack slot
6788 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
6789 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6791 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
6792 DAG.getEntryNode(), StackSlot);
6794 // Load FP Control Word from stack slot
6795 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0);
6797 // Transform as necessary
6799 DAG.getNode(ISD::SRL, dl, MVT::i16,
6800 DAG.getNode(ISD::AND, dl, MVT::i16,
6801 CWD, DAG.getConstant(0x800, MVT::i16)),
6802 DAG.getConstant(11, MVT::i8));
6804 DAG.getNode(ISD::SRL, dl, MVT::i16,
6805 DAG.getNode(ISD::AND, dl, MVT::i16,
6806 CWD, DAG.getConstant(0x400, MVT::i16)),
6807 DAG.getConstant(9, MVT::i8));
6810 DAG.getNode(ISD::AND, dl, MVT::i16,
6811 DAG.getNode(ISD::ADD, dl, MVT::i16,
6812 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
6813 DAG.getConstant(1, MVT::i16)),
6814 DAG.getConstant(3, MVT::i16));
6817 return DAG.getNode((VT.getSizeInBits() < 16 ?
6818 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6821 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
6822 EVT VT = Op.getValueType();
6824 unsigned NumBits = VT.getSizeInBits();
6825 DebugLoc dl = Op.getDebugLoc();
6827 Op = Op.getOperand(0);
6828 if (VT == MVT::i8) {
6829 // Zero extend to i32 since there is not an i8 bsr.
6831 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6834 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
6835 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6836 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
6838 // If src is zero (i.e. bsr sets ZF), returns NumBits.
6839 SmallVector<SDValue, 4> Ops;
6841 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
6842 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6843 Ops.push_back(Op.getValue(1));
6844 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6846 // Finally xor with NumBits-1.
6847 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
6850 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6854 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
6855 EVT VT = Op.getValueType();
6857 unsigned NumBits = VT.getSizeInBits();
6858 DebugLoc dl = Op.getDebugLoc();
6860 Op = Op.getOperand(0);
6861 if (VT == MVT::i8) {
6863 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6866 // Issue a bsf (scan bits forward) which also sets EFLAGS.
6867 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6868 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
6870 // If src is zero (i.e. bsf sets ZF), returns NumBits.
6871 SmallVector<SDValue, 4> Ops;
6873 Ops.push_back(DAG.getConstant(NumBits, OpVT));
6874 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6875 Ops.push_back(Op.getValue(1));
6876 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6879 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6883 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
6884 EVT VT = Op.getValueType();
6885 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
6886 DebugLoc dl = Op.getDebugLoc();
6888 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
6889 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
6890 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
6891 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
6892 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
6894 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
6895 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
6896 // return AloBlo + AloBhi + AhiBlo;
6898 SDValue A = Op.getOperand(0);
6899 SDValue B = Op.getOperand(1);
6901 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6902 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6903 A, DAG.getConstant(32, MVT::i32));
6904 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6905 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6906 B, DAG.getConstant(32, MVT::i32));
6907 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6908 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6910 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6911 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6913 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6914 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6916 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6917 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6918 AloBhi, DAG.getConstant(32, MVT::i32));
6919 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6920 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6921 AhiBlo, DAG.getConstant(32, MVT::i32));
6922 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
6923 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
6928 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
6929 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
6930 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
6931 // looks for this combo and may remove the "setcc" instruction if the "setcc"
6932 // has only one use.
6933 SDNode *N = Op.getNode();
6934 SDValue LHS = N->getOperand(0);
6935 SDValue RHS = N->getOperand(1);
6936 unsigned BaseOp = 0;
6938 DebugLoc dl = Op.getDebugLoc();
6940 switch (Op.getOpcode()) {
6941 default: llvm_unreachable("Unknown ovf instruction!");
6943 // A subtract of one will be selected as a INC. Note that INC doesn't
6944 // set CF, so we can't do this for UADDO.
6945 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6946 if (C->getAPIntValue() == 1) {
6947 BaseOp = X86ISD::INC;
6951 BaseOp = X86ISD::ADD;
6955 BaseOp = X86ISD::ADD;
6959 // A subtract of one will be selected as a DEC. Note that DEC doesn't
6960 // set CF, so we can't do this for USUBO.
6961 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6962 if (C->getAPIntValue() == 1) {
6963 BaseOp = X86ISD::DEC;
6967 BaseOp = X86ISD::SUB;
6971 BaseOp = X86ISD::SUB;
6975 BaseOp = X86ISD::SMUL;
6979 BaseOp = X86ISD::UMUL;
6984 // Also sets EFLAGS.
6985 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
6986 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
6989 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
6990 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
6992 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
6996 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
6997 EVT T = Op.getValueType();
6998 DebugLoc dl = Op.getDebugLoc();
7001 switch(T.getSimpleVT().SimpleTy) {
7003 assert(false && "Invalid value type!");
7004 case MVT::i8: Reg = X86::AL; size = 1; break;
7005 case MVT::i16: Reg = X86::AX; size = 2; break;
7006 case MVT::i32: Reg = X86::EAX; size = 4; break;
7008 assert(Subtarget->is64Bit() && "Node not type legal!");
7009 Reg = X86::RAX; size = 8;
7012 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
7013 Op.getOperand(2), SDValue());
7014 SDValue Ops[] = { cpIn.getValue(0),
7017 DAG.getTargetConstant(size, MVT::i8),
7019 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7020 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
7022 DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
7026 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
7027 SelectionDAG &DAG) {
7028 assert(Subtarget->is64Bit() && "Result not type legalized?");
7029 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7030 SDValue TheChain = Op.getOperand(0);
7031 DebugLoc dl = Op.getDebugLoc();
7032 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7033 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
7034 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
7036 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
7037 DAG.getConstant(32, MVT::i8));
7039 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
7042 return DAG.getMergeValues(Ops, 2, dl);
7045 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
7046 SDNode *Node = Op.getNode();
7047 DebugLoc dl = Node->getDebugLoc();
7048 EVT T = Node->getValueType(0);
7049 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
7050 DAG.getConstant(0, T), Node->getOperand(2));
7051 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
7052 cast<AtomicSDNode>(Node)->getMemoryVT(),
7053 Node->getOperand(0),
7054 Node->getOperand(1), negOp,
7055 cast<AtomicSDNode>(Node)->getSrcValue(),
7056 cast<AtomicSDNode>(Node)->getAlignment());
7059 /// LowerOperation - Provide custom lowering hooks for some operations.
7061 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
7062 switch (Op.getOpcode()) {
7063 default: llvm_unreachable("Should not custom lower this!");
7064 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
7065 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
7066 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
7067 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7068 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7069 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7070 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
7071 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
7072 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
7073 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7074 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
7075 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
7076 case ISD::SHL_PARTS:
7077 case ISD::SRA_PARTS:
7078 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
7079 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
7080 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
7081 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
7082 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
7083 case ISD::FABS: return LowerFABS(Op, DAG);
7084 case ISD::FNEG: return LowerFNEG(Op, DAG);
7085 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
7086 case ISD::SETCC: return LowerSETCC(Op, DAG);
7087 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
7088 case ISD::SELECT: return LowerSELECT(Op, DAG);
7089 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
7090 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
7091 case ISD::VASTART: return LowerVASTART(Op, DAG);
7092 case ISD::VAARG: return LowerVAARG(Op, DAG);
7093 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
7094 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7095 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
7096 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
7097 case ISD::FRAME_TO_ARGS_OFFSET:
7098 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
7099 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
7100 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
7101 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
7102 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
7103 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
7104 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
7105 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
7111 case ISD::UMULO: return LowerXALUO(Op, DAG);
7112 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
7116 void X86TargetLowering::
7117 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
7118 SelectionDAG &DAG, unsigned NewOp) {
7119 EVT T = Node->getValueType(0);
7120 DebugLoc dl = Node->getDebugLoc();
7121 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
7123 SDValue Chain = Node->getOperand(0);
7124 SDValue In1 = Node->getOperand(1);
7125 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7126 Node->getOperand(2), DAG.getIntPtrConstant(0));
7127 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7128 Node->getOperand(2), DAG.getIntPtrConstant(1));
7129 SDValue Ops[] = { Chain, In1, In2L, In2H };
7130 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7132 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
7133 cast<MemSDNode>(Node)->getMemOperand());
7134 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7135 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7136 Results.push_back(Result.getValue(2));
7139 /// ReplaceNodeResults - Replace a node with an illegal result type
7140 /// with a new node built out of custom code.
7141 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7142 SmallVectorImpl<SDValue>&Results,
7143 SelectionDAG &DAG) {
7144 DebugLoc dl = N->getDebugLoc();
7145 switch (N->getOpcode()) {
7147 assert(false && "Do not know how to custom type legalize this operation!");
7149 case ISD::FP_TO_SINT: {
7150 std::pair<SDValue,SDValue> Vals =
7151 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
7152 SDValue FIST = Vals.first, StackSlot = Vals.second;
7153 if (FIST.getNode() != 0) {
7154 EVT VT = N->getValueType(0);
7155 // Return a load from the stack slot.
7156 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0));
7160 case ISD::READCYCLECOUNTER: {
7161 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7162 SDValue TheChain = N->getOperand(0);
7163 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7164 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7166 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7168 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7169 SDValue Ops[] = { eax, edx };
7170 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7171 Results.push_back(edx.getValue(1));
7174 case ISD::ATOMIC_CMP_SWAP: {
7175 EVT T = N->getValueType(0);
7176 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7177 SDValue cpInL, cpInH;
7178 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7179 DAG.getConstant(0, MVT::i32));
7180 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7181 DAG.getConstant(1, MVT::i32));
7182 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7183 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7185 SDValue swapInL, swapInH;
7186 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7187 DAG.getConstant(0, MVT::i32));
7188 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7189 DAG.getConstant(1, MVT::i32));
7190 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7192 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7193 swapInL.getValue(1));
7194 SDValue Ops[] = { swapInH.getValue(0),
7196 swapInH.getValue(1) };
7197 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7198 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7199 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7200 MVT::i32, Result.getValue(1));
7201 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7202 MVT::i32, cpOutL.getValue(2));
7203 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7204 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7205 Results.push_back(cpOutH.getValue(1));
7208 case ISD::ATOMIC_LOAD_ADD:
7209 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7211 case ISD::ATOMIC_LOAD_AND:
7212 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7214 case ISD::ATOMIC_LOAD_NAND:
7215 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7217 case ISD::ATOMIC_LOAD_OR:
7218 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7220 case ISD::ATOMIC_LOAD_SUB:
7221 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7223 case ISD::ATOMIC_LOAD_XOR:
7224 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7226 case ISD::ATOMIC_SWAP:
7227 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7232 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7234 default: return NULL;
7235 case X86ISD::BSF: return "X86ISD::BSF";
7236 case X86ISD::BSR: return "X86ISD::BSR";
7237 case X86ISD::SHLD: return "X86ISD::SHLD";
7238 case X86ISD::SHRD: return "X86ISD::SHRD";
7239 case X86ISD::FAND: return "X86ISD::FAND";
7240 case X86ISD::FOR: return "X86ISD::FOR";
7241 case X86ISD::FXOR: return "X86ISD::FXOR";
7242 case X86ISD::FSRL: return "X86ISD::FSRL";
7243 case X86ISD::FILD: return "X86ISD::FILD";
7244 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
7245 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7246 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7247 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7248 case X86ISD::FLD: return "X86ISD::FLD";
7249 case X86ISD::FST: return "X86ISD::FST";
7250 case X86ISD::CALL: return "X86ISD::CALL";
7251 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
7252 case X86ISD::BT: return "X86ISD::BT";
7253 case X86ISD::CMP: return "X86ISD::CMP";
7254 case X86ISD::COMI: return "X86ISD::COMI";
7255 case X86ISD::UCOMI: return "X86ISD::UCOMI";
7256 case X86ISD::SETCC: return "X86ISD::SETCC";
7257 case X86ISD::CMOV: return "X86ISD::CMOV";
7258 case X86ISD::BRCOND: return "X86ISD::BRCOND";
7259 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
7260 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
7261 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
7262 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
7263 case X86ISD::Wrapper: return "X86ISD::Wrapper";
7264 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
7265 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
7266 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
7267 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
7268 case X86ISD::PINSRB: return "X86ISD::PINSRB";
7269 case X86ISD::PINSRW: return "X86ISD::PINSRW";
7270 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
7271 case X86ISD::FMAX: return "X86ISD::FMAX";
7272 case X86ISD::FMIN: return "X86ISD::FMIN";
7273 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
7274 case X86ISD::FRCP: return "X86ISD::FRCP";
7275 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
7276 case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7277 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
7278 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
7279 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
7280 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
7281 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
7282 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
7283 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
7284 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
7285 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
7286 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
7287 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
7288 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
7289 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
7290 case X86ISD::VSHL: return "X86ISD::VSHL";
7291 case X86ISD::VSRL: return "X86ISD::VSRL";
7292 case X86ISD::CMPPD: return "X86ISD::CMPPD";
7293 case X86ISD::CMPPS: return "X86ISD::CMPPS";
7294 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
7295 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
7296 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
7297 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
7298 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
7299 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
7300 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
7301 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
7302 case X86ISD::ADD: return "X86ISD::ADD";
7303 case X86ISD::SUB: return "X86ISD::SUB";
7304 case X86ISD::SMUL: return "X86ISD::SMUL";
7305 case X86ISD::UMUL: return "X86ISD::UMUL";
7306 case X86ISD::INC: return "X86ISD::INC";
7307 case X86ISD::DEC: return "X86ISD::DEC";
7308 case X86ISD::OR: return "X86ISD::OR";
7309 case X86ISD::XOR: return "X86ISD::XOR";
7310 case X86ISD::AND: return "X86ISD::AND";
7311 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
7312 case X86ISD::PTEST: return "X86ISD::PTEST";
7313 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
7317 // isLegalAddressingMode - Return true if the addressing mode represented
7318 // by AM is legal for this target, for a load/store of the specified type.
7319 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7320 const Type *Ty) const {
7321 // X86 supports extremely general addressing modes.
7322 CodeModel::Model M = getTargetMachine().getCodeModel();
7324 // X86 allows a sign-extended 32-bit immediate field as a displacement.
7325 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
7330 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7332 // If a reference to this global requires an extra load, we can't fold it.
7333 if (isGlobalStubReference(GVFlags))
7336 // If BaseGV requires a register for the PIC base, we cannot also have a
7337 // BaseReg specified.
7338 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
7341 // If lower 4G is not available, then we must use rip-relative addressing.
7342 if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
7352 // These scales always work.
7357 // These scales are formed with basereg+scalereg. Only accept if there is
7362 default: // Other stuff never works.
7370 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7371 if (!Ty1->isInteger() || !Ty2->isInteger())
7373 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7374 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7375 if (NumBits1 <= NumBits2)
7377 return Subtarget->is64Bit() || NumBits1 < 64;
7380 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7381 if (!VT1.isInteger() || !VT2.isInteger())
7383 unsigned NumBits1 = VT1.getSizeInBits();
7384 unsigned NumBits2 = VT2.getSizeInBits();
7385 if (NumBits1 <= NumBits2)
7387 return Subtarget->is64Bit() || NumBits1 < 64;
7390 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7391 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7392 return Ty1 == Type::getInt32Ty(Ty1->getContext()) &&
7393 Ty2 == Type::getInt64Ty(Ty1->getContext()) && Subtarget->is64Bit();
7396 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7397 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7398 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7401 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
7402 // i16 instructions are longer (0x66 prefix) and potentially slower.
7403 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7406 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7407 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7408 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7409 /// are assumed to be legal.
7411 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
7413 // Only do shuffles on 128-bit vector types for now.
7414 if (VT.getSizeInBits() == 64)
7417 // FIXME: pshufb, blends, shifts.
7418 return (VT.getVectorNumElements() == 2 ||
7419 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7420 isMOVLMask(M, VT) ||
7421 isSHUFPMask(M, VT) ||
7422 isPSHUFDMask(M, VT) ||
7423 isPSHUFHWMask(M, VT) ||
7424 isPSHUFLWMask(M, VT) ||
7425 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
7426 isUNPCKLMask(M, VT) ||
7427 isUNPCKHMask(M, VT) ||
7428 isUNPCKL_v_undef_Mask(M, VT) ||
7429 isUNPCKH_v_undef_Mask(M, VT));
7433 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
7435 unsigned NumElts = VT.getVectorNumElements();
7436 // FIXME: This collection of masks seems suspect.
7439 if (NumElts == 4 && VT.getSizeInBits() == 128) {
7440 return (isMOVLMask(Mask, VT) ||
7441 isCommutedMOVLMask(Mask, VT, true) ||
7442 isSHUFPMask(Mask, VT) ||
7443 isCommutedSHUFPMask(Mask, VT));
7448 //===----------------------------------------------------------------------===//
7449 // X86 Scheduler Hooks
7450 //===----------------------------------------------------------------------===//
7452 // private utility function
7454 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7455 MachineBasicBlock *MBB,
7463 TargetRegisterClass *RC,
7464 bool invSrc) const {
7465 // For the atomic bitwise operator, we generate
7468 // ld t1 = [bitinstr.addr]
7469 // op t2 = t1, [bitinstr.val]
7471 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7473 // fallthrough -->nextMBB
7474 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7475 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7476 MachineFunction::iterator MBBIter = MBB;
7479 /// First build the CFG
7480 MachineFunction *F = MBB->getParent();
7481 MachineBasicBlock *thisMBB = MBB;
7482 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7483 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7484 F->insert(MBBIter, newMBB);
7485 F->insert(MBBIter, nextMBB);
7487 // Move all successors to thisMBB to nextMBB
7488 nextMBB->transferSuccessors(thisMBB);
7490 // Update thisMBB to fall through to newMBB
7491 thisMBB->addSuccessor(newMBB);
7493 // newMBB jumps to itself and fall through to nextMBB
7494 newMBB->addSuccessor(nextMBB);
7495 newMBB->addSuccessor(newMBB);
7497 // Insert instructions into newMBB based on incoming instruction
7498 assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7499 "unexpected number of operands");
7500 DebugLoc dl = bInstr->getDebugLoc();
7501 MachineOperand& destOper = bInstr->getOperand(0);
7502 MachineOperand* argOpers[2 + X86AddrNumOperands];
7503 int numArgs = bInstr->getNumOperands() - 1;
7504 for (int i=0; i < numArgs; ++i)
7505 argOpers[i] = &bInstr->getOperand(i+1);
7507 // x86 address has 4 operands: base, index, scale, and displacement
7508 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7509 int valArgIndx = lastAddrIndx + 1;
7511 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7512 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7513 for (int i=0; i <= lastAddrIndx; ++i)
7514 (*MIB).addOperand(*argOpers[i]);
7516 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7518 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7523 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7524 assert((argOpers[valArgIndx]->isReg() ||
7525 argOpers[valArgIndx]->isImm()) &&
7527 if (argOpers[valArgIndx]->isReg())
7528 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7530 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7532 (*MIB).addOperand(*argOpers[valArgIndx]);
7534 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7537 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7538 for (int i=0; i <= lastAddrIndx; ++i)
7539 (*MIB).addOperand(*argOpers[i]);
7541 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7542 (*MIB).setMemRefs(bInstr->memoperands_begin(),
7543 bInstr->memoperands_end());
7545 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7549 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7551 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7555 // private utility function: 64 bit atomics on 32 bit host.
7557 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7558 MachineBasicBlock *MBB,
7563 bool invSrc) const {
7564 // For the atomic bitwise operator, we generate
7565 // thisMBB (instructions are in pairs, except cmpxchg8b)
7566 // ld t1,t2 = [bitinstr.addr]
7568 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7569 // op t5, t6 <- out1, out2, [bitinstr.val]
7570 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
7571 // mov ECX, EBX <- t5, t6
7572 // mov EAX, EDX <- t1, t2
7573 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
7574 // mov t3, t4 <- EAX, EDX
7576 // result in out1, out2
7577 // fallthrough -->nextMBB
7579 const TargetRegisterClass *RC = X86::GR32RegisterClass;
7580 const unsigned LoadOpc = X86::MOV32rm;
7581 const unsigned copyOpc = X86::MOV32rr;
7582 const unsigned NotOpc = X86::NOT32r;
7583 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7584 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7585 MachineFunction::iterator MBBIter = MBB;
7588 /// First build the CFG
7589 MachineFunction *F = MBB->getParent();
7590 MachineBasicBlock *thisMBB = MBB;
7591 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7592 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7593 F->insert(MBBIter, newMBB);
7594 F->insert(MBBIter, nextMBB);
7596 // Move all successors to thisMBB to nextMBB
7597 nextMBB->transferSuccessors(thisMBB);
7599 // Update thisMBB to fall through to newMBB
7600 thisMBB->addSuccessor(newMBB);
7602 // newMBB jumps to itself and fall through to nextMBB
7603 newMBB->addSuccessor(nextMBB);
7604 newMBB->addSuccessor(newMBB);
7606 DebugLoc dl = bInstr->getDebugLoc();
7607 // Insert instructions into newMBB based on incoming instruction
7608 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7609 assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
7610 "unexpected number of operands");
7611 MachineOperand& dest1Oper = bInstr->getOperand(0);
7612 MachineOperand& dest2Oper = bInstr->getOperand(1);
7613 MachineOperand* argOpers[2 + X86AddrNumOperands];
7614 for (int i=0; i < 2 + X86AddrNumOperands; ++i)
7615 argOpers[i] = &bInstr->getOperand(i+2);
7617 // x86 address has 4 operands: base, index, scale, and displacement
7618 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7620 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7621 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
7622 for (int i=0; i <= lastAddrIndx; ++i)
7623 (*MIB).addOperand(*argOpers[i]);
7624 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7625 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
7626 // add 4 to displacement.
7627 for (int i=0; i <= lastAddrIndx-2; ++i)
7628 (*MIB).addOperand(*argOpers[i]);
7629 MachineOperand newOp3 = *(argOpers[3]);
7631 newOp3.setImm(newOp3.getImm()+4);
7633 newOp3.setOffset(newOp3.getOffset()+4);
7634 (*MIB).addOperand(newOp3);
7635 (*MIB).addOperand(*argOpers[lastAddrIndx]);
7637 // t3/4 are defined later, at the bottom of the loop
7638 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
7639 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
7640 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
7641 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
7642 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
7643 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
7645 unsigned tt1 = F->getRegInfo().createVirtualRegister(RC);
7646 unsigned tt2 = F->getRegInfo().createVirtualRegister(RC);
7648 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt1).addReg(t1);
7649 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt2).addReg(t2);
7655 int valArgIndx = lastAddrIndx + 1;
7656 assert((argOpers[valArgIndx]->isReg() ||
7657 argOpers[valArgIndx]->isImm()) &&
7659 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
7660 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
7661 if (argOpers[valArgIndx]->isReg())
7662 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
7664 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
7665 if (regOpcL != X86::MOV32rr)
7667 (*MIB).addOperand(*argOpers[valArgIndx]);
7668 assert(argOpers[valArgIndx + 1]->isReg() ==
7669 argOpers[valArgIndx]->isReg());
7670 assert(argOpers[valArgIndx + 1]->isImm() ==
7671 argOpers[valArgIndx]->isImm());
7672 if (argOpers[valArgIndx + 1]->isReg())
7673 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
7675 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
7676 if (regOpcH != X86::MOV32rr)
7678 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
7680 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
7682 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
7685 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
7687 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
7690 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
7691 for (int i=0; i <= lastAddrIndx; ++i)
7692 (*MIB).addOperand(*argOpers[i]);
7694 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7695 (*MIB).setMemRefs(bInstr->memoperands_begin(),
7696 bInstr->memoperands_end());
7698 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
7699 MIB.addReg(X86::EAX);
7700 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
7701 MIB.addReg(X86::EDX);
7704 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7706 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7710 // private utility function
7712 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
7713 MachineBasicBlock *MBB,
7714 unsigned cmovOpc) const {
7715 // For the atomic min/max operator, we generate
7718 // ld t1 = [min/max.addr]
7719 // mov t2 = [min/max.val]
7721 // cmov[cond] t2 = t1
7723 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7725 // fallthrough -->nextMBB
7727 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7728 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7729 MachineFunction::iterator MBBIter = MBB;
7732 /// First build the CFG
7733 MachineFunction *F = MBB->getParent();
7734 MachineBasicBlock *thisMBB = MBB;
7735 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7736 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7737 F->insert(MBBIter, newMBB);
7738 F->insert(MBBIter, nextMBB);
7740 // Move all successors of thisMBB to nextMBB
7741 nextMBB->transferSuccessors(thisMBB);
7743 // Update thisMBB to fall through to newMBB
7744 thisMBB->addSuccessor(newMBB);
7746 // newMBB jumps to newMBB and fall through to nextMBB
7747 newMBB->addSuccessor(nextMBB);
7748 newMBB->addSuccessor(newMBB);
7750 DebugLoc dl = mInstr->getDebugLoc();
7751 // Insert instructions into newMBB based on incoming instruction
7752 assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7753 "unexpected number of operands");
7754 MachineOperand& destOper = mInstr->getOperand(0);
7755 MachineOperand* argOpers[2 + X86AddrNumOperands];
7756 int numArgs = mInstr->getNumOperands() - 1;
7757 for (int i=0; i < numArgs; ++i)
7758 argOpers[i] = &mInstr->getOperand(i+1);
7760 // x86 address has 4 operands: base, index, scale, and displacement
7761 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7762 int valArgIndx = lastAddrIndx + 1;
7764 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7765 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
7766 for (int i=0; i <= lastAddrIndx; ++i)
7767 (*MIB).addOperand(*argOpers[i]);
7769 // We only support register and immediate values
7770 assert((argOpers[valArgIndx]->isReg() ||
7771 argOpers[valArgIndx]->isImm()) &&
7774 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7775 if (argOpers[valArgIndx]->isReg())
7776 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7778 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7779 (*MIB).addOperand(*argOpers[valArgIndx]);
7781 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
7784 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
7789 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7790 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
7794 // Cmp and exchange if none has modified the memory location
7795 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
7796 for (int i=0; i <= lastAddrIndx; ++i)
7797 (*MIB).addOperand(*argOpers[i]);
7799 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7800 (*MIB).setMemRefs(mInstr->memoperands_begin(),
7801 mInstr->memoperands_end());
7803 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
7804 MIB.addReg(X86::EAX);
7807 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7809 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
7813 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
7814 // all of this code can be replaced with that in the .td file.
7816 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
7817 unsigned numArgs, bool memArg) const {
7819 MachineFunction *F = BB->getParent();
7820 DebugLoc dl = MI->getDebugLoc();
7821 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7825 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
7827 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
7829 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
7831 for (unsigned i = 0; i < numArgs; ++i) {
7832 MachineOperand &Op = MI->getOperand(i+1);
7834 if (!(Op.isReg() && Op.isImplicit()))
7838 BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
7841 F->DeleteMachineInstr(MI);
7847 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
7849 MachineBasicBlock *MBB) const {
7850 // Emit code to save XMM registers to the stack. The ABI says that the
7851 // number of registers to save is given in %al, so it's theoretically
7852 // possible to do an indirect jump trick to avoid saving all of them,
7853 // however this code takes a simpler approach and just executes all
7854 // of the stores if %al is non-zero. It's less code, and it's probably
7855 // easier on the hardware branch predictor, and stores aren't all that
7856 // expensive anyway.
7858 // Create the new basic blocks. One block contains all the XMM stores,
7859 // and one block is the final destination regardless of whether any
7860 // stores were performed.
7861 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7862 MachineFunction *F = MBB->getParent();
7863 MachineFunction::iterator MBBIter = MBB;
7865 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
7866 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
7867 F->insert(MBBIter, XMMSaveMBB);
7868 F->insert(MBBIter, EndMBB);
7871 // Move any original successors of MBB to the end block.
7872 EndMBB->transferSuccessors(MBB);
7873 // The original block will now fall through to the XMM save block.
7874 MBB->addSuccessor(XMMSaveMBB);
7875 // The XMMSaveMBB will fall through to the end block.
7876 XMMSaveMBB->addSuccessor(EndMBB);
7878 // Now add the instructions.
7879 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7880 DebugLoc DL = MI->getDebugLoc();
7882 unsigned CountReg = MI->getOperand(0).getReg();
7883 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
7884 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
7886 if (!Subtarget->isTargetWin64()) {
7887 // If %al is 0, branch around the XMM save block.
7888 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
7889 BuildMI(MBB, DL, TII->get(X86::JE)).addMBB(EndMBB);
7890 MBB->addSuccessor(EndMBB);
7893 // In the XMM save block, save all the XMM argument registers.
7894 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
7895 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
7896 MachineMemOperand *MMO =
7897 F->getMachineMemOperand(
7898 PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
7899 MachineMemOperand::MOStore, Offset,
7900 /*Size=*/16, /*Align=*/16);
7901 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
7902 .addFrameIndex(RegSaveFrameIndex)
7903 .addImm(/*Scale=*/1)
7904 .addReg(/*IndexReg=*/0)
7905 .addImm(/*Disp=*/Offset)
7906 .addReg(/*Segment=*/0)
7907 .addReg(MI->getOperand(i).getReg())
7908 .addMemOperand(MMO);
7911 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7917 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
7918 MachineBasicBlock *BB,
7919 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
7920 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7921 DebugLoc DL = MI->getDebugLoc();
7923 // To "insert" a SELECT_CC instruction, we actually have to insert the
7924 // diamond control-flow pattern. The incoming instruction knows the
7925 // destination vreg to set, the condition code register to branch on, the
7926 // true/false values to select between, and a branch opcode to use.
7927 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7928 MachineFunction::iterator It = BB;
7934 // cmpTY ccX, r1, r2
7936 // fallthrough --> copy0MBB
7937 MachineBasicBlock *thisMBB = BB;
7938 MachineFunction *F = BB->getParent();
7939 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7940 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7942 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
7943 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
7944 F->insert(It, copy0MBB);
7945 F->insert(It, sinkMBB);
7946 // Update machine-CFG edges by first adding all successors of the current
7947 // block to the new block which will contain the Phi node for the select.
7948 // Also inform sdisel of the edge changes.
7949 for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
7950 E = BB->succ_end(); I != E; ++I) {
7951 EM->insert(std::make_pair(*I, sinkMBB));
7952 sinkMBB->addSuccessor(*I);
7954 // Next, remove all successors of the current block, and add the true
7955 // and fallthrough blocks as its successors.
7956 while (!BB->succ_empty())
7957 BB->removeSuccessor(BB->succ_begin());
7958 // Add the true and fallthrough blocks as its successors.
7959 BB->addSuccessor(copy0MBB);
7960 BB->addSuccessor(sinkMBB);
7963 // %FalseValue = ...
7964 // # fallthrough to sinkMBB
7967 // Update machine-CFG edges
7968 BB->addSuccessor(sinkMBB);
7971 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7974 BuildMI(BB, DL, TII->get(X86::PHI), MI->getOperand(0).getReg())
7975 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7976 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7978 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7984 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7985 MachineBasicBlock *BB,
7986 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
7987 switch (MI->getOpcode()) {
7988 default: assert(false && "Unexpected instr type to insert");
7990 case X86::CMOV_V1I64:
7991 case X86::CMOV_FR32:
7992 case X86::CMOV_FR64:
7993 case X86::CMOV_V4F32:
7994 case X86::CMOV_V2F64:
7995 case X86::CMOV_V2I64:
7996 return EmitLoweredSelect(MI, BB, EM);
7998 case X86::FP32_TO_INT16_IN_MEM:
7999 case X86::FP32_TO_INT32_IN_MEM:
8000 case X86::FP32_TO_INT64_IN_MEM:
8001 case X86::FP64_TO_INT16_IN_MEM:
8002 case X86::FP64_TO_INT32_IN_MEM:
8003 case X86::FP64_TO_INT64_IN_MEM:
8004 case X86::FP80_TO_INT16_IN_MEM:
8005 case X86::FP80_TO_INT32_IN_MEM:
8006 case X86::FP80_TO_INT64_IN_MEM: {
8007 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8008 DebugLoc DL = MI->getDebugLoc();
8010 // Change the floating point control register to use "round towards zero"
8011 // mode when truncating to an integer value.
8012 MachineFunction *F = BB->getParent();
8013 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
8014 addFrameReference(BuildMI(BB, DL, TII->get(X86::FNSTCW16m)), CWFrameIdx);
8016 // Load the old value of the high byte of the control word...
8018 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
8019 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16rm), OldCW),
8022 // Set the high part to be round to zero...
8023 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
8026 // Reload the modified control word now...
8027 addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8029 // Restore the memory image of control word to original value
8030 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
8033 // Get the X86 opcode to use.
8035 switch (MI->getOpcode()) {
8036 default: llvm_unreachable("illegal opcode!");
8037 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
8038 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
8039 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
8040 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
8041 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
8042 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
8043 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
8044 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
8045 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
8049 MachineOperand &Op = MI->getOperand(0);
8051 AM.BaseType = X86AddressMode::RegBase;
8052 AM.Base.Reg = Op.getReg();
8054 AM.BaseType = X86AddressMode::FrameIndexBase;
8055 AM.Base.FrameIndex = Op.getIndex();
8057 Op = MI->getOperand(1);
8059 AM.Scale = Op.getImm();
8060 Op = MI->getOperand(2);
8062 AM.IndexReg = Op.getImm();
8063 Op = MI->getOperand(3);
8064 if (Op.isGlobal()) {
8065 AM.GV = Op.getGlobal();
8067 AM.Disp = Op.getImm();
8069 addFullAddress(BuildMI(BB, DL, TII->get(Opc)), AM)
8070 .addReg(MI->getOperand(X86AddrNumOperands).getReg());
8072 // Reload the original control word now.
8073 addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8075 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8078 // String/text processing lowering.
8079 case X86::PCMPISTRM128REG:
8080 return EmitPCMP(MI, BB, 3, false /* in-mem */);
8081 case X86::PCMPISTRM128MEM:
8082 return EmitPCMP(MI, BB, 3, true /* in-mem */);
8083 case X86::PCMPESTRM128REG:
8084 return EmitPCMP(MI, BB, 5, false /* in mem */);
8085 case X86::PCMPESTRM128MEM:
8086 return EmitPCMP(MI, BB, 5, true /* in mem */);
8089 case X86::ATOMAND32:
8090 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8091 X86::AND32ri, X86::MOV32rm,
8092 X86::LCMPXCHG32, X86::MOV32rr,
8093 X86::NOT32r, X86::EAX,
8094 X86::GR32RegisterClass);
8096 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
8097 X86::OR32ri, X86::MOV32rm,
8098 X86::LCMPXCHG32, X86::MOV32rr,
8099 X86::NOT32r, X86::EAX,
8100 X86::GR32RegisterClass);
8101 case X86::ATOMXOR32:
8102 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
8103 X86::XOR32ri, X86::MOV32rm,
8104 X86::LCMPXCHG32, X86::MOV32rr,
8105 X86::NOT32r, X86::EAX,
8106 X86::GR32RegisterClass);
8107 case X86::ATOMNAND32:
8108 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8109 X86::AND32ri, X86::MOV32rm,
8110 X86::LCMPXCHG32, X86::MOV32rr,
8111 X86::NOT32r, X86::EAX,
8112 X86::GR32RegisterClass, true);
8113 case X86::ATOMMIN32:
8114 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
8115 case X86::ATOMMAX32:
8116 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
8117 case X86::ATOMUMIN32:
8118 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
8119 case X86::ATOMUMAX32:
8120 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
8122 case X86::ATOMAND16:
8123 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8124 X86::AND16ri, X86::MOV16rm,
8125 X86::LCMPXCHG16, X86::MOV16rr,
8126 X86::NOT16r, X86::AX,
8127 X86::GR16RegisterClass);
8129 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
8130 X86::OR16ri, X86::MOV16rm,
8131 X86::LCMPXCHG16, X86::MOV16rr,
8132 X86::NOT16r, X86::AX,
8133 X86::GR16RegisterClass);
8134 case X86::ATOMXOR16:
8135 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
8136 X86::XOR16ri, X86::MOV16rm,
8137 X86::LCMPXCHG16, X86::MOV16rr,
8138 X86::NOT16r, X86::AX,
8139 X86::GR16RegisterClass);
8140 case X86::ATOMNAND16:
8141 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8142 X86::AND16ri, X86::MOV16rm,
8143 X86::LCMPXCHG16, X86::MOV16rr,
8144 X86::NOT16r, X86::AX,
8145 X86::GR16RegisterClass, true);
8146 case X86::ATOMMIN16:
8147 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
8148 case X86::ATOMMAX16:
8149 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
8150 case X86::ATOMUMIN16:
8151 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
8152 case X86::ATOMUMAX16:
8153 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
8156 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8157 X86::AND8ri, X86::MOV8rm,
8158 X86::LCMPXCHG8, X86::MOV8rr,
8159 X86::NOT8r, X86::AL,
8160 X86::GR8RegisterClass);
8162 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
8163 X86::OR8ri, X86::MOV8rm,
8164 X86::LCMPXCHG8, X86::MOV8rr,
8165 X86::NOT8r, X86::AL,
8166 X86::GR8RegisterClass);
8168 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
8169 X86::XOR8ri, X86::MOV8rm,
8170 X86::LCMPXCHG8, X86::MOV8rr,
8171 X86::NOT8r, X86::AL,
8172 X86::GR8RegisterClass);
8173 case X86::ATOMNAND8:
8174 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8175 X86::AND8ri, X86::MOV8rm,
8176 X86::LCMPXCHG8, X86::MOV8rr,
8177 X86::NOT8r, X86::AL,
8178 X86::GR8RegisterClass, true);
8179 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
8180 // This group is for 64-bit host.
8181 case X86::ATOMAND64:
8182 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8183 X86::AND64ri32, X86::MOV64rm,
8184 X86::LCMPXCHG64, X86::MOV64rr,
8185 X86::NOT64r, X86::RAX,
8186 X86::GR64RegisterClass);
8188 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
8189 X86::OR64ri32, X86::MOV64rm,
8190 X86::LCMPXCHG64, X86::MOV64rr,
8191 X86::NOT64r, X86::RAX,
8192 X86::GR64RegisterClass);
8193 case X86::ATOMXOR64:
8194 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
8195 X86::XOR64ri32, X86::MOV64rm,
8196 X86::LCMPXCHG64, X86::MOV64rr,
8197 X86::NOT64r, X86::RAX,
8198 X86::GR64RegisterClass);
8199 case X86::ATOMNAND64:
8200 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8201 X86::AND64ri32, X86::MOV64rm,
8202 X86::LCMPXCHG64, X86::MOV64rr,
8203 X86::NOT64r, X86::RAX,
8204 X86::GR64RegisterClass, true);
8205 case X86::ATOMMIN64:
8206 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
8207 case X86::ATOMMAX64:
8208 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
8209 case X86::ATOMUMIN64:
8210 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
8211 case X86::ATOMUMAX64:
8212 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
8214 // This group does 64-bit operations on a 32-bit host.
8215 case X86::ATOMAND6432:
8216 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8217 X86::AND32rr, X86::AND32rr,
8218 X86::AND32ri, X86::AND32ri,
8220 case X86::ATOMOR6432:
8221 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8222 X86::OR32rr, X86::OR32rr,
8223 X86::OR32ri, X86::OR32ri,
8225 case X86::ATOMXOR6432:
8226 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8227 X86::XOR32rr, X86::XOR32rr,
8228 X86::XOR32ri, X86::XOR32ri,
8230 case X86::ATOMNAND6432:
8231 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8232 X86::AND32rr, X86::AND32rr,
8233 X86::AND32ri, X86::AND32ri,
8235 case X86::ATOMADD6432:
8236 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8237 X86::ADD32rr, X86::ADC32rr,
8238 X86::ADD32ri, X86::ADC32ri,
8240 case X86::ATOMSUB6432:
8241 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8242 X86::SUB32rr, X86::SBB32rr,
8243 X86::SUB32ri, X86::SBB32ri,
8245 case X86::ATOMSWAP6432:
8246 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8247 X86::MOV32rr, X86::MOV32rr,
8248 X86::MOV32ri, X86::MOV32ri,
8250 case X86::VASTART_SAVE_XMM_REGS:
8251 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
8255 //===----------------------------------------------------------------------===//
8256 // X86 Optimization Hooks
8257 //===----------------------------------------------------------------------===//
8259 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8263 const SelectionDAG &DAG,
8264 unsigned Depth) const {
8265 unsigned Opc = Op.getOpcode();
8266 assert((Opc >= ISD::BUILTIN_OP_END ||
8267 Opc == ISD::INTRINSIC_WO_CHAIN ||
8268 Opc == ISD::INTRINSIC_W_CHAIN ||
8269 Opc == ISD::INTRINSIC_VOID) &&
8270 "Should use MaskedValueIsZero if you don't know whether Op"
8271 " is a target node!");
8273 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
8285 // These nodes' second result is a boolean.
8286 if (Op.getResNo() == 0)
8290 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
8291 Mask.getBitWidth() - 1);
8296 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
8297 /// node is a GlobalAddress + offset.
8298 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
8299 GlobalValue* &GA, int64_t &Offset) const{
8300 if (N->getOpcode() == X86ISD::Wrapper) {
8301 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
8302 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
8303 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
8307 return TargetLowering::isGAPlusOffset(N, GA, Offset);
8310 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
8311 const TargetLowering &TLI) {
8314 if (TLI.isGAPlusOffset(Base, GV, Offset))
8315 return (GV->getAlignment() >= N && (Offset % N) == 0);
8316 // DAG combine handles the stack object case.
8320 static bool EltsFromConsecutiveLoads(ShuffleVectorSDNode *N, unsigned NumElems,
8321 EVT EltVT, LoadSDNode *&LDBase,
8322 unsigned &LastLoadedElt,
8323 SelectionDAG &DAG, MachineFrameInfo *MFI,
8324 const TargetLowering &TLI) {
8326 LastLoadedElt = -1U;
8327 for (unsigned i = 0; i < NumElems; ++i) {
8328 if (N->getMaskElt(i) < 0) {
8334 SDValue Elt = DAG.getShuffleScalarElt(N, i);
8335 if (!Elt.getNode() ||
8336 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
8339 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
8341 LDBase = cast<LoadSDNode>(Elt.getNode());
8345 if (Elt.getOpcode() == ISD::UNDEF)
8348 LoadSDNode *LD = cast<LoadSDNode>(Elt);
8349 if (!TLI.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i, MFI))
8356 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8357 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8358 /// if the load addresses are consecutive, non-overlapping, and in the right
8359 /// order. In the case of v2i64, it will see if it can rewrite the
8360 /// shuffle to be an appropriate build vector so it can take advantage of
8361 // performBuildVectorCombine.
8362 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8363 const TargetLowering &TLI) {
8364 DebugLoc dl = N->getDebugLoc();
8365 EVT VT = N->getValueType(0);
8366 EVT EltVT = VT.getVectorElementType();
8367 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8368 unsigned NumElems = VT.getVectorNumElements();
8370 if (VT.getSizeInBits() != 128)
8373 // Try to combine a vector_shuffle into a 128-bit load.
8374 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8375 LoadSDNode *LD = NULL;
8376 unsigned LastLoadedElt;
8377 if (!EltsFromConsecutiveLoads(SVN, NumElems, EltVT, LD, LastLoadedElt, DAG,
8381 if (LastLoadedElt == NumElems - 1) {
8382 if (isBaseAlignmentOfN(16, LD->getBasePtr().getNode(), TLI))
8383 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8384 LD->getSrcValue(), LD->getSrcValueOffset(),
8386 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8387 LD->getSrcValue(), LD->getSrcValueOffset(),
8388 LD->isVolatile(), LD->getAlignment());
8389 } else if (NumElems == 4 && LastLoadedElt == 1) {
8390 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
8391 SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
8392 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
8393 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
8398 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
8399 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
8400 const X86Subtarget *Subtarget) {
8401 DebugLoc DL = N->getDebugLoc();
8402 SDValue Cond = N->getOperand(0);
8403 // Get the LHS/RHS of the select.
8404 SDValue LHS = N->getOperand(1);
8405 SDValue RHS = N->getOperand(2);
8407 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
8408 // instructions have the peculiarity that if either operand is a NaN,
8409 // they chose what we call the RHS operand (and as such are not symmetric).
8410 // It happens that this matches the semantics of the common C idiom
8411 // x<y?x:y and related forms, so we can recognize these cases.
8412 if (Subtarget->hasSSE2() &&
8413 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
8414 Cond.getOpcode() == ISD::SETCC) {
8415 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
8417 unsigned Opcode = 0;
8418 // Check for x CC y ? x : y.
8419 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
8423 // This can be a min if we can prove that at least one of the operands
8425 if (!FiniteOnlyFPMath()) {
8426 if (DAG.isKnownNeverNaN(RHS)) {
8427 // Put the potential NaN in the RHS so that SSE will preserve it.
8428 std::swap(LHS, RHS);
8429 } else if (!DAG.isKnownNeverNaN(LHS))
8432 Opcode = X86ISD::FMIN;
8435 // This can be a min if we can prove that at least one of the operands
8437 if (!FiniteOnlyFPMath()) {
8438 if (DAG.isKnownNeverNaN(LHS)) {
8439 // Put the potential NaN in the RHS so that SSE will preserve it.
8440 std::swap(LHS, RHS);
8441 } else if (!DAG.isKnownNeverNaN(RHS))
8444 Opcode = X86ISD::FMIN;
8447 // This can be a min, but if either operand is a NaN we need it to
8448 // preserve the original LHS.
8449 std::swap(LHS, RHS);
8453 Opcode = X86ISD::FMIN;
8457 // This can be a max if we can prove that at least one of the operands
8459 if (!FiniteOnlyFPMath()) {
8460 if (DAG.isKnownNeverNaN(LHS)) {
8461 // Put the potential NaN in the RHS so that SSE will preserve it.
8462 std::swap(LHS, RHS);
8463 } else if (!DAG.isKnownNeverNaN(RHS))
8466 Opcode = X86ISD::FMAX;
8469 // This can be a max if we can prove that at least one of the operands
8471 if (!FiniteOnlyFPMath()) {
8472 if (DAG.isKnownNeverNaN(RHS)) {
8473 // Put the potential NaN in the RHS so that SSE will preserve it.
8474 std::swap(LHS, RHS);
8475 } else if (!DAG.isKnownNeverNaN(LHS))
8478 Opcode = X86ISD::FMAX;
8481 // This can be a max, but if either operand is a NaN we need it to
8482 // preserve the original LHS.
8483 std::swap(LHS, RHS);
8487 Opcode = X86ISD::FMAX;
8490 // Check for x CC y ? y : x -- a min/max with reversed arms.
8491 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
8495 // This can be a min if we can prove that at least one of the operands
8497 if (!FiniteOnlyFPMath()) {
8498 if (DAG.isKnownNeverNaN(RHS)) {
8499 // Put the potential NaN in the RHS so that SSE will preserve it.
8500 std::swap(LHS, RHS);
8501 } else if (!DAG.isKnownNeverNaN(LHS))
8504 Opcode = X86ISD::FMIN;
8507 // This can be a min if we can prove that at least one of the operands
8509 if (!FiniteOnlyFPMath()) {
8510 if (DAG.isKnownNeverNaN(LHS)) {
8511 // Put the potential NaN in the RHS so that SSE will preserve it.
8512 std::swap(LHS, RHS);
8513 } else if (!DAG.isKnownNeverNaN(RHS))
8516 Opcode = X86ISD::FMIN;
8519 // This can be a min, but if either operand is a NaN we need it to
8520 // preserve the original LHS.
8521 std::swap(LHS, RHS);
8525 Opcode = X86ISD::FMIN;
8529 // This can be a max if we can prove that at least one of the operands
8531 if (!FiniteOnlyFPMath()) {
8532 if (DAG.isKnownNeverNaN(LHS)) {
8533 // Put the potential NaN in the RHS so that SSE will preserve it.
8534 std::swap(LHS, RHS);
8535 } else if (!DAG.isKnownNeverNaN(RHS))
8538 Opcode = X86ISD::FMAX;
8541 // This can be a max if we can prove that at least one of the operands
8543 if (!FiniteOnlyFPMath()) {
8544 if (DAG.isKnownNeverNaN(RHS)) {
8545 // Put the potential NaN in the RHS so that SSE will preserve it.
8546 std::swap(LHS, RHS);
8547 } else if (!DAG.isKnownNeverNaN(LHS))
8550 Opcode = X86ISD::FMAX;
8553 // This can be a max, but if either operand is a NaN we need it to
8554 // preserve the original LHS.
8555 std::swap(LHS, RHS);
8559 Opcode = X86ISD::FMAX;
8565 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
8568 // If this is a select between two integer constants, try to do some
8570 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
8571 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
8572 // Don't do this for crazy integer types.
8573 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
8574 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
8575 // so that TrueC (the true value) is larger than FalseC.
8576 bool NeedsCondInvert = false;
8578 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
8579 // Efficiently invertible.
8580 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
8581 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
8582 isa<ConstantSDNode>(Cond.getOperand(1))))) {
8583 NeedsCondInvert = true;
8584 std::swap(TrueC, FalseC);
8587 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
8588 if (FalseC->getAPIntValue() == 0 &&
8589 TrueC->getAPIntValue().isPowerOf2()) {
8590 if (NeedsCondInvert) // Invert the condition if needed.
8591 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8592 DAG.getConstant(1, Cond.getValueType()));
8594 // Zero extend the condition if needed.
8595 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
8597 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8598 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
8599 DAG.getConstant(ShAmt, MVT::i8));
8602 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
8603 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8604 if (NeedsCondInvert) // Invert the condition if needed.
8605 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8606 DAG.getConstant(1, Cond.getValueType()));
8608 // Zero extend the condition if needed.
8609 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8610 FalseC->getValueType(0), Cond);
8611 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8612 SDValue(FalseC, 0));
8615 // Optimize cases that will turn into an LEA instruction. This requires
8616 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8617 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8618 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8619 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8621 bool isFastMultiplier = false;
8623 switch ((unsigned char)Diff) {
8625 case 1: // result = add base, cond
8626 case 2: // result = lea base( , cond*2)
8627 case 3: // result = lea base(cond, cond*2)
8628 case 4: // result = lea base( , cond*4)
8629 case 5: // result = lea base(cond, cond*4)
8630 case 8: // result = lea base( , cond*8)
8631 case 9: // result = lea base(cond, cond*8)
8632 isFastMultiplier = true;
8637 if (isFastMultiplier) {
8638 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8639 if (NeedsCondInvert) // Invert the condition if needed.
8640 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8641 DAG.getConstant(1, Cond.getValueType()));
8643 // Zero extend the condition if needed.
8644 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8646 // Scale the condition by the difference.
8648 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8649 DAG.getConstant(Diff, Cond.getValueType()));
8651 // Add the base if non-zero.
8652 if (FalseC->getAPIntValue() != 0)
8653 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8654 SDValue(FalseC, 0));
8664 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
8665 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
8666 TargetLowering::DAGCombinerInfo &DCI) {
8667 DebugLoc DL = N->getDebugLoc();
8669 // If the flag operand isn't dead, don't touch this CMOV.
8670 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
8673 // If this is a select between two integer constants, try to do some
8674 // optimizations. Note that the operands are ordered the opposite of SELECT
8676 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
8677 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8678 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
8679 // larger than FalseC (the false value).
8680 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
8682 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
8683 CC = X86::GetOppositeBranchCondition(CC);
8684 std::swap(TrueC, FalseC);
8687 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
8688 // This is efficient for any integer data type (including i8/i16) and
8690 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
8691 SDValue Cond = N->getOperand(3);
8692 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8693 DAG.getConstant(CC, MVT::i8), Cond);
8695 // Zero extend the condition if needed.
8696 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
8698 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8699 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
8700 DAG.getConstant(ShAmt, MVT::i8));
8701 if (N->getNumValues() == 2) // Dead flag value?
8702 return DCI.CombineTo(N, Cond, SDValue());
8706 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
8707 // for any integer data type, including i8/i16.
8708 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8709 SDValue Cond = N->getOperand(3);
8710 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8711 DAG.getConstant(CC, MVT::i8), Cond);
8713 // Zero extend the condition if needed.
8714 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8715 FalseC->getValueType(0), Cond);
8716 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8717 SDValue(FalseC, 0));
8719 if (N->getNumValues() == 2) // Dead flag value?
8720 return DCI.CombineTo(N, Cond, SDValue());
8724 // Optimize cases that will turn into an LEA instruction. This requires
8725 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8726 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8727 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8728 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8730 bool isFastMultiplier = false;
8732 switch ((unsigned char)Diff) {
8734 case 1: // result = add base, cond
8735 case 2: // result = lea base( , cond*2)
8736 case 3: // result = lea base(cond, cond*2)
8737 case 4: // result = lea base( , cond*4)
8738 case 5: // result = lea base(cond, cond*4)
8739 case 8: // result = lea base( , cond*8)
8740 case 9: // result = lea base(cond, cond*8)
8741 isFastMultiplier = true;
8746 if (isFastMultiplier) {
8747 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8748 SDValue Cond = N->getOperand(3);
8749 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8750 DAG.getConstant(CC, MVT::i8), Cond);
8751 // Zero extend the condition if needed.
8752 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8754 // Scale the condition by the difference.
8756 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8757 DAG.getConstant(Diff, Cond.getValueType()));
8759 // Add the base if non-zero.
8760 if (FalseC->getAPIntValue() != 0)
8761 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8762 SDValue(FalseC, 0));
8763 if (N->getNumValues() == 2) // Dead flag value?
8764 return DCI.CombineTo(N, Cond, SDValue());
8774 /// PerformMulCombine - Optimize a single multiply with constant into two
8775 /// in order to implement it with two cheaper instructions, e.g.
8776 /// LEA + SHL, LEA + LEA.
8777 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
8778 TargetLowering::DAGCombinerInfo &DCI) {
8779 if (DAG.getMachineFunction().
8780 getFunction()->hasFnAttr(Attribute::OptimizeForSize))
8783 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8786 EVT VT = N->getValueType(0);
8790 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8793 uint64_t MulAmt = C->getZExtValue();
8794 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
8797 uint64_t MulAmt1 = 0;
8798 uint64_t MulAmt2 = 0;
8799 if ((MulAmt % 9) == 0) {
8801 MulAmt2 = MulAmt / 9;
8802 } else if ((MulAmt % 5) == 0) {
8804 MulAmt2 = MulAmt / 5;
8805 } else if ((MulAmt % 3) == 0) {
8807 MulAmt2 = MulAmt / 3;
8810 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
8811 DebugLoc DL = N->getDebugLoc();
8813 if (isPowerOf2_64(MulAmt2) &&
8814 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
8815 // If second multiplifer is pow2, issue it first. We want the multiply by
8816 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
8818 std::swap(MulAmt1, MulAmt2);
8821 if (isPowerOf2_64(MulAmt1))
8822 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
8823 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
8825 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
8826 DAG.getConstant(MulAmt1, VT));
8828 if (isPowerOf2_64(MulAmt2))
8829 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
8830 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
8832 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
8833 DAG.getConstant(MulAmt2, VT));
8835 // Do not add new nodes to DAG combiner worklist.
8836 DCI.CombineTo(N, NewMul, false);
8842 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
8844 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
8845 const X86Subtarget *Subtarget) {
8846 // On X86 with SSE2 support, we can transform this to a vector shift if
8847 // all elements are shifted by the same amount. We can't do this in legalize
8848 // because the a constant vector is typically transformed to a constant pool
8849 // so we have no knowledge of the shift amount.
8850 if (!Subtarget->hasSSE2())
8853 EVT VT = N->getValueType(0);
8854 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
8857 SDValue ShAmtOp = N->getOperand(1);
8858 EVT EltVT = VT.getVectorElementType();
8859 DebugLoc DL = N->getDebugLoc();
8860 SDValue BaseShAmt = SDValue();
8861 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
8862 unsigned NumElts = VT.getVectorNumElements();
8864 for (; i != NumElts; ++i) {
8865 SDValue Arg = ShAmtOp.getOperand(i);
8866 if (Arg.getOpcode() == ISD::UNDEF) continue;
8870 for (; i != NumElts; ++i) {
8871 SDValue Arg = ShAmtOp.getOperand(i);
8872 if (Arg.getOpcode() == ISD::UNDEF) continue;
8873 if (Arg != BaseShAmt) {
8877 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
8878 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
8879 SDValue InVec = ShAmtOp.getOperand(0);
8880 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
8881 unsigned NumElts = InVec.getValueType().getVectorNumElements();
8883 for (; i != NumElts; ++i) {
8884 SDValue Arg = InVec.getOperand(i);
8885 if (Arg.getOpcode() == ISD::UNDEF) continue;
8889 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
8890 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
8891 unsigned SplatIdx = cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
8892 if (C->getZExtValue() == SplatIdx)
8893 BaseShAmt = InVec.getOperand(1);
8896 if (BaseShAmt.getNode() == 0)
8897 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
8898 DAG.getIntPtrConstant(0));
8902 // The shift amount is an i32.
8903 if (EltVT.bitsGT(MVT::i32))
8904 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
8905 else if (EltVT.bitsLT(MVT::i32))
8906 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
8908 // The shift amount is identical so we can do a vector shift.
8909 SDValue ValOp = N->getOperand(0);
8910 switch (N->getOpcode()) {
8912 llvm_unreachable("Unknown shift opcode!");
8915 if (VT == MVT::v2i64)
8916 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8917 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8919 if (VT == MVT::v4i32)
8920 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8921 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8923 if (VT == MVT::v8i16)
8924 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8925 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8929 if (VT == MVT::v4i32)
8930 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8931 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8933 if (VT == MVT::v8i16)
8934 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8935 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8939 if (VT == MVT::v2i64)
8940 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8941 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8943 if (VT == MVT::v4i32)
8944 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8945 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8947 if (VT == MVT::v8i16)
8948 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8949 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8956 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
8957 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
8958 const X86Subtarget *Subtarget) {
8959 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
8960 // the FP state in cases where an emms may be missing.
8961 // A preferable solution to the general problem is to figure out the right
8962 // places to insert EMMS. This qualifies as a quick hack.
8964 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
8965 StoreSDNode *St = cast<StoreSDNode>(N);
8966 EVT VT = St->getValue().getValueType();
8967 if (VT.getSizeInBits() != 64)
8970 const Function *F = DAG.getMachineFunction().getFunction();
8971 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
8972 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
8973 && Subtarget->hasSSE2();
8974 if ((VT.isVector() ||
8975 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
8976 isa<LoadSDNode>(St->getValue()) &&
8977 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
8978 St->getChain().hasOneUse() && !St->isVolatile()) {
8979 SDNode* LdVal = St->getValue().getNode();
8981 int TokenFactorIndex = -1;
8982 SmallVector<SDValue, 8> Ops;
8983 SDNode* ChainVal = St->getChain().getNode();
8984 // Must be a store of a load. We currently handle two cases: the load
8985 // is a direct child, and it's under an intervening TokenFactor. It is
8986 // possible to dig deeper under nested TokenFactors.
8987 if (ChainVal == LdVal)
8988 Ld = cast<LoadSDNode>(St->getChain());
8989 else if (St->getValue().hasOneUse() &&
8990 ChainVal->getOpcode() == ISD::TokenFactor) {
8991 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
8992 if (ChainVal->getOperand(i).getNode() == LdVal) {
8993 TokenFactorIndex = i;
8994 Ld = cast<LoadSDNode>(St->getValue());
8996 Ops.push_back(ChainVal->getOperand(i));
9000 if (!Ld || !ISD::isNormalLoad(Ld))
9003 // If this is not the MMX case, i.e. we are just turning i64 load/store
9004 // into f64 load/store, avoid the transformation if there are multiple
9005 // uses of the loaded value.
9006 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
9009 DebugLoc LdDL = Ld->getDebugLoc();
9010 DebugLoc StDL = N->getDebugLoc();
9011 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
9012 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
9014 if (Subtarget->is64Bit() || F64IsLegal) {
9015 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
9016 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
9017 Ld->getBasePtr(), Ld->getSrcValue(),
9018 Ld->getSrcValueOffset(), Ld->isVolatile(),
9019 Ld->getAlignment());
9020 SDValue NewChain = NewLd.getValue(1);
9021 if (TokenFactorIndex != -1) {
9022 Ops.push_back(NewChain);
9023 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9026 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
9027 St->getSrcValue(), St->getSrcValueOffset(),
9028 St->isVolatile(), St->getAlignment());
9031 // Otherwise, lower to two pairs of 32-bit loads / stores.
9032 SDValue LoAddr = Ld->getBasePtr();
9033 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
9034 DAG.getConstant(4, MVT::i32));
9036 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
9037 Ld->getSrcValue(), Ld->getSrcValueOffset(),
9038 Ld->isVolatile(), Ld->getAlignment());
9039 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
9040 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
9042 MinAlign(Ld->getAlignment(), 4));
9044 SDValue NewChain = LoLd.getValue(1);
9045 if (TokenFactorIndex != -1) {
9046 Ops.push_back(LoLd);
9047 Ops.push_back(HiLd);
9048 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9052 LoAddr = St->getBasePtr();
9053 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
9054 DAG.getConstant(4, MVT::i32));
9056 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
9057 St->getSrcValue(), St->getSrcValueOffset(),
9058 St->isVolatile(), St->getAlignment());
9059 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
9061 St->getSrcValueOffset() + 4,
9063 MinAlign(St->getAlignment(), 4));
9064 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
9069 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
9070 /// X86ISD::FXOR nodes.
9071 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
9072 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
9073 // F[X]OR(0.0, x) -> x
9074 // F[X]OR(x, 0.0) -> x
9075 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9076 if (C->getValueAPF().isPosZero())
9077 return N->getOperand(1);
9078 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9079 if (C->getValueAPF().isPosZero())
9080 return N->getOperand(0);
9084 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
9085 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
9086 // FAND(0.0, x) -> 0.0
9087 // FAND(x, 0.0) -> 0.0
9088 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9089 if (C->getValueAPF().isPosZero())
9090 return N->getOperand(0);
9091 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9092 if (C->getValueAPF().isPosZero())
9093 return N->getOperand(1);
9097 static SDValue PerformBTCombine(SDNode *N,
9099 TargetLowering::DAGCombinerInfo &DCI) {
9100 // BT ignores high bits in the bit index operand.
9101 SDValue Op1 = N->getOperand(1);
9102 if (Op1.hasOneUse()) {
9103 unsigned BitWidth = Op1.getValueSizeInBits();
9104 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
9105 APInt KnownZero, KnownOne;
9106 TargetLowering::TargetLoweringOpt TLO(DAG);
9107 TargetLowering &TLI = DAG.getTargetLoweringInfo();
9108 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
9109 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
9110 DCI.CommitTargetLoweringOpt(TLO);
9115 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
9116 SDValue Op = N->getOperand(0);
9117 if (Op.getOpcode() == ISD::BIT_CONVERT)
9118 Op = Op.getOperand(0);
9119 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
9120 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
9121 VT.getVectorElementType().getSizeInBits() ==
9122 OpVT.getVectorElementType().getSizeInBits()) {
9123 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
9128 // On X86 and X86-64, atomic operations are lowered to locked instructions.
9129 // Locked instructions, in turn, have implicit fence semantics (all memory
9130 // operations are flushed before issuing the locked instruction, and the
9131 // are not buffered), so we can fold away the common pattern of
9132 // fence-atomic-fence.
9133 static SDValue PerformMEMBARRIERCombine(SDNode* N, SelectionDAG &DAG) {
9134 SDValue atomic = N->getOperand(0);
9135 switch (atomic.getOpcode()) {
9136 case ISD::ATOMIC_CMP_SWAP:
9137 case ISD::ATOMIC_SWAP:
9138 case ISD::ATOMIC_LOAD_ADD:
9139 case ISD::ATOMIC_LOAD_SUB:
9140 case ISD::ATOMIC_LOAD_AND:
9141 case ISD::ATOMIC_LOAD_OR:
9142 case ISD::ATOMIC_LOAD_XOR:
9143 case ISD::ATOMIC_LOAD_NAND:
9144 case ISD::ATOMIC_LOAD_MIN:
9145 case ISD::ATOMIC_LOAD_MAX:
9146 case ISD::ATOMIC_LOAD_UMIN:
9147 case ISD::ATOMIC_LOAD_UMAX:
9153 SDValue fence = atomic.getOperand(0);
9154 if (fence.getOpcode() != ISD::MEMBARRIER)
9157 switch (atomic.getOpcode()) {
9158 case ISD::ATOMIC_CMP_SWAP:
9159 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9160 atomic.getOperand(1), atomic.getOperand(2),
9161 atomic.getOperand(3));
9162 case ISD::ATOMIC_SWAP:
9163 case ISD::ATOMIC_LOAD_ADD:
9164 case ISD::ATOMIC_LOAD_SUB:
9165 case ISD::ATOMIC_LOAD_AND:
9166 case ISD::ATOMIC_LOAD_OR:
9167 case ISD::ATOMIC_LOAD_XOR:
9168 case ISD::ATOMIC_LOAD_NAND:
9169 case ISD::ATOMIC_LOAD_MIN:
9170 case ISD::ATOMIC_LOAD_MAX:
9171 case ISD::ATOMIC_LOAD_UMIN:
9172 case ISD::ATOMIC_LOAD_UMAX:
9173 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9174 atomic.getOperand(1), atomic.getOperand(2));
9180 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
9181 DAGCombinerInfo &DCI) const {
9182 SelectionDAG &DAG = DCI.DAG;
9183 switch (N->getOpcode()) {
9185 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
9186 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
9187 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
9188 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
9191 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
9192 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
9194 case X86ISD::FOR: return PerformFORCombine(N, DAG);
9195 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
9196 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
9197 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
9198 case ISD::MEMBARRIER: return PerformMEMBARRIERCombine(N, DAG);
9204 //===----------------------------------------------------------------------===//
9205 // X86 Inline Assembly Support
9206 //===----------------------------------------------------------------------===//
9208 static bool LowerToBSwap(CallInst *CI) {
9209 // FIXME: this should verify that we are targetting a 486 or better. If not,
9210 // we will turn this bswap into something that will be lowered to logical ops
9211 // instead of emitting the bswap asm. For now, we don't support 486 or lower
9212 // so don't worry about this.
9214 // Verify this is a simple bswap.
9215 if (CI->getNumOperands() != 2 ||
9216 CI->getType() != CI->getOperand(1)->getType() ||
9217 !CI->getType()->isInteger())
9220 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9221 if (!Ty || Ty->getBitWidth() % 16 != 0)
9224 // Okay, we can do this xform, do so now.
9225 const Type *Tys[] = { Ty };
9226 Module *M = CI->getParent()->getParent()->getParent();
9227 Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
9229 Value *Op = CI->getOperand(1);
9230 Op = CallInst::Create(Int, Op, CI->getName(), CI);
9232 CI->replaceAllUsesWith(Op);
9233 CI->eraseFromParent();
9237 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
9238 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9239 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
9241 std::string AsmStr = IA->getAsmString();
9243 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
9244 std::vector<std::string> AsmPieces;
9245 SplitString(AsmStr, AsmPieces, "\n"); // ; as separator?
9247 switch (AsmPieces.size()) {
9248 default: return false;
9250 AsmStr = AsmPieces[0];
9252 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
9255 if (AsmPieces.size() == 2 &&
9256 (AsmPieces[0] == "bswap" ||
9257 AsmPieces[0] == "bswapq" ||
9258 AsmPieces[0] == "bswapl") &&
9259 (AsmPieces[1] == "$0" ||
9260 AsmPieces[1] == "${0:q}")) {
9261 // No need to check constraints, nothing other than the equivalent of
9262 // "=r,0" would be valid here.
9263 return LowerToBSwap(CI);
9265 // rorw $$8, ${0:w} --> llvm.bswap.i16
9266 if (CI->getType() == Type::getInt16Ty(CI->getContext()) &&
9267 AsmPieces.size() == 3 &&
9268 AsmPieces[0] == "rorw" &&
9269 AsmPieces[1] == "$$8," &&
9270 AsmPieces[2] == "${0:w}" &&
9271 IA->getConstraintString() == "=r,0,~{dirflag},~{fpsr},~{flags},~{cc}") {
9272 return LowerToBSwap(CI);
9276 if (CI->getType() == Type::getInt64Ty(CI->getContext()) &&
9277 Constraints.size() >= 2 &&
9278 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
9279 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
9280 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
9281 std::vector<std::string> Words;
9282 SplitString(AsmPieces[0], Words, " \t");
9283 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
9285 SplitString(AsmPieces[1], Words, " \t");
9286 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
9288 SplitString(AsmPieces[2], Words, " \t,");
9289 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
9290 Words[2] == "%edx") {
9291 return LowerToBSwap(CI);
9303 /// getConstraintType - Given a constraint letter, return the type of
9304 /// constraint it is for this target.
9305 X86TargetLowering::ConstraintType
9306 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
9307 if (Constraint.size() == 1) {
9308 switch (Constraint[0]) {
9320 return C_RegisterClass;
9328 return TargetLowering::getConstraintType(Constraint);
9331 /// LowerXConstraint - try to replace an X constraint, which matches anything,
9332 /// with another that has more specific requirements based on the type of the
9333 /// corresponding operand.
9334 const char *X86TargetLowering::
9335 LowerXConstraint(EVT ConstraintVT) const {
9336 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
9337 // 'f' like normal targets.
9338 if (ConstraintVT.isFloatingPoint()) {
9339 if (Subtarget->hasSSE2())
9341 if (Subtarget->hasSSE1())
9345 return TargetLowering::LowerXConstraint(ConstraintVT);
9348 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9349 /// vector. If it is invalid, don't add anything to Ops.
9350 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9353 std::vector<SDValue>&Ops,
9354 SelectionDAG &DAG) const {
9355 SDValue Result(0, 0);
9357 switch (Constraint) {
9360 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9361 if (C->getZExtValue() <= 31) {
9362 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9368 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9369 if (C->getZExtValue() <= 63) {
9370 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9376 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9377 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
9378 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9384 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9385 if (C->getZExtValue() <= 255) {
9386 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9392 // 32-bit signed value
9393 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9394 const ConstantInt *CI = C->getConstantIntValue();
9395 if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
9396 C->getSExtValue())) {
9397 // Widen to 64 bits here to get it sign extended.
9398 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
9401 // FIXME gcc accepts some relocatable values here too, but only in certain
9402 // memory models; it's complicated.
9407 // 32-bit unsigned value
9408 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9409 const ConstantInt *CI = C->getConstantIntValue();
9410 if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
9411 C->getZExtValue())) {
9412 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9416 // FIXME gcc accepts some relocatable values here too, but only in certain
9417 // memory models; it's complicated.
9421 // Literal immediates are always ok.
9422 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
9423 // Widen to 64 bits here to get it sign extended.
9424 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
9428 // If we are in non-pic codegen mode, we allow the address of a global (with
9429 // an optional displacement) to be used with 'i'.
9430 GlobalAddressSDNode *GA = 0;
9433 // Match either (GA), (GA+C), (GA+C1+C2), etc.
9435 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
9436 Offset += GA->getOffset();
9438 } else if (Op.getOpcode() == ISD::ADD) {
9439 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9440 Offset += C->getZExtValue();
9441 Op = Op.getOperand(0);
9444 } else if (Op.getOpcode() == ISD::SUB) {
9445 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9446 Offset += -C->getZExtValue();
9447 Op = Op.getOperand(0);
9452 // Otherwise, this isn't something we can handle, reject it.
9456 GlobalValue *GV = GA->getGlobal();
9457 // If we require an extra load to get this address, as in PIC mode, we
9459 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
9460 getTargetMachine())))
9464 Op = LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
9466 Op = DAG.getTargetGlobalAddress(GV, GA->getValueType(0), Offset);
9472 if (Result.getNode()) {
9473 Ops.push_back(Result);
9476 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
9480 std::vector<unsigned> X86TargetLowering::
9481 getRegClassForInlineAsmConstraint(const std::string &Constraint,
9483 if (Constraint.size() == 1) {
9484 // FIXME: not handling fp-stack yet!
9485 switch (Constraint[0]) { // GCC X86 Constraint Letters
9486 default: break; // Unknown constraint letter
9487 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
9488 if (Subtarget->is64Bit()) {
9490 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
9491 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
9492 X86::R10D,X86::R11D,X86::R12D,
9493 X86::R13D,X86::R14D,X86::R15D,
9494 X86::EBP, X86::ESP, 0);
9495 else if (VT == MVT::i16)
9496 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
9497 X86::SI, X86::DI, X86::R8W,X86::R9W,
9498 X86::R10W,X86::R11W,X86::R12W,
9499 X86::R13W,X86::R14W,X86::R15W,
9500 X86::BP, X86::SP, 0);
9501 else if (VT == MVT::i8)
9502 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
9503 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
9504 X86::R10B,X86::R11B,X86::R12B,
9505 X86::R13B,X86::R14B,X86::R15B,
9506 X86::BPL, X86::SPL, 0);
9508 else if (VT == MVT::i64)
9509 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
9510 X86::RSI, X86::RDI, X86::R8, X86::R9,
9511 X86::R10, X86::R11, X86::R12,
9512 X86::R13, X86::R14, X86::R15,
9513 X86::RBP, X86::RSP, 0);
9517 // 32-bit fallthrough
9520 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
9521 else if (VT == MVT::i16)
9522 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
9523 else if (VT == MVT::i8)
9524 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
9525 else if (VT == MVT::i64)
9526 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
9531 return std::vector<unsigned>();
9534 std::pair<unsigned, const TargetRegisterClass*>
9535 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9537 // First, see if this is a constraint that directly corresponds to an LLVM
9539 if (Constraint.size() == 1) {
9540 // GCC Constraint Letters
9541 switch (Constraint[0]) {
9543 case 'r': // GENERAL_REGS
9544 case 'l': // INDEX_REGS
9546 return std::make_pair(0U, X86::GR8RegisterClass);
9548 return std::make_pair(0U, X86::GR16RegisterClass);
9549 if (VT == MVT::i32 || !Subtarget->is64Bit())
9550 return std::make_pair(0U, X86::GR32RegisterClass);
9551 return std::make_pair(0U, X86::GR64RegisterClass);
9552 case 'R': // LEGACY_REGS
9554 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
9556 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
9557 if (VT == MVT::i32 || !Subtarget->is64Bit())
9558 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
9559 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
9560 case 'f': // FP Stack registers.
9561 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
9562 // value to the correct fpstack register class.
9563 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
9564 return std::make_pair(0U, X86::RFP32RegisterClass);
9565 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
9566 return std::make_pair(0U, X86::RFP64RegisterClass);
9567 return std::make_pair(0U, X86::RFP80RegisterClass);
9568 case 'y': // MMX_REGS if MMX allowed.
9569 if (!Subtarget->hasMMX()) break;
9570 return std::make_pair(0U, X86::VR64RegisterClass);
9571 case 'Y': // SSE_REGS if SSE2 allowed
9572 if (!Subtarget->hasSSE2()) break;
9574 case 'x': // SSE_REGS if SSE1 allowed
9575 if (!Subtarget->hasSSE1()) break;
9577 switch (VT.getSimpleVT().SimpleTy) {
9579 // Scalar SSE types.
9582 return std::make_pair(0U, X86::FR32RegisterClass);
9585 return std::make_pair(0U, X86::FR64RegisterClass);
9593 return std::make_pair(0U, X86::VR128RegisterClass);
9599 // Use the default implementation in TargetLowering to convert the register
9600 // constraint into a member of a register class.
9601 std::pair<unsigned, const TargetRegisterClass*> Res;
9602 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9604 // Not found as a standard register?
9605 if (Res.second == 0) {
9606 // Map st(0) -> st(7) -> ST0
9607 if (Constraint.size() == 7 && Constraint[0] == '{' &&
9608 tolower(Constraint[1]) == 's' &&
9609 tolower(Constraint[2]) == 't' &&
9610 Constraint[3] == '(' &&
9611 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
9612 Constraint[5] == ')' &&
9613 Constraint[6] == '}') {
9615 Res.first = X86::ST0+Constraint[4]-'0';
9616 Res.second = X86::RFP80RegisterClass;
9620 // GCC allows "st(0)" to be called just plain "st".
9621 if (StringRef("{st}").equals_lower(Constraint)) {
9622 Res.first = X86::ST0;
9623 Res.second = X86::RFP80RegisterClass;
9628 if (StringRef("{flags}").equals_lower(Constraint)) {
9629 Res.first = X86::EFLAGS;
9630 Res.second = X86::CCRRegisterClass;
9634 // 'A' means EAX + EDX.
9635 if (Constraint == "A") {
9636 Res.first = X86::EAX;
9637 Res.second = X86::GR32_ADRegisterClass;
9643 // Otherwise, check to see if this is a register class of the wrong value
9644 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
9645 // turn into {ax},{dx}.
9646 if (Res.second->hasType(VT))
9647 return Res; // Correct type already, nothing to do.
9649 // All of the single-register GCC register classes map their values onto
9650 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
9651 // really want an 8-bit or 32-bit register, map to the appropriate register
9652 // class and return the appropriate register.
9653 if (Res.second == X86::GR16RegisterClass) {
9654 if (VT == MVT::i8) {
9655 unsigned DestReg = 0;
9656 switch (Res.first) {
9658 case X86::AX: DestReg = X86::AL; break;
9659 case X86::DX: DestReg = X86::DL; break;
9660 case X86::CX: DestReg = X86::CL; break;
9661 case X86::BX: DestReg = X86::BL; break;
9664 Res.first = DestReg;
9665 Res.second = X86::GR8RegisterClass;
9667 } else if (VT == MVT::i32) {
9668 unsigned DestReg = 0;
9669 switch (Res.first) {
9671 case X86::AX: DestReg = X86::EAX; break;
9672 case X86::DX: DestReg = X86::EDX; break;
9673 case X86::CX: DestReg = X86::ECX; break;
9674 case X86::BX: DestReg = X86::EBX; break;
9675 case X86::SI: DestReg = X86::ESI; break;
9676 case X86::DI: DestReg = X86::EDI; break;
9677 case X86::BP: DestReg = X86::EBP; break;
9678 case X86::SP: DestReg = X86::ESP; break;
9681 Res.first = DestReg;
9682 Res.second = X86::GR32RegisterClass;
9684 } else if (VT == MVT::i64) {
9685 unsigned DestReg = 0;
9686 switch (Res.first) {
9688 case X86::AX: DestReg = X86::RAX; break;
9689 case X86::DX: DestReg = X86::RDX; break;
9690 case X86::CX: DestReg = X86::RCX; break;
9691 case X86::BX: DestReg = X86::RBX; break;
9692 case X86::SI: DestReg = X86::RSI; break;
9693 case X86::DI: DestReg = X86::RDI; break;
9694 case X86::BP: DestReg = X86::RBP; break;
9695 case X86::SP: DestReg = X86::RSP; break;
9698 Res.first = DestReg;
9699 Res.second = X86::GR64RegisterClass;
9702 } else if (Res.second == X86::FR32RegisterClass ||
9703 Res.second == X86::FR64RegisterClass ||
9704 Res.second == X86::VR128RegisterClass) {
9705 // Handle references to XMM physical registers that got mapped into the
9706 // wrong class. This can happen with constraints like {xmm0} where the
9707 // target independent register mapper will just pick the first match it can
9708 // find, ignoring the required type.
9710 Res.second = X86::FR32RegisterClass;
9711 else if (VT == MVT::f64)
9712 Res.second = X86::FR64RegisterClass;
9713 else if (X86::VR128RegisterClass->hasType(VT))
9714 Res.second = X86::VR128RegisterClass;
9720 //===----------------------------------------------------------------------===//
9721 // X86 Widen vector type
9722 //===----------------------------------------------------------------------===//
9724 /// getWidenVectorType: given a vector type, returns the type to widen
9725 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
9726 /// If there is no vector type that we want to widen to, returns MVT::Other
9727 /// When and where to widen is target dependent based on the cost of
9728 /// scalarizing vs using the wider vector type.
9730 EVT X86TargetLowering::getWidenVectorType(EVT VT) const {
9731 assert(VT.isVector());
9732 if (isTypeLegal(VT))
9735 // TODO: In computeRegisterProperty, we can compute the list of legal vector
9736 // type based on element type. This would speed up our search (though
9737 // it may not be worth it since the size of the list is relatively
9739 EVT EltVT = VT.getVectorElementType();
9740 unsigned NElts = VT.getVectorNumElements();
9742 // On X86, it make sense to widen any vector wider than 1
9746 for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
9747 nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
9748 EVT SVT = (MVT::SimpleValueType)nVT;
9750 if (isTypeLegal(SVT) &&
9751 SVT.getVectorElementType() == EltVT &&
9752 SVT.getVectorNumElements() > NElts)