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::EH_LABEL, MVT::Other, Expand);
383 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
384 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
385 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
386 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
387 if (Subtarget->is64Bit()) {
388 setExceptionPointerRegister(X86::RAX);
389 setExceptionSelectorRegister(X86::RDX);
391 setExceptionPointerRegister(X86::EAX);
392 setExceptionSelectorRegister(X86::EDX);
394 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
395 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
397 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
399 setOperationAction(ISD::TRAP, MVT::Other, Legal);
401 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
402 setOperationAction(ISD::VASTART , MVT::Other, Custom);
403 setOperationAction(ISD::VAEND , MVT::Other, Expand);
404 if (Subtarget->is64Bit()) {
405 setOperationAction(ISD::VAARG , MVT::Other, Custom);
406 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
408 setOperationAction(ISD::VAARG , MVT::Other, Expand);
409 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
412 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
413 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
414 if (Subtarget->is64Bit())
415 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
416 if (Subtarget->isTargetCygMing())
417 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
419 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
421 if (!UseSoftFloat && X86ScalarSSEf64) {
422 // f32 and f64 use SSE.
423 // Set up the FP register classes.
424 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
425 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
427 // Use ANDPD to simulate FABS.
428 setOperationAction(ISD::FABS , MVT::f64, Custom);
429 setOperationAction(ISD::FABS , MVT::f32, Custom);
431 // Use XORP to simulate FNEG.
432 setOperationAction(ISD::FNEG , MVT::f64, Custom);
433 setOperationAction(ISD::FNEG , MVT::f32, Custom);
435 // Use ANDPD and ORPD to simulate FCOPYSIGN.
436 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
437 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
439 // We don't support sin/cos/fmod
440 setOperationAction(ISD::FSIN , MVT::f64, Expand);
441 setOperationAction(ISD::FCOS , MVT::f64, Expand);
442 setOperationAction(ISD::FSIN , MVT::f32, Expand);
443 setOperationAction(ISD::FCOS , MVT::f32, Expand);
445 // Expand FP immediates into loads from the stack, except for the special
447 addLegalFPImmediate(APFloat(+0.0)); // xorpd
448 addLegalFPImmediate(APFloat(+0.0f)); // xorps
449 } else if (!UseSoftFloat && X86ScalarSSEf32) {
450 // Use SSE for f32, x87 for f64.
451 // Set up the FP register classes.
452 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
453 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
455 // Use ANDPS to simulate FABS.
456 setOperationAction(ISD::FABS , MVT::f32, Custom);
458 // Use XORP to simulate FNEG.
459 setOperationAction(ISD::FNEG , MVT::f32, Custom);
461 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
463 // Use ANDPS and ORPS to simulate FCOPYSIGN.
464 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
465 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
467 // We don't support sin/cos/fmod
468 setOperationAction(ISD::FSIN , MVT::f32, Expand);
469 setOperationAction(ISD::FCOS , MVT::f32, Expand);
471 // Special cases we handle for FP constants.
472 addLegalFPImmediate(APFloat(+0.0f)); // xorps
473 addLegalFPImmediate(APFloat(+0.0)); // FLD0
474 addLegalFPImmediate(APFloat(+1.0)); // FLD1
475 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
476 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
479 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
480 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
482 } else if (!UseSoftFloat) {
483 // f32 and f64 in x87.
484 // Set up the FP register classes.
485 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
486 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
488 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
489 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
490 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
491 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
494 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
495 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
497 addLegalFPImmediate(APFloat(+0.0)); // FLD0
498 addLegalFPImmediate(APFloat(+1.0)); // FLD1
499 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
500 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
501 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
502 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
503 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
504 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
507 // Long double always uses X87.
509 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
510 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
511 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
514 APFloat TmpFlt(+0.0);
515 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
517 addLegalFPImmediate(TmpFlt); // FLD0
519 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
520 APFloat TmpFlt2(+1.0);
521 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
523 addLegalFPImmediate(TmpFlt2); // FLD1
524 TmpFlt2.changeSign();
525 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
529 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
530 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
534 // Always use a library call for pow.
535 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
536 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
537 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
539 setOperationAction(ISD::FLOG, MVT::f80, Expand);
540 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
541 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
542 setOperationAction(ISD::FEXP, MVT::f80, Expand);
543 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
545 // First set operation action for all vector types to either promote
546 // (for widening) or expand (for scalarization). Then we will selectively
547 // turn on ones that can be effectively codegen'd.
548 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
549 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
550 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
551 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
552 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
553 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
554 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
555 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
556 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
557 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
558 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
559 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
560 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
561 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
562 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
563 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
564 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
565 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
566 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
567 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
568 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
569 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
570 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
571 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
572 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
573 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
574 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
575 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
576 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
577 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
578 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
579 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
580 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
581 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
582 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
583 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
584 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
585 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
586 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
587 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
588 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
589 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
590 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
591 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
592 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
593 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
594 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
595 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
596 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
597 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
598 setOperationAction(ISD::SIGN_EXTEND_INREG, (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 // Divide and reminder operations have no vector equivalent and can
980 // trap. Do a custom widening for these operations in which we never
981 // generate more divides/remainder than the original vector width.
982 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
983 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
984 if (!isTypeLegal((MVT::SimpleValueType)VT)) {
985 setOperationAction(ISD::SDIV, (MVT::SimpleValueType) VT, Custom);
986 setOperationAction(ISD::UDIV, (MVT::SimpleValueType) VT, Custom);
987 setOperationAction(ISD::SREM, (MVT::SimpleValueType) VT, Custom);
988 setOperationAction(ISD::UREM, (MVT::SimpleValueType) VT, Custom);
992 // FIXME: These should be based on subtarget info. Plus, the values should
993 // be smaller when we are in optimizing for size mode.
994 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
995 maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
996 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
997 setPrefLoopAlignment(16);
998 benefitFromCodePlacementOpt = true;
1002 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1007 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1008 /// the desired ByVal argument alignment.
1009 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1012 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1013 if (VTy->getBitWidth() == 128)
1015 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1016 unsigned EltAlign = 0;
1017 getMaxByValAlign(ATy->getElementType(), EltAlign);
1018 if (EltAlign > MaxAlign)
1019 MaxAlign = EltAlign;
1020 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1021 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1022 unsigned EltAlign = 0;
1023 getMaxByValAlign(STy->getElementType(i), EltAlign);
1024 if (EltAlign > MaxAlign)
1025 MaxAlign = EltAlign;
1033 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1034 /// function arguments in the caller parameter area. For X86, aggregates
1035 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1036 /// are at 4-byte boundaries.
1037 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1038 if (Subtarget->is64Bit()) {
1039 // Max of 8 and alignment of type.
1040 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1047 if (Subtarget->hasSSE1())
1048 getMaxByValAlign(Ty, Align);
1052 /// getOptimalMemOpType - Returns the target specific optimal type for load
1053 /// and store operations as a result of memset, memcpy, and memmove
1054 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
1057 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
1058 bool isSrcConst, bool isSrcStr,
1059 SelectionDAG &DAG) const {
1060 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1061 // linux. This is because the stack realignment code can't handle certain
1062 // cases like PR2962. This should be removed when PR2962 is fixed.
1063 const Function *F = DAG.getMachineFunction().getFunction();
1064 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
1065 if (!NoImplicitFloatOps && Subtarget->getStackAlignment() >= 16) {
1066 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
1068 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
1071 if (Subtarget->is64Bit() && Size >= 8)
1076 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1078 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1079 SelectionDAG &DAG) const {
1080 if (usesGlobalOffsetTable())
1081 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy());
1082 if (!Subtarget->is64Bit())
1083 // This doesn't have DebugLoc associated with it, but is not really the
1084 // same as a Register.
1085 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc::getUnknownLoc(),
1090 /// getFunctionAlignment - Return the Log2 alignment of this function.
1091 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1092 return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1095 //===----------------------------------------------------------------------===//
1096 // Return Value Calling Convention Implementation
1097 //===----------------------------------------------------------------------===//
1099 #include "X86GenCallingConv.inc"
1102 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1103 const SmallVectorImpl<EVT> &OutTys,
1104 const SmallVectorImpl<ISD::ArgFlagsTy> &ArgsFlags,
1105 SelectionDAG &DAG) {
1106 SmallVector<CCValAssign, 16> RVLocs;
1107 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1108 RVLocs, *DAG.getContext());
1109 return CCInfo.CheckReturn(OutTys, ArgsFlags, RetCC_X86);
1113 X86TargetLowering::LowerReturn(SDValue Chain,
1114 CallingConv::ID CallConv, bool isVarArg,
1115 const SmallVectorImpl<ISD::OutputArg> &Outs,
1116 DebugLoc dl, SelectionDAG &DAG) {
1118 SmallVector<CCValAssign, 16> RVLocs;
1119 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1120 RVLocs, *DAG.getContext());
1121 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1123 // If this is the first return lowered for this function, add the regs to the
1124 // liveout set for the function.
1125 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1126 for (unsigned i = 0; i != RVLocs.size(); ++i)
1127 if (RVLocs[i].isRegLoc())
1128 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1133 SmallVector<SDValue, 6> RetOps;
1134 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1135 // Operand #1 = Bytes To Pop
1136 RetOps.push_back(DAG.getTargetConstant(getBytesToPopOnReturn(), MVT::i16));
1138 // Copy the result values into the output registers.
1139 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1140 CCValAssign &VA = RVLocs[i];
1141 assert(VA.isRegLoc() && "Can only return in registers!");
1142 SDValue ValToCopy = Outs[i].Val;
1144 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1145 // the RET instruction and handled by the FP Stackifier.
1146 if (VA.getLocReg() == X86::ST0 ||
1147 VA.getLocReg() == X86::ST1) {
1148 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1149 // change the value to the FP stack register class.
1150 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1151 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1152 RetOps.push_back(ValToCopy);
1153 // Don't emit a copytoreg.
1157 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1158 // which is returned in RAX / RDX.
1159 if (Subtarget->is64Bit()) {
1160 EVT ValVT = ValToCopy.getValueType();
1161 if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1162 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1163 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1164 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1168 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1169 Flag = Chain.getValue(1);
1172 // The x86-64 ABI for returning structs by value requires that we copy
1173 // the sret argument into %rax for the return. We saved the argument into
1174 // a virtual register in the entry block, so now we copy the value out
1176 if (Subtarget->is64Bit() &&
1177 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1178 MachineFunction &MF = DAG.getMachineFunction();
1179 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1180 unsigned Reg = FuncInfo->getSRetReturnReg();
1182 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1183 FuncInfo->setSRetReturnReg(Reg);
1185 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1187 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1188 Flag = Chain.getValue(1);
1190 // RAX now acts like a return value.
1191 MF.getRegInfo().addLiveOut(X86::RAX);
1194 RetOps[0] = Chain; // Update chain.
1196 // Add the flag if we have it.
1198 RetOps.push_back(Flag);
1200 return DAG.getNode(X86ISD::RET_FLAG, dl,
1201 MVT::Other, &RetOps[0], RetOps.size());
1204 /// LowerCallResult - Lower the result values of a call into the
1205 /// appropriate copies out of appropriate physical registers.
1208 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1209 CallingConv::ID CallConv, bool isVarArg,
1210 const SmallVectorImpl<ISD::InputArg> &Ins,
1211 DebugLoc dl, SelectionDAG &DAG,
1212 SmallVectorImpl<SDValue> &InVals) {
1214 // Assign locations to each value returned by this call.
1215 SmallVector<CCValAssign, 16> RVLocs;
1216 bool Is64Bit = Subtarget->is64Bit();
1217 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1218 RVLocs, *DAG.getContext());
1219 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1221 // Copy all of the result registers out of their specified physreg.
1222 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1223 CCValAssign &VA = RVLocs[i];
1224 EVT CopyVT = VA.getValVT();
1226 // If this is x86-64, and we disabled SSE, we can't return FP values
1227 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1228 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1229 llvm_report_error("SSE register return with SSE disabled");
1232 // If this is a call to a function that returns an fp value on the floating
1233 // point stack, but where we prefer to use the value in xmm registers, copy
1234 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1235 if ((VA.getLocReg() == X86::ST0 ||
1236 VA.getLocReg() == X86::ST1) &&
1237 isScalarFPTypeInSSEReg(VA.getValVT())) {
1242 if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1243 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1244 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1245 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1246 MVT::v2i64, InFlag).getValue(1);
1247 Val = Chain.getValue(0);
1248 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1249 Val, DAG.getConstant(0, MVT::i64));
1251 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1252 MVT::i64, InFlag).getValue(1);
1253 Val = Chain.getValue(0);
1255 Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1257 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1258 CopyVT, InFlag).getValue(1);
1259 Val = Chain.getValue(0);
1261 InFlag = Chain.getValue(2);
1263 if (CopyVT != VA.getValVT()) {
1264 // Round the F80 the right size, which also moves to the appropriate xmm
1266 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1267 // This truncation won't change the value.
1268 DAG.getIntPtrConstant(1));
1271 InVals.push_back(Val);
1278 //===----------------------------------------------------------------------===//
1279 // C & StdCall & Fast Calling Convention implementation
1280 //===----------------------------------------------------------------------===//
1281 // StdCall calling convention seems to be standard for many Windows' API
1282 // routines and around. It differs from C calling convention just a little:
1283 // callee should clean up the stack, not caller. Symbols should be also
1284 // decorated in some fancy way :) It doesn't support any vector arguments.
1285 // For info on fast calling convention see Fast Calling Convention (tail call)
1286 // implementation LowerX86_32FastCCCallTo.
1288 /// CallIsStructReturn - Determines whether a call uses struct return
1290 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1294 return Outs[0].Flags.isSRet();
1297 /// ArgsAreStructReturn - Determines whether a function uses struct
1298 /// return semantics.
1300 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1304 return Ins[0].Flags.isSRet();
1307 /// IsCalleePop - Determines whether the callee is required to pop its
1308 /// own arguments. Callee pop is necessary to support tail calls.
1309 bool X86TargetLowering::IsCalleePop(bool IsVarArg, CallingConv::ID CallingConv){
1313 switch (CallingConv) {
1316 case CallingConv::X86_StdCall:
1317 return !Subtarget->is64Bit();
1318 case CallingConv::X86_FastCall:
1319 return !Subtarget->is64Bit();
1320 case CallingConv::Fast:
1321 return PerformTailCallOpt;
1325 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1326 /// given CallingConvention value.
1327 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1328 if (Subtarget->is64Bit()) {
1329 if (Subtarget->isTargetWin64())
1330 return CC_X86_Win64_C;
1335 if (CC == CallingConv::X86_FastCall)
1336 return CC_X86_32_FastCall;
1337 else if (CC == CallingConv::Fast)
1338 return CC_X86_32_FastCC;
1343 /// NameDecorationForCallConv - Selects the appropriate decoration to
1344 /// apply to a MachineFunction containing a given calling convention.
1346 X86TargetLowering::NameDecorationForCallConv(CallingConv::ID CallConv) {
1347 if (CallConv == CallingConv::X86_FastCall)
1349 else if (CallConv == CallingConv::X86_StdCall)
1355 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1356 /// by "Src" to address "Dst" with size and alignment information specified by
1357 /// the specific parameter attribute. The copy will be passed as a byval
1358 /// function parameter.
1360 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1361 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1363 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1364 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1365 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1369 X86TargetLowering::LowerMemArgument(SDValue Chain,
1370 CallingConv::ID CallConv,
1371 const SmallVectorImpl<ISD::InputArg> &Ins,
1372 DebugLoc dl, SelectionDAG &DAG,
1373 const CCValAssign &VA,
1374 MachineFrameInfo *MFI,
1377 // Create the nodes corresponding to a load from this parameter slot.
1378 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1379 bool AlwaysUseMutable = (CallConv==CallingConv::Fast) && PerformTailCallOpt;
1380 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1383 // If value is passed by pointer we have address passed instead of the value
1385 if (VA.getLocInfo() == CCValAssign::Indirect)
1386 ValVT = VA.getLocVT();
1388 ValVT = VA.getValVT();
1390 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1391 // changed with more analysis.
1392 // In case of tail call optimization mark all arguments mutable. Since they
1393 // could be overwritten by lowering of arguments in case of a tail call.
1394 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1395 VA.getLocMemOffset(), isImmutable, false);
1396 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1397 if (Flags.isByVal())
1399 return DAG.getLoad(ValVT, dl, Chain, FIN,
1400 PseudoSourceValue::getFixedStack(FI), 0);
1404 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1405 CallingConv::ID CallConv,
1407 const SmallVectorImpl<ISD::InputArg> &Ins,
1410 SmallVectorImpl<SDValue> &InVals) {
1412 MachineFunction &MF = DAG.getMachineFunction();
1413 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1415 const Function* Fn = MF.getFunction();
1416 if (Fn->hasExternalLinkage() &&
1417 Subtarget->isTargetCygMing() &&
1418 Fn->getName() == "main")
1419 FuncInfo->setForceFramePointer(true);
1421 // Decorate the function name.
1422 FuncInfo->setDecorationStyle(NameDecorationForCallConv(CallConv));
1424 MachineFrameInfo *MFI = MF.getFrameInfo();
1425 bool Is64Bit = Subtarget->is64Bit();
1426 bool IsWin64 = Subtarget->isTargetWin64();
1428 assert(!(isVarArg && CallConv == CallingConv::Fast) &&
1429 "Var args not supported with calling convention fastcc");
1431 // Assign locations to all of the incoming arguments.
1432 SmallVector<CCValAssign, 16> ArgLocs;
1433 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1434 ArgLocs, *DAG.getContext());
1435 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1437 unsigned LastVal = ~0U;
1439 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1440 CCValAssign &VA = ArgLocs[i];
1441 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1443 assert(VA.getValNo() != LastVal &&
1444 "Don't support value assigned to multiple locs yet");
1445 LastVal = VA.getValNo();
1447 if (VA.isRegLoc()) {
1448 EVT RegVT = VA.getLocVT();
1449 TargetRegisterClass *RC = NULL;
1450 if (RegVT == MVT::i32)
1451 RC = X86::GR32RegisterClass;
1452 else if (Is64Bit && RegVT == MVT::i64)
1453 RC = X86::GR64RegisterClass;
1454 else if (RegVT == MVT::f32)
1455 RC = X86::FR32RegisterClass;
1456 else if (RegVT == MVT::f64)
1457 RC = X86::FR64RegisterClass;
1458 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1459 RC = X86::VR128RegisterClass;
1460 else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1461 RC = X86::VR64RegisterClass;
1463 llvm_unreachable("Unknown argument type!");
1465 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1466 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1468 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1469 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1471 if (VA.getLocInfo() == CCValAssign::SExt)
1472 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1473 DAG.getValueType(VA.getValVT()));
1474 else if (VA.getLocInfo() == CCValAssign::ZExt)
1475 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1476 DAG.getValueType(VA.getValVT()));
1477 else if (VA.getLocInfo() == CCValAssign::BCvt)
1478 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1480 if (VA.isExtInLoc()) {
1481 // Handle MMX values passed in XMM regs.
1482 if (RegVT.isVector()) {
1483 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1484 ArgValue, DAG.getConstant(0, MVT::i64));
1485 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1487 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1490 assert(VA.isMemLoc());
1491 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1494 // If value is passed via pointer - do a load.
1495 if (VA.getLocInfo() == CCValAssign::Indirect)
1496 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0);
1498 InVals.push_back(ArgValue);
1501 // The x86-64 ABI for returning structs by value requires that we copy
1502 // the sret argument into %rax for the return. Save the argument into
1503 // a virtual register so that we can access it from the return points.
1504 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1505 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1506 unsigned Reg = FuncInfo->getSRetReturnReg();
1508 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1509 FuncInfo->setSRetReturnReg(Reg);
1511 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1512 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1515 unsigned StackSize = CCInfo.getNextStackOffset();
1516 // align stack specially for tail calls
1517 if (PerformTailCallOpt && CallConv == CallingConv::Fast)
1518 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1520 // If the function takes variable number of arguments, make a frame index for
1521 // the start of the first vararg value... for expansion of llvm.va_start.
1523 if (Is64Bit || CallConv != CallingConv::X86_FastCall) {
1524 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize, true, false);
1527 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1529 // FIXME: We should really autogenerate these arrays
1530 static const unsigned GPR64ArgRegsWin64[] = {
1531 X86::RCX, X86::RDX, X86::R8, X86::R9
1533 static const unsigned XMMArgRegsWin64[] = {
1534 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1536 static const unsigned GPR64ArgRegs64Bit[] = {
1537 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1539 static const unsigned XMMArgRegs64Bit[] = {
1540 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1541 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1543 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1546 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1547 GPR64ArgRegs = GPR64ArgRegsWin64;
1548 XMMArgRegs = XMMArgRegsWin64;
1550 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1551 GPR64ArgRegs = GPR64ArgRegs64Bit;
1552 XMMArgRegs = XMMArgRegs64Bit;
1554 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1556 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1559 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1560 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1561 "SSE register cannot be used when SSE is disabled!");
1562 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1563 "SSE register cannot be used when SSE is disabled!");
1564 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1565 // Kernel mode asks for SSE to be disabled, so don't push them
1567 TotalNumXMMRegs = 0;
1569 // For X86-64, if there are vararg parameters that are passed via
1570 // registers, then we must store them to their spots on the stack so they
1571 // may be loaded by deferencing the result of va_next.
1572 VarArgsGPOffset = NumIntRegs * 8;
1573 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1574 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1575 TotalNumXMMRegs * 16, 16,
1578 // Store the integer parameter registers.
1579 SmallVector<SDValue, 8> MemOps;
1580 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1581 unsigned Offset = VarArgsGPOffset;
1582 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1583 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1584 DAG.getIntPtrConstant(Offset));
1585 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1586 X86::GR64RegisterClass);
1587 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1589 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1590 PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
1592 MemOps.push_back(Store);
1596 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1597 // Now store the XMM (fp + vector) parameter registers.
1598 SmallVector<SDValue, 11> SaveXMMOps;
1599 SaveXMMOps.push_back(Chain);
1601 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1602 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1603 SaveXMMOps.push_back(ALVal);
1605 SaveXMMOps.push_back(DAG.getIntPtrConstant(RegSaveFrameIndex));
1606 SaveXMMOps.push_back(DAG.getIntPtrConstant(VarArgsFPOffset));
1608 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1609 unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1610 X86::VR128RegisterClass);
1611 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1612 SaveXMMOps.push_back(Val);
1614 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1616 &SaveXMMOps[0], SaveXMMOps.size()));
1619 if (!MemOps.empty())
1620 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1621 &MemOps[0], MemOps.size());
1625 // Some CCs need callee pop.
1626 if (IsCalleePop(isVarArg, CallConv)) {
1627 BytesToPopOnReturn = StackSize; // Callee pops everything.
1628 BytesCallerReserves = 0;
1630 BytesToPopOnReturn = 0; // Callee pops nothing.
1631 // If this is an sret function, the return should pop the hidden pointer.
1632 if (!Is64Bit && CallConv != CallingConv::Fast && ArgsAreStructReturn(Ins))
1633 BytesToPopOnReturn = 4;
1634 BytesCallerReserves = StackSize;
1638 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1639 if (CallConv == CallingConv::X86_FastCall)
1640 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1643 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1649 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1650 SDValue StackPtr, SDValue Arg,
1651 DebugLoc dl, SelectionDAG &DAG,
1652 const CCValAssign &VA,
1653 ISD::ArgFlagsTy Flags) {
1654 const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1655 unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1656 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1657 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1658 if (Flags.isByVal()) {
1659 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1661 return DAG.getStore(Chain, dl, Arg, PtrOff,
1662 PseudoSourceValue::getStack(), LocMemOffset);
1665 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1666 /// optimization is performed and it is required.
1668 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1669 SDValue &OutRetAddr,
1675 if (!IsTailCall || FPDiff==0) return Chain;
1677 // Adjust the Return address stack slot.
1678 EVT VT = getPointerTy();
1679 OutRetAddr = getReturnAddressFrameIndex(DAG);
1681 // Load the "old" Return address.
1682 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0);
1683 return SDValue(OutRetAddr.getNode(), 1);
1686 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1687 /// optimization is performed and it is required (FPDiff!=0).
1689 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1690 SDValue Chain, SDValue RetAddrFrIdx,
1691 bool Is64Bit, int FPDiff, DebugLoc dl) {
1692 // Store the return address to the appropriate stack slot.
1693 if (!FPDiff) return Chain;
1694 // Calculate the new stack slot for the return address.
1695 int SlotSize = Is64Bit ? 8 : 4;
1696 int NewReturnAddrFI =
1697 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize,
1699 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1700 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1701 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1702 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1707 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1708 CallingConv::ID CallConv, bool isVarArg,
1710 const SmallVectorImpl<ISD::OutputArg> &Outs,
1711 const SmallVectorImpl<ISD::InputArg> &Ins,
1712 DebugLoc dl, SelectionDAG &DAG,
1713 SmallVectorImpl<SDValue> &InVals) {
1715 MachineFunction &MF = DAG.getMachineFunction();
1716 bool Is64Bit = Subtarget->is64Bit();
1717 bool IsStructRet = CallIsStructReturn(Outs);
1719 assert((!isTailCall ||
1720 (CallConv == CallingConv::Fast && PerformTailCallOpt)) &&
1721 "IsEligibleForTailCallOptimization missed a case!");
1722 assert(!(isVarArg && CallConv == CallingConv::Fast) &&
1723 "Var args not supported with calling convention fastcc");
1725 // Analyze operands of the call, assigning locations to each operand.
1726 SmallVector<CCValAssign, 16> ArgLocs;
1727 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1728 ArgLocs, *DAG.getContext());
1729 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1731 // Get a count of how many bytes are to be pushed on the stack.
1732 unsigned NumBytes = CCInfo.getNextStackOffset();
1733 if (PerformTailCallOpt && CallConv == CallingConv::Fast)
1734 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1738 // Lower arguments at fp - stackoffset + fpdiff.
1739 unsigned NumBytesCallerPushed =
1740 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1741 FPDiff = NumBytesCallerPushed - NumBytes;
1743 // Set the delta of movement of the returnaddr stackslot.
1744 // But only set if delta is greater than previous delta.
1745 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1746 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1749 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1751 SDValue RetAddrFrIdx;
1752 // Load return adress for tail calls.
1753 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall, Is64Bit,
1756 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1757 SmallVector<SDValue, 8> MemOpChains;
1760 // Walk the register/memloc assignments, inserting copies/loads. In the case
1761 // of tail call optimization arguments are handle later.
1762 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1763 CCValAssign &VA = ArgLocs[i];
1764 EVT RegVT = VA.getLocVT();
1765 SDValue Arg = Outs[i].Val;
1766 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1767 bool isByVal = Flags.isByVal();
1769 // Promote the value if needed.
1770 switch (VA.getLocInfo()) {
1771 default: llvm_unreachable("Unknown loc info!");
1772 case CCValAssign::Full: break;
1773 case CCValAssign::SExt:
1774 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1776 case CCValAssign::ZExt:
1777 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1779 case CCValAssign::AExt:
1780 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1781 // Special case: passing MMX values in XMM registers.
1782 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1783 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1784 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1786 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1788 case CCValAssign::BCvt:
1789 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1791 case CCValAssign::Indirect: {
1792 // Store the argument.
1793 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1794 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1795 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1796 PseudoSourceValue::getFixedStack(FI), 0);
1802 if (VA.isRegLoc()) {
1803 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1805 if (!isTailCall || (isTailCall && isByVal)) {
1806 assert(VA.isMemLoc());
1807 if (StackPtr.getNode() == 0)
1808 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1810 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1811 dl, DAG, VA, Flags));
1816 if (!MemOpChains.empty())
1817 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1818 &MemOpChains[0], MemOpChains.size());
1820 // Build a sequence of copy-to-reg nodes chained together with token chain
1821 // and flag operands which copy the outgoing args into registers.
1823 // Tail call byval lowering might overwrite argument registers so in case of
1824 // tail call optimization the copies to registers are lowered later.
1826 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1827 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1828 RegsToPass[i].second, InFlag);
1829 InFlag = Chain.getValue(1);
1833 if (Subtarget->isPICStyleGOT()) {
1834 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1837 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1838 DAG.getNode(X86ISD::GlobalBaseReg,
1839 DebugLoc::getUnknownLoc(),
1842 InFlag = Chain.getValue(1);
1844 // If we are tail calling and generating PIC/GOT style code load the
1845 // address of the callee into ECX. The value in ecx is used as target of
1846 // the tail jump. This is done to circumvent the ebx/callee-saved problem
1847 // for tail calls on PIC/GOT architectures. Normally we would just put the
1848 // address of GOT into ebx and then call target@PLT. But for tail calls
1849 // ebx would be restored (since ebx is callee saved) before jumping to the
1852 // Note: The actual moving to ECX is done further down.
1853 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1854 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1855 !G->getGlobal()->hasProtectedVisibility())
1856 Callee = LowerGlobalAddress(Callee, DAG);
1857 else if (isa<ExternalSymbolSDNode>(Callee))
1858 Callee = LowerExternalSymbol(Callee, DAG);
1862 if (Is64Bit && isVarArg) {
1863 // From AMD64 ABI document:
1864 // For calls that may call functions that use varargs or stdargs
1865 // (prototype-less calls or calls to functions containing ellipsis (...) in
1866 // the declaration) %al is used as hidden argument to specify the number
1867 // of SSE registers used. The contents of %al do not need to match exactly
1868 // the number of registers, but must be an ubound on the number of SSE
1869 // registers used and is in the range 0 - 8 inclusive.
1871 // FIXME: Verify this on Win64
1872 // Count the number of XMM registers allocated.
1873 static const unsigned XMMArgRegs[] = {
1874 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1875 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1877 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1878 assert((Subtarget->hasSSE1() || !NumXMMRegs)
1879 && "SSE registers cannot be used when SSE is disabled");
1881 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1882 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1883 InFlag = Chain.getValue(1);
1887 // For tail calls lower the arguments to the 'real' stack slot.
1889 // Force all the incoming stack arguments to be loaded from the stack
1890 // before any new outgoing arguments are stored to the stack, because the
1891 // outgoing stack slots may alias the incoming argument stack slots, and
1892 // the alias isn't otherwise explicit. This is slightly more conservative
1893 // than necessary, because it means that each store effectively depends
1894 // on every argument instead of just those arguments it would clobber.
1895 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
1897 SmallVector<SDValue, 8> MemOpChains2;
1900 // Do not flag preceeding copytoreg stuff together with the following stuff.
1902 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1903 CCValAssign &VA = ArgLocs[i];
1904 if (!VA.isRegLoc()) {
1905 assert(VA.isMemLoc());
1906 SDValue Arg = Outs[i].Val;
1907 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1908 // Create frame index.
1909 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1910 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1911 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true, false);
1912 FIN = DAG.getFrameIndex(FI, getPointerTy());
1914 if (Flags.isByVal()) {
1915 // Copy relative to framepointer.
1916 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1917 if (StackPtr.getNode() == 0)
1918 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
1920 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
1922 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
1926 // Store relative to framepointer.
1927 MemOpChains2.push_back(
1928 DAG.getStore(ArgChain, dl, Arg, FIN,
1929 PseudoSourceValue::getFixedStack(FI), 0));
1934 if (!MemOpChains2.empty())
1935 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1936 &MemOpChains2[0], MemOpChains2.size());
1938 // Copy arguments to their registers.
1939 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1940 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1941 RegsToPass[i].second, InFlag);
1942 InFlag = Chain.getValue(1);
1946 // Store the return address to the appropriate stack slot.
1947 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1951 bool WasGlobalOrExternal = false;
1952 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
1953 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
1954 // In the 64-bit large code model, we have to make all calls
1955 // through a register, since the call instruction's 32-bit
1956 // pc-relative offset may not be large enough to hold the whole
1958 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1959 WasGlobalOrExternal = true;
1960 // If the callee is a GlobalAddress node (quite common, every direct call
1961 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
1964 // We should use extra load for direct calls to dllimported functions in
1966 GlobalValue *GV = G->getGlobal();
1967 if (!GV->hasDLLImportLinkage()) {
1968 unsigned char OpFlags = 0;
1970 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
1971 // external symbols most go through the PLT in PIC mode. If the symbol
1972 // has hidden or protected visibility, or if it is static or local, then
1973 // we don't need to use the PLT - we can directly call it.
1974 if (Subtarget->isTargetELF() &&
1975 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1976 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
1977 OpFlags = X86II::MO_PLT;
1978 } else if (Subtarget->isPICStyleStubAny() &&
1979 (GV->isDeclaration() || GV->isWeakForLinker()) &&
1980 Subtarget->getDarwinVers() < 9) {
1981 // PC-relative references to external symbols should go through $stub,
1982 // unless we're building with the leopard linker or later, which
1983 // automatically synthesizes these stubs.
1984 OpFlags = X86II::MO_DARWIN_STUB;
1987 Callee = DAG.getTargetGlobalAddress(GV, getPointerTy(),
1988 G->getOffset(), OpFlags);
1990 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1991 WasGlobalOrExternal = true;
1992 unsigned char OpFlags = 0;
1994 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
1995 // symbols should go through the PLT.
1996 if (Subtarget->isTargetELF() &&
1997 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1998 OpFlags = X86II::MO_PLT;
1999 } else if (Subtarget->isPICStyleStubAny() &&
2000 Subtarget->getDarwinVers() < 9) {
2001 // PC-relative references to external symbols should go through $stub,
2002 // unless we're building with the leopard linker or later, which
2003 // automatically synthesizes these stubs.
2004 OpFlags = X86II::MO_DARWIN_STUB;
2007 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2011 if (isTailCall && !WasGlobalOrExternal) {
2012 unsigned Opc = Is64Bit ? X86::R11 : X86::EAX;
2014 Chain = DAG.getCopyToReg(Chain, dl,
2015 DAG.getRegister(Opc, getPointerTy()),
2017 Callee = DAG.getRegister(Opc, getPointerTy());
2018 // Add register as live out.
2019 MF.getRegInfo().addLiveOut(Opc);
2022 // Returns a chain & a flag for retval copy to use.
2023 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2024 SmallVector<SDValue, 8> Ops;
2027 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2028 DAG.getIntPtrConstant(0, true), InFlag);
2029 InFlag = Chain.getValue(1);
2032 Ops.push_back(Chain);
2033 Ops.push_back(Callee);
2036 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2038 // Add argument registers to the end of the list so that they are known live
2040 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2041 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2042 RegsToPass[i].second.getValueType()));
2044 // Add an implicit use GOT pointer in EBX.
2045 if (!isTailCall && Subtarget->isPICStyleGOT())
2046 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2048 // Add an implicit use of AL for x86 vararg functions.
2049 if (Is64Bit && isVarArg)
2050 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2052 if (InFlag.getNode())
2053 Ops.push_back(InFlag);
2056 // If this is the first return lowered for this function, add the regs
2057 // to the liveout set for the function.
2058 if (MF.getRegInfo().liveout_empty()) {
2059 SmallVector<CCValAssign, 16> RVLocs;
2060 CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
2062 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2063 for (unsigned i = 0; i != RVLocs.size(); ++i)
2064 if (RVLocs[i].isRegLoc())
2065 MF.getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2068 assert(((Callee.getOpcode() == ISD::Register &&
2069 (cast<RegisterSDNode>(Callee)->getReg() == X86::EAX ||
2070 cast<RegisterSDNode>(Callee)->getReg() == X86::R9)) ||
2071 Callee.getOpcode() == ISD::TargetExternalSymbol ||
2072 Callee.getOpcode() == ISD::TargetGlobalAddress) &&
2073 "Expecting an global address, external symbol, or register");
2075 return DAG.getNode(X86ISD::TC_RETURN, dl,
2076 NodeTys, &Ops[0], Ops.size());
2079 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2080 InFlag = Chain.getValue(1);
2082 // Create the CALLSEQ_END node.
2083 unsigned NumBytesForCalleeToPush;
2084 if (IsCalleePop(isVarArg, CallConv))
2085 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2086 else if (!Is64Bit && CallConv != CallingConv::Fast && IsStructRet)
2087 // If this is is a call to a struct-return function, the callee
2088 // pops the hidden struct pointer, so we have to push it back.
2089 // This is common for Darwin/X86, Linux & Mingw32 targets.
2090 NumBytesForCalleeToPush = 4;
2092 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2094 // Returns a flag for retval copy to use.
2095 Chain = DAG.getCALLSEQ_END(Chain,
2096 DAG.getIntPtrConstant(NumBytes, true),
2097 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2100 InFlag = Chain.getValue(1);
2102 // Handle result values, copying them out of physregs into vregs that we
2104 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2105 Ins, dl, DAG, InVals);
2109 //===----------------------------------------------------------------------===//
2110 // Fast Calling Convention (tail call) implementation
2111 //===----------------------------------------------------------------------===//
2113 // Like std call, callee cleans arguments, convention except that ECX is
2114 // reserved for storing the tail called function address. Only 2 registers are
2115 // free for argument passing (inreg). Tail call optimization is performed
2117 // * tailcallopt is enabled
2118 // * caller/callee are fastcc
2119 // On X86_64 architecture with GOT-style position independent code only local
2120 // (within module) calls are supported at the moment.
2121 // To keep the stack aligned according to platform abi the function
2122 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2123 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2124 // If a tail called function callee has more arguments than the caller the
2125 // caller needs to make sure that there is room to move the RETADDR to. This is
2126 // achieved by reserving an area the size of the argument delta right after the
2127 // original REtADDR, but before the saved framepointer or the spilled registers
2128 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2140 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2141 /// for a 16 byte align requirement.
2142 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2143 SelectionDAG& DAG) {
2144 MachineFunction &MF = DAG.getMachineFunction();
2145 const TargetMachine &TM = MF.getTarget();
2146 const TargetFrameInfo &TFI = *TM.getFrameInfo();
2147 unsigned StackAlignment = TFI.getStackAlignment();
2148 uint64_t AlignMask = StackAlignment - 1;
2149 int64_t Offset = StackSize;
2150 uint64_t SlotSize = TD->getPointerSize();
2151 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2152 // Number smaller than 12 so just add the difference.
2153 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2155 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2156 Offset = ((~AlignMask) & Offset) + StackAlignment +
2157 (StackAlignment-SlotSize);
2162 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2163 /// for tail call optimization. Targets which want to do tail call
2164 /// optimization should implement this function.
2166 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2167 CallingConv::ID CalleeCC,
2169 const SmallVectorImpl<ISD::InputArg> &Ins,
2170 SelectionDAG& DAG) const {
2171 MachineFunction &MF = DAG.getMachineFunction();
2172 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
2173 return CalleeCC == CallingConv::Fast && CallerCC == CalleeCC;
2177 X86TargetLowering::createFastISel(MachineFunction &mf,
2178 MachineModuleInfo *mmo,
2180 DenseMap<const Value *, unsigned> &vm,
2181 DenseMap<const BasicBlock *,
2182 MachineBasicBlock *> &bm,
2183 DenseMap<const AllocaInst *, int> &am
2185 , SmallSet<Instruction*, 8> &cil
2188 return X86::createFastISel(mf, mmo, dw, vm, bm, am
2196 //===----------------------------------------------------------------------===//
2197 // Other Lowering Hooks
2198 //===----------------------------------------------------------------------===//
2201 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2202 MachineFunction &MF = DAG.getMachineFunction();
2203 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2204 int ReturnAddrIndex = FuncInfo->getRAIndex();
2206 if (ReturnAddrIndex == 0) {
2207 // Set up a frame object for the return address.
2208 uint64_t SlotSize = TD->getPointerSize();
2209 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2211 FuncInfo->setRAIndex(ReturnAddrIndex);
2214 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2218 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2219 bool hasSymbolicDisplacement) {
2220 // Offset should fit into 32 bit immediate field.
2221 if (!isInt32(Offset))
2224 // If we don't have a symbolic displacement - we don't have any extra
2226 if (!hasSymbolicDisplacement)
2229 // FIXME: Some tweaks might be needed for medium code model.
2230 if (M != CodeModel::Small && M != CodeModel::Kernel)
2233 // For small code model we assume that latest object is 16MB before end of 31
2234 // bits boundary. We may also accept pretty large negative constants knowing
2235 // that all objects are in the positive half of address space.
2236 if (M == CodeModel::Small && Offset < 16*1024*1024)
2239 // For kernel code model we know that all object resist in the negative half
2240 // of 32bits address space. We may not accept negative offsets, since they may
2241 // be just off and we may accept pretty large positive ones.
2242 if (M == CodeModel::Kernel && Offset > 0)
2248 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2249 /// specific condition code, returning the condition code and the LHS/RHS of the
2250 /// comparison to make.
2251 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2252 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2254 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2255 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2256 // X > -1 -> X == 0, jump !sign.
2257 RHS = DAG.getConstant(0, RHS.getValueType());
2258 return X86::COND_NS;
2259 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2260 // X < 0 -> X == 0, jump on sign.
2262 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2264 RHS = DAG.getConstant(0, RHS.getValueType());
2265 return X86::COND_LE;
2269 switch (SetCCOpcode) {
2270 default: llvm_unreachable("Invalid integer condition!");
2271 case ISD::SETEQ: return X86::COND_E;
2272 case ISD::SETGT: return X86::COND_G;
2273 case ISD::SETGE: return X86::COND_GE;
2274 case ISD::SETLT: return X86::COND_L;
2275 case ISD::SETLE: return X86::COND_LE;
2276 case ISD::SETNE: return X86::COND_NE;
2277 case ISD::SETULT: return X86::COND_B;
2278 case ISD::SETUGT: return X86::COND_A;
2279 case ISD::SETULE: return X86::COND_BE;
2280 case ISD::SETUGE: return X86::COND_AE;
2284 // First determine if it is required or is profitable to flip the operands.
2286 // If LHS is a foldable load, but RHS is not, flip the condition.
2287 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2288 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2289 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2290 std::swap(LHS, RHS);
2293 switch (SetCCOpcode) {
2299 std::swap(LHS, RHS);
2303 // On a floating point condition, the flags are set as follows:
2305 // 0 | 0 | 0 | X > Y
2306 // 0 | 0 | 1 | X < Y
2307 // 1 | 0 | 0 | X == Y
2308 // 1 | 1 | 1 | unordered
2309 switch (SetCCOpcode) {
2310 default: llvm_unreachable("Condcode should be pre-legalized away");
2312 case ISD::SETEQ: return X86::COND_E;
2313 case ISD::SETOLT: // flipped
2315 case ISD::SETGT: return X86::COND_A;
2316 case ISD::SETOLE: // flipped
2318 case ISD::SETGE: return X86::COND_AE;
2319 case ISD::SETUGT: // flipped
2321 case ISD::SETLT: return X86::COND_B;
2322 case ISD::SETUGE: // flipped
2324 case ISD::SETLE: return X86::COND_BE;
2326 case ISD::SETNE: return X86::COND_NE;
2327 case ISD::SETUO: return X86::COND_P;
2328 case ISD::SETO: return X86::COND_NP;
2330 case ISD::SETUNE: return X86::COND_INVALID;
2334 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2335 /// code. Current x86 isa includes the following FP cmov instructions:
2336 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2337 static bool hasFPCMov(unsigned X86CC) {
2353 /// isFPImmLegal - Returns true if the target can instruction select the
2354 /// specified FP immediate natively. If false, the legalizer will
2355 /// materialize the FP immediate as a load from a constant pool.
2356 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2357 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2358 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2364 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2365 /// the specified range (L, H].
2366 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2367 return (Val < 0) || (Val >= Low && Val < Hi);
2370 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2371 /// specified value.
2372 static bool isUndefOrEqual(int Val, int CmpVal) {
2373 if (Val < 0 || Val == CmpVal)
2378 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2379 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2380 /// the second operand.
2381 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2382 if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2383 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2384 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2385 return (Mask[0] < 2 && Mask[1] < 2);
2389 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2390 SmallVector<int, 8> M;
2392 return ::isPSHUFDMask(M, N->getValueType(0));
2395 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2396 /// is suitable for input to PSHUFHW.
2397 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2398 if (VT != MVT::v8i16)
2401 // Lower quadword copied in order or undef.
2402 for (int i = 0; i != 4; ++i)
2403 if (Mask[i] >= 0 && Mask[i] != i)
2406 // Upper quadword shuffled.
2407 for (int i = 4; i != 8; ++i)
2408 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2414 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2415 SmallVector<int, 8> M;
2417 return ::isPSHUFHWMask(M, N->getValueType(0));
2420 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2421 /// is suitable for input to PSHUFLW.
2422 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2423 if (VT != MVT::v8i16)
2426 // Upper quadword copied in order.
2427 for (int i = 4; i != 8; ++i)
2428 if (Mask[i] >= 0 && Mask[i] != i)
2431 // Lower quadword shuffled.
2432 for (int i = 0; i != 4; ++i)
2439 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2440 SmallVector<int, 8> M;
2442 return ::isPSHUFLWMask(M, N->getValueType(0));
2445 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2446 /// is suitable for input to PALIGNR.
2447 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2449 int i, e = VT.getVectorNumElements();
2451 // Do not handle v2i64 / v2f64 shuffles with palignr.
2452 if (e < 4 || !hasSSSE3)
2455 for (i = 0; i != e; ++i)
2459 // All undef, not a palignr.
2463 // Determine if it's ok to perform a palignr with only the LHS, since we
2464 // don't have access to the actual shuffle elements to see if RHS is undef.
2465 bool Unary = Mask[i] < (int)e;
2466 bool NeedsUnary = false;
2468 int s = Mask[i] - i;
2470 // Check the rest of the elements to see if they are consecutive.
2471 for (++i; i != e; ++i) {
2476 Unary = Unary && (m < (int)e);
2477 NeedsUnary = NeedsUnary || (m < s);
2479 if (NeedsUnary && !Unary)
2481 if (Unary && m != ((s+i) & (e-1)))
2483 if (!Unary && m != (s+i))
2489 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2490 SmallVector<int, 8> M;
2492 return ::isPALIGNRMask(M, N->getValueType(0), true);
2495 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2496 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2497 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2498 int NumElems = VT.getVectorNumElements();
2499 if (NumElems != 2 && NumElems != 4)
2502 int Half = NumElems / 2;
2503 for (int i = 0; i < Half; ++i)
2504 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2506 for (int i = Half; i < NumElems; ++i)
2507 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2513 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2514 SmallVector<int, 8> M;
2516 return ::isSHUFPMask(M, N->getValueType(0));
2519 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2520 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2521 /// half elements to come from vector 1 (which would equal the dest.) and
2522 /// the upper half to come from vector 2.
2523 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2524 int NumElems = VT.getVectorNumElements();
2526 if (NumElems != 2 && NumElems != 4)
2529 int Half = NumElems / 2;
2530 for (int i = 0; i < Half; ++i)
2531 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2533 for (int i = Half; i < NumElems; ++i)
2534 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2539 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2540 SmallVector<int, 8> M;
2542 return isCommutedSHUFPMask(M, N->getValueType(0));
2545 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2546 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2547 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2548 if (N->getValueType(0).getVectorNumElements() != 4)
2551 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2552 return isUndefOrEqual(N->getMaskElt(0), 6) &&
2553 isUndefOrEqual(N->getMaskElt(1), 7) &&
2554 isUndefOrEqual(N->getMaskElt(2), 2) &&
2555 isUndefOrEqual(N->getMaskElt(3), 3);
2558 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2559 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2561 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2562 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2567 return isUndefOrEqual(N->getMaskElt(0), 2) &&
2568 isUndefOrEqual(N->getMaskElt(1), 3) &&
2569 isUndefOrEqual(N->getMaskElt(2), 2) &&
2570 isUndefOrEqual(N->getMaskElt(3), 3);
2573 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2574 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2575 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2576 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2578 if (NumElems != 2 && NumElems != 4)
2581 for (unsigned i = 0; i < NumElems/2; ++i)
2582 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2585 for (unsigned i = NumElems/2; i < NumElems; ++i)
2586 if (!isUndefOrEqual(N->getMaskElt(i), i))
2592 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
2593 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
2594 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
2595 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2597 if (NumElems != 2 && NumElems != 4)
2600 for (unsigned i = 0; i < NumElems/2; ++i)
2601 if (!isUndefOrEqual(N->getMaskElt(i), i))
2604 for (unsigned i = 0; i < NumElems/2; ++i)
2605 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2611 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2612 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2613 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2614 bool V2IsSplat = false) {
2615 int NumElts = VT.getVectorNumElements();
2616 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2619 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2621 int BitI1 = Mask[i+1];
2622 if (!isUndefOrEqual(BitI, j))
2625 if (!isUndefOrEqual(BitI1, NumElts))
2628 if (!isUndefOrEqual(BitI1, j + NumElts))
2635 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2636 SmallVector<int, 8> M;
2638 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2641 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2642 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2643 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
2644 bool V2IsSplat = false) {
2645 int NumElts = VT.getVectorNumElements();
2646 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2649 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2651 int BitI1 = Mask[i+1];
2652 if (!isUndefOrEqual(BitI, j + NumElts/2))
2655 if (isUndefOrEqual(BitI1, NumElts))
2658 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2665 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2666 SmallVector<int, 8> M;
2668 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2671 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2672 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2674 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2675 int NumElems = VT.getVectorNumElements();
2676 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2679 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2681 int BitI1 = Mask[i+1];
2682 if (!isUndefOrEqual(BitI, j))
2684 if (!isUndefOrEqual(BitI1, j))
2690 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2691 SmallVector<int, 8> M;
2693 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2696 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2697 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2699 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2700 int NumElems = VT.getVectorNumElements();
2701 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2704 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2706 int BitI1 = Mask[i+1];
2707 if (!isUndefOrEqual(BitI, j))
2709 if (!isUndefOrEqual(BitI1, j))
2715 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2716 SmallVector<int, 8> M;
2718 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2721 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2722 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2723 /// MOVSD, and MOVD, i.e. setting the lowest element.
2724 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2725 if (VT.getVectorElementType().getSizeInBits() < 32)
2728 int NumElts = VT.getVectorNumElements();
2730 if (!isUndefOrEqual(Mask[0], NumElts))
2733 for (int i = 1; i < NumElts; ++i)
2734 if (!isUndefOrEqual(Mask[i], i))
2740 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2741 SmallVector<int, 8> M;
2743 return ::isMOVLMask(M, N->getValueType(0));
2746 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2747 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2748 /// element of vector 2 and the other elements to come from vector 1 in order.
2749 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2750 bool V2IsSplat = false, bool V2IsUndef = false) {
2751 int NumOps = VT.getVectorNumElements();
2752 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2755 if (!isUndefOrEqual(Mask[0], 0))
2758 for (int i = 1; i < NumOps; ++i)
2759 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
2760 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
2761 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
2767 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
2768 bool V2IsUndef = false) {
2769 SmallVector<int, 8> M;
2771 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
2774 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2775 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2776 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
2777 if (N->getValueType(0).getVectorNumElements() != 4)
2780 // Expect 1, 1, 3, 3
2781 for (unsigned i = 0; i < 2; ++i) {
2782 int Elt = N->getMaskElt(i);
2783 if (Elt >= 0 && Elt != 1)
2788 for (unsigned i = 2; i < 4; ++i) {
2789 int Elt = N->getMaskElt(i);
2790 if (Elt >= 0 && Elt != 3)
2795 // Don't use movshdup if it can be done with a shufps.
2796 // FIXME: verify that matching u, u, 3, 3 is what we want.
2800 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2801 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2802 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
2803 if (N->getValueType(0).getVectorNumElements() != 4)
2806 // Expect 0, 0, 2, 2
2807 for (unsigned i = 0; i < 2; ++i)
2808 if (N->getMaskElt(i) > 0)
2812 for (unsigned i = 2; i < 4; ++i) {
2813 int Elt = N->getMaskElt(i);
2814 if (Elt >= 0 && Elt != 2)
2819 // Don't use movsldup if it can be done with a shufps.
2823 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2824 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2825 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
2826 int e = N->getValueType(0).getVectorNumElements() / 2;
2828 for (int i = 0; i < e; ++i)
2829 if (!isUndefOrEqual(N->getMaskElt(i), i))
2831 for (int i = 0; i < e; ++i)
2832 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
2837 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2838 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
2839 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2840 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2841 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
2843 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2845 for (int i = 0; i < NumOperands; ++i) {
2846 int Val = SVOp->getMaskElt(NumOperands-i-1);
2847 if (Val < 0) Val = 0;
2848 if (Val >= NumOperands) Val -= NumOperands;
2850 if (i != NumOperands - 1)
2856 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2857 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
2858 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2859 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2861 // 8 nodes, but we only care about the last 4.
2862 for (unsigned i = 7; i >= 4; --i) {
2863 int Val = SVOp->getMaskElt(i);
2872 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2873 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
2874 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2875 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2877 // 8 nodes, but we only care about the first 4.
2878 for (int i = 3; i >= 0; --i) {
2879 int Val = SVOp->getMaskElt(i);
2888 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
2889 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
2890 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
2891 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2892 EVT VVT = N->getValueType(0);
2893 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
2897 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
2898 Val = SVOp->getMaskElt(i);
2902 return (Val - i) * EltSize;
2905 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2907 bool X86::isZeroNode(SDValue Elt) {
2908 return ((isa<ConstantSDNode>(Elt) &&
2909 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2910 (isa<ConstantFPSDNode>(Elt) &&
2911 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2914 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
2915 /// their permute mask.
2916 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
2917 SelectionDAG &DAG) {
2918 EVT VT = SVOp->getValueType(0);
2919 unsigned NumElems = VT.getVectorNumElements();
2920 SmallVector<int, 8> MaskVec;
2922 for (unsigned i = 0; i != NumElems; ++i) {
2923 int idx = SVOp->getMaskElt(i);
2925 MaskVec.push_back(idx);
2926 else if (idx < (int)NumElems)
2927 MaskVec.push_back(idx + NumElems);
2929 MaskVec.push_back(idx - NumElems);
2931 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
2932 SVOp->getOperand(0), &MaskVec[0]);
2935 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2936 /// the two vector operands have swapped position.
2937 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
2938 unsigned NumElems = VT.getVectorNumElements();
2939 for (unsigned i = 0; i != NumElems; ++i) {
2943 else if (idx < (int)NumElems)
2944 Mask[i] = idx + NumElems;
2946 Mask[i] = idx - NumElems;
2950 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2951 /// match movhlps. The lower half elements should come from upper half of
2952 /// V1 (and in order), and the upper half elements should come from the upper
2953 /// half of V2 (and in order).
2954 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
2955 if (Op->getValueType(0).getVectorNumElements() != 4)
2957 for (unsigned i = 0, e = 2; i != e; ++i)
2958 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
2960 for (unsigned i = 2; i != 4; ++i)
2961 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
2966 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2967 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2969 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2970 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
2972 N = N->getOperand(0).getNode();
2973 if (!ISD::isNON_EXTLoad(N))
2976 *LD = cast<LoadSDNode>(N);
2980 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2981 /// match movlp{s|d}. The lower half elements should come from lower half of
2982 /// V1 (and in order), and the upper half elements should come from the upper
2983 /// half of V2 (and in order). And since V1 will become the source of the
2984 /// MOVLP, it must be either a vector load or a scalar load to vector.
2985 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
2986 ShuffleVectorSDNode *Op) {
2987 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2989 // Is V2 is a vector load, don't do this transformation. We will try to use
2990 // load folding shufps op.
2991 if (ISD::isNON_EXTLoad(V2))
2994 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
2996 if (NumElems != 2 && NumElems != 4)
2998 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2999 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3001 for (unsigned i = NumElems/2; i != NumElems; ++i)
3002 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3007 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3009 static bool isSplatVector(SDNode *N) {
3010 if (N->getOpcode() != ISD::BUILD_VECTOR)
3013 SDValue SplatValue = N->getOperand(0);
3014 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3015 if (N->getOperand(i) != SplatValue)
3020 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3021 /// to an zero vector.
3022 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3023 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3024 SDValue V1 = N->getOperand(0);
3025 SDValue V2 = N->getOperand(1);
3026 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3027 for (unsigned i = 0; i != NumElems; ++i) {
3028 int Idx = N->getMaskElt(i);
3029 if (Idx >= (int)NumElems) {
3030 unsigned Opc = V2.getOpcode();
3031 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3033 if (Opc != ISD::BUILD_VECTOR ||
3034 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3036 } else if (Idx >= 0) {
3037 unsigned Opc = V1.getOpcode();
3038 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3040 if (Opc != ISD::BUILD_VECTOR ||
3041 !X86::isZeroNode(V1.getOperand(Idx)))
3048 /// getZeroVector - Returns a vector of specified type with all zero elements.
3050 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3052 assert(VT.isVector() && "Expected a vector type");
3054 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3055 // type. This ensures they get CSE'd.
3057 if (VT.getSizeInBits() == 64) { // MMX
3058 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3059 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3060 } else if (HasSSE2) { // SSE2
3061 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3062 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3064 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3065 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3067 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3070 /// getOnesVector - Returns a vector of specified type with all bits set.
3072 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3073 assert(VT.isVector() && "Expected a vector type");
3075 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3076 // type. This ensures they get CSE'd.
3077 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3079 if (VT.getSizeInBits() == 64) // MMX
3080 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3082 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3083 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3087 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3088 /// that point to V2 points to its first element.
3089 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3090 EVT VT = SVOp->getValueType(0);
3091 unsigned NumElems = VT.getVectorNumElements();
3093 bool Changed = false;
3094 SmallVector<int, 8> MaskVec;
3095 SVOp->getMask(MaskVec);
3097 for (unsigned i = 0; i != NumElems; ++i) {
3098 if (MaskVec[i] > (int)NumElems) {
3099 MaskVec[i] = NumElems;
3104 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3105 SVOp->getOperand(1), &MaskVec[0]);
3106 return SDValue(SVOp, 0);
3109 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3110 /// operation of specified width.
3111 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3113 unsigned NumElems = VT.getVectorNumElements();
3114 SmallVector<int, 8> Mask;
3115 Mask.push_back(NumElems);
3116 for (unsigned i = 1; i != NumElems; ++i)
3118 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3121 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3122 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3124 unsigned NumElems = VT.getVectorNumElements();
3125 SmallVector<int, 8> Mask;
3126 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3128 Mask.push_back(i + NumElems);
3130 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3133 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3134 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3136 unsigned NumElems = VT.getVectorNumElements();
3137 unsigned Half = NumElems/2;
3138 SmallVector<int, 8> Mask;
3139 for (unsigned i = 0; i != Half; ++i) {
3140 Mask.push_back(i + Half);
3141 Mask.push_back(i + NumElems + Half);
3143 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3146 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3147 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3149 if (SV->getValueType(0).getVectorNumElements() <= 4)
3150 return SDValue(SV, 0);
3152 EVT PVT = MVT::v4f32;
3153 EVT VT = SV->getValueType(0);
3154 DebugLoc dl = SV->getDebugLoc();
3155 SDValue V1 = SV->getOperand(0);
3156 int NumElems = VT.getVectorNumElements();
3157 int EltNo = SV->getSplatIndex();
3159 // unpack elements to the correct location
3160 while (NumElems > 4) {
3161 if (EltNo < NumElems/2) {
3162 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3164 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3165 EltNo -= NumElems/2;
3170 // Perform the splat.
3171 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3172 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3173 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3174 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3177 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3178 /// vector of zero or undef vector. This produces a shuffle where the low
3179 /// element of V2 is swizzled into the zero/undef vector, landing at element
3180 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3181 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3182 bool isZero, bool HasSSE2,
3183 SelectionDAG &DAG) {
3184 EVT VT = V2.getValueType();
3186 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3187 unsigned NumElems = VT.getVectorNumElements();
3188 SmallVector<int, 16> MaskVec;
3189 for (unsigned i = 0; i != NumElems; ++i)
3190 // If this is the insertion idx, put the low elt of V2 here.
3191 MaskVec.push_back(i == Idx ? NumElems : i);
3192 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3195 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3196 /// a shuffle that is zero.
3198 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3199 bool Low, SelectionDAG &DAG) {
3200 unsigned NumZeros = 0;
3201 for (int i = 0; i < NumElems; ++i) {
3202 unsigned Index = Low ? i : NumElems-i-1;
3203 int Idx = SVOp->getMaskElt(Index);
3208 SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3209 if (Elt.getNode() && X86::isZeroNode(Elt))
3217 /// isVectorShift - Returns true if the shuffle can be implemented as a
3218 /// logical left or right shift of a vector.
3219 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3220 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3221 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3222 int NumElems = SVOp->getValueType(0).getVectorNumElements();
3225 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3228 NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3232 bool SeenV1 = false;
3233 bool SeenV2 = false;
3234 for (int i = NumZeros; i < NumElems; ++i) {
3235 int Val = isLeft ? (i - NumZeros) : i;
3236 int Idx = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3248 if (SeenV1 && SeenV2)
3251 ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3257 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3259 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3260 unsigned NumNonZero, unsigned NumZero,
3261 SelectionDAG &DAG, TargetLowering &TLI) {
3265 DebugLoc dl = Op.getDebugLoc();
3268 for (unsigned i = 0; i < 16; ++i) {
3269 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3270 if (ThisIsNonZero && First) {
3272 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3274 V = DAG.getUNDEF(MVT::v8i16);
3279 SDValue ThisElt(0, 0), LastElt(0, 0);
3280 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3281 if (LastIsNonZero) {
3282 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3283 MVT::i16, Op.getOperand(i-1));
3285 if (ThisIsNonZero) {
3286 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3287 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3288 ThisElt, DAG.getConstant(8, MVT::i8));
3290 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3294 if (ThisElt.getNode())
3295 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3296 DAG.getIntPtrConstant(i/2));
3300 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3303 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3305 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3306 unsigned NumNonZero, unsigned NumZero,
3307 SelectionDAG &DAG, TargetLowering &TLI) {
3311 DebugLoc dl = Op.getDebugLoc();
3314 for (unsigned i = 0; i < 8; ++i) {
3315 bool isNonZero = (NonZeros & (1 << i)) != 0;
3319 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3321 V = DAG.getUNDEF(MVT::v8i16);
3324 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3325 MVT::v8i16, V, Op.getOperand(i),
3326 DAG.getIntPtrConstant(i));
3333 /// getVShift - Return a vector logical shift node.
3335 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3336 unsigned NumBits, SelectionDAG &DAG,
3337 const TargetLowering &TLI, DebugLoc dl) {
3338 bool isMMX = VT.getSizeInBits() == 64;
3339 EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3340 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3341 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3342 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3343 DAG.getNode(Opc, dl, ShVT, SrcOp,
3344 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3348 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3349 SelectionDAG &DAG) {
3351 // Check if the scalar load can be widened into a vector load. And if
3352 // the address is "base + cst" see if the cst can be "absorbed" into
3353 // the shuffle mask.
3354 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3355 SDValue Ptr = LD->getBasePtr();
3356 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3358 EVT PVT = LD->getValueType(0);
3359 if (PVT != MVT::i32 && PVT != MVT::f32)
3364 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3365 FI = FINode->getIndex();
3367 } else if (Ptr.getOpcode() == ISD::ADD &&
3368 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
3369 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
3370 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
3371 Offset = Ptr.getConstantOperandVal(1);
3372 Ptr = Ptr.getOperand(0);
3377 SDValue Chain = LD->getChain();
3378 // Make sure the stack object alignment is at least 16.
3379 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3380 if (DAG.InferPtrAlignment(Ptr) < 16) {
3381 if (MFI->isFixedObjectIndex(FI)) {
3382 // Can't change the alignment. Reference stack + offset explicitly
3383 // if stack pointer is at least 16-byte aligned.
3384 unsigned StackAlign = Subtarget->getStackAlignment();
3385 if (StackAlign < 16)
3387 Offset = MFI->getObjectOffset(FI) + Offset;
3388 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
3390 Ptr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr,
3391 DAG.getConstant(Offset & ~15, getPointerTy()));
3394 MFI->setObjectAlignment(FI, 16);
3398 // (Offset % 16) must be multiple of 4. Then address is then
3399 // Ptr + (Offset & ~15).
3402 if ((Offset % 16) & 3)
3404 int64_t StartOffset = Offset & ~15;
3406 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
3407 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
3409 int EltNo = (Offset - StartOffset) >> 2;
3410 int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
3411 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
3412 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,LD->getSrcValue(),0);
3413 // Canonicalize it to a v4i32 shuffle.
3414 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
3415 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3416 DAG.getVectorShuffle(MVT::v4i32, dl, V1,
3417 DAG.getUNDEF(MVT::v4i32), &Mask[0]));
3424 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3425 DebugLoc dl = Op.getDebugLoc();
3426 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3427 if (ISD::isBuildVectorAllZeros(Op.getNode())
3428 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3429 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3430 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3431 // eliminated on x86-32 hosts.
3432 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3435 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3436 return getOnesVector(Op.getValueType(), DAG, dl);
3437 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3440 EVT VT = Op.getValueType();
3441 EVT ExtVT = VT.getVectorElementType();
3442 unsigned EVTBits = ExtVT.getSizeInBits();
3444 unsigned NumElems = Op.getNumOperands();
3445 unsigned NumZero = 0;
3446 unsigned NumNonZero = 0;
3447 unsigned NonZeros = 0;
3448 bool IsAllConstants = true;
3449 SmallSet<SDValue, 8> Values;
3450 for (unsigned i = 0; i < NumElems; ++i) {
3451 SDValue Elt = Op.getOperand(i);
3452 if (Elt.getOpcode() == ISD::UNDEF)
3455 if (Elt.getOpcode() != ISD::Constant &&
3456 Elt.getOpcode() != ISD::ConstantFP)
3457 IsAllConstants = false;
3458 if (X86::isZeroNode(Elt))
3461 NonZeros |= (1 << i);
3466 if (NumNonZero == 0) {
3467 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3468 return DAG.getUNDEF(VT);
3471 // Special case for single non-zero, non-undef, element.
3472 if (NumNonZero == 1) {
3473 unsigned Idx = CountTrailingZeros_32(NonZeros);
3474 SDValue Item = Op.getOperand(Idx);
3476 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3477 // the value are obviously zero, truncate the value to i32 and do the
3478 // insertion that way. Only do this if the value is non-constant or if the
3479 // value is a constant being inserted into element 0. It is cheaper to do
3480 // a constant pool load than it is to do a movd + shuffle.
3481 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3482 (!IsAllConstants || Idx == 0)) {
3483 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3484 // Handle MMX and SSE both.
3485 EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3486 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3488 // Truncate the value (which may itself be a constant) to i32, and
3489 // convert it to a vector with movd (S2V+shuffle to zero extend).
3490 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3491 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3492 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3493 Subtarget->hasSSE2(), DAG);
3495 // Now we have our 32-bit value zero extended in the low element of
3496 // a vector. If Idx != 0, swizzle it into place.
3498 SmallVector<int, 4> Mask;
3499 Mask.push_back(Idx);
3500 for (unsigned i = 1; i != VecElts; ++i)
3502 Item = DAG.getVectorShuffle(VecVT, dl, Item,
3503 DAG.getUNDEF(Item.getValueType()),
3506 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3510 // If we have a constant or non-constant insertion into the low element of
3511 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3512 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3513 // depending on what the source datatype is.
3516 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3517 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3518 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3519 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3520 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3521 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3523 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3524 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3525 EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3526 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3527 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3528 Subtarget->hasSSE2(), DAG);
3529 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3533 // Is it a vector logical left shift?
3534 if (NumElems == 2 && Idx == 1 &&
3535 X86::isZeroNode(Op.getOperand(0)) &&
3536 !X86::isZeroNode(Op.getOperand(1))) {
3537 unsigned NumBits = VT.getSizeInBits();
3538 return getVShift(true, VT,
3539 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3540 VT, Op.getOperand(1)),
3541 NumBits/2, DAG, *this, dl);
3544 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3547 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3548 // is a non-constant being inserted into an element other than the low one,
3549 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3550 // movd/movss) to move this into the low element, then shuffle it into
3552 if (EVTBits == 32) {
3553 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3555 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3556 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3557 Subtarget->hasSSE2(), DAG);
3558 SmallVector<int, 8> MaskVec;
3559 for (unsigned i = 0; i < NumElems; i++)
3560 MaskVec.push_back(i == Idx ? 0 : 1);
3561 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3565 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3566 if (Values.size() == 1) {
3567 if (EVTBits == 32) {
3568 // Instead of a shuffle like this:
3569 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
3570 // Check if it's possible to issue this instead.
3571 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
3572 unsigned Idx = CountTrailingZeros_32(NonZeros);
3573 SDValue Item = Op.getOperand(Idx);
3574 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
3575 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
3580 // A vector full of immediates; various special cases are already
3581 // handled, so this is best done with a single constant-pool load.
3585 // Let legalizer expand 2-wide build_vectors.
3586 if (EVTBits == 64) {
3587 if (NumNonZero == 1) {
3588 // One half is zero or undef.
3589 unsigned Idx = CountTrailingZeros_32(NonZeros);
3590 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3591 Op.getOperand(Idx));
3592 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3593 Subtarget->hasSSE2(), DAG);
3598 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3599 if (EVTBits == 8 && NumElems == 16) {
3600 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3602 if (V.getNode()) return V;
3605 if (EVTBits == 16 && NumElems == 8) {
3606 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3608 if (V.getNode()) return V;
3611 // If element VT is == 32 bits, turn it into a number of shuffles.
3612 SmallVector<SDValue, 8> V;
3614 if (NumElems == 4 && NumZero > 0) {
3615 for (unsigned i = 0; i < 4; ++i) {
3616 bool isZero = !(NonZeros & (1 << i));
3618 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3620 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3623 for (unsigned i = 0; i < 2; ++i) {
3624 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3627 V[i] = V[i*2]; // Must be a zero vector.
3630 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3633 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3636 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3641 SmallVector<int, 8> MaskVec;
3642 bool Reverse = (NonZeros & 0x3) == 2;
3643 for (unsigned i = 0; i < 2; ++i)
3644 MaskVec.push_back(Reverse ? 1-i : i);
3645 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3646 for (unsigned i = 0; i < 2; ++i)
3647 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3648 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3651 if (Values.size() > 2) {
3652 // If we have SSE 4.1, Expand into a number of inserts unless the number of
3653 // values to be inserted is equal to the number of elements, in which case
3654 // use the unpack code below in the hopes of matching the consecutive elts
3655 // load merge pattern for shuffles.
3656 // FIXME: We could probably just check that here directly.
3657 if (Values.size() < NumElems && VT.getSizeInBits() == 128 &&
3658 getSubtarget()->hasSSE41()) {
3659 V[0] = DAG.getUNDEF(VT);
3660 for (unsigned i = 0; i < NumElems; ++i)
3661 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3662 V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3663 Op.getOperand(i), DAG.getIntPtrConstant(i));
3666 // Expand into a number of unpckl*.
3668 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3669 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3670 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3671 for (unsigned i = 0; i < NumElems; ++i)
3672 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3674 while (NumElems != 0) {
3675 for (unsigned i = 0; i < NumElems; ++i)
3676 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3685 // v8i16 shuffles - Prefer shuffles in the following order:
3686 // 1. [all] pshuflw, pshufhw, optional move
3687 // 2. [ssse3] 1 x pshufb
3688 // 3. [ssse3] 2 x pshufb + 1 x por
3689 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
3691 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
3692 SelectionDAG &DAG, X86TargetLowering &TLI) {
3693 SDValue V1 = SVOp->getOperand(0);
3694 SDValue V2 = SVOp->getOperand(1);
3695 DebugLoc dl = SVOp->getDebugLoc();
3696 SmallVector<int, 8> MaskVals;
3698 // Determine if more than 1 of the words in each of the low and high quadwords
3699 // of the result come from the same quadword of one of the two inputs. Undef
3700 // mask values count as coming from any quadword, for better codegen.
3701 SmallVector<unsigned, 4> LoQuad(4);
3702 SmallVector<unsigned, 4> HiQuad(4);
3703 BitVector InputQuads(4);
3704 for (unsigned i = 0; i < 8; ++i) {
3705 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
3706 int EltIdx = SVOp->getMaskElt(i);
3707 MaskVals.push_back(EltIdx);
3716 InputQuads.set(EltIdx / 4);
3719 int BestLoQuad = -1;
3720 unsigned MaxQuad = 1;
3721 for (unsigned i = 0; i < 4; ++i) {
3722 if (LoQuad[i] > MaxQuad) {
3724 MaxQuad = LoQuad[i];
3728 int BestHiQuad = -1;
3730 for (unsigned i = 0; i < 4; ++i) {
3731 if (HiQuad[i] > MaxQuad) {
3733 MaxQuad = HiQuad[i];
3737 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
3738 // of the two input vectors, shuffle them into one input vector so only a
3739 // single pshufb instruction is necessary. If There are more than 2 input
3740 // quads, disable the next transformation since it does not help SSSE3.
3741 bool V1Used = InputQuads[0] || InputQuads[1];
3742 bool V2Used = InputQuads[2] || InputQuads[3];
3743 if (TLI.getSubtarget()->hasSSSE3()) {
3744 if (InputQuads.count() == 2 && V1Used && V2Used) {
3745 BestLoQuad = InputQuads.find_first();
3746 BestHiQuad = InputQuads.find_next(BestLoQuad);
3748 if (InputQuads.count() > 2) {
3754 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
3755 // the shuffle mask. If a quad is scored as -1, that means that it contains
3756 // words from all 4 input quadwords.
3758 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
3759 SmallVector<int, 8> MaskV;
3760 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
3761 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
3762 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
3763 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
3764 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
3765 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
3767 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
3768 // source words for the shuffle, to aid later transformations.
3769 bool AllWordsInNewV = true;
3770 bool InOrder[2] = { true, true };
3771 for (unsigned i = 0; i != 8; ++i) {
3772 int idx = MaskVals[i];
3774 InOrder[i/4] = false;
3775 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
3777 AllWordsInNewV = false;
3781 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
3782 if (AllWordsInNewV) {
3783 for (int i = 0; i != 8; ++i) {
3784 int idx = MaskVals[i];
3787 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
3788 if ((idx != i) && idx < 4)
3790 if ((idx != i) && idx > 3)
3799 // If we've eliminated the use of V2, and the new mask is a pshuflw or
3800 // pshufhw, that's as cheap as it gets. Return the new shuffle.
3801 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
3802 return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
3803 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
3807 // If we have SSSE3, and all words of the result are from 1 input vector,
3808 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
3809 // is present, fall back to case 4.
3810 if (TLI.getSubtarget()->hasSSSE3()) {
3811 SmallVector<SDValue,16> pshufbMask;
3813 // If we have elements from both input vectors, set the high bit of the
3814 // shuffle mask element to zero out elements that come from V2 in the V1
3815 // mask, and elements that come from V1 in the V2 mask, so that the two
3816 // results can be OR'd together.
3817 bool TwoInputs = V1Used && V2Used;
3818 for (unsigned i = 0; i != 8; ++i) {
3819 int EltIdx = MaskVals[i] * 2;
3820 if (TwoInputs && (EltIdx >= 16)) {
3821 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3822 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3825 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3826 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
3828 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
3829 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3830 DAG.getNode(ISD::BUILD_VECTOR, dl,
3831 MVT::v16i8, &pshufbMask[0], 16));
3833 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3835 // Calculate the shuffle mask for the second input, shuffle it, and
3836 // OR it with the first shuffled input.
3838 for (unsigned i = 0; i != 8; ++i) {
3839 int EltIdx = MaskVals[i] * 2;
3841 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3842 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3845 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3846 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
3848 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
3849 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3850 DAG.getNode(ISD::BUILD_VECTOR, dl,
3851 MVT::v16i8, &pshufbMask[0], 16));
3852 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3853 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3856 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
3857 // and update MaskVals with new element order.
3858 BitVector InOrder(8);
3859 if (BestLoQuad >= 0) {
3860 SmallVector<int, 8> MaskV;
3861 for (int i = 0; i != 4; ++i) {
3862 int idx = MaskVals[i];
3864 MaskV.push_back(-1);
3866 } else if ((idx / 4) == BestLoQuad) {
3867 MaskV.push_back(idx & 3);
3870 MaskV.push_back(-1);
3873 for (unsigned i = 4; i != 8; ++i)
3875 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3879 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
3880 // and update MaskVals with the new element order.
3881 if (BestHiQuad >= 0) {
3882 SmallVector<int, 8> MaskV;
3883 for (unsigned i = 0; i != 4; ++i)
3885 for (unsigned i = 4; i != 8; ++i) {
3886 int idx = MaskVals[i];
3888 MaskV.push_back(-1);
3890 } else if ((idx / 4) == BestHiQuad) {
3891 MaskV.push_back((idx & 3) + 4);
3894 MaskV.push_back(-1);
3897 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3901 // In case BestHi & BestLo were both -1, which means each quadword has a word
3902 // from each of the four input quadwords, calculate the InOrder bitvector now
3903 // before falling through to the insert/extract cleanup.
3904 if (BestLoQuad == -1 && BestHiQuad == -1) {
3906 for (int i = 0; i != 8; ++i)
3907 if (MaskVals[i] < 0 || MaskVals[i] == i)
3911 // The other elements are put in the right place using pextrw and pinsrw.
3912 for (unsigned i = 0; i != 8; ++i) {
3915 int EltIdx = MaskVals[i];
3918 SDValue ExtOp = (EltIdx < 8)
3919 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
3920 DAG.getIntPtrConstant(EltIdx))
3921 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
3922 DAG.getIntPtrConstant(EltIdx - 8));
3923 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3924 DAG.getIntPtrConstant(i));
3929 // v16i8 shuffles - Prefer shuffles in the following order:
3930 // 1. [ssse3] 1 x pshufb
3931 // 2. [ssse3] 2 x pshufb + 1 x por
3932 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
3934 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
3935 SelectionDAG &DAG, X86TargetLowering &TLI) {
3936 SDValue V1 = SVOp->getOperand(0);
3937 SDValue V2 = SVOp->getOperand(1);
3938 DebugLoc dl = SVOp->getDebugLoc();
3939 SmallVector<int, 16> MaskVals;
3940 SVOp->getMask(MaskVals);
3942 // If we have SSSE3, case 1 is generated when all result bytes come from
3943 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
3944 // present, fall back to case 3.
3945 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
3948 for (unsigned i = 0; i < 16; ++i) {
3949 int EltIdx = MaskVals[i];
3958 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
3959 if (TLI.getSubtarget()->hasSSSE3()) {
3960 SmallVector<SDValue,16> pshufbMask;
3962 // If all result elements are from one input vector, then only translate
3963 // undef mask values to 0x80 (zero out result) in the pshufb mask.
3965 // Otherwise, we have elements from both input vectors, and must zero out
3966 // elements that come from V2 in the first mask, and V1 in the second mask
3967 // so that we can OR them together.
3968 bool TwoInputs = !(V1Only || V2Only);
3969 for (unsigned i = 0; i != 16; ++i) {
3970 int EltIdx = MaskVals[i];
3971 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
3972 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3975 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3977 // If all the elements are from V2, assign it to V1 and return after
3978 // building the first pshufb.
3981 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3982 DAG.getNode(ISD::BUILD_VECTOR, dl,
3983 MVT::v16i8, &pshufbMask[0], 16));
3987 // Calculate the shuffle mask for the second input, shuffle it, and
3988 // OR it with the first shuffled input.
3990 for (unsigned i = 0; i != 16; ++i) {
3991 int EltIdx = MaskVals[i];
3993 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3996 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3998 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3999 DAG.getNode(ISD::BUILD_VECTOR, dl,
4000 MVT::v16i8, &pshufbMask[0], 16));
4001 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4004 // No SSSE3 - Calculate in place words and then fix all out of place words
4005 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
4006 // the 16 different words that comprise the two doublequadword input vectors.
4007 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4008 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4009 SDValue NewV = V2Only ? V2 : V1;
4010 for (int i = 0; i != 8; ++i) {
4011 int Elt0 = MaskVals[i*2];
4012 int Elt1 = MaskVals[i*2+1];
4014 // This word of the result is all undef, skip it.
4015 if (Elt0 < 0 && Elt1 < 0)
4018 // This word of the result is already in the correct place, skip it.
4019 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4021 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4024 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4025 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4028 // If Elt0 and Elt1 are defined, are consecutive, and can be load
4029 // using a single extract together, load it and store it.
4030 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4031 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4032 DAG.getIntPtrConstant(Elt1 / 2));
4033 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4034 DAG.getIntPtrConstant(i));
4038 // If Elt1 is defined, extract it from the appropriate source. If the
4039 // source byte is not also odd, shift the extracted word left 8 bits
4040 // otherwise clear the bottom 8 bits if we need to do an or.
4042 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4043 DAG.getIntPtrConstant(Elt1 / 2));
4044 if ((Elt1 & 1) == 0)
4045 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4046 DAG.getConstant(8, TLI.getShiftAmountTy()));
4048 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4049 DAG.getConstant(0xFF00, MVT::i16));
4051 // If Elt0 is defined, extract it from the appropriate source. If the
4052 // source byte is not also even, shift the extracted word right 8 bits. If
4053 // Elt1 was also defined, OR the extracted values together before
4054 // inserting them in the result.
4056 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4057 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4058 if ((Elt0 & 1) != 0)
4059 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4060 DAG.getConstant(8, TLI.getShiftAmountTy()));
4062 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4063 DAG.getConstant(0x00FF, MVT::i16));
4064 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4067 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4068 DAG.getIntPtrConstant(i));
4070 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4073 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4074 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
4075 /// done when every pair / quad of shuffle mask elements point to elements in
4076 /// the right sequence. e.g.
4077 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
4079 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4081 TargetLowering &TLI, DebugLoc dl) {
4082 EVT VT = SVOp->getValueType(0);
4083 SDValue V1 = SVOp->getOperand(0);
4084 SDValue V2 = SVOp->getOperand(1);
4085 unsigned NumElems = VT.getVectorNumElements();
4086 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4087 EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
4088 EVT MaskEltVT = MaskVT.getVectorElementType();
4090 switch (VT.getSimpleVT().SimpleTy) {
4091 default: assert(false && "Unexpected!");
4092 case MVT::v4f32: NewVT = MVT::v2f64; break;
4093 case MVT::v4i32: NewVT = MVT::v2i64; break;
4094 case MVT::v8i16: NewVT = MVT::v4i32; break;
4095 case MVT::v16i8: NewVT = MVT::v4i32; break;
4098 if (NewWidth == 2) {
4104 int Scale = NumElems / NewWidth;
4105 SmallVector<int, 8> MaskVec;
4106 for (unsigned i = 0; i < NumElems; i += Scale) {
4108 for (int j = 0; j < Scale; ++j) {
4109 int EltIdx = SVOp->getMaskElt(i+j);
4113 StartIdx = EltIdx - (EltIdx % Scale);
4114 if (EltIdx != StartIdx + j)
4118 MaskVec.push_back(-1);
4120 MaskVec.push_back(StartIdx / Scale);
4123 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4124 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4125 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4128 /// getVZextMovL - Return a zero-extending vector move low node.
4130 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4131 SDValue SrcOp, SelectionDAG &DAG,
4132 const X86Subtarget *Subtarget, DebugLoc dl) {
4133 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4134 LoadSDNode *LD = NULL;
4135 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4136 LD = dyn_cast<LoadSDNode>(SrcOp);
4138 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4140 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4141 if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4142 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4143 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4144 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4146 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4147 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4148 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4149 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4157 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4158 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4159 DAG.getNode(ISD::BIT_CONVERT, dl,
4163 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4166 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4167 SDValue V1 = SVOp->getOperand(0);
4168 SDValue V2 = SVOp->getOperand(1);
4169 DebugLoc dl = SVOp->getDebugLoc();
4170 EVT VT = SVOp->getValueType(0);
4172 SmallVector<std::pair<int, int>, 8> Locs;
4174 SmallVector<int, 8> Mask1(4U, -1);
4175 SmallVector<int, 8> PermMask;
4176 SVOp->getMask(PermMask);
4180 for (unsigned i = 0; i != 4; ++i) {
4181 int Idx = PermMask[i];
4183 Locs[i] = std::make_pair(-1, -1);
4185 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4187 Locs[i] = std::make_pair(0, NumLo);
4191 Locs[i] = std::make_pair(1, NumHi);
4193 Mask1[2+NumHi] = Idx;
4199 if (NumLo <= 2 && NumHi <= 2) {
4200 // If no more than two elements come from either vector. This can be
4201 // implemented with two shuffles. First shuffle gather the elements.
4202 // The second shuffle, which takes the first shuffle as both of its
4203 // vector operands, put the elements into the right order.
4204 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4206 SmallVector<int, 8> Mask2(4U, -1);
4208 for (unsigned i = 0; i != 4; ++i) {
4209 if (Locs[i].first == -1)
4212 unsigned Idx = (i < 2) ? 0 : 4;
4213 Idx += Locs[i].first * 2 + Locs[i].second;
4218 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4219 } else if (NumLo == 3 || NumHi == 3) {
4220 // Otherwise, we must have three elements from one vector, call it X, and
4221 // one element from the other, call it Y. First, use a shufps to build an
4222 // intermediate vector with the one element from Y and the element from X
4223 // that will be in the same half in the final destination (the indexes don't
4224 // matter). Then, use a shufps to build the final vector, taking the half
4225 // containing the element from Y from the intermediate, and the other half
4228 // Normalize it so the 3 elements come from V1.
4229 CommuteVectorShuffleMask(PermMask, VT);
4233 // Find the element from V2.
4235 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4236 int Val = PermMask[HiIndex];
4243 Mask1[0] = PermMask[HiIndex];
4245 Mask1[2] = PermMask[HiIndex^1];
4247 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4250 Mask1[0] = PermMask[0];
4251 Mask1[1] = PermMask[1];
4252 Mask1[2] = HiIndex & 1 ? 6 : 4;
4253 Mask1[3] = HiIndex & 1 ? 4 : 6;
4254 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4256 Mask1[0] = HiIndex & 1 ? 2 : 0;
4257 Mask1[1] = HiIndex & 1 ? 0 : 2;
4258 Mask1[2] = PermMask[2];
4259 Mask1[3] = PermMask[3];
4264 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4268 // Break it into (shuffle shuffle_hi, shuffle_lo).
4270 SmallVector<int,8> LoMask(4U, -1);
4271 SmallVector<int,8> HiMask(4U, -1);
4273 SmallVector<int,8> *MaskPtr = &LoMask;
4274 unsigned MaskIdx = 0;
4277 for (unsigned i = 0; i != 4; ++i) {
4284 int Idx = PermMask[i];
4286 Locs[i] = std::make_pair(-1, -1);
4287 } else if (Idx < 4) {
4288 Locs[i] = std::make_pair(MaskIdx, LoIdx);
4289 (*MaskPtr)[LoIdx] = Idx;
4292 Locs[i] = std::make_pair(MaskIdx, HiIdx);
4293 (*MaskPtr)[HiIdx] = Idx;
4298 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4299 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4300 SmallVector<int, 8> MaskOps;
4301 for (unsigned i = 0; i != 4; ++i) {
4302 if (Locs[i].first == -1) {
4303 MaskOps.push_back(-1);
4305 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4306 MaskOps.push_back(Idx);
4309 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4313 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4314 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4315 SDValue V1 = Op.getOperand(0);
4316 SDValue V2 = Op.getOperand(1);
4317 EVT VT = Op.getValueType();
4318 DebugLoc dl = Op.getDebugLoc();
4319 unsigned NumElems = VT.getVectorNumElements();
4320 bool isMMX = VT.getSizeInBits() == 64;
4321 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4322 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4323 bool V1IsSplat = false;
4324 bool V2IsSplat = false;
4326 if (isZeroShuffle(SVOp))
4327 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4329 // Promote splats to v4f32.
4330 if (SVOp->isSplat()) {
4331 if (isMMX || NumElems < 4)
4333 return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4336 // If the shuffle can be profitably rewritten as a narrower shuffle, then
4338 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4339 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4340 if (NewOp.getNode())
4341 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4342 LowerVECTOR_SHUFFLE(NewOp, DAG));
4343 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4344 // FIXME: Figure out a cleaner way to do this.
4345 // Try to make use of movq to zero out the top part.
4346 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4347 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4348 if (NewOp.getNode()) {
4349 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4350 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4351 DAG, Subtarget, dl);
4353 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4354 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4355 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4356 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4357 DAG, Subtarget, dl);
4361 if (X86::isPSHUFDMask(SVOp))
4364 // Check if this can be converted into a logical shift.
4365 bool isLeft = false;
4368 bool isShift = getSubtarget()->hasSSE2() &&
4369 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4370 if (isShift && ShVal.hasOneUse()) {
4371 // If the shifted value has multiple uses, it may be cheaper to use
4372 // v_set0 + movlhps or movhlps, etc.
4373 EVT EltVT = VT.getVectorElementType();
4374 ShAmt *= EltVT.getSizeInBits();
4375 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4378 if (X86::isMOVLMask(SVOp)) {
4381 if (ISD::isBuildVectorAllZeros(V1.getNode()))
4382 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4387 // FIXME: fold these into legal mask.
4388 if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4389 X86::isMOVSLDUPMask(SVOp) ||
4390 X86::isMOVHLPSMask(SVOp) ||
4391 X86::isMOVLHPSMask(SVOp) ||
4392 X86::isMOVLPMask(SVOp)))
4395 if (ShouldXformToMOVHLPS(SVOp) ||
4396 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4397 return CommuteVectorShuffle(SVOp, DAG);
4400 // No better options. Use a vshl / vsrl.
4401 EVT EltVT = VT.getVectorElementType();
4402 ShAmt *= EltVT.getSizeInBits();
4403 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4406 bool Commuted = false;
4407 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4408 // 1,1,1,1 -> v8i16 though.
4409 V1IsSplat = isSplatVector(V1.getNode());
4410 V2IsSplat = isSplatVector(V2.getNode());
4412 // Canonicalize the splat or undef, if present, to be on the RHS.
4413 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4414 Op = CommuteVectorShuffle(SVOp, DAG);
4415 SVOp = cast<ShuffleVectorSDNode>(Op);
4416 V1 = SVOp->getOperand(0);
4417 V2 = SVOp->getOperand(1);
4418 std::swap(V1IsSplat, V2IsSplat);
4419 std::swap(V1IsUndef, V2IsUndef);
4423 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4424 // Shuffling low element of v1 into undef, just return v1.
4427 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4428 // the instruction selector will not match, so get a canonical MOVL with
4429 // swapped operands to undo the commute.
4430 return getMOVL(DAG, dl, VT, V2, V1);
4433 if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4434 X86::isUNPCKH_v_undef_Mask(SVOp) ||
4435 X86::isUNPCKLMask(SVOp) ||
4436 X86::isUNPCKHMask(SVOp))
4440 // Normalize mask so all entries that point to V2 points to its first
4441 // element then try to match unpck{h|l} again. If match, return a
4442 // new vector_shuffle with the corrected mask.
4443 SDValue NewMask = NormalizeMask(SVOp, DAG);
4444 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4445 if (NSVOp != SVOp) {
4446 if (X86::isUNPCKLMask(NSVOp, true)) {
4448 } else if (X86::isUNPCKHMask(NSVOp, true)) {
4455 // Commute is back and try unpck* again.
4456 // FIXME: this seems wrong.
4457 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4458 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4459 if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4460 X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4461 X86::isUNPCKLMask(NewSVOp) ||
4462 X86::isUNPCKHMask(NewSVOp))
4466 // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4468 // Normalize the node to match x86 shuffle ops if needed
4469 if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4470 return CommuteVectorShuffle(SVOp, DAG);
4472 // Check for legal shuffle and return?
4473 SmallVector<int, 16> PermMask;
4474 SVOp->getMask(PermMask);
4475 if (isShuffleMaskLegal(PermMask, VT))
4478 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4479 if (VT == MVT::v8i16) {
4480 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4481 if (NewOp.getNode())
4485 if (VT == MVT::v16i8) {
4486 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4487 if (NewOp.getNode())
4491 // Handle all 4 wide cases with a number of shuffles except for MMX.
4492 if (NumElems == 4 && !isMMX)
4493 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4499 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4500 SelectionDAG &DAG) {
4501 EVT VT = Op.getValueType();
4502 DebugLoc dl = Op.getDebugLoc();
4503 if (VT.getSizeInBits() == 8) {
4504 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4505 Op.getOperand(0), Op.getOperand(1));
4506 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4507 DAG.getValueType(VT));
4508 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4509 } else if (VT.getSizeInBits() == 16) {
4510 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4511 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4513 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4514 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4515 DAG.getNode(ISD::BIT_CONVERT, dl,
4519 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4520 Op.getOperand(0), Op.getOperand(1));
4521 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4522 DAG.getValueType(VT));
4523 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4524 } else if (VT == MVT::f32) {
4525 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4526 // the result back to FR32 register. It's only worth matching if the
4527 // result has a single use which is a store or a bitcast to i32. And in
4528 // the case of a store, it's not worth it if the index is a constant 0,
4529 // because a MOVSSmr can be used instead, which is smaller and faster.
4530 if (!Op.hasOneUse())
4532 SDNode *User = *Op.getNode()->use_begin();
4533 if ((User->getOpcode() != ISD::STORE ||
4534 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4535 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4536 (User->getOpcode() != ISD::BIT_CONVERT ||
4537 User->getValueType(0) != MVT::i32))
4539 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4540 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4543 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4544 } else if (VT == MVT::i32) {
4545 // ExtractPS works with constant index.
4546 if (isa<ConstantSDNode>(Op.getOperand(1)))
4554 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4555 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4558 if (Subtarget->hasSSE41()) {
4559 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4564 EVT VT = Op.getValueType();
4565 DebugLoc dl = Op.getDebugLoc();
4566 // TODO: handle v16i8.
4567 if (VT.getSizeInBits() == 16) {
4568 SDValue Vec = Op.getOperand(0);
4569 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4571 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4572 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4573 DAG.getNode(ISD::BIT_CONVERT, dl,
4576 // Transform it so it match pextrw which produces a 32-bit result.
4577 EVT EltVT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy+1);
4578 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
4579 Op.getOperand(0), Op.getOperand(1));
4580 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
4581 DAG.getValueType(VT));
4582 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4583 } else if (VT.getSizeInBits() == 32) {
4584 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4588 // SHUFPS the element to the lowest double word, then movss.
4589 int Mask[4] = { Idx, -1, -1, -1 };
4590 EVT VVT = Op.getOperand(0).getValueType();
4591 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4592 DAG.getUNDEF(VVT), Mask);
4593 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4594 DAG.getIntPtrConstant(0));
4595 } else if (VT.getSizeInBits() == 64) {
4596 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4597 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4598 // to match extract_elt for f64.
4599 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4603 // UNPCKHPD the element to the lowest double word, then movsd.
4604 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4605 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4606 int Mask[2] = { 1, -1 };
4607 EVT VVT = Op.getOperand(0).getValueType();
4608 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4609 DAG.getUNDEF(VVT), Mask);
4610 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4611 DAG.getIntPtrConstant(0));
4618 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4619 EVT VT = Op.getValueType();
4620 EVT EltVT = VT.getVectorElementType();
4621 DebugLoc dl = Op.getDebugLoc();
4623 SDValue N0 = Op.getOperand(0);
4624 SDValue N1 = Op.getOperand(1);
4625 SDValue N2 = Op.getOperand(2);
4627 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
4628 isa<ConstantSDNode>(N2)) {
4629 unsigned Opc = (EltVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4631 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4633 if (N1.getValueType() != MVT::i32)
4634 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4635 if (N2.getValueType() != MVT::i32)
4636 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4637 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4638 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4639 // Bits [7:6] of the constant are the source select. This will always be
4640 // zero here. The DAG Combiner may combine an extract_elt index into these
4641 // bits. For example (insert (extract, 3), 2) could be matched by putting
4642 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4643 // Bits [5:4] of the constant are the destination select. This is the
4644 // value of the incoming immediate.
4645 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4646 // combine either bitwise AND or insert of float 0.0 to set these bits.
4647 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4648 // Create this as a scalar to vector..
4649 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
4650 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4651 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
4652 // PINSR* works with constant index.
4659 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4660 EVT VT = Op.getValueType();
4661 EVT EltVT = VT.getVectorElementType();
4663 if (Subtarget->hasSSE41())
4664 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4666 if (EltVT == MVT::i8)
4669 DebugLoc dl = Op.getDebugLoc();
4670 SDValue N0 = Op.getOperand(0);
4671 SDValue N1 = Op.getOperand(1);
4672 SDValue N2 = Op.getOperand(2);
4674 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
4675 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4676 // as its second argument.
4677 if (N1.getValueType() != MVT::i32)
4678 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4679 if (N2.getValueType() != MVT::i32)
4680 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4681 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
4687 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4688 DebugLoc dl = Op.getDebugLoc();
4689 if (Op.getValueType() == MVT::v2f32)
4690 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4691 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4692 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4693 Op.getOperand(0))));
4695 if (Op.getValueType() == MVT::v1i64 && Op.getOperand(0).getValueType() == MVT::i64)
4696 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
4698 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4699 EVT VT = MVT::v2i32;
4700 switch (Op.getValueType().getSimpleVT().SimpleTy) {
4707 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4708 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4711 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4712 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4713 // one of the above mentioned nodes. It has to be wrapped because otherwise
4714 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4715 // be used to form addressing mode. These wrapped nodes will be selected
4718 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4719 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4721 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4723 unsigned char OpFlag = 0;
4724 unsigned WrapperKind = X86ISD::Wrapper;
4725 CodeModel::Model M = getTargetMachine().getCodeModel();
4727 if (Subtarget->isPICStyleRIPRel() &&
4728 (M == CodeModel::Small || M == CodeModel::Kernel))
4729 WrapperKind = X86ISD::WrapperRIP;
4730 else if (Subtarget->isPICStyleGOT())
4731 OpFlag = X86II::MO_GOTOFF;
4732 else if (Subtarget->isPICStyleStubPIC())
4733 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4735 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
4737 CP->getOffset(), OpFlag);
4738 DebugLoc DL = CP->getDebugLoc();
4739 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4740 // With PIC, the address is actually $g + Offset.
4742 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4743 DAG.getNode(X86ISD::GlobalBaseReg,
4744 DebugLoc::getUnknownLoc(), getPointerTy()),
4751 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4752 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4754 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4756 unsigned char OpFlag = 0;
4757 unsigned WrapperKind = X86ISD::Wrapper;
4758 CodeModel::Model M = getTargetMachine().getCodeModel();
4760 if (Subtarget->isPICStyleRIPRel() &&
4761 (M == CodeModel::Small || M == CodeModel::Kernel))
4762 WrapperKind = X86ISD::WrapperRIP;
4763 else if (Subtarget->isPICStyleGOT())
4764 OpFlag = X86II::MO_GOTOFF;
4765 else if (Subtarget->isPICStyleStubPIC())
4766 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4768 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
4770 DebugLoc DL = JT->getDebugLoc();
4771 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4773 // With PIC, the address is actually $g + Offset.
4775 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4776 DAG.getNode(X86ISD::GlobalBaseReg,
4777 DebugLoc::getUnknownLoc(), getPointerTy()),
4785 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4786 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4788 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4790 unsigned char OpFlag = 0;
4791 unsigned WrapperKind = X86ISD::Wrapper;
4792 CodeModel::Model M = getTargetMachine().getCodeModel();
4794 if (Subtarget->isPICStyleRIPRel() &&
4795 (M == CodeModel::Small || M == CodeModel::Kernel))
4796 WrapperKind = X86ISD::WrapperRIP;
4797 else if (Subtarget->isPICStyleGOT())
4798 OpFlag = X86II::MO_GOTOFF;
4799 else if (Subtarget->isPICStyleStubPIC())
4800 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4802 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
4804 DebugLoc DL = Op.getDebugLoc();
4805 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4808 // With PIC, the address is actually $g + Offset.
4809 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4810 !Subtarget->is64Bit()) {
4811 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4812 DAG.getNode(X86ISD::GlobalBaseReg,
4813 DebugLoc::getUnknownLoc(),
4822 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) {
4823 // Create the TargetBlockAddressAddress node.
4824 unsigned char OpFlags =
4825 Subtarget->ClassifyBlockAddressReference();
4826 CodeModel::Model M = getTargetMachine().getCodeModel();
4827 BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
4828 DebugLoc dl = Op.getDebugLoc();
4829 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
4830 /*isTarget=*/true, OpFlags);
4832 if (Subtarget->isPICStyleRIPRel() &&
4833 (M == CodeModel::Small || M == CodeModel::Kernel))
4834 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
4836 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4838 // With PIC, the address is actually $g + Offset.
4839 if (isGlobalRelativeToPICBase(OpFlags)) {
4840 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4841 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4849 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
4851 SelectionDAG &DAG) const {
4852 // Create the TargetGlobalAddress node, folding in the constant
4853 // offset if it is legal.
4854 unsigned char OpFlags =
4855 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
4856 CodeModel::Model M = getTargetMachine().getCodeModel();
4858 if (OpFlags == X86II::MO_NO_FLAG &&
4859 X86::isOffsetSuitableForCodeModel(Offset, M)) {
4860 // A direct static reference to a global.
4861 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4864 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
4867 if (Subtarget->isPICStyleRIPRel() &&
4868 (M == CodeModel::Small || M == CodeModel::Kernel))
4869 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
4871 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4873 // With PIC, the address is actually $g + Offset.
4874 if (isGlobalRelativeToPICBase(OpFlags)) {
4875 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4876 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4880 // For globals that require a load from a stub to get the address, emit the
4882 if (isGlobalStubReference(OpFlags))
4883 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
4884 PseudoSourceValue::getGOT(), 0);
4886 // If there was a non-zero offset that we didn't fold, create an explicit
4889 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
4890 DAG.getConstant(Offset, getPointerTy()));
4896 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4897 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4898 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4899 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
4903 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
4904 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
4905 unsigned char OperandFlags) {
4906 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4907 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4908 DebugLoc dl = GA->getDebugLoc();
4909 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4910 GA->getValueType(0),
4914 SDValue Ops[] = { Chain, TGA, *InFlag };
4915 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
4917 SDValue Ops[] = { Chain, TGA };
4918 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
4921 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
4922 MFI->setHasCalls(true);
4924 SDValue Flag = Chain.getValue(1);
4925 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
4928 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4930 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4933 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
4934 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
4935 DAG.getNode(X86ISD::GlobalBaseReg,
4936 DebugLoc::getUnknownLoc(),
4938 InFlag = Chain.getValue(1);
4940 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
4943 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4945 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4947 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
4948 X86::RAX, X86II::MO_TLSGD);
4951 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4952 // "local exec" model.
4953 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4954 const EVT PtrVT, TLSModel::Model model,
4956 DebugLoc dl = GA->getDebugLoc();
4957 // Get the Thread Pointer
4958 SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
4959 DebugLoc::getUnknownLoc(), PtrVT,
4960 DAG.getRegister(is64Bit? X86::FS : X86::GS,
4963 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
4966 unsigned char OperandFlags = 0;
4967 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
4969 unsigned WrapperKind = X86ISD::Wrapper;
4970 if (model == TLSModel::LocalExec) {
4971 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
4972 } else if (is64Bit) {
4973 assert(model == TLSModel::InitialExec);
4974 OperandFlags = X86II::MO_GOTTPOFF;
4975 WrapperKind = X86ISD::WrapperRIP;
4977 assert(model == TLSModel::InitialExec);
4978 OperandFlags = X86II::MO_INDNTPOFF;
4981 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4983 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
4984 GA->getOffset(), OperandFlags);
4985 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
4987 if (model == TLSModel::InitialExec)
4988 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
4989 PseudoSourceValue::getGOT(), 0);
4991 // The address of the thread local variable is the add of the thread
4992 // pointer with the offset of the variable.
4993 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
4997 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4998 // TODO: implement the "local dynamic" model
4999 // TODO: implement the "initial exec"model for pic executables
5000 assert(Subtarget->isTargetELF() &&
5001 "TLS not implemented for non-ELF targets");
5002 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5003 const GlobalValue *GV = GA->getGlobal();
5005 // If GV is an alias then use the aliasee for determining
5006 // thread-localness.
5007 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
5008 GV = GA->resolveAliasedGlobal(false);
5010 TLSModel::Model model = getTLSModel(GV,
5011 getTargetMachine().getRelocationModel());
5014 case TLSModel::GeneralDynamic:
5015 case TLSModel::LocalDynamic: // not implemented
5016 if (Subtarget->is64Bit())
5017 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
5018 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
5020 case TLSModel::InitialExec:
5021 case TLSModel::LocalExec:
5022 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
5023 Subtarget->is64Bit());
5026 llvm_unreachable("Unreachable");
5031 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
5032 /// take a 2 x i32 value to shift plus a shift amount.
5033 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
5034 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5035 EVT VT = Op.getValueType();
5036 unsigned VTBits = VT.getSizeInBits();
5037 DebugLoc dl = Op.getDebugLoc();
5038 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
5039 SDValue ShOpLo = Op.getOperand(0);
5040 SDValue ShOpHi = Op.getOperand(1);
5041 SDValue ShAmt = Op.getOperand(2);
5042 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
5043 DAG.getConstant(VTBits - 1, MVT::i8))
5044 : DAG.getConstant(0, VT);
5047 if (Op.getOpcode() == ISD::SHL_PARTS) {
5048 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
5049 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5051 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
5052 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
5055 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
5056 DAG.getConstant(VTBits, MVT::i8));
5057 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, VT,
5058 AndNode, DAG.getConstant(0, MVT::i8));
5061 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5062 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
5063 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
5065 if (Op.getOpcode() == ISD::SHL_PARTS) {
5066 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5067 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5069 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5070 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5073 SDValue Ops[2] = { Lo, Hi };
5074 return DAG.getMergeValues(Ops, 2, dl);
5077 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5078 EVT SrcVT = Op.getOperand(0).getValueType();
5080 if (SrcVT.isVector()) {
5081 if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
5087 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
5088 "Unknown SINT_TO_FP to lower!");
5090 // These are really Legal; return the operand so the caller accepts it as
5092 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
5094 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
5095 Subtarget->is64Bit()) {
5099 DebugLoc dl = Op.getDebugLoc();
5100 unsigned Size = SrcVT.getSizeInBits()/8;
5101 MachineFunction &MF = DAG.getMachineFunction();
5102 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
5103 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5104 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5106 PseudoSourceValue::getFixedStack(SSFI), 0);
5107 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
5110 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
5112 SelectionDAG &DAG) {
5114 DebugLoc dl = Op.getDebugLoc();
5116 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
5118 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
5120 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
5121 SmallVector<SDValue, 8> Ops;
5122 Ops.push_back(Chain);
5123 Ops.push_back(StackSlot);
5124 Ops.push_back(DAG.getValueType(SrcVT));
5125 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
5126 Tys, &Ops[0], Ops.size());
5129 Chain = Result.getValue(1);
5130 SDValue InFlag = Result.getValue(2);
5132 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5133 // shouldn't be necessary except that RFP cannot be live across
5134 // multiple blocks. When stackifier is fixed, they can be uncoupled.
5135 MachineFunction &MF = DAG.getMachineFunction();
5136 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5137 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5138 Tys = DAG.getVTList(MVT::Other);
5139 SmallVector<SDValue, 8> Ops;
5140 Ops.push_back(Chain);
5141 Ops.push_back(Result);
5142 Ops.push_back(StackSlot);
5143 Ops.push_back(DAG.getValueType(Op.getValueType()));
5144 Ops.push_back(InFlag);
5145 Chain = DAG.getNode(X86ISD::FST, dl, Tys, &Ops[0], Ops.size());
5146 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5147 PseudoSourceValue::getFixedStack(SSFI), 0);
5153 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5154 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
5155 // This algorithm is not obvious. Here it is in C code, more or less:
5157 double uint64_to_double( uint32_t hi, uint32_t lo ) {
5158 static const __m128i exp = { 0x4330000045300000ULL, 0 };
5159 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5161 // Copy ints to xmm registers.
5162 __m128i xh = _mm_cvtsi32_si128( hi );
5163 __m128i xl = _mm_cvtsi32_si128( lo );
5165 // Combine into low half of a single xmm register.
5166 __m128i x = _mm_unpacklo_epi32( xh, xl );
5170 // Merge in appropriate exponents to give the integer bits the right
5172 x = _mm_unpacklo_epi32( x, exp );
5174 // Subtract away the biases to deal with the IEEE-754 double precision
5176 d = _mm_sub_pd( (__m128d) x, bias );
5178 // All conversions up to here are exact. The correctly rounded result is
5179 // calculated using the current rounding mode using the following
5181 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5182 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
5183 // store doesn't really need to be here (except
5184 // maybe to zero the other double)
5189 DebugLoc dl = Op.getDebugLoc();
5190 LLVMContext *Context = DAG.getContext();
5192 // Build some magic constants.
5193 std::vector<Constant*> CV0;
5194 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
5195 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
5196 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5197 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5198 Constant *C0 = ConstantVector::get(CV0);
5199 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5201 std::vector<Constant*> CV1;
5203 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
5205 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
5206 Constant *C1 = ConstantVector::get(CV1);
5207 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5209 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5210 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5212 DAG.getIntPtrConstant(1)));
5213 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5214 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5216 DAG.getIntPtrConstant(0)));
5217 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
5218 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5219 PseudoSourceValue::getConstantPool(), 0,
5221 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
5222 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5223 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5224 PseudoSourceValue::getConstantPool(), 0,
5226 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5228 // Add the halves; easiest way is to swap them into another reg first.
5229 int ShufMask[2] = { 1, -1 };
5230 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
5231 DAG.getUNDEF(MVT::v2f64), ShufMask);
5232 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5233 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5234 DAG.getIntPtrConstant(0));
5237 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5238 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
5239 DebugLoc dl = Op.getDebugLoc();
5240 // FP constant to bias correct the final result.
5241 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5244 // Load the 32-bit value into an XMM register.
5245 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5246 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5248 DAG.getIntPtrConstant(0)));
5250 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5251 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5252 DAG.getIntPtrConstant(0));
5254 // Or the load with the bias.
5255 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5256 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5257 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5259 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5260 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5261 MVT::v2f64, Bias)));
5262 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5263 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5264 DAG.getIntPtrConstant(0));
5266 // Subtract the bias.
5267 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5269 // Handle final rounding.
5270 EVT DestVT = Op.getValueType();
5272 if (DestVT.bitsLT(MVT::f64)) {
5273 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5274 DAG.getIntPtrConstant(0));
5275 } else if (DestVT.bitsGT(MVT::f64)) {
5276 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5279 // Handle final rounding.
5283 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5284 SDValue N0 = Op.getOperand(0);
5285 DebugLoc dl = Op.getDebugLoc();
5287 // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
5288 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5289 // the optimization here.
5290 if (DAG.SignBitIsZero(N0))
5291 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5293 EVT SrcVT = N0.getValueType();
5294 if (SrcVT == MVT::i64) {
5295 // We only handle SSE2 f64 target here; caller can expand the rest.
5296 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
5299 return LowerUINT_TO_FP_i64(Op, DAG);
5300 } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
5301 return LowerUINT_TO_FP_i32(Op, DAG);
5304 assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
5306 // Make a 64-bit buffer, and use it to build an FILD.
5307 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5308 SDValue WordOff = DAG.getConstant(4, getPointerTy());
5309 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5310 getPointerTy(), StackSlot, WordOff);
5311 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5312 StackSlot, NULL, 0);
5313 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5314 OffsetSlot, NULL, 0);
5315 return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5318 std::pair<SDValue,SDValue> X86TargetLowering::
5319 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) {
5320 DebugLoc dl = Op.getDebugLoc();
5322 EVT DstTy = Op.getValueType();
5325 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5329 assert(DstTy.getSimpleVT() <= MVT::i64 &&
5330 DstTy.getSimpleVT() >= MVT::i16 &&
5331 "Unknown FP_TO_SINT to lower!");
5333 // These are really Legal.
5334 if (DstTy == MVT::i32 &&
5335 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5336 return std::make_pair(SDValue(), SDValue());
5337 if (Subtarget->is64Bit() &&
5338 DstTy == MVT::i64 &&
5339 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5340 return std::make_pair(SDValue(), SDValue());
5342 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5344 MachineFunction &MF = DAG.getMachineFunction();
5345 unsigned MemSize = DstTy.getSizeInBits()/8;
5346 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5347 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5350 switch (DstTy.getSimpleVT().SimpleTy) {
5351 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5352 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5353 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5354 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5357 SDValue Chain = DAG.getEntryNode();
5358 SDValue Value = Op.getOperand(0);
5359 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5360 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5361 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5362 PseudoSourceValue::getFixedStack(SSFI), 0);
5363 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5365 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5367 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5368 Chain = Value.getValue(1);
5369 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5370 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5373 // Build the FP_TO_INT*_IN_MEM
5374 SDValue Ops[] = { Chain, Value, StackSlot };
5375 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5377 return std::make_pair(FIST, StackSlot);
5380 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
5381 if (Op.getValueType().isVector()) {
5382 if (Op.getValueType() == MVT::v2i32 &&
5383 Op.getOperand(0).getValueType() == MVT::v2f64) {
5389 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5390 SDValue FIST = Vals.first, StackSlot = Vals.second;
5391 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5392 if (FIST.getNode() == 0) return Op;
5395 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5396 FIST, StackSlot, NULL, 0);
5399 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG) {
5400 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5401 SDValue FIST = Vals.first, StackSlot = Vals.second;
5402 assert(FIST.getNode() && "Unexpected failure");
5405 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5406 FIST, StackSlot, NULL, 0);
5409 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
5410 LLVMContext *Context = DAG.getContext();
5411 DebugLoc dl = Op.getDebugLoc();
5412 EVT VT = Op.getValueType();
5415 EltVT = VT.getVectorElementType();
5416 std::vector<Constant*> CV;
5417 if (EltVT == MVT::f64) {
5418 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5422 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5428 Constant *C = ConstantVector::get(CV);
5429 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5430 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5431 PseudoSourceValue::getConstantPool(), 0,
5433 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5436 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
5437 LLVMContext *Context = DAG.getContext();
5438 DebugLoc dl = Op.getDebugLoc();
5439 EVT VT = Op.getValueType();
5442 EltVT = VT.getVectorElementType();
5443 std::vector<Constant*> CV;
5444 if (EltVT == MVT::f64) {
5445 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5449 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5455 Constant *C = ConstantVector::get(CV);
5456 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5457 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5458 PseudoSourceValue::getConstantPool(), 0,
5460 if (VT.isVector()) {
5461 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5462 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5463 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5465 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5467 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5471 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5472 LLVMContext *Context = DAG.getContext();
5473 SDValue Op0 = Op.getOperand(0);
5474 SDValue Op1 = Op.getOperand(1);
5475 DebugLoc dl = Op.getDebugLoc();
5476 EVT VT = Op.getValueType();
5477 EVT SrcVT = Op1.getValueType();
5479 // If second operand is smaller, extend it first.
5480 if (SrcVT.bitsLT(VT)) {
5481 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5484 // And if it is bigger, shrink it first.
5485 if (SrcVT.bitsGT(VT)) {
5486 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5490 // At this point the operands and the result should have the same
5491 // type, and that won't be f80 since that is not custom lowered.
5493 // First get the sign bit of second operand.
5494 std::vector<Constant*> CV;
5495 if (SrcVT == MVT::f64) {
5496 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
5497 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5499 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
5500 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5501 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5502 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5504 Constant *C = ConstantVector::get(CV);
5505 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5506 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5507 PseudoSourceValue::getConstantPool(), 0,
5509 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5511 // Shift sign bit right or left if the two operands have different types.
5512 if (SrcVT.bitsGT(VT)) {
5513 // Op0 is MVT::f32, Op1 is MVT::f64.
5514 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5515 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5516 DAG.getConstant(32, MVT::i32));
5517 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5518 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5519 DAG.getIntPtrConstant(0));
5522 // Clear first operand sign bit.
5524 if (VT == MVT::f64) {
5525 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
5526 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5528 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
5529 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5530 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5531 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5533 C = ConstantVector::get(CV);
5534 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5535 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5536 PseudoSourceValue::getConstantPool(), 0,
5538 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5540 // Or the value with the sign bit.
5541 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5544 /// Emit nodes that will be selected as "test Op0,Op0", or something
5546 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5547 SelectionDAG &DAG) {
5548 DebugLoc dl = Op.getDebugLoc();
5550 // CF and OF aren't always set the way we want. Determine which
5551 // of these we need.
5552 bool NeedCF = false;
5553 bool NeedOF = false;
5555 case X86::COND_A: case X86::COND_AE:
5556 case X86::COND_B: case X86::COND_BE:
5559 case X86::COND_G: case X86::COND_GE:
5560 case X86::COND_L: case X86::COND_LE:
5561 case X86::COND_O: case X86::COND_NO:
5567 // See if we can use the EFLAGS value from the operand instead of
5568 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5569 // we prove that the arithmetic won't overflow, we can't use OF or CF.
5570 if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5571 unsigned Opcode = 0;
5572 unsigned NumOperands = 0;
5573 switch (Op.getNode()->getOpcode()) {
5575 // Due to an isel shortcoming, be conservative if this add is likely to
5576 // be selected as part of a load-modify-store instruction. When the root
5577 // node in a match is a store, isel doesn't know how to remap non-chain
5578 // non-flag uses of other nodes in the match, such as the ADD in this
5579 // case. This leads to the ADD being left around and reselected, with
5580 // the result being two adds in the output.
5581 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5582 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5583 if (UI->getOpcode() == ISD::STORE)
5585 if (ConstantSDNode *C =
5586 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5587 // An add of one will be selected as an INC.
5588 if (C->getAPIntValue() == 1) {
5589 Opcode = X86ISD::INC;
5593 // An add of negative one (subtract of one) will be selected as a DEC.
5594 if (C->getAPIntValue().isAllOnesValue()) {
5595 Opcode = X86ISD::DEC;
5600 // Otherwise use a regular EFLAGS-setting add.
5601 Opcode = X86ISD::ADD;
5605 // If the primary and result isn't used, don't bother using X86ISD::AND,
5606 // because a TEST instruction will be better.
5607 bool NonFlagUse = false;
5608 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5609 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5610 if (UI->getOpcode() != ISD::BRCOND &&
5611 UI->getOpcode() != ISD::SELECT &&
5612 UI->getOpcode() != ISD::SETCC) {
5623 // Due to the ISEL shortcoming noted above, be conservative if this op is
5624 // likely to be selected as part of a load-modify-store instruction.
5625 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5626 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5627 if (UI->getOpcode() == ISD::STORE)
5629 // Otherwise use a regular EFLAGS-setting instruction.
5630 switch (Op.getNode()->getOpcode()) {
5631 case ISD::SUB: Opcode = X86ISD::SUB; break;
5632 case ISD::OR: Opcode = X86ISD::OR; break;
5633 case ISD::XOR: Opcode = X86ISD::XOR; break;
5634 case ISD::AND: Opcode = X86ISD::AND; break;
5635 default: llvm_unreachable("unexpected operator!");
5646 return SDValue(Op.getNode(), 1);
5652 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
5653 SmallVector<SDValue, 4> Ops;
5654 for (unsigned i = 0; i != NumOperands; ++i)
5655 Ops.push_back(Op.getOperand(i));
5656 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
5657 DAG.ReplaceAllUsesWith(Op, New);
5658 return SDValue(New.getNode(), 1);
5662 // Otherwise just emit a CMP with 0, which is the TEST pattern.
5663 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5664 DAG.getConstant(0, Op.getValueType()));
5667 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
5669 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5670 SelectionDAG &DAG) {
5671 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5672 if (C->getAPIntValue() == 0)
5673 return EmitTest(Op0, X86CC, DAG);
5675 DebugLoc dl = Op0.getDebugLoc();
5676 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5679 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5680 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5681 SDValue Op0 = Op.getOperand(0);
5682 SDValue Op1 = Op.getOperand(1);
5683 DebugLoc dl = Op.getDebugLoc();
5684 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5686 // Lower (X & (1 << N)) == 0 to BT(X, N).
5687 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5688 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5689 if (Op0.getOpcode() == ISD::AND &&
5691 Op1.getOpcode() == ISD::Constant &&
5692 cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5693 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5695 if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
5696 if (ConstantSDNode *Op010C =
5697 dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
5698 if (Op010C->getZExtValue() == 1) {
5699 LHS = Op0.getOperand(0);
5700 RHS = Op0.getOperand(1).getOperand(1);
5702 } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
5703 if (ConstantSDNode *Op000C =
5704 dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
5705 if (Op000C->getZExtValue() == 1) {
5706 LHS = Op0.getOperand(1);
5707 RHS = Op0.getOperand(0).getOperand(1);
5709 } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
5710 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5711 SDValue AndLHS = Op0.getOperand(0);
5712 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5713 LHS = AndLHS.getOperand(0);
5714 RHS = AndLHS.getOperand(1);
5718 if (LHS.getNode()) {
5719 // If LHS is i8, promote it to i16 with any_extend. There is no i8 BT
5720 // instruction. Since the shift amount is in-range-or-undefined, we know
5721 // that doing a bittest on the i16 value is ok. We extend to i32 because
5722 // the encoding for the i16 version is larger than the i32 version.
5723 if (LHS.getValueType() == MVT::i8)
5724 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5726 // If the operand types disagree, extend the shift amount to match. Since
5727 // BT ignores high bits (like shifts) we can use anyextend.
5728 if (LHS.getValueType() != RHS.getValueType())
5729 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5731 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5732 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5733 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5734 DAG.getConstant(Cond, MVT::i8), BT);
5738 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5739 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5740 if (X86CC == X86::COND_INVALID)
5743 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
5744 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5745 DAG.getConstant(X86CC, MVT::i8), Cond);
5748 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5750 SDValue Op0 = Op.getOperand(0);
5751 SDValue Op1 = Op.getOperand(1);
5752 SDValue CC = Op.getOperand(2);
5753 EVT VT = Op.getValueType();
5754 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5755 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5756 DebugLoc dl = Op.getDebugLoc();
5760 EVT VT0 = Op0.getValueType();
5761 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5762 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5765 switch (SetCCOpcode) {
5768 case ISD::SETEQ: SSECC = 0; break;
5770 case ISD::SETGT: Swap = true; // Fallthrough
5772 case ISD::SETOLT: SSECC = 1; break;
5774 case ISD::SETGE: Swap = true; // Fallthrough
5776 case ISD::SETOLE: SSECC = 2; break;
5777 case ISD::SETUO: SSECC = 3; break;
5779 case ISD::SETNE: SSECC = 4; break;
5780 case ISD::SETULE: Swap = true;
5781 case ISD::SETUGE: SSECC = 5; break;
5782 case ISD::SETULT: Swap = true;
5783 case ISD::SETUGT: SSECC = 6; break;
5784 case ISD::SETO: SSECC = 7; break;
5787 std::swap(Op0, Op1);
5789 // In the two special cases we can't handle, emit two comparisons.
5791 if (SetCCOpcode == ISD::SETUEQ) {
5793 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5794 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5795 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
5797 else if (SetCCOpcode == ISD::SETONE) {
5799 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5800 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5801 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
5803 llvm_unreachable("Illegal FP comparison");
5805 // Handle all other FP comparisons here.
5806 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5809 // We are handling one of the integer comparisons here. Since SSE only has
5810 // GT and EQ comparisons for integer, swapping operands and multiple
5811 // operations may be required for some comparisons.
5812 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5813 bool Swap = false, Invert = false, FlipSigns = false;
5815 switch (VT.getSimpleVT().SimpleTy) {
5818 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5820 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5822 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5823 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5826 switch (SetCCOpcode) {
5828 case ISD::SETNE: Invert = true;
5829 case ISD::SETEQ: Opc = EQOpc; break;
5830 case ISD::SETLT: Swap = true;
5831 case ISD::SETGT: Opc = GTOpc; break;
5832 case ISD::SETGE: Swap = true;
5833 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
5834 case ISD::SETULT: Swap = true;
5835 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5836 case ISD::SETUGE: Swap = true;
5837 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5840 std::swap(Op0, Op1);
5842 // Since SSE has no unsigned integer comparisons, we need to flip the sign
5843 // bits of the inputs before performing those operations.
5845 EVT EltVT = VT.getVectorElementType();
5846 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
5848 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5849 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
5851 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
5852 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
5855 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
5857 // If the logical-not of the result is required, perform that now.
5859 Result = DAG.getNOT(dl, Result, VT);
5864 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5865 static bool isX86LogicalCmp(SDValue Op) {
5866 unsigned Opc = Op.getNode()->getOpcode();
5867 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
5869 if (Op.getResNo() == 1 &&
5870 (Opc == X86ISD::ADD ||
5871 Opc == X86ISD::SUB ||
5872 Opc == X86ISD::SMUL ||
5873 Opc == X86ISD::UMUL ||
5874 Opc == X86ISD::INC ||
5875 Opc == X86ISD::DEC ||
5876 Opc == X86ISD::OR ||
5877 Opc == X86ISD::XOR ||
5878 Opc == X86ISD::AND))
5884 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5885 bool addTest = true;
5886 SDValue Cond = Op.getOperand(0);
5887 DebugLoc dl = Op.getDebugLoc();
5890 if (Cond.getOpcode() == ISD::SETCC) {
5891 SDValue NewCond = LowerSETCC(Cond, DAG);
5892 if (NewCond.getNode())
5896 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5897 // setting operand in place of the X86ISD::SETCC.
5898 if (Cond.getOpcode() == X86ISD::SETCC) {
5899 CC = Cond.getOperand(0);
5901 SDValue Cmp = Cond.getOperand(1);
5902 unsigned Opc = Cmp.getOpcode();
5903 EVT VT = Op.getValueType();
5905 bool IllegalFPCMov = false;
5906 if (VT.isFloatingPoint() && !VT.isVector() &&
5907 !isScalarFPTypeInSSEReg(VT)) // FPStack?
5908 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
5910 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
5911 Opc == X86ISD::BT) { // FIXME
5918 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5919 Cond = EmitTest(Cond, X86::COND_NE, DAG);
5922 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
5923 SmallVector<SDValue, 4> Ops;
5924 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
5925 // condition is true.
5926 Ops.push_back(Op.getOperand(2));
5927 Ops.push_back(Op.getOperand(1));
5929 Ops.push_back(Cond);
5930 return DAG.getNode(X86ISD::CMOV, dl, VTs, &Ops[0], Ops.size());
5933 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
5934 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
5935 // from the AND / OR.
5936 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
5937 Opc = Op.getOpcode();
5938 if (Opc != ISD::OR && Opc != ISD::AND)
5940 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5941 Op.getOperand(0).hasOneUse() &&
5942 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
5943 Op.getOperand(1).hasOneUse());
5946 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
5947 // 1 and that the SETCC node has a single use.
5948 static bool isXor1OfSetCC(SDValue Op) {
5949 if (Op.getOpcode() != ISD::XOR)
5951 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5952 if (N1C && N1C->getAPIntValue() == 1) {
5953 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5954 Op.getOperand(0).hasOneUse();
5959 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
5960 bool addTest = true;
5961 SDValue Chain = Op.getOperand(0);
5962 SDValue Cond = Op.getOperand(1);
5963 SDValue Dest = Op.getOperand(2);
5964 DebugLoc dl = Op.getDebugLoc();
5967 if (Cond.getOpcode() == ISD::SETCC) {
5968 SDValue NewCond = LowerSETCC(Cond, DAG);
5969 if (NewCond.getNode())
5973 // FIXME: LowerXALUO doesn't handle these!!
5974 else if (Cond.getOpcode() == X86ISD::ADD ||
5975 Cond.getOpcode() == X86ISD::SUB ||
5976 Cond.getOpcode() == X86ISD::SMUL ||
5977 Cond.getOpcode() == X86ISD::UMUL)
5978 Cond = LowerXALUO(Cond, DAG);
5981 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5982 // setting operand in place of the X86ISD::SETCC.
5983 if (Cond.getOpcode() == X86ISD::SETCC) {
5984 CC = Cond.getOperand(0);
5986 SDValue Cmp = Cond.getOperand(1);
5987 unsigned Opc = Cmp.getOpcode();
5988 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
5989 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
5993 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
5997 // These can only come from an arithmetic instruction with overflow,
5998 // e.g. SADDO, UADDO.
5999 Cond = Cond.getNode()->getOperand(1);
6006 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
6007 SDValue Cmp = Cond.getOperand(0).getOperand(1);
6008 if (CondOpc == ISD::OR) {
6009 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
6010 // two branches instead of an explicit OR instruction with a
6012 if (Cmp == Cond.getOperand(1).getOperand(1) &&
6013 isX86LogicalCmp(Cmp)) {
6014 CC = Cond.getOperand(0).getOperand(0);
6015 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6016 Chain, Dest, CC, Cmp);
6017 CC = Cond.getOperand(1).getOperand(0);
6021 } else { // ISD::AND
6022 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
6023 // two branches instead of an explicit AND instruction with a
6024 // separate test. However, we only do this if this block doesn't
6025 // have a fall-through edge, because this requires an explicit
6026 // jmp when the condition is false.
6027 if (Cmp == Cond.getOperand(1).getOperand(1) &&
6028 isX86LogicalCmp(Cmp) &&
6029 Op.getNode()->hasOneUse()) {
6030 X86::CondCode CCode =
6031 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6032 CCode = X86::GetOppositeBranchCondition(CCode);
6033 CC = DAG.getConstant(CCode, MVT::i8);
6034 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
6035 // Look for an unconditional branch following this conditional branch.
6036 // We need this because we need to reverse the successors in order
6037 // to implement FCMP_OEQ.
6038 if (User.getOpcode() == ISD::BR) {
6039 SDValue FalseBB = User.getOperand(1);
6041 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
6042 assert(NewBR == User);
6045 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6046 Chain, Dest, CC, Cmp);
6047 X86::CondCode CCode =
6048 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
6049 CCode = X86::GetOppositeBranchCondition(CCode);
6050 CC = DAG.getConstant(CCode, MVT::i8);
6056 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
6057 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
6058 // It should be transformed during dag combiner except when the condition
6059 // is set by a arithmetics with overflow node.
6060 X86::CondCode CCode =
6061 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6062 CCode = X86::GetOppositeBranchCondition(CCode);
6063 CC = DAG.getConstant(CCode, MVT::i8);
6064 Cond = Cond.getOperand(0).getOperand(1);
6070 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6071 Cond = EmitTest(Cond, X86::COND_NE, DAG);
6073 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6074 Chain, Dest, CC, Cond);
6078 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
6079 // Calls to _alloca is needed to probe the stack when allocating more than 4k
6080 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
6081 // that the guard pages used by the OS virtual memory manager are allocated in
6082 // correct sequence.
6084 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6085 SelectionDAG &DAG) {
6086 assert(Subtarget->isTargetCygMing() &&
6087 "This should be used only on Cygwin/Mingw targets");
6088 DebugLoc dl = Op.getDebugLoc();
6091 SDValue Chain = Op.getOperand(0);
6092 SDValue Size = Op.getOperand(1);
6093 // FIXME: Ensure alignment here
6097 EVT IntPtr = getPointerTy();
6098 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
6100 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
6102 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
6103 Flag = Chain.getValue(1);
6105 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6106 SDValue Ops[] = { Chain,
6107 DAG.getTargetExternalSymbol("_alloca", IntPtr),
6108 DAG.getRegister(X86::EAX, IntPtr),
6109 DAG.getRegister(X86StackPtr, SPTy),
6111 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops, 5);
6112 Flag = Chain.getValue(1);
6114 Chain = DAG.getCALLSEQ_END(Chain,
6115 DAG.getIntPtrConstant(0, true),
6116 DAG.getIntPtrConstant(0, true),
6119 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
6121 SDValue Ops1[2] = { Chain.getValue(0), Chain };
6122 return DAG.getMergeValues(Ops1, 2, dl);
6126 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
6128 SDValue Dst, SDValue Src,
6129 SDValue Size, unsigned Align,
6131 uint64_t DstSVOff) {
6132 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6134 // If not DWORD aligned or size is more than the threshold, call the library.
6135 // The libc version is likely to be faster for these cases. It can use the
6136 // address value and run time information about the CPU.
6137 if ((Align & 3) != 0 ||
6139 ConstantSize->getZExtValue() >
6140 getSubtarget()->getMaxInlineSizeThreshold()) {
6141 SDValue InFlag(0, 0);
6143 // Check to see if there is a specialized entry-point for memory zeroing.
6144 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
6146 if (const char *bzeroEntry = V &&
6147 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
6148 EVT IntPtr = getPointerTy();
6149 const Type *IntPtrTy = TD->getIntPtrType(*DAG.getContext());
6150 TargetLowering::ArgListTy Args;
6151 TargetLowering::ArgListEntry Entry;
6153 Entry.Ty = IntPtrTy;
6154 Args.push_back(Entry);
6156 Args.push_back(Entry);
6157 std::pair<SDValue,SDValue> CallResult =
6158 LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()),
6159 false, false, false, false,
6160 0, CallingConv::C, false, /*isReturnValueUsed=*/false,
6161 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl);
6162 return CallResult.second;
6165 // Otherwise have the target-independent code call memset.
6169 uint64_t SizeVal = ConstantSize->getZExtValue();
6170 SDValue InFlag(0, 0);
6173 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
6174 unsigned BytesLeft = 0;
6175 bool TwoRepStos = false;
6178 uint64_t Val = ValC->getZExtValue() & 255;
6180 // If the value is a constant, then we can potentially use larger sets.
6181 switch (Align & 3) {
6182 case 2: // WORD aligned
6185 Val = (Val << 8) | Val;
6187 case 0: // DWORD aligned
6190 Val = (Val << 8) | Val;
6191 Val = (Val << 16) | Val;
6192 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
6195 Val = (Val << 32) | Val;
6198 default: // Byte aligned
6201 Count = DAG.getIntPtrConstant(SizeVal);
6205 if (AVT.bitsGT(MVT::i8)) {
6206 unsigned UBytes = AVT.getSizeInBits() / 8;
6207 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
6208 BytesLeft = SizeVal % UBytes;
6211 Chain = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
6213 InFlag = Chain.getValue(1);
6216 Count = DAG.getIntPtrConstant(SizeVal);
6217 Chain = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
6218 InFlag = Chain.getValue(1);
6221 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6224 InFlag = Chain.getValue(1);
6225 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6228 InFlag = Chain.getValue(1);
6230 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6231 SmallVector<SDValue, 8> Ops;
6232 Ops.push_back(Chain);
6233 Ops.push_back(DAG.getValueType(AVT));
6234 Ops.push_back(InFlag);
6235 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
6238 InFlag = Chain.getValue(1);
6240 EVT CVT = Count.getValueType();
6241 SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
6242 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
6243 Chain = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
6246 InFlag = Chain.getValue(1);
6247 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6249 Ops.push_back(Chain);
6250 Ops.push_back(DAG.getValueType(MVT::i8));
6251 Ops.push_back(InFlag);
6252 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
6253 } else if (BytesLeft) {
6254 // Handle the last 1 - 7 bytes.
6255 unsigned Offset = SizeVal - BytesLeft;
6256 EVT AddrVT = Dst.getValueType();
6257 EVT SizeVT = Size.getValueType();
6259 Chain = DAG.getMemset(Chain, dl,
6260 DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
6261 DAG.getConstant(Offset, AddrVT)),
6263 DAG.getConstant(BytesLeft, SizeVT),
6264 Align, DstSV, DstSVOff + Offset);
6267 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
6272 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
6273 SDValue Chain, SDValue Dst, SDValue Src,
6274 SDValue Size, unsigned Align,
6276 const Value *DstSV, uint64_t DstSVOff,
6277 const Value *SrcSV, uint64_t SrcSVOff) {
6278 // This requires the copy size to be a constant, preferrably
6279 // within a subtarget-specific limit.
6280 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6283 uint64_t SizeVal = ConstantSize->getZExtValue();
6284 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
6287 /// If not DWORD aligned, call the library.
6288 if ((Align & 3) != 0)
6293 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
6296 unsigned UBytes = AVT.getSizeInBits() / 8;
6297 unsigned CountVal = SizeVal / UBytes;
6298 SDValue Count = DAG.getIntPtrConstant(CountVal);
6299 unsigned BytesLeft = SizeVal % UBytes;
6301 SDValue InFlag(0, 0);
6302 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6305 InFlag = Chain.getValue(1);
6306 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6309 InFlag = Chain.getValue(1);
6310 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
6313 InFlag = Chain.getValue(1);
6315 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6316 SmallVector<SDValue, 8> Ops;
6317 Ops.push_back(Chain);
6318 Ops.push_back(DAG.getValueType(AVT));
6319 Ops.push_back(InFlag);
6320 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, &Ops[0], Ops.size());
6322 SmallVector<SDValue, 4> Results;
6323 Results.push_back(RepMovs);
6325 // Handle the last 1 - 7 bytes.
6326 unsigned Offset = SizeVal - BytesLeft;
6327 EVT DstVT = Dst.getValueType();
6328 EVT SrcVT = Src.getValueType();
6329 EVT SizeVT = Size.getValueType();
6330 Results.push_back(DAG.getMemcpy(Chain, dl,
6331 DAG.getNode(ISD::ADD, dl, DstVT, Dst,
6332 DAG.getConstant(Offset, DstVT)),
6333 DAG.getNode(ISD::ADD, dl, SrcVT, Src,
6334 DAG.getConstant(Offset, SrcVT)),
6335 DAG.getConstant(BytesLeft, SizeVT),
6336 Align, AlwaysInline,
6337 DstSV, DstSVOff + Offset,
6338 SrcSV, SrcSVOff + Offset));
6341 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6342 &Results[0], Results.size());
6345 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
6346 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6347 DebugLoc dl = Op.getDebugLoc();
6349 if (!Subtarget->is64Bit()) {
6350 // vastart just stores the address of the VarArgsFrameIndex slot into the
6351 // memory location argument.
6352 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6353 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
6357 // gp_offset (0 - 6 * 8)
6358 // fp_offset (48 - 48 + 8 * 16)
6359 // overflow_arg_area (point to parameters coming in memory).
6361 SmallVector<SDValue, 8> MemOps;
6362 SDValue FIN = Op.getOperand(1);
6364 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6365 DAG.getConstant(VarArgsGPOffset, MVT::i32),
6367 MemOps.push_back(Store);
6370 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6371 FIN, DAG.getIntPtrConstant(4));
6372 Store = DAG.getStore(Op.getOperand(0), dl,
6373 DAG.getConstant(VarArgsFPOffset, MVT::i32),
6375 MemOps.push_back(Store);
6377 // Store ptr to overflow_arg_area
6378 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6379 FIN, DAG.getIntPtrConstant(4));
6380 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6381 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0);
6382 MemOps.push_back(Store);
6384 // Store ptr to reg_save_area.
6385 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6386 FIN, DAG.getIntPtrConstant(8));
6387 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
6388 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0);
6389 MemOps.push_back(Store);
6390 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6391 &MemOps[0], MemOps.size());
6394 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
6395 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6396 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6397 SDValue Chain = Op.getOperand(0);
6398 SDValue SrcPtr = Op.getOperand(1);
6399 SDValue SrcSV = Op.getOperand(2);
6401 llvm_report_error("VAArgInst is not yet implemented for x86-64!");
6405 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
6406 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6407 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6408 SDValue Chain = Op.getOperand(0);
6409 SDValue DstPtr = Op.getOperand(1);
6410 SDValue SrcPtr = Op.getOperand(2);
6411 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6412 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6413 DebugLoc dl = Op.getDebugLoc();
6415 return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6416 DAG.getIntPtrConstant(24), 8, false,
6417 DstSV, 0, SrcSV, 0);
6421 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
6422 DebugLoc dl = Op.getDebugLoc();
6423 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6425 default: return SDValue(); // Don't custom lower most intrinsics.
6426 // Comparison intrinsics.
6427 case Intrinsic::x86_sse_comieq_ss:
6428 case Intrinsic::x86_sse_comilt_ss:
6429 case Intrinsic::x86_sse_comile_ss:
6430 case Intrinsic::x86_sse_comigt_ss:
6431 case Intrinsic::x86_sse_comige_ss:
6432 case Intrinsic::x86_sse_comineq_ss:
6433 case Intrinsic::x86_sse_ucomieq_ss:
6434 case Intrinsic::x86_sse_ucomilt_ss:
6435 case Intrinsic::x86_sse_ucomile_ss:
6436 case Intrinsic::x86_sse_ucomigt_ss:
6437 case Intrinsic::x86_sse_ucomige_ss:
6438 case Intrinsic::x86_sse_ucomineq_ss:
6439 case Intrinsic::x86_sse2_comieq_sd:
6440 case Intrinsic::x86_sse2_comilt_sd:
6441 case Intrinsic::x86_sse2_comile_sd:
6442 case Intrinsic::x86_sse2_comigt_sd:
6443 case Intrinsic::x86_sse2_comige_sd:
6444 case Intrinsic::x86_sse2_comineq_sd:
6445 case Intrinsic::x86_sse2_ucomieq_sd:
6446 case Intrinsic::x86_sse2_ucomilt_sd:
6447 case Intrinsic::x86_sse2_ucomile_sd:
6448 case Intrinsic::x86_sse2_ucomigt_sd:
6449 case Intrinsic::x86_sse2_ucomige_sd:
6450 case Intrinsic::x86_sse2_ucomineq_sd: {
6452 ISD::CondCode CC = ISD::SETCC_INVALID;
6455 case Intrinsic::x86_sse_comieq_ss:
6456 case Intrinsic::x86_sse2_comieq_sd:
6460 case Intrinsic::x86_sse_comilt_ss:
6461 case Intrinsic::x86_sse2_comilt_sd:
6465 case Intrinsic::x86_sse_comile_ss:
6466 case Intrinsic::x86_sse2_comile_sd:
6470 case Intrinsic::x86_sse_comigt_ss:
6471 case Intrinsic::x86_sse2_comigt_sd:
6475 case Intrinsic::x86_sse_comige_ss:
6476 case Intrinsic::x86_sse2_comige_sd:
6480 case Intrinsic::x86_sse_comineq_ss:
6481 case Intrinsic::x86_sse2_comineq_sd:
6485 case Intrinsic::x86_sse_ucomieq_ss:
6486 case Intrinsic::x86_sse2_ucomieq_sd:
6487 Opc = X86ISD::UCOMI;
6490 case Intrinsic::x86_sse_ucomilt_ss:
6491 case Intrinsic::x86_sse2_ucomilt_sd:
6492 Opc = X86ISD::UCOMI;
6495 case Intrinsic::x86_sse_ucomile_ss:
6496 case Intrinsic::x86_sse2_ucomile_sd:
6497 Opc = X86ISD::UCOMI;
6500 case Intrinsic::x86_sse_ucomigt_ss:
6501 case Intrinsic::x86_sse2_ucomigt_sd:
6502 Opc = X86ISD::UCOMI;
6505 case Intrinsic::x86_sse_ucomige_ss:
6506 case Intrinsic::x86_sse2_ucomige_sd:
6507 Opc = X86ISD::UCOMI;
6510 case Intrinsic::x86_sse_ucomineq_ss:
6511 case Intrinsic::x86_sse2_ucomineq_sd:
6512 Opc = X86ISD::UCOMI;
6517 SDValue LHS = Op.getOperand(1);
6518 SDValue RHS = Op.getOperand(2);
6519 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6520 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
6521 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6522 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6523 DAG.getConstant(X86CC, MVT::i8), Cond);
6524 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6526 // ptest intrinsics. The intrinsic these come from are designed to return
6527 // an integer value, not just an instruction so lower it to the ptest
6528 // pattern and a setcc for the result.
6529 case Intrinsic::x86_sse41_ptestz:
6530 case Intrinsic::x86_sse41_ptestc:
6531 case Intrinsic::x86_sse41_ptestnzc:{
6534 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
6535 case Intrinsic::x86_sse41_ptestz:
6537 X86CC = X86::COND_E;
6539 case Intrinsic::x86_sse41_ptestc:
6541 X86CC = X86::COND_B;
6543 case Intrinsic::x86_sse41_ptestnzc:
6545 X86CC = X86::COND_A;
6549 SDValue LHS = Op.getOperand(1);
6550 SDValue RHS = Op.getOperand(2);
6551 SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
6552 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
6553 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
6554 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6557 // Fix vector shift instructions where the last operand is a non-immediate
6559 case Intrinsic::x86_sse2_pslli_w:
6560 case Intrinsic::x86_sse2_pslli_d:
6561 case Intrinsic::x86_sse2_pslli_q:
6562 case Intrinsic::x86_sse2_psrli_w:
6563 case Intrinsic::x86_sse2_psrli_d:
6564 case Intrinsic::x86_sse2_psrli_q:
6565 case Intrinsic::x86_sse2_psrai_w:
6566 case Intrinsic::x86_sse2_psrai_d:
6567 case Intrinsic::x86_mmx_pslli_w:
6568 case Intrinsic::x86_mmx_pslli_d:
6569 case Intrinsic::x86_mmx_pslli_q:
6570 case Intrinsic::x86_mmx_psrli_w:
6571 case Intrinsic::x86_mmx_psrli_d:
6572 case Intrinsic::x86_mmx_psrli_q:
6573 case Intrinsic::x86_mmx_psrai_w:
6574 case Intrinsic::x86_mmx_psrai_d: {
6575 SDValue ShAmt = Op.getOperand(2);
6576 if (isa<ConstantSDNode>(ShAmt))
6579 unsigned NewIntNo = 0;
6580 EVT ShAmtVT = MVT::v4i32;
6582 case Intrinsic::x86_sse2_pslli_w:
6583 NewIntNo = Intrinsic::x86_sse2_psll_w;
6585 case Intrinsic::x86_sse2_pslli_d:
6586 NewIntNo = Intrinsic::x86_sse2_psll_d;
6588 case Intrinsic::x86_sse2_pslli_q:
6589 NewIntNo = Intrinsic::x86_sse2_psll_q;
6591 case Intrinsic::x86_sse2_psrli_w:
6592 NewIntNo = Intrinsic::x86_sse2_psrl_w;
6594 case Intrinsic::x86_sse2_psrli_d:
6595 NewIntNo = Intrinsic::x86_sse2_psrl_d;
6597 case Intrinsic::x86_sse2_psrli_q:
6598 NewIntNo = Intrinsic::x86_sse2_psrl_q;
6600 case Intrinsic::x86_sse2_psrai_w:
6601 NewIntNo = Intrinsic::x86_sse2_psra_w;
6603 case Intrinsic::x86_sse2_psrai_d:
6604 NewIntNo = Intrinsic::x86_sse2_psra_d;
6607 ShAmtVT = MVT::v2i32;
6609 case Intrinsic::x86_mmx_pslli_w:
6610 NewIntNo = Intrinsic::x86_mmx_psll_w;
6612 case Intrinsic::x86_mmx_pslli_d:
6613 NewIntNo = Intrinsic::x86_mmx_psll_d;
6615 case Intrinsic::x86_mmx_pslli_q:
6616 NewIntNo = Intrinsic::x86_mmx_psll_q;
6618 case Intrinsic::x86_mmx_psrli_w:
6619 NewIntNo = Intrinsic::x86_mmx_psrl_w;
6621 case Intrinsic::x86_mmx_psrli_d:
6622 NewIntNo = Intrinsic::x86_mmx_psrl_d;
6624 case Intrinsic::x86_mmx_psrli_q:
6625 NewIntNo = Intrinsic::x86_mmx_psrl_q;
6627 case Intrinsic::x86_mmx_psrai_w:
6628 NewIntNo = Intrinsic::x86_mmx_psra_w;
6630 case Intrinsic::x86_mmx_psrai_d:
6631 NewIntNo = Intrinsic::x86_mmx_psra_d;
6633 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
6639 // The vector shift intrinsics with scalars uses 32b shift amounts but
6640 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
6644 ShOps[1] = DAG.getConstant(0, MVT::i32);
6645 if (ShAmtVT == MVT::v4i32) {
6646 ShOps[2] = DAG.getUNDEF(MVT::i32);
6647 ShOps[3] = DAG.getUNDEF(MVT::i32);
6648 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
6650 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
6653 EVT VT = Op.getValueType();
6654 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
6655 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6656 DAG.getConstant(NewIntNo, MVT::i32),
6657 Op.getOperand(1), ShAmt);
6662 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
6663 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6664 DebugLoc dl = Op.getDebugLoc();
6667 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6669 DAG.getConstant(TD->getPointerSize(),
6670 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6671 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6672 DAG.getNode(ISD::ADD, dl, getPointerTy(),
6677 // Just load the return address.
6678 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6679 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6680 RetAddrFI, NULL, 0);
6683 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
6684 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6685 MFI->setFrameAddressIsTaken(true);
6686 EVT VT = Op.getValueType();
6687 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
6688 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6689 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6690 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6692 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
6696 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6697 SelectionDAG &DAG) {
6698 return DAG.getIntPtrConstant(2*TD->getPointerSize());
6701 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
6703 MachineFunction &MF = DAG.getMachineFunction();
6704 SDValue Chain = Op.getOperand(0);
6705 SDValue Offset = Op.getOperand(1);
6706 SDValue Handler = Op.getOperand(2);
6707 DebugLoc dl = Op.getDebugLoc();
6709 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6711 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6713 SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
6714 DAG.getIntPtrConstant(-TD->getPointerSize()));
6715 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
6716 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0);
6717 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
6718 MF.getRegInfo().addLiveOut(StoreAddrReg);
6720 return DAG.getNode(X86ISD::EH_RETURN, dl,
6722 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6725 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6726 SelectionDAG &DAG) {
6727 SDValue Root = Op.getOperand(0);
6728 SDValue Trmp = Op.getOperand(1); // trampoline
6729 SDValue FPtr = Op.getOperand(2); // nested function
6730 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6731 DebugLoc dl = Op.getDebugLoc();
6733 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6735 const X86InstrInfo *TII =
6736 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
6738 if (Subtarget->is64Bit()) {
6739 SDValue OutChains[6];
6741 // Large code-model.
6743 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
6744 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
6746 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
6747 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
6749 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
6751 // Load the pointer to the nested function into R11.
6752 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
6753 SDValue Addr = Trmp;
6754 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6757 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6758 DAG.getConstant(2, MVT::i64));
6759 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2, false, 2);
6761 // Load the 'nest' parameter value into R10.
6762 // R10 is specified in X86CallingConv.td
6763 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
6764 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6765 DAG.getConstant(10, MVT::i64));
6766 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6767 Addr, TrmpAddr, 10);
6769 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6770 DAG.getConstant(12, MVT::i64));
6771 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12, false, 2);
6773 // Jump to the nested function.
6774 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
6775 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6776 DAG.getConstant(20, MVT::i64));
6777 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6778 Addr, TrmpAddr, 20);
6780 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
6781 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6782 DAG.getConstant(22, MVT::i64));
6783 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
6787 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
6788 return DAG.getMergeValues(Ops, 2, dl);
6790 const Function *Func =
6791 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
6792 CallingConv::ID CC = Func->getCallingConv();
6797 llvm_unreachable("Unsupported calling convention");
6798 case CallingConv::C:
6799 case CallingConv::X86_StdCall: {
6800 // Pass 'nest' parameter in ECX.
6801 // Must be kept in sync with X86CallingConv.td
6804 // Check that ECX wasn't needed by an 'inreg' parameter.
6805 const FunctionType *FTy = Func->getFunctionType();
6806 const AttrListPtr &Attrs = Func->getAttributes();
6808 if (!Attrs.isEmpty() && !Func->isVarArg()) {
6809 unsigned InRegCount = 0;
6812 for (FunctionType::param_iterator I = FTy->param_begin(),
6813 E = FTy->param_end(); I != E; ++I, ++Idx)
6814 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6815 // FIXME: should only count parameters that are lowered to integers.
6816 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6818 if (InRegCount > 2) {
6819 llvm_report_error("Nest register in use - reduce number of inreg parameters!");
6824 case CallingConv::X86_FastCall:
6825 case CallingConv::Fast:
6826 // Pass 'nest' parameter in EAX.
6827 // Must be kept in sync with X86CallingConv.td
6832 SDValue OutChains[4];
6835 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6836 DAG.getConstant(10, MVT::i32));
6837 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
6839 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
6840 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
6841 OutChains[0] = DAG.getStore(Root, dl,
6842 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
6845 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6846 DAG.getConstant(1, MVT::i32));
6847 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1, false, 1);
6849 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
6850 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6851 DAG.getConstant(5, MVT::i32));
6852 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
6853 TrmpAddr, 5, false, 1);
6855 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6856 DAG.getConstant(6, MVT::i32));
6857 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6, false, 1);
6860 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
6861 return DAG.getMergeValues(Ops, 2, dl);
6865 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
6867 The rounding mode is in bits 11:10 of FPSR, and has the following
6874 FLT_ROUNDS, on the other hand, expects the following:
6881 To perform the conversion, we do:
6882 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
6885 MachineFunction &MF = DAG.getMachineFunction();
6886 const TargetMachine &TM = MF.getTarget();
6887 const TargetFrameInfo &TFI = *TM.getFrameInfo();
6888 unsigned StackAlignment = TFI.getStackAlignment();
6889 EVT VT = Op.getValueType();
6890 DebugLoc dl = Op.getDebugLoc();
6892 // Save FP Control Word to stack slot
6893 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
6894 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6896 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
6897 DAG.getEntryNode(), StackSlot);
6899 // Load FP Control Word from stack slot
6900 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0);
6902 // Transform as necessary
6904 DAG.getNode(ISD::SRL, dl, MVT::i16,
6905 DAG.getNode(ISD::AND, dl, MVT::i16,
6906 CWD, DAG.getConstant(0x800, MVT::i16)),
6907 DAG.getConstant(11, MVT::i8));
6909 DAG.getNode(ISD::SRL, dl, MVT::i16,
6910 DAG.getNode(ISD::AND, dl, MVT::i16,
6911 CWD, DAG.getConstant(0x400, MVT::i16)),
6912 DAG.getConstant(9, MVT::i8));
6915 DAG.getNode(ISD::AND, dl, MVT::i16,
6916 DAG.getNode(ISD::ADD, dl, MVT::i16,
6917 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
6918 DAG.getConstant(1, MVT::i16)),
6919 DAG.getConstant(3, MVT::i16));
6922 return DAG.getNode((VT.getSizeInBits() < 16 ?
6923 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6926 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
6927 EVT VT = Op.getValueType();
6929 unsigned NumBits = VT.getSizeInBits();
6930 DebugLoc dl = Op.getDebugLoc();
6932 Op = Op.getOperand(0);
6933 if (VT == MVT::i8) {
6934 // Zero extend to i32 since there is not an i8 bsr.
6936 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6939 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
6940 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6941 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
6943 // If src is zero (i.e. bsr sets ZF), returns NumBits.
6944 SmallVector<SDValue, 4> Ops;
6946 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
6947 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6948 Ops.push_back(Op.getValue(1));
6949 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6951 // Finally xor with NumBits-1.
6952 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
6955 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6959 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
6960 EVT VT = Op.getValueType();
6962 unsigned NumBits = VT.getSizeInBits();
6963 DebugLoc dl = Op.getDebugLoc();
6965 Op = Op.getOperand(0);
6966 if (VT == MVT::i8) {
6968 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6971 // Issue a bsf (scan bits forward) which also sets EFLAGS.
6972 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6973 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
6975 // If src is zero (i.e. bsf sets ZF), returns NumBits.
6976 SmallVector<SDValue, 4> Ops;
6978 Ops.push_back(DAG.getConstant(NumBits, OpVT));
6979 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6980 Ops.push_back(Op.getValue(1));
6981 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6984 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6988 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
6989 EVT VT = Op.getValueType();
6990 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
6991 DebugLoc dl = Op.getDebugLoc();
6993 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
6994 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
6995 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
6996 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
6997 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
6999 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
7000 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
7001 // return AloBlo + AloBhi + AhiBlo;
7003 SDValue A = Op.getOperand(0);
7004 SDValue B = Op.getOperand(1);
7006 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7007 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7008 A, DAG.getConstant(32, MVT::i32));
7009 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7010 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7011 B, DAG.getConstant(32, MVT::i32));
7012 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7013 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7015 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7016 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7018 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7019 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7021 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7022 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7023 AloBhi, DAG.getConstant(32, MVT::i32));
7024 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7025 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7026 AhiBlo, DAG.getConstant(32, MVT::i32));
7027 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
7028 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
7033 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
7034 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
7035 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
7036 // looks for this combo and may remove the "setcc" instruction if the "setcc"
7037 // has only one use.
7038 SDNode *N = Op.getNode();
7039 SDValue LHS = N->getOperand(0);
7040 SDValue RHS = N->getOperand(1);
7041 unsigned BaseOp = 0;
7043 DebugLoc dl = Op.getDebugLoc();
7045 switch (Op.getOpcode()) {
7046 default: llvm_unreachable("Unknown ovf instruction!");
7048 // A subtract of one will be selected as a INC. Note that INC doesn't
7049 // set CF, so we can't do this for UADDO.
7050 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7051 if (C->getAPIntValue() == 1) {
7052 BaseOp = X86ISD::INC;
7056 BaseOp = X86ISD::ADD;
7060 BaseOp = X86ISD::ADD;
7064 // A subtract of one will be selected as a DEC. Note that DEC doesn't
7065 // set CF, so we can't do this for USUBO.
7066 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7067 if (C->getAPIntValue() == 1) {
7068 BaseOp = X86ISD::DEC;
7072 BaseOp = X86ISD::SUB;
7076 BaseOp = X86ISD::SUB;
7080 BaseOp = X86ISD::SMUL;
7084 BaseOp = X86ISD::UMUL;
7089 // Also sets EFLAGS.
7090 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
7091 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
7094 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
7095 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
7097 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
7101 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
7102 EVT T = Op.getValueType();
7103 DebugLoc dl = Op.getDebugLoc();
7106 switch(T.getSimpleVT().SimpleTy) {
7108 assert(false && "Invalid value type!");
7109 case MVT::i8: Reg = X86::AL; size = 1; break;
7110 case MVT::i16: Reg = X86::AX; size = 2; break;
7111 case MVT::i32: Reg = X86::EAX; size = 4; break;
7113 assert(Subtarget->is64Bit() && "Node not type legal!");
7114 Reg = X86::RAX; size = 8;
7117 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
7118 Op.getOperand(2), SDValue());
7119 SDValue Ops[] = { cpIn.getValue(0),
7122 DAG.getTargetConstant(size, MVT::i8),
7124 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7125 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
7127 DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
7131 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
7132 SelectionDAG &DAG) {
7133 assert(Subtarget->is64Bit() && "Result not type legalized?");
7134 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7135 SDValue TheChain = Op.getOperand(0);
7136 DebugLoc dl = Op.getDebugLoc();
7137 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7138 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
7139 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
7141 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
7142 DAG.getConstant(32, MVT::i8));
7144 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
7147 return DAG.getMergeValues(Ops, 2, dl);
7150 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
7151 SDNode *Node = Op.getNode();
7152 DebugLoc dl = Node->getDebugLoc();
7153 EVT T = Node->getValueType(0);
7154 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
7155 DAG.getConstant(0, T), Node->getOperand(2));
7156 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
7157 cast<AtomicSDNode>(Node)->getMemoryVT(),
7158 Node->getOperand(0),
7159 Node->getOperand(1), negOp,
7160 cast<AtomicSDNode>(Node)->getSrcValue(),
7161 cast<AtomicSDNode>(Node)->getAlignment());
7164 /// LowerOperation - Provide custom lowering hooks for some operations.
7166 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
7167 switch (Op.getOpcode()) {
7168 default: llvm_unreachable("Should not custom lower this!");
7169 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
7170 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
7171 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
7172 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7173 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7174 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7175 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
7176 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
7177 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
7178 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7179 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
7180 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
7181 case ISD::SHL_PARTS:
7182 case ISD::SRA_PARTS:
7183 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
7184 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
7185 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
7186 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
7187 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
7188 case ISD::FABS: return LowerFABS(Op, DAG);
7189 case ISD::FNEG: return LowerFNEG(Op, DAG);
7190 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
7191 case ISD::SETCC: return LowerSETCC(Op, DAG);
7192 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
7193 case ISD::SELECT: return LowerSELECT(Op, DAG);
7194 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
7195 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
7196 case ISD::VASTART: return LowerVASTART(Op, DAG);
7197 case ISD::VAARG: return LowerVAARG(Op, DAG);
7198 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
7199 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7200 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
7201 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
7202 case ISD::FRAME_TO_ARGS_OFFSET:
7203 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
7204 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
7205 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
7206 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
7207 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
7208 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
7209 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
7210 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
7216 case ISD::UMULO: return LowerXALUO(Op, DAG);
7217 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
7221 void X86TargetLowering::
7222 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
7223 SelectionDAG &DAG, unsigned NewOp) {
7224 EVT T = Node->getValueType(0);
7225 DebugLoc dl = Node->getDebugLoc();
7226 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
7228 SDValue Chain = Node->getOperand(0);
7229 SDValue In1 = Node->getOperand(1);
7230 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7231 Node->getOperand(2), DAG.getIntPtrConstant(0));
7232 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7233 Node->getOperand(2), DAG.getIntPtrConstant(1));
7234 SDValue Ops[] = { Chain, In1, In2L, In2H };
7235 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7237 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
7238 cast<MemSDNode>(Node)->getMemOperand());
7239 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7240 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7241 Results.push_back(Result.getValue(2));
7244 /// ReplaceNodeResults - Replace a node with an illegal result type
7245 /// with a new node built out of custom code.
7246 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7247 SmallVectorImpl<SDValue>&Results,
7248 SelectionDAG &DAG) {
7249 DebugLoc dl = N->getDebugLoc();
7250 switch (N->getOpcode()) {
7252 assert(false && "Do not know how to custom type legalize this operation!");
7254 case ISD::FP_TO_SINT: {
7255 std::pair<SDValue,SDValue> Vals =
7256 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
7257 SDValue FIST = Vals.first, StackSlot = Vals.second;
7258 if (FIST.getNode() != 0) {
7259 EVT VT = N->getValueType(0);
7260 // Return a load from the stack slot.
7261 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0));
7265 case ISD::READCYCLECOUNTER: {
7266 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7267 SDValue TheChain = N->getOperand(0);
7268 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7269 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7271 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7273 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7274 SDValue Ops[] = { eax, edx };
7275 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7276 Results.push_back(edx.getValue(1));
7283 EVT WidenVT = getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
7284 Results.push_back(DAG.UnrollVectorOp(N, WidenVT.getVectorNumElements()));
7287 case ISD::ATOMIC_CMP_SWAP: {
7288 EVT T = N->getValueType(0);
7289 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7290 SDValue cpInL, cpInH;
7291 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7292 DAG.getConstant(0, MVT::i32));
7293 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7294 DAG.getConstant(1, MVT::i32));
7295 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7296 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7298 SDValue swapInL, swapInH;
7299 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7300 DAG.getConstant(0, MVT::i32));
7301 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7302 DAG.getConstant(1, MVT::i32));
7303 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7305 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7306 swapInL.getValue(1));
7307 SDValue Ops[] = { swapInH.getValue(0),
7309 swapInH.getValue(1) };
7310 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7311 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7312 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7313 MVT::i32, Result.getValue(1));
7314 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7315 MVT::i32, cpOutL.getValue(2));
7316 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7317 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7318 Results.push_back(cpOutH.getValue(1));
7321 case ISD::ATOMIC_LOAD_ADD:
7322 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7324 case ISD::ATOMIC_LOAD_AND:
7325 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7327 case ISD::ATOMIC_LOAD_NAND:
7328 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7330 case ISD::ATOMIC_LOAD_OR:
7331 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7333 case ISD::ATOMIC_LOAD_SUB:
7334 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7336 case ISD::ATOMIC_LOAD_XOR:
7337 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7339 case ISD::ATOMIC_SWAP:
7340 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7345 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7347 default: return NULL;
7348 case X86ISD::BSF: return "X86ISD::BSF";
7349 case X86ISD::BSR: return "X86ISD::BSR";
7350 case X86ISD::SHLD: return "X86ISD::SHLD";
7351 case X86ISD::SHRD: return "X86ISD::SHRD";
7352 case X86ISD::FAND: return "X86ISD::FAND";
7353 case X86ISD::FOR: return "X86ISD::FOR";
7354 case X86ISD::FXOR: return "X86ISD::FXOR";
7355 case X86ISD::FSRL: return "X86ISD::FSRL";
7356 case X86ISD::FILD: return "X86ISD::FILD";
7357 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
7358 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7359 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7360 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7361 case X86ISD::FLD: return "X86ISD::FLD";
7362 case X86ISD::FST: return "X86ISD::FST";
7363 case X86ISD::CALL: return "X86ISD::CALL";
7364 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
7365 case X86ISD::BT: return "X86ISD::BT";
7366 case X86ISD::CMP: return "X86ISD::CMP";
7367 case X86ISD::COMI: return "X86ISD::COMI";
7368 case X86ISD::UCOMI: return "X86ISD::UCOMI";
7369 case X86ISD::SETCC: return "X86ISD::SETCC";
7370 case X86ISD::CMOV: return "X86ISD::CMOV";
7371 case X86ISD::BRCOND: return "X86ISD::BRCOND";
7372 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
7373 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
7374 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
7375 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
7376 case X86ISD::Wrapper: return "X86ISD::Wrapper";
7377 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
7378 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
7379 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
7380 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
7381 case X86ISD::PINSRB: return "X86ISD::PINSRB";
7382 case X86ISD::PINSRW: return "X86ISD::PINSRW";
7383 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
7384 case X86ISD::FMAX: return "X86ISD::FMAX";
7385 case X86ISD::FMIN: return "X86ISD::FMIN";
7386 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
7387 case X86ISD::FRCP: return "X86ISD::FRCP";
7388 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
7389 case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7390 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
7391 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
7392 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
7393 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
7394 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
7395 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
7396 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
7397 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
7398 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
7399 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
7400 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
7401 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
7402 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
7403 case X86ISD::VSHL: return "X86ISD::VSHL";
7404 case X86ISD::VSRL: return "X86ISD::VSRL";
7405 case X86ISD::CMPPD: return "X86ISD::CMPPD";
7406 case X86ISD::CMPPS: return "X86ISD::CMPPS";
7407 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
7408 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
7409 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
7410 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
7411 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
7412 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
7413 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
7414 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
7415 case X86ISD::ADD: return "X86ISD::ADD";
7416 case X86ISD::SUB: return "X86ISD::SUB";
7417 case X86ISD::SMUL: return "X86ISD::SMUL";
7418 case X86ISD::UMUL: return "X86ISD::UMUL";
7419 case X86ISD::INC: return "X86ISD::INC";
7420 case X86ISD::DEC: return "X86ISD::DEC";
7421 case X86ISD::OR: return "X86ISD::OR";
7422 case X86ISD::XOR: return "X86ISD::XOR";
7423 case X86ISD::AND: return "X86ISD::AND";
7424 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
7425 case X86ISD::PTEST: return "X86ISD::PTEST";
7426 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
7430 // isLegalAddressingMode - Return true if the addressing mode represented
7431 // by AM is legal for this target, for a load/store of the specified type.
7432 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7433 const Type *Ty) const {
7434 // X86 supports extremely general addressing modes.
7435 CodeModel::Model M = getTargetMachine().getCodeModel();
7437 // X86 allows a sign-extended 32-bit immediate field as a displacement.
7438 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
7443 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7445 // If a reference to this global requires an extra load, we can't fold it.
7446 if (isGlobalStubReference(GVFlags))
7449 // If BaseGV requires a register for the PIC base, we cannot also have a
7450 // BaseReg specified.
7451 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
7454 // If lower 4G is not available, then we must use rip-relative addressing.
7455 if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
7465 // These scales always work.
7470 // These scales are formed with basereg+scalereg. Only accept if there is
7475 default: // Other stuff never works.
7483 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7484 if (!Ty1->isInteger() || !Ty2->isInteger())
7486 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7487 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7488 if (NumBits1 <= NumBits2)
7490 return Subtarget->is64Bit() || NumBits1 < 64;
7493 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7494 if (!VT1.isInteger() || !VT2.isInteger())
7496 unsigned NumBits1 = VT1.getSizeInBits();
7497 unsigned NumBits2 = VT2.getSizeInBits();
7498 if (NumBits1 <= NumBits2)
7500 return Subtarget->is64Bit() || NumBits1 < 64;
7503 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7504 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7505 return Ty1 == Type::getInt32Ty(Ty1->getContext()) &&
7506 Ty2 == Type::getInt64Ty(Ty1->getContext()) && Subtarget->is64Bit();
7509 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7510 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7511 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7514 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
7515 // i16 instructions are longer (0x66 prefix) and potentially slower.
7516 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7519 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7520 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7521 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7522 /// are assumed to be legal.
7524 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
7526 // Only do shuffles on 128-bit vector types for now.
7527 if (VT.getSizeInBits() == 64)
7530 // FIXME: pshufb, blends, shifts.
7531 return (VT.getVectorNumElements() == 2 ||
7532 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7533 isMOVLMask(M, VT) ||
7534 isSHUFPMask(M, VT) ||
7535 isPSHUFDMask(M, VT) ||
7536 isPSHUFHWMask(M, VT) ||
7537 isPSHUFLWMask(M, VT) ||
7538 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
7539 isUNPCKLMask(M, VT) ||
7540 isUNPCKHMask(M, VT) ||
7541 isUNPCKL_v_undef_Mask(M, VT) ||
7542 isUNPCKH_v_undef_Mask(M, VT));
7546 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
7548 unsigned NumElts = VT.getVectorNumElements();
7549 // FIXME: This collection of masks seems suspect.
7552 if (NumElts == 4 && VT.getSizeInBits() == 128) {
7553 return (isMOVLMask(Mask, VT) ||
7554 isCommutedMOVLMask(Mask, VT, true) ||
7555 isSHUFPMask(Mask, VT) ||
7556 isCommutedSHUFPMask(Mask, VT));
7561 //===----------------------------------------------------------------------===//
7562 // X86 Scheduler Hooks
7563 //===----------------------------------------------------------------------===//
7565 // private utility function
7567 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7568 MachineBasicBlock *MBB,
7576 TargetRegisterClass *RC,
7577 bool invSrc) const {
7578 // For the atomic bitwise operator, we generate
7581 // ld t1 = [bitinstr.addr]
7582 // op t2 = t1, [bitinstr.val]
7584 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7586 // fallthrough -->nextMBB
7587 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7588 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7589 MachineFunction::iterator MBBIter = MBB;
7592 /// First build the CFG
7593 MachineFunction *F = MBB->getParent();
7594 MachineBasicBlock *thisMBB = MBB;
7595 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7596 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7597 F->insert(MBBIter, newMBB);
7598 F->insert(MBBIter, nextMBB);
7600 // Move all successors to thisMBB to nextMBB
7601 nextMBB->transferSuccessors(thisMBB);
7603 // Update thisMBB to fall through to newMBB
7604 thisMBB->addSuccessor(newMBB);
7606 // newMBB jumps to itself and fall through to nextMBB
7607 newMBB->addSuccessor(nextMBB);
7608 newMBB->addSuccessor(newMBB);
7610 // Insert instructions into newMBB based on incoming instruction
7611 assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7612 "unexpected number of operands");
7613 DebugLoc dl = bInstr->getDebugLoc();
7614 MachineOperand& destOper = bInstr->getOperand(0);
7615 MachineOperand* argOpers[2 + X86AddrNumOperands];
7616 int numArgs = bInstr->getNumOperands() - 1;
7617 for (int i=0; i < numArgs; ++i)
7618 argOpers[i] = &bInstr->getOperand(i+1);
7620 // x86 address has 4 operands: base, index, scale, and displacement
7621 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7622 int valArgIndx = lastAddrIndx + 1;
7624 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7625 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7626 for (int i=0; i <= lastAddrIndx; ++i)
7627 (*MIB).addOperand(*argOpers[i]);
7629 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7631 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7636 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7637 assert((argOpers[valArgIndx]->isReg() ||
7638 argOpers[valArgIndx]->isImm()) &&
7640 if (argOpers[valArgIndx]->isReg())
7641 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7643 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7645 (*MIB).addOperand(*argOpers[valArgIndx]);
7647 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7650 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7651 for (int i=0; i <= lastAddrIndx; ++i)
7652 (*MIB).addOperand(*argOpers[i]);
7654 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7655 (*MIB).setMemRefs(bInstr->memoperands_begin(),
7656 bInstr->memoperands_end());
7658 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7662 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7664 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7668 // private utility function: 64 bit atomics on 32 bit host.
7670 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7671 MachineBasicBlock *MBB,
7676 bool invSrc) const {
7677 // For the atomic bitwise operator, we generate
7678 // thisMBB (instructions are in pairs, except cmpxchg8b)
7679 // ld t1,t2 = [bitinstr.addr]
7681 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7682 // op t5, t6 <- out1, out2, [bitinstr.val]
7683 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
7684 // mov ECX, EBX <- t5, t6
7685 // mov EAX, EDX <- t1, t2
7686 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
7687 // mov t3, t4 <- EAX, EDX
7689 // result in out1, out2
7690 // fallthrough -->nextMBB
7692 const TargetRegisterClass *RC = X86::GR32RegisterClass;
7693 const unsigned LoadOpc = X86::MOV32rm;
7694 const unsigned copyOpc = X86::MOV32rr;
7695 const unsigned NotOpc = X86::NOT32r;
7696 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7697 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7698 MachineFunction::iterator MBBIter = MBB;
7701 /// First build the CFG
7702 MachineFunction *F = MBB->getParent();
7703 MachineBasicBlock *thisMBB = MBB;
7704 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7705 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7706 F->insert(MBBIter, newMBB);
7707 F->insert(MBBIter, nextMBB);
7709 // Move all successors to thisMBB to nextMBB
7710 nextMBB->transferSuccessors(thisMBB);
7712 // Update thisMBB to fall through to newMBB
7713 thisMBB->addSuccessor(newMBB);
7715 // newMBB jumps to itself and fall through to nextMBB
7716 newMBB->addSuccessor(nextMBB);
7717 newMBB->addSuccessor(newMBB);
7719 DebugLoc dl = bInstr->getDebugLoc();
7720 // Insert instructions into newMBB based on incoming instruction
7721 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7722 assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
7723 "unexpected number of operands");
7724 MachineOperand& dest1Oper = bInstr->getOperand(0);
7725 MachineOperand& dest2Oper = bInstr->getOperand(1);
7726 MachineOperand* argOpers[2 + X86AddrNumOperands];
7727 for (int i=0; i < 2 + X86AddrNumOperands; ++i)
7728 argOpers[i] = &bInstr->getOperand(i+2);
7730 // x86 address has 4 operands: base, index, scale, and displacement
7731 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7733 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7734 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
7735 for (int i=0; i <= lastAddrIndx; ++i)
7736 (*MIB).addOperand(*argOpers[i]);
7737 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7738 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
7739 // add 4 to displacement.
7740 for (int i=0; i <= lastAddrIndx-2; ++i)
7741 (*MIB).addOperand(*argOpers[i]);
7742 MachineOperand newOp3 = *(argOpers[3]);
7744 newOp3.setImm(newOp3.getImm()+4);
7746 newOp3.setOffset(newOp3.getOffset()+4);
7747 (*MIB).addOperand(newOp3);
7748 (*MIB).addOperand(*argOpers[lastAddrIndx]);
7750 // t3/4 are defined later, at the bottom of the loop
7751 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
7752 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
7753 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
7754 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
7755 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
7756 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
7758 unsigned tt1 = F->getRegInfo().createVirtualRegister(RC);
7759 unsigned tt2 = F->getRegInfo().createVirtualRegister(RC);
7761 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt1).addReg(t1);
7762 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt2).addReg(t2);
7768 int valArgIndx = lastAddrIndx + 1;
7769 assert((argOpers[valArgIndx]->isReg() ||
7770 argOpers[valArgIndx]->isImm()) &&
7772 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
7773 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
7774 if (argOpers[valArgIndx]->isReg())
7775 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
7777 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
7778 if (regOpcL != X86::MOV32rr)
7780 (*MIB).addOperand(*argOpers[valArgIndx]);
7781 assert(argOpers[valArgIndx + 1]->isReg() ==
7782 argOpers[valArgIndx]->isReg());
7783 assert(argOpers[valArgIndx + 1]->isImm() ==
7784 argOpers[valArgIndx]->isImm());
7785 if (argOpers[valArgIndx + 1]->isReg())
7786 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
7788 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
7789 if (regOpcH != X86::MOV32rr)
7791 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
7793 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
7795 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
7798 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
7800 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
7803 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
7804 for (int i=0; i <= lastAddrIndx; ++i)
7805 (*MIB).addOperand(*argOpers[i]);
7807 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7808 (*MIB).setMemRefs(bInstr->memoperands_begin(),
7809 bInstr->memoperands_end());
7811 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
7812 MIB.addReg(X86::EAX);
7813 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
7814 MIB.addReg(X86::EDX);
7817 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7819 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7823 // private utility function
7825 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
7826 MachineBasicBlock *MBB,
7827 unsigned cmovOpc) const {
7828 // For the atomic min/max operator, we generate
7831 // ld t1 = [min/max.addr]
7832 // mov t2 = [min/max.val]
7834 // cmov[cond] t2 = t1
7836 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7838 // fallthrough -->nextMBB
7840 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7841 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7842 MachineFunction::iterator MBBIter = MBB;
7845 /// First build the CFG
7846 MachineFunction *F = MBB->getParent();
7847 MachineBasicBlock *thisMBB = MBB;
7848 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7849 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7850 F->insert(MBBIter, newMBB);
7851 F->insert(MBBIter, nextMBB);
7853 // Move all successors of thisMBB to nextMBB
7854 nextMBB->transferSuccessors(thisMBB);
7856 // Update thisMBB to fall through to newMBB
7857 thisMBB->addSuccessor(newMBB);
7859 // newMBB jumps to newMBB and fall through to nextMBB
7860 newMBB->addSuccessor(nextMBB);
7861 newMBB->addSuccessor(newMBB);
7863 DebugLoc dl = mInstr->getDebugLoc();
7864 // Insert instructions into newMBB based on incoming instruction
7865 assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7866 "unexpected number of operands");
7867 MachineOperand& destOper = mInstr->getOperand(0);
7868 MachineOperand* argOpers[2 + X86AddrNumOperands];
7869 int numArgs = mInstr->getNumOperands() - 1;
7870 for (int i=0; i < numArgs; ++i)
7871 argOpers[i] = &mInstr->getOperand(i+1);
7873 // x86 address has 4 operands: base, index, scale, and displacement
7874 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7875 int valArgIndx = lastAddrIndx + 1;
7877 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7878 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
7879 for (int i=0; i <= lastAddrIndx; ++i)
7880 (*MIB).addOperand(*argOpers[i]);
7882 // We only support register and immediate values
7883 assert((argOpers[valArgIndx]->isReg() ||
7884 argOpers[valArgIndx]->isImm()) &&
7887 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7888 if (argOpers[valArgIndx]->isReg())
7889 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7891 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7892 (*MIB).addOperand(*argOpers[valArgIndx]);
7894 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
7897 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
7902 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7903 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
7907 // Cmp and exchange if none has modified the memory location
7908 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
7909 for (int i=0; i <= lastAddrIndx; ++i)
7910 (*MIB).addOperand(*argOpers[i]);
7912 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7913 (*MIB).setMemRefs(mInstr->memoperands_begin(),
7914 mInstr->memoperands_end());
7916 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
7917 MIB.addReg(X86::EAX);
7920 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7922 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
7926 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
7927 // all of this code can be replaced with that in the .td file.
7929 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
7930 unsigned numArgs, bool memArg) const {
7932 MachineFunction *F = BB->getParent();
7933 DebugLoc dl = MI->getDebugLoc();
7934 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7938 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
7940 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
7942 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
7944 for (unsigned i = 0; i < numArgs; ++i) {
7945 MachineOperand &Op = MI->getOperand(i+1);
7947 if (!(Op.isReg() && Op.isImplicit()))
7951 BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
7954 F->DeleteMachineInstr(MI);
7960 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
7962 MachineBasicBlock *MBB) const {
7963 // Emit code to save XMM registers to the stack. The ABI says that the
7964 // number of registers to save is given in %al, so it's theoretically
7965 // possible to do an indirect jump trick to avoid saving all of them,
7966 // however this code takes a simpler approach and just executes all
7967 // of the stores if %al is non-zero. It's less code, and it's probably
7968 // easier on the hardware branch predictor, and stores aren't all that
7969 // expensive anyway.
7971 // Create the new basic blocks. One block contains all the XMM stores,
7972 // and one block is the final destination regardless of whether any
7973 // stores were performed.
7974 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7975 MachineFunction *F = MBB->getParent();
7976 MachineFunction::iterator MBBIter = MBB;
7978 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
7979 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
7980 F->insert(MBBIter, XMMSaveMBB);
7981 F->insert(MBBIter, EndMBB);
7984 // Move any original successors of MBB to the end block.
7985 EndMBB->transferSuccessors(MBB);
7986 // The original block will now fall through to the XMM save block.
7987 MBB->addSuccessor(XMMSaveMBB);
7988 // The XMMSaveMBB will fall through to the end block.
7989 XMMSaveMBB->addSuccessor(EndMBB);
7991 // Now add the instructions.
7992 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7993 DebugLoc DL = MI->getDebugLoc();
7995 unsigned CountReg = MI->getOperand(0).getReg();
7996 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
7997 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
7999 if (!Subtarget->isTargetWin64()) {
8000 // If %al is 0, branch around the XMM save block.
8001 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
8002 BuildMI(MBB, DL, TII->get(X86::JE)).addMBB(EndMBB);
8003 MBB->addSuccessor(EndMBB);
8006 // In the XMM save block, save all the XMM argument registers.
8007 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
8008 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
8009 MachineMemOperand *MMO =
8010 F->getMachineMemOperand(
8011 PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
8012 MachineMemOperand::MOStore, Offset,
8013 /*Size=*/16, /*Align=*/16);
8014 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
8015 .addFrameIndex(RegSaveFrameIndex)
8016 .addImm(/*Scale=*/1)
8017 .addReg(/*IndexReg=*/0)
8018 .addImm(/*Disp=*/Offset)
8019 .addReg(/*Segment=*/0)
8020 .addReg(MI->getOperand(i).getReg())
8021 .addMemOperand(MMO);
8024 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8030 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
8031 MachineBasicBlock *BB,
8032 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8033 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8034 DebugLoc DL = MI->getDebugLoc();
8036 // To "insert" a SELECT_CC instruction, we actually have to insert the
8037 // diamond control-flow pattern. The incoming instruction knows the
8038 // destination vreg to set, the condition code register to branch on, the
8039 // true/false values to select between, and a branch opcode to use.
8040 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8041 MachineFunction::iterator It = BB;
8047 // cmpTY ccX, r1, r2
8049 // fallthrough --> copy0MBB
8050 MachineBasicBlock *thisMBB = BB;
8051 MachineFunction *F = BB->getParent();
8052 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8053 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8055 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
8056 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
8057 F->insert(It, copy0MBB);
8058 F->insert(It, sinkMBB);
8059 // Update machine-CFG edges by first adding all successors of the current
8060 // block to the new block which will contain the Phi node for the select.
8061 // Also inform sdisel of the edge changes.
8062 for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
8063 E = BB->succ_end(); I != E; ++I) {
8064 EM->insert(std::make_pair(*I, sinkMBB));
8065 sinkMBB->addSuccessor(*I);
8067 // Next, remove all successors of the current block, and add the true
8068 // and fallthrough blocks as its successors.
8069 while (!BB->succ_empty())
8070 BB->removeSuccessor(BB->succ_begin());
8071 // Add the true and fallthrough blocks as its successors.
8072 BB->addSuccessor(copy0MBB);
8073 BB->addSuccessor(sinkMBB);
8076 // %FalseValue = ...
8077 // # fallthrough to sinkMBB
8080 // Update machine-CFG edges
8081 BB->addSuccessor(sinkMBB);
8084 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8087 BuildMI(BB, DL, TII->get(X86::PHI), MI->getOperand(0).getReg())
8088 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8089 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8091 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8097 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8098 MachineBasicBlock *BB,
8099 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
8100 switch (MI->getOpcode()) {
8101 default: assert(false && "Unexpected instr type to insert");
8103 case X86::CMOV_V1I64:
8104 case X86::CMOV_FR32:
8105 case X86::CMOV_FR64:
8106 case X86::CMOV_V4F32:
8107 case X86::CMOV_V2F64:
8108 case X86::CMOV_V2I64:
8109 return EmitLoweredSelect(MI, BB, EM);
8111 case X86::FP32_TO_INT16_IN_MEM:
8112 case X86::FP32_TO_INT32_IN_MEM:
8113 case X86::FP32_TO_INT64_IN_MEM:
8114 case X86::FP64_TO_INT16_IN_MEM:
8115 case X86::FP64_TO_INT32_IN_MEM:
8116 case X86::FP64_TO_INT64_IN_MEM:
8117 case X86::FP80_TO_INT16_IN_MEM:
8118 case X86::FP80_TO_INT32_IN_MEM:
8119 case X86::FP80_TO_INT64_IN_MEM: {
8120 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8121 DebugLoc DL = MI->getDebugLoc();
8123 // Change the floating point control register to use "round towards zero"
8124 // mode when truncating to an integer value.
8125 MachineFunction *F = BB->getParent();
8126 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
8127 addFrameReference(BuildMI(BB, DL, TII->get(X86::FNSTCW16m)), CWFrameIdx);
8129 // Load the old value of the high byte of the control word...
8131 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
8132 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16rm), OldCW),
8135 // Set the high part to be round to zero...
8136 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
8139 // Reload the modified control word now...
8140 addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8142 // Restore the memory image of control word to original value
8143 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
8146 // Get the X86 opcode to use.
8148 switch (MI->getOpcode()) {
8149 default: llvm_unreachable("illegal opcode!");
8150 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
8151 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
8152 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
8153 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
8154 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
8155 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
8156 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
8157 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
8158 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
8162 MachineOperand &Op = MI->getOperand(0);
8164 AM.BaseType = X86AddressMode::RegBase;
8165 AM.Base.Reg = Op.getReg();
8167 AM.BaseType = X86AddressMode::FrameIndexBase;
8168 AM.Base.FrameIndex = Op.getIndex();
8170 Op = MI->getOperand(1);
8172 AM.Scale = Op.getImm();
8173 Op = MI->getOperand(2);
8175 AM.IndexReg = Op.getImm();
8176 Op = MI->getOperand(3);
8177 if (Op.isGlobal()) {
8178 AM.GV = Op.getGlobal();
8180 AM.Disp = Op.getImm();
8182 addFullAddress(BuildMI(BB, DL, TII->get(Opc)), AM)
8183 .addReg(MI->getOperand(X86AddrNumOperands).getReg());
8185 // Reload the original control word now.
8186 addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8188 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8191 // String/text processing lowering.
8192 case X86::PCMPISTRM128REG:
8193 return EmitPCMP(MI, BB, 3, false /* in-mem */);
8194 case X86::PCMPISTRM128MEM:
8195 return EmitPCMP(MI, BB, 3, true /* in-mem */);
8196 case X86::PCMPESTRM128REG:
8197 return EmitPCMP(MI, BB, 5, false /* in mem */);
8198 case X86::PCMPESTRM128MEM:
8199 return EmitPCMP(MI, BB, 5, true /* in mem */);
8202 case X86::ATOMAND32:
8203 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8204 X86::AND32ri, X86::MOV32rm,
8205 X86::LCMPXCHG32, X86::MOV32rr,
8206 X86::NOT32r, X86::EAX,
8207 X86::GR32RegisterClass);
8209 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
8210 X86::OR32ri, X86::MOV32rm,
8211 X86::LCMPXCHG32, X86::MOV32rr,
8212 X86::NOT32r, X86::EAX,
8213 X86::GR32RegisterClass);
8214 case X86::ATOMXOR32:
8215 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
8216 X86::XOR32ri, X86::MOV32rm,
8217 X86::LCMPXCHG32, X86::MOV32rr,
8218 X86::NOT32r, X86::EAX,
8219 X86::GR32RegisterClass);
8220 case X86::ATOMNAND32:
8221 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8222 X86::AND32ri, X86::MOV32rm,
8223 X86::LCMPXCHG32, X86::MOV32rr,
8224 X86::NOT32r, X86::EAX,
8225 X86::GR32RegisterClass, true);
8226 case X86::ATOMMIN32:
8227 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
8228 case X86::ATOMMAX32:
8229 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
8230 case X86::ATOMUMIN32:
8231 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
8232 case X86::ATOMUMAX32:
8233 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
8235 case X86::ATOMAND16:
8236 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8237 X86::AND16ri, X86::MOV16rm,
8238 X86::LCMPXCHG16, X86::MOV16rr,
8239 X86::NOT16r, X86::AX,
8240 X86::GR16RegisterClass);
8242 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
8243 X86::OR16ri, X86::MOV16rm,
8244 X86::LCMPXCHG16, X86::MOV16rr,
8245 X86::NOT16r, X86::AX,
8246 X86::GR16RegisterClass);
8247 case X86::ATOMXOR16:
8248 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
8249 X86::XOR16ri, X86::MOV16rm,
8250 X86::LCMPXCHG16, X86::MOV16rr,
8251 X86::NOT16r, X86::AX,
8252 X86::GR16RegisterClass);
8253 case X86::ATOMNAND16:
8254 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8255 X86::AND16ri, X86::MOV16rm,
8256 X86::LCMPXCHG16, X86::MOV16rr,
8257 X86::NOT16r, X86::AX,
8258 X86::GR16RegisterClass, true);
8259 case X86::ATOMMIN16:
8260 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
8261 case X86::ATOMMAX16:
8262 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
8263 case X86::ATOMUMIN16:
8264 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
8265 case X86::ATOMUMAX16:
8266 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
8269 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8270 X86::AND8ri, X86::MOV8rm,
8271 X86::LCMPXCHG8, X86::MOV8rr,
8272 X86::NOT8r, X86::AL,
8273 X86::GR8RegisterClass);
8275 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
8276 X86::OR8ri, X86::MOV8rm,
8277 X86::LCMPXCHG8, X86::MOV8rr,
8278 X86::NOT8r, X86::AL,
8279 X86::GR8RegisterClass);
8281 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
8282 X86::XOR8ri, X86::MOV8rm,
8283 X86::LCMPXCHG8, X86::MOV8rr,
8284 X86::NOT8r, X86::AL,
8285 X86::GR8RegisterClass);
8286 case X86::ATOMNAND8:
8287 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8288 X86::AND8ri, X86::MOV8rm,
8289 X86::LCMPXCHG8, X86::MOV8rr,
8290 X86::NOT8r, X86::AL,
8291 X86::GR8RegisterClass, true);
8292 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
8293 // This group is for 64-bit host.
8294 case X86::ATOMAND64:
8295 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8296 X86::AND64ri32, X86::MOV64rm,
8297 X86::LCMPXCHG64, X86::MOV64rr,
8298 X86::NOT64r, X86::RAX,
8299 X86::GR64RegisterClass);
8301 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
8302 X86::OR64ri32, X86::MOV64rm,
8303 X86::LCMPXCHG64, X86::MOV64rr,
8304 X86::NOT64r, X86::RAX,
8305 X86::GR64RegisterClass);
8306 case X86::ATOMXOR64:
8307 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
8308 X86::XOR64ri32, X86::MOV64rm,
8309 X86::LCMPXCHG64, X86::MOV64rr,
8310 X86::NOT64r, X86::RAX,
8311 X86::GR64RegisterClass);
8312 case X86::ATOMNAND64:
8313 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8314 X86::AND64ri32, X86::MOV64rm,
8315 X86::LCMPXCHG64, X86::MOV64rr,
8316 X86::NOT64r, X86::RAX,
8317 X86::GR64RegisterClass, true);
8318 case X86::ATOMMIN64:
8319 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
8320 case X86::ATOMMAX64:
8321 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
8322 case X86::ATOMUMIN64:
8323 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
8324 case X86::ATOMUMAX64:
8325 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
8327 // This group does 64-bit operations on a 32-bit host.
8328 case X86::ATOMAND6432:
8329 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8330 X86::AND32rr, X86::AND32rr,
8331 X86::AND32ri, X86::AND32ri,
8333 case X86::ATOMOR6432:
8334 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8335 X86::OR32rr, X86::OR32rr,
8336 X86::OR32ri, X86::OR32ri,
8338 case X86::ATOMXOR6432:
8339 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8340 X86::XOR32rr, X86::XOR32rr,
8341 X86::XOR32ri, X86::XOR32ri,
8343 case X86::ATOMNAND6432:
8344 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8345 X86::AND32rr, X86::AND32rr,
8346 X86::AND32ri, X86::AND32ri,
8348 case X86::ATOMADD6432:
8349 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8350 X86::ADD32rr, X86::ADC32rr,
8351 X86::ADD32ri, X86::ADC32ri,
8353 case X86::ATOMSUB6432:
8354 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8355 X86::SUB32rr, X86::SBB32rr,
8356 X86::SUB32ri, X86::SBB32ri,
8358 case X86::ATOMSWAP6432:
8359 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8360 X86::MOV32rr, X86::MOV32rr,
8361 X86::MOV32ri, X86::MOV32ri,
8363 case X86::VASTART_SAVE_XMM_REGS:
8364 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
8368 //===----------------------------------------------------------------------===//
8369 // X86 Optimization Hooks
8370 //===----------------------------------------------------------------------===//
8372 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8376 const SelectionDAG &DAG,
8377 unsigned Depth) const {
8378 unsigned Opc = Op.getOpcode();
8379 assert((Opc >= ISD::BUILTIN_OP_END ||
8380 Opc == ISD::INTRINSIC_WO_CHAIN ||
8381 Opc == ISD::INTRINSIC_W_CHAIN ||
8382 Opc == ISD::INTRINSIC_VOID) &&
8383 "Should use MaskedValueIsZero if you don't know whether Op"
8384 " is a target node!");
8386 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
8398 // These nodes' second result is a boolean.
8399 if (Op.getResNo() == 0)
8403 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
8404 Mask.getBitWidth() - 1);
8409 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
8410 /// node is a GlobalAddress + offset.
8411 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
8412 GlobalValue* &GA, int64_t &Offset) const{
8413 if (N->getOpcode() == X86ISD::Wrapper) {
8414 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
8415 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
8416 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
8420 return TargetLowering::isGAPlusOffset(N, GA, Offset);
8423 static bool EltsFromConsecutiveLoads(ShuffleVectorSDNode *N, unsigned NumElems,
8424 EVT EltVT, LoadSDNode *&LDBase,
8425 unsigned &LastLoadedElt,
8426 SelectionDAG &DAG, MachineFrameInfo *MFI,
8427 const TargetLowering &TLI) {
8429 LastLoadedElt = -1U;
8430 for (unsigned i = 0; i < NumElems; ++i) {
8431 if (N->getMaskElt(i) < 0) {
8437 SDValue Elt = DAG.getShuffleScalarElt(N, i);
8438 if (!Elt.getNode() ||
8439 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
8442 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
8444 LDBase = cast<LoadSDNode>(Elt.getNode());
8448 if (Elt.getOpcode() == ISD::UNDEF)
8451 LoadSDNode *LD = cast<LoadSDNode>(Elt);
8452 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
8459 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8460 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8461 /// if the load addresses are consecutive, non-overlapping, and in the right
8462 /// order. In the case of v2i64, it will see if it can rewrite the
8463 /// shuffle to be an appropriate build vector so it can take advantage of
8464 // performBuildVectorCombine.
8465 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8466 const TargetLowering &TLI) {
8467 DebugLoc dl = N->getDebugLoc();
8468 EVT VT = N->getValueType(0);
8469 EVT EltVT = VT.getVectorElementType();
8470 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8471 unsigned NumElems = VT.getVectorNumElements();
8473 if (VT.getSizeInBits() != 128)
8476 // Try to combine a vector_shuffle into a 128-bit load.
8477 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8478 LoadSDNode *LD = NULL;
8479 unsigned LastLoadedElt;
8480 if (!EltsFromConsecutiveLoads(SVN, NumElems, EltVT, LD, LastLoadedElt, DAG,
8484 if (LastLoadedElt == NumElems - 1) {
8485 if (DAG.InferPtrAlignment(LD->getBasePtr()) >= 16)
8486 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8487 LD->getSrcValue(), LD->getSrcValueOffset(),
8489 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8490 LD->getSrcValue(), LD->getSrcValueOffset(),
8491 LD->isVolatile(), LD->getAlignment());
8492 } else if (NumElems == 4 && LastLoadedElt == 1) {
8493 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
8494 SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
8495 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
8496 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
8501 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
8502 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
8503 const X86Subtarget *Subtarget) {
8504 DebugLoc DL = N->getDebugLoc();
8505 SDValue Cond = N->getOperand(0);
8506 // Get the LHS/RHS of the select.
8507 SDValue LHS = N->getOperand(1);
8508 SDValue RHS = N->getOperand(2);
8510 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
8511 // instructions have the peculiarity that if either operand is a NaN,
8512 // they chose what we call the RHS operand (and as such are not symmetric).
8513 // It happens that this matches the semantics of the common C idiom
8514 // x<y?x:y and related forms, so we can recognize these cases.
8515 if (Subtarget->hasSSE2() &&
8516 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
8517 Cond.getOpcode() == ISD::SETCC) {
8518 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
8520 unsigned Opcode = 0;
8521 // Check for x CC y ? x : y.
8522 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
8526 // This can be a min if we can prove that at least one of the operands
8528 if (!FiniteOnlyFPMath()) {
8529 if (DAG.isKnownNeverNaN(RHS)) {
8530 // Put the potential NaN in the RHS so that SSE will preserve it.
8531 std::swap(LHS, RHS);
8532 } else if (!DAG.isKnownNeverNaN(LHS))
8535 Opcode = X86ISD::FMIN;
8538 // This can be a min if we can prove that at least one of the operands
8540 if (!FiniteOnlyFPMath()) {
8541 if (DAG.isKnownNeverNaN(LHS)) {
8542 // Put the potential NaN in the RHS so that SSE will preserve it.
8543 std::swap(LHS, RHS);
8544 } else if (!DAG.isKnownNeverNaN(RHS))
8547 Opcode = X86ISD::FMIN;
8550 // This can be a min, but if either operand is a NaN we need it to
8551 // preserve the original LHS.
8552 std::swap(LHS, RHS);
8556 Opcode = X86ISD::FMIN;
8560 // This can be a max if we can prove that at least one of the operands
8562 if (!FiniteOnlyFPMath()) {
8563 if (DAG.isKnownNeverNaN(LHS)) {
8564 // Put the potential NaN in the RHS so that SSE will preserve it.
8565 std::swap(LHS, RHS);
8566 } else if (!DAG.isKnownNeverNaN(RHS))
8569 Opcode = X86ISD::FMAX;
8572 // This can be a max if we can prove that at least one of the operands
8574 if (!FiniteOnlyFPMath()) {
8575 if (DAG.isKnownNeverNaN(RHS)) {
8576 // Put the potential NaN in the RHS so that SSE will preserve it.
8577 std::swap(LHS, RHS);
8578 } else if (!DAG.isKnownNeverNaN(LHS))
8581 Opcode = X86ISD::FMAX;
8584 // This can be a max, but if either operand is a NaN we need it to
8585 // preserve the original LHS.
8586 std::swap(LHS, RHS);
8590 Opcode = X86ISD::FMAX;
8593 // Check for x CC y ? y : x -- a min/max with reversed arms.
8594 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
8598 // This can be a min if we can prove that at least one of the operands
8600 if (!FiniteOnlyFPMath()) {
8601 if (DAG.isKnownNeverNaN(RHS)) {
8602 // Put the potential NaN in the RHS so that SSE will preserve it.
8603 std::swap(LHS, RHS);
8604 } else if (!DAG.isKnownNeverNaN(LHS))
8607 Opcode = X86ISD::FMIN;
8610 // This can be a min if we can prove that at least one of the operands
8612 if (!FiniteOnlyFPMath()) {
8613 if (DAG.isKnownNeverNaN(LHS)) {
8614 // Put the potential NaN in the RHS so that SSE will preserve it.
8615 std::swap(LHS, RHS);
8616 } else if (!DAG.isKnownNeverNaN(RHS))
8619 Opcode = X86ISD::FMIN;
8622 // This can be a min, but if either operand is a NaN we need it to
8623 // preserve the original LHS.
8624 std::swap(LHS, RHS);
8628 Opcode = X86ISD::FMIN;
8632 // This can be a max if we can prove that at least one of the operands
8634 if (!FiniteOnlyFPMath()) {
8635 if (DAG.isKnownNeverNaN(LHS)) {
8636 // Put the potential NaN in the RHS so that SSE will preserve it.
8637 std::swap(LHS, RHS);
8638 } else if (!DAG.isKnownNeverNaN(RHS))
8641 Opcode = X86ISD::FMAX;
8644 // This can be a max if we can prove that at least one of the operands
8646 if (!FiniteOnlyFPMath()) {
8647 if (DAG.isKnownNeverNaN(RHS)) {
8648 // Put the potential NaN in the RHS so that SSE will preserve it.
8649 std::swap(LHS, RHS);
8650 } else if (!DAG.isKnownNeverNaN(LHS))
8653 Opcode = X86ISD::FMAX;
8656 // This can be a max, but if either operand is a NaN we need it to
8657 // preserve the original LHS.
8658 std::swap(LHS, RHS);
8662 Opcode = X86ISD::FMAX;
8668 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
8671 // If this is a select between two integer constants, try to do some
8673 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
8674 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
8675 // Don't do this for crazy integer types.
8676 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
8677 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
8678 // so that TrueC (the true value) is larger than FalseC.
8679 bool NeedsCondInvert = false;
8681 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
8682 // Efficiently invertible.
8683 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
8684 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
8685 isa<ConstantSDNode>(Cond.getOperand(1))))) {
8686 NeedsCondInvert = true;
8687 std::swap(TrueC, FalseC);
8690 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
8691 if (FalseC->getAPIntValue() == 0 &&
8692 TrueC->getAPIntValue().isPowerOf2()) {
8693 if (NeedsCondInvert) // Invert the condition if needed.
8694 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8695 DAG.getConstant(1, Cond.getValueType()));
8697 // Zero extend the condition if needed.
8698 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
8700 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8701 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
8702 DAG.getConstant(ShAmt, MVT::i8));
8705 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
8706 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8707 if (NeedsCondInvert) // Invert the condition if needed.
8708 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8709 DAG.getConstant(1, Cond.getValueType()));
8711 // Zero extend the condition if needed.
8712 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8713 FalseC->getValueType(0), Cond);
8714 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8715 SDValue(FalseC, 0));
8718 // Optimize cases that will turn into an LEA instruction. This requires
8719 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8720 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8721 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8722 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8724 bool isFastMultiplier = false;
8726 switch ((unsigned char)Diff) {
8728 case 1: // result = add base, cond
8729 case 2: // result = lea base( , cond*2)
8730 case 3: // result = lea base(cond, cond*2)
8731 case 4: // result = lea base( , cond*4)
8732 case 5: // result = lea base(cond, cond*4)
8733 case 8: // result = lea base( , cond*8)
8734 case 9: // result = lea base(cond, cond*8)
8735 isFastMultiplier = true;
8740 if (isFastMultiplier) {
8741 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8742 if (NeedsCondInvert) // Invert the condition if needed.
8743 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8744 DAG.getConstant(1, Cond.getValueType()));
8746 // Zero extend the condition if needed.
8747 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8749 // Scale the condition by the difference.
8751 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8752 DAG.getConstant(Diff, Cond.getValueType()));
8754 // Add the base if non-zero.
8755 if (FalseC->getAPIntValue() != 0)
8756 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8757 SDValue(FalseC, 0));
8767 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
8768 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
8769 TargetLowering::DAGCombinerInfo &DCI) {
8770 DebugLoc DL = N->getDebugLoc();
8772 // If the flag operand isn't dead, don't touch this CMOV.
8773 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
8776 // If this is a select between two integer constants, try to do some
8777 // optimizations. Note that the operands are ordered the opposite of SELECT
8779 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
8780 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8781 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
8782 // larger than FalseC (the false value).
8783 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
8785 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
8786 CC = X86::GetOppositeBranchCondition(CC);
8787 std::swap(TrueC, FalseC);
8790 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
8791 // This is efficient for any integer data type (including i8/i16) and
8793 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
8794 SDValue Cond = N->getOperand(3);
8795 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8796 DAG.getConstant(CC, MVT::i8), Cond);
8798 // Zero extend the condition if needed.
8799 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
8801 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8802 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
8803 DAG.getConstant(ShAmt, MVT::i8));
8804 if (N->getNumValues() == 2) // Dead flag value?
8805 return DCI.CombineTo(N, Cond, SDValue());
8809 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
8810 // for any integer data type, including i8/i16.
8811 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8812 SDValue Cond = N->getOperand(3);
8813 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8814 DAG.getConstant(CC, MVT::i8), Cond);
8816 // Zero extend the condition if needed.
8817 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8818 FalseC->getValueType(0), Cond);
8819 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8820 SDValue(FalseC, 0));
8822 if (N->getNumValues() == 2) // Dead flag value?
8823 return DCI.CombineTo(N, Cond, SDValue());
8827 // Optimize cases that will turn into an LEA instruction. This requires
8828 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8829 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8830 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8831 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8833 bool isFastMultiplier = false;
8835 switch ((unsigned char)Diff) {
8837 case 1: // result = add base, cond
8838 case 2: // result = lea base( , cond*2)
8839 case 3: // result = lea base(cond, cond*2)
8840 case 4: // result = lea base( , cond*4)
8841 case 5: // result = lea base(cond, cond*4)
8842 case 8: // result = lea base( , cond*8)
8843 case 9: // result = lea base(cond, cond*8)
8844 isFastMultiplier = true;
8849 if (isFastMultiplier) {
8850 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8851 SDValue Cond = N->getOperand(3);
8852 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8853 DAG.getConstant(CC, MVT::i8), Cond);
8854 // Zero extend the condition if needed.
8855 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8857 // Scale the condition by the difference.
8859 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8860 DAG.getConstant(Diff, Cond.getValueType()));
8862 // Add the base if non-zero.
8863 if (FalseC->getAPIntValue() != 0)
8864 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8865 SDValue(FalseC, 0));
8866 if (N->getNumValues() == 2) // Dead flag value?
8867 return DCI.CombineTo(N, Cond, SDValue());
8877 /// PerformMulCombine - Optimize a single multiply with constant into two
8878 /// in order to implement it with two cheaper instructions, e.g.
8879 /// LEA + SHL, LEA + LEA.
8880 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
8881 TargetLowering::DAGCombinerInfo &DCI) {
8882 if (DAG.getMachineFunction().
8883 getFunction()->hasFnAttr(Attribute::OptimizeForSize))
8886 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8889 EVT VT = N->getValueType(0);
8893 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8896 uint64_t MulAmt = C->getZExtValue();
8897 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
8900 uint64_t MulAmt1 = 0;
8901 uint64_t MulAmt2 = 0;
8902 if ((MulAmt % 9) == 0) {
8904 MulAmt2 = MulAmt / 9;
8905 } else if ((MulAmt % 5) == 0) {
8907 MulAmt2 = MulAmt / 5;
8908 } else if ((MulAmt % 3) == 0) {
8910 MulAmt2 = MulAmt / 3;
8913 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
8914 DebugLoc DL = N->getDebugLoc();
8916 if (isPowerOf2_64(MulAmt2) &&
8917 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
8918 // If second multiplifer is pow2, issue it first. We want the multiply by
8919 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
8921 std::swap(MulAmt1, MulAmt2);
8924 if (isPowerOf2_64(MulAmt1))
8925 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
8926 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
8928 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
8929 DAG.getConstant(MulAmt1, VT));
8931 if (isPowerOf2_64(MulAmt2))
8932 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
8933 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
8935 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
8936 DAG.getConstant(MulAmt2, VT));
8938 // Do not add new nodes to DAG combiner worklist.
8939 DCI.CombineTo(N, NewMul, false);
8945 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
8947 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
8948 const X86Subtarget *Subtarget) {
8949 // On X86 with SSE2 support, we can transform this to a vector shift if
8950 // all elements are shifted by the same amount. We can't do this in legalize
8951 // because the a constant vector is typically transformed to a constant pool
8952 // so we have no knowledge of the shift amount.
8953 if (!Subtarget->hasSSE2())
8956 EVT VT = N->getValueType(0);
8957 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
8960 SDValue ShAmtOp = N->getOperand(1);
8961 EVT EltVT = VT.getVectorElementType();
8962 DebugLoc DL = N->getDebugLoc();
8963 SDValue BaseShAmt = SDValue();
8964 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
8965 unsigned NumElts = VT.getVectorNumElements();
8967 for (; i != NumElts; ++i) {
8968 SDValue Arg = ShAmtOp.getOperand(i);
8969 if (Arg.getOpcode() == ISD::UNDEF) continue;
8973 for (; i != NumElts; ++i) {
8974 SDValue Arg = ShAmtOp.getOperand(i);
8975 if (Arg.getOpcode() == ISD::UNDEF) continue;
8976 if (Arg != BaseShAmt) {
8980 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
8981 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
8982 SDValue InVec = ShAmtOp.getOperand(0);
8983 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
8984 unsigned NumElts = InVec.getValueType().getVectorNumElements();
8986 for (; i != NumElts; ++i) {
8987 SDValue Arg = InVec.getOperand(i);
8988 if (Arg.getOpcode() == ISD::UNDEF) continue;
8992 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
8993 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
8994 unsigned SplatIdx = cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
8995 if (C->getZExtValue() == SplatIdx)
8996 BaseShAmt = InVec.getOperand(1);
8999 if (BaseShAmt.getNode() == 0)
9000 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
9001 DAG.getIntPtrConstant(0));
9005 // The shift amount is an i32.
9006 if (EltVT.bitsGT(MVT::i32))
9007 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
9008 else if (EltVT.bitsLT(MVT::i32))
9009 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
9011 // The shift amount is identical so we can do a vector shift.
9012 SDValue ValOp = N->getOperand(0);
9013 switch (N->getOpcode()) {
9015 llvm_unreachable("Unknown shift opcode!");
9018 if (VT == MVT::v2i64)
9019 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9020 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9022 if (VT == MVT::v4i32)
9023 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9024 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9026 if (VT == MVT::v8i16)
9027 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9028 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9032 if (VT == MVT::v4i32)
9033 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9034 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9036 if (VT == MVT::v8i16)
9037 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9038 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9042 if (VT == MVT::v2i64)
9043 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9044 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9046 if (VT == MVT::v4i32)
9047 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9048 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9050 if (VT == MVT::v8i16)
9051 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9052 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9059 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
9060 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
9061 const X86Subtarget *Subtarget) {
9062 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
9063 // the FP state in cases where an emms may be missing.
9064 // A preferable solution to the general problem is to figure out the right
9065 // places to insert EMMS. This qualifies as a quick hack.
9067 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
9068 StoreSDNode *St = cast<StoreSDNode>(N);
9069 EVT VT = St->getValue().getValueType();
9070 if (VT.getSizeInBits() != 64)
9073 const Function *F = DAG.getMachineFunction().getFunction();
9074 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
9075 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
9076 && Subtarget->hasSSE2();
9077 if ((VT.isVector() ||
9078 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
9079 isa<LoadSDNode>(St->getValue()) &&
9080 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
9081 St->getChain().hasOneUse() && !St->isVolatile()) {
9082 SDNode* LdVal = St->getValue().getNode();
9084 int TokenFactorIndex = -1;
9085 SmallVector<SDValue, 8> Ops;
9086 SDNode* ChainVal = St->getChain().getNode();
9087 // Must be a store of a load. We currently handle two cases: the load
9088 // is a direct child, and it's under an intervening TokenFactor. It is
9089 // possible to dig deeper under nested TokenFactors.
9090 if (ChainVal == LdVal)
9091 Ld = cast<LoadSDNode>(St->getChain());
9092 else if (St->getValue().hasOneUse() &&
9093 ChainVal->getOpcode() == ISD::TokenFactor) {
9094 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
9095 if (ChainVal->getOperand(i).getNode() == LdVal) {
9096 TokenFactorIndex = i;
9097 Ld = cast<LoadSDNode>(St->getValue());
9099 Ops.push_back(ChainVal->getOperand(i));
9103 if (!Ld || !ISD::isNormalLoad(Ld))
9106 // If this is not the MMX case, i.e. we are just turning i64 load/store
9107 // into f64 load/store, avoid the transformation if there are multiple
9108 // uses of the loaded value.
9109 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
9112 DebugLoc LdDL = Ld->getDebugLoc();
9113 DebugLoc StDL = N->getDebugLoc();
9114 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
9115 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
9117 if (Subtarget->is64Bit() || F64IsLegal) {
9118 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
9119 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
9120 Ld->getBasePtr(), Ld->getSrcValue(),
9121 Ld->getSrcValueOffset(), Ld->isVolatile(),
9122 Ld->getAlignment());
9123 SDValue NewChain = NewLd.getValue(1);
9124 if (TokenFactorIndex != -1) {
9125 Ops.push_back(NewChain);
9126 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9129 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
9130 St->getSrcValue(), St->getSrcValueOffset(),
9131 St->isVolatile(), St->getAlignment());
9134 // Otherwise, lower to two pairs of 32-bit loads / stores.
9135 SDValue LoAddr = Ld->getBasePtr();
9136 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
9137 DAG.getConstant(4, MVT::i32));
9139 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
9140 Ld->getSrcValue(), Ld->getSrcValueOffset(),
9141 Ld->isVolatile(), Ld->getAlignment());
9142 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
9143 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
9145 MinAlign(Ld->getAlignment(), 4));
9147 SDValue NewChain = LoLd.getValue(1);
9148 if (TokenFactorIndex != -1) {
9149 Ops.push_back(LoLd);
9150 Ops.push_back(HiLd);
9151 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9155 LoAddr = St->getBasePtr();
9156 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
9157 DAG.getConstant(4, MVT::i32));
9159 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
9160 St->getSrcValue(), St->getSrcValueOffset(),
9161 St->isVolatile(), St->getAlignment());
9162 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
9164 St->getSrcValueOffset() + 4,
9166 MinAlign(St->getAlignment(), 4));
9167 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
9172 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
9173 /// X86ISD::FXOR nodes.
9174 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
9175 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
9176 // F[X]OR(0.0, x) -> x
9177 // F[X]OR(x, 0.0) -> x
9178 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9179 if (C->getValueAPF().isPosZero())
9180 return N->getOperand(1);
9181 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9182 if (C->getValueAPF().isPosZero())
9183 return N->getOperand(0);
9187 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
9188 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
9189 // FAND(0.0, x) -> 0.0
9190 // FAND(x, 0.0) -> 0.0
9191 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9192 if (C->getValueAPF().isPosZero())
9193 return N->getOperand(0);
9194 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9195 if (C->getValueAPF().isPosZero())
9196 return N->getOperand(1);
9200 static SDValue PerformBTCombine(SDNode *N,
9202 TargetLowering::DAGCombinerInfo &DCI) {
9203 // BT ignores high bits in the bit index operand.
9204 SDValue Op1 = N->getOperand(1);
9205 if (Op1.hasOneUse()) {
9206 unsigned BitWidth = Op1.getValueSizeInBits();
9207 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
9208 APInt KnownZero, KnownOne;
9209 TargetLowering::TargetLoweringOpt TLO(DAG);
9210 TargetLowering &TLI = DAG.getTargetLoweringInfo();
9211 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
9212 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
9213 DCI.CommitTargetLoweringOpt(TLO);
9218 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
9219 SDValue Op = N->getOperand(0);
9220 if (Op.getOpcode() == ISD::BIT_CONVERT)
9221 Op = Op.getOperand(0);
9222 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
9223 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
9224 VT.getVectorElementType().getSizeInBits() ==
9225 OpVT.getVectorElementType().getSizeInBits()) {
9226 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
9231 // On X86 and X86-64, atomic operations are lowered to locked instructions.
9232 // Locked instructions, in turn, have implicit fence semantics (all memory
9233 // operations are flushed before issuing the locked instruction, and the
9234 // are not buffered), so we can fold away the common pattern of
9235 // fence-atomic-fence.
9236 static SDValue PerformMEMBARRIERCombine(SDNode* N, SelectionDAG &DAG) {
9237 SDValue atomic = N->getOperand(0);
9238 switch (atomic.getOpcode()) {
9239 case ISD::ATOMIC_CMP_SWAP:
9240 case ISD::ATOMIC_SWAP:
9241 case ISD::ATOMIC_LOAD_ADD:
9242 case ISD::ATOMIC_LOAD_SUB:
9243 case ISD::ATOMIC_LOAD_AND:
9244 case ISD::ATOMIC_LOAD_OR:
9245 case ISD::ATOMIC_LOAD_XOR:
9246 case ISD::ATOMIC_LOAD_NAND:
9247 case ISD::ATOMIC_LOAD_MIN:
9248 case ISD::ATOMIC_LOAD_MAX:
9249 case ISD::ATOMIC_LOAD_UMIN:
9250 case ISD::ATOMIC_LOAD_UMAX:
9256 SDValue fence = atomic.getOperand(0);
9257 if (fence.getOpcode() != ISD::MEMBARRIER)
9260 switch (atomic.getOpcode()) {
9261 case ISD::ATOMIC_CMP_SWAP:
9262 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9263 atomic.getOperand(1), atomic.getOperand(2),
9264 atomic.getOperand(3));
9265 case ISD::ATOMIC_SWAP:
9266 case ISD::ATOMIC_LOAD_ADD:
9267 case ISD::ATOMIC_LOAD_SUB:
9268 case ISD::ATOMIC_LOAD_AND:
9269 case ISD::ATOMIC_LOAD_OR:
9270 case ISD::ATOMIC_LOAD_XOR:
9271 case ISD::ATOMIC_LOAD_NAND:
9272 case ISD::ATOMIC_LOAD_MIN:
9273 case ISD::ATOMIC_LOAD_MAX:
9274 case ISD::ATOMIC_LOAD_UMIN:
9275 case ISD::ATOMIC_LOAD_UMAX:
9276 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9277 atomic.getOperand(1), atomic.getOperand(2));
9283 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
9284 DAGCombinerInfo &DCI) const {
9285 SelectionDAG &DAG = DCI.DAG;
9286 switch (N->getOpcode()) {
9288 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
9289 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
9290 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
9291 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
9294 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
9295 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
9297 case X86ISD::FOR: return PerformFORCombine(N, DAG);
9298 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
9299 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
9300 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
9301 case ISD::MEMBARRIER: return PerformMEMBARRIERCombine(N, DAG);
9307 //===----------------------------------------------------------------------===//
9308 // X86 Inline Assembly Support
9309 //===----------------------------------------------------------------------===//
9311 static bool LowerToBSwap(CallInst *CI) {
9312 // FIXME: this should verify that we are targetting a 486 or better. If not,
9313 // we will turn this bswap into something that will be lowered to logical ops
9314 // instead of emitting the bswap asm. For now, we don't support 486 or lower
9315 // so don't worry about this.
9317 // Verify this is a simple bswap.
9318 if (CI->getNumOperands() != 2 ||
9319 CI->getType() != CI->getOperand(1)->getType() ||
9320 !CI->getType()->isInteger())
9323 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9324 if (!Ty || Ty->getBitWidth() % 16 != 0)
9327 // Okay, we can do this xform, do so now.
9328 const Type *Tys[] = { Ty };
9329 Module *M = CI->getParent()->getParent()->getParent();
9330 Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
9332 Value *Op = CI->getOperand(1);
9333 Op = CallInst::Create(Int, Op, CI->getName(), CI);
9335 CI->replaceAllUsesWith(Op);
9336 CI->eraseFromParent();
9340 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
9341 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9342 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
9344 std::string AsmStr = IA->getAsmString();
9346 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
9347 std::vector<std::string> AsmPieces;
9348 SplitString(AsmStr, AsmPieces, "\n"); // ; as separator?
9350 switch (AsmPieces.size()) {
9351 default: return false;
9353 AsmStr = AsmPieces[0];
9355 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
9358 if (AsmPieces.size() == 2 &&
9359 (AsmPieces[0] == "bswap" ||
9360 AsmPieces[0] == "bswapq" ||
9361 AsmPieces[0] == "bswapl") &&
9362 (AsmPieces[1] == "$0" ||
9363 AsmPieces[1] == "${0:q}")) {
9364 // No need to check constraints, nothing other than the equivalent of
9365 // "=r,0" would be valid here.
9366 return LowerToBSwap(CI);
9368 // rorw $$8, ${0:w} --> llvm.bswap.i16
9369 if (CI->getType() == Type::getInt16Ty(CI->getContext()) &&
9370 AsmPieces.size() == 3 &&
9371 AsmPieces[0] == "rorw" &&
9372 AsmPieces[1] == "$$8," &&
9373 AsmPieces[2] == "${0:w}" &&
9374 IA->getConstraintString() == "=r,0,~{dirflag},~{fpsr},~{flags},~{cc}") {
9375 return LowerToBSwap(CI);
9379 if (CI->getType() == Type::getInt64Ty(CI->getContext()) &&
9380 Constraints.size() >= 2 &&
9381 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
9382 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
9383 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
9384 std::vector<std::string> Words;
9385 SplitString(AsmPieces[0], Words, " \t");
9386 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
9388 SplitString(AsmPieces[1], Words, " \t");
9389 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
9391 SplitString(AsmPieces[2], Words, " \t,");
9392 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
9393 Words[2] == "%edx") {
9394 return LowerToBSwap(CI);
9406 /// getConstraintType - Given a constraint letter, return the type of
9407 /// constraint it is for this target.
9408 X86TargetLowering::ConstraintType
9409 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
9410 if (Constraint.size() == 1) {
9411 switch (Constraint[0]) {
9423 return C_RegisterClass;
9431 return TargetLowering::getConstraintType(Constraint);
9434 /// LowerXConstraint - try to replace an X constraint, which matches anything,
9435 /// with another that has more specific requirements based on the type of the
9436 /// corresponding operand.
9437 const char *X86TargetLowering::
9438 LowerXConstraint(EVT ConstraintVT) const {
9439 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
9440 // 'f' like normal targets.
9441 if (ConstraintVT.isFloatingPoint()) {
9442 if (Subtarget->hasSSE2())
9444 if (Subtarget->hasSSE1())
9448 return TargetLowering::LowerXConstraint(ConstraintVT);
9451 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9452 /// vector. If it is invalid, don't add anything to Ops.
9453 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9456 std::vector<SDValue>&Ops,
9457 SelectionDAG &DAG) const {
9458 SDValue Result(0, 0);
9460 switch (Constraint) {
9463 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9464 if (C->getZExtValue() <= 31) {
9465 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9471 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9472 if (C->getZExtValue() <= 63) {
9473 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9479 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9480 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
9481 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9487 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9488 if (C->getZExtValue() <= 255) {
9489 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9495 // 32-bit signed value
9496 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9497 const ConstantInt *CI = C->getConstantIntValue();
9498 if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
9499 C->getSExtValue())) {
9500 // Widen to 64 bits here to get it sign extended.
9501 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
9504 // FIXME gcc accepts some relocatable values here too, but only in certain
9505 // memory models; it's complicated.
9510 // 32-bit unsigned value
9511 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9512 const ConstantInt *CI = C->getConstantIntValue();
9513 if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
9514 C->getZExtValue())) {
9515 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9519 // FIXME gcc accepts some relocatable values here too, but only in certain
9520 // memory models; it's complicated.
9524 // Literal immediates are always ok.
9525 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
9526 // Widen to 64 bits here to get it sign extended.
9527 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
9531 // If we are in non-pic codegen mode, we allow the address of a global (with
9532 // an optional displacement) to be used with 'i'.
9533 GlobalAddressSDNode *GA = 0;
9536 // Match either (GA), (GA+C), (GA+C1+C2), etc.
9538 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
9539 Offset += GA->getOffset();
9541 } else if (Op.getOpcode() == ISD::ADD) {
9542 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9543 Offset += C->getZExtValue();
9544 Op = Op.getOperand(0);
9547 } else if (Op.getOpcode() == ISD::SUB) {
9548 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9549 Offset += -C->getZExtValue();
9550 Op = Op.getOperand(0);
9555 // Otherwise, this isn't something we can handle, reject it.
9559 GlobalValue *GV = GA->getGlobal();
9560 // If we require an extra load to get this address, as in PIC mode, we
9562 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
9563 getTargetMachine())))
9567 Op = LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
9569 Op = DAG.getTargetGlobalAddress(GV, GA->getValueType(0), Offset);
9575 if (Result.getNode()) {
9576 Ops.push_back(Result);
9579 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
9583 std::vector<unsigned> X86TargetLowering::
9584 getRegClassForInlineAsmConstraint(const std::string &Constraint,
9586 if (Constraint.size() == 1) {
9587 // FIXME: not handling fp-stack yet!
9588 switch (Constraint[0]) { // GCC X86 Constraint Letters
9589 default: break; // Unknown constraint letter
9590 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
9591 if (Subtarget->is64Bit()) {
9593 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
9594 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
9595 X86::R10D,X86::R11D,X86::R12D,
9596 X86::R13D,X86::R14D,X86::R15D,
9597 X86::EBP, X86::ESP, 0);
9598 else if (VT == MVT::i16)
9599 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
9600 X86::SI, X86::DI, X86::R8W,X86::R9W,
9601 X86::R10W,X86::R11W,X86::R12W,
9602 X86::R13W,X86::R14W,X86::R15W,
9603 X86::BP, X86::SP, 0);
9604 else if (VT == MVT::i8)
9605 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
9606 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
9607 X86::R10B,X86::R11B,X86::R12B,
9608 X86::R13B,X86::R14B,X86::R15B,
9609 X86::BPL, X86::SPL, 0);
9611 else if (VT == MVT::i64)
9612 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
9613 X86::RSI, X86::RDI, X86::R8, X86::R9,
9614 X86::R10, X86::R11, X86::R12,
9615 X86::R13, X86::R14, X86::R15,
9616 X86::RBP, X86::RSP, 0);
9620 // 32-bit fallthrough
9623 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
9624 else if (VT == MVT::i16)
9625 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
9626 else if (VT == MVT::i8)
9627 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
9628 else if (VT == MVT::i64)
9629 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
9634 return std::vector<unsigned>();
9637 std::pair<unsigned, const TargetRegisterClass*>
9638 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9640 // First, see if this is a constraint that directly corresponds to an LLVM
9642 if (Constraint.size() == 1) {
9643 // GCC Constraint Letters
9644 switch (Constraint[0]) {
9646 case 'r': // GENERAL_REGS
9647 case 'l': // INDEX_REGS
9649 return std::make_pair(0U, X86::GR8RegisterClass);
9651 return std::make_pair(0U, X86::GR16RegisterClass);
9652 if (VT == MVT::i32 || !Subtarget->is64Bit())
9653 return std::make_pair(0U, X86::GR32RegisterClass);
9654 return std::make_pair(0U, X86::GR64RegisterClass);
9655 case 'R': // LEGACY_REGS
9657 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
9659 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
9660 if (VT == MVT::i32 || !Subtarget->is64Bit())
9661 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
9662 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
9663 case 'f': // FP Stack registers.
9664 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
9665 // value to the correct fpstack register class.
9666 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
9667 return std::make_pair(0U, X86::RFP32RegisterClass);
9668 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
9669 return std::make_pair(0U, X86::RFP64RegisterClass);
9670 return std::make_pair(0U, X86::RFP80RegisterClass);
9671 case 'y': // MMX_REGS if MMX allowed.
9672 if (!Subtarget->hasMMX()) break;
9673 return std::make_pair(0U, X86::VR64RegisterClass);
9674 case 'Y': // SSE_REGS if SSE2 allowed
9675 if (!Subtarget->hasSSE2()) break;
9677 case 'x': // SSE_REGS if SSE1 allowed
9678 if (!Subtarget->hasSSE1()) break;
9680 switch (VT.getSimpleVT().SimpleTy) {
9682 // Scalar SSE types.
9685 return std::make_pair(0U, X86::FR32RegisterClass);
9688 return std::make_pair(0U, X86::FR64RegisterClass);
9696 return std::make_pair(0U, X86::VR128RegisterClass);
9702 // Use the default implementation in TargetLowering to convert the register
9703 // constraint into a member of a register class.
9704 std::pair<unsigned, const TargetRegisterClass*> Res;
9705 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9707 // Not found as a standard register?
9708 if (Res.second == 0) {
9709 // Map st(0) -> st(7) -> ST0
9710 if (Constraint.size() == 7 && Constraint[0] == '{' &&
9711 tolower(Constraint[1]) == 's' &&
9712 tolower(Constraint[2]) == 't' &&
9713 Constraint[3] == '(' &&
9714 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
9715 Constraint[5] == ')' &&
9716 Constraint[6] == '}') {
9718 Res.first = X86::ST0+Constraint[4]-'0';
9719 Res.second = X86::RFP80RegisterClass;
9723 // GCC allows "st(0)" to be called just plain "st".
9724 if (StringRef("{st}").equals_lower(Constraint)) {
9725 Res.first = X86::ST0;
9726 Res.second = X86::RFP80RegisterClass;
9731 if (StringRef("{flags}").equals_lower(Constraint)) {
9732 Res.first = X86::EFLAGS;
9733 Res.second = X86::CCRRegisterClass;
9737 // 'A' means EAX + EDX.
9738 if (Constraint == "A") {
9739 Res.first = X86::EAX;
9740 Res.second = X86::GR32_ADRegisterClass;
9746 // Otherwise, check to see if this is a register class of the wrong value
9747 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
9748 // turn into {ax},{dx}.
9749 if (Res.second->hasType(VT))
9750 return Res; // Correct type already, nothing to do.
9752 // All of the single-register GCC register classes map their values onto
9753 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
9754 // really want an 8-bit or 32-bit register, map to the appropriate register
9755 // class and return the appropriate register.
9756 if (Res.second == X86::GR16RegisterClass) {
9757 if (VT == MVT::i8) {
9758 unsigned DestReg = 0;
9759 switch (Res.first) {
9761 case X86::AX: DestReg = X86::AL; break;
9762 case X86::DX: DestReg = X86::DL; break;
9763 case X86::CX: DestReg = X86::CL; break;
9764 case X86::BX: DestReg = X86::BL; break;
9767 Res.first = DestReg;
9768 Res.second = X86::GR8RegisterClass;
9770 } else if (VT == MVT::i32) {
9771 unsigned DestReg = 0;
9772 switch (Res.first) {
9774 case X86::AX: DestReg = X86::EAX; break;
9775 case X86::DX: DestReg = X86::EDX; break;
9776 case X86::CX: DestReg = X86::ECX; break;
9777 case X86::BX: DestReg = X86::EBX; break;
9778 case X86::SI: DestReg = X86::ESI; break;
9779 case X86::DI: DestReg = X86::EDI; break;
9780 case X86::BP: DestReg = X86::EBP; break;
9781 case X86::SP: DestReg = X86::ESP; break;
9784 Res.first = DestReg;
9785 Res.second = X86::GR32RegisterClass;
9787 } else if (VT == MVT::i64) {
9788 unsigned DestReg = 0;
9789 switch (Res.first) {
9791 case X86::AX: DestReg = X86::RAX; break;
9792 case X86::DX: DestReg = X86::RDX; break;
9793 case X86::CX: DestReg = X86::RCX; break;
9794 case X86::BX: DestReg = X86::RBX; break;
9795 case X86::SI: DestReg = X86::RSI; break;
9796 case X86::DI: DestReg = X86::RDI; break;
9797 case X86::BP: DestReg = X86::RBP; break;
9798 case X86::SP: DestReg = X86::RSP; break;
9801 Res.first = DestReg;
9802 Res.second = X86::GR64RegisterClass;
9805 } else if (Res.second == X86::FR32RegisterClass ||
9806 Res.second == X86::FR64RegisterClass ||
9807 Res.second == X86::VR128RegisterClass) {
9808 // Handle references to XMM physical registers that got mapped into the
9809 // wrong class. This can happen with constraints like {xmm0} where the
9810 // target independent register mapper will just pick the first match it can
9811 // find, ignoring the required type.
9813 Res.second = X86::FR32RegisterClass;
9814 else if (VT == MVT::f64)
9815 Res.second = X86::FR64RegisterClass;
9816 else if (X86::VR128RegisterClass->hasType(VT))
9817 Res.second = X86::VR128RegisterClass;
9823 //===----------------------------------------------------------------------===//
9824 // X86 Widen vector type
9825 //===----------------------------------------------------------------------===//
9827 /// getWidenVectorType: given a vector type, returns the type to widen
9828 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
9829 /// If there is no vector type that we want to widen to, returns MVT::Other
9830 /// When and where to widen is target dependent based on the cost of
9831 /// scalarizing vs using the wider vector type.
9833 EVT X86TargetLowering::getWidenVectorType(EVT VT) const {
9834 assert(VT.isVector());
9835 if (isTypeLegal(VT))
9838 // TODO: In computeRegisterProperty, we can compute the list of legal vector
9839 // type based on element type. This would speed up our search (though
9840 // it may not be worth it since the size of the list is relatively
9842 EVT EltVT = VT.getVectorElementType();
9843 unsigned NElts = VT.getVectorNumElements();
9845 // On X86, it make sense to widen any vector wider than 1
9849 for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
9850 nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
9851 EVT SVT = (MVT::SimpleValueType)nVT;
9853 if (isTypeLegal(SVT) &&
9854 SVT.getVectorElementType() == EltVT &&
9855 SVT.getVectorNumElements() > NElts)