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);
600 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
601 // with -msoft-float, disable use of MMX as well.
602 if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
603 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass);
604 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass);
605 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass);
606 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass);
607 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass);
609 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
610 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
611 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
612 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
614 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
615 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
616 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
617 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
619 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
620 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
622 setOperationAction(ISD::AND, MVT::v8i8, Promote);
623 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
624 setOperationAction(ISD::AND, MVT::v4i16, Promote);
625 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
626 setOperationAction(ISD::AND, MVT::v2i32, Promote);
627 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
628 setOperationAction(ISD::AND, MVT::v1i64, Legal);
630 setOperationAction(ISD::OR, MVT::v8i8, Promote);
631 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
632 setOperationAction(ISD::OR, MVT::v4i16, Promote);
633 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
634 setOperationAction(ISD::OR, MVT::v2i32, Promote);
635 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
636 setOperationAction(ISD::OR, MVT::v1i64, Legal);
638 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
639 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
640 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
641 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
642 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
643 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
644 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
646 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
647 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
648 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
649 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
650 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
651 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
652 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
653 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
654 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
656 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
657 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
658 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
659 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
660 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
662 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
663 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
664 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
665 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
667 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
668 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
669 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
670 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
672 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
674 setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
675 setOperationAction(ISD::TRUNCATE, MVT::v8i8, Expand);
676 setOperationAction(ISD::SELECT, MVT::v8i8, Promote);
677 setOperationAction(ISD::SELECT, MVT::v4i16, Promote);
678 setOperationAction(ISD::SELECT, MVT::v2i32, Promote);
679 setOperationAction(ISD::SELECT, MVT::v1i64, Custom);
680 setOperationAction(ISD::VSETCC, MVT::v8i8, Custom);
681 setOperationAction(ISD::VSETCC, MVT::v4i16, Custom);
682 setOperationAction(ISD::VSETCC, MVT::v2i32, Custom);
685 if (!UseSoftFloat && Subtarget->hasSSE1()) {
686 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
688 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
689 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
690 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
691 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
692 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
693 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
694 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
695 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
696 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
697 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
698 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
699 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
702 if (!UseSoftFloat && Subtarget->hasSSE2()) {
703 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
705 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
706 // registers cannot be used even for integer operations.
707 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
708 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
709 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
710 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
712 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
713 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
714 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
715 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
716 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
717 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
718 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
719 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
720 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
721 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
722 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
723 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
724 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
725 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
726 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
727 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
729 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
730 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
731 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
732 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
734 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
735 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
736 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
737 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
738 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
740 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
741 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
742 EVT VT = (MVT::SimpleValueType)i;
743 // Do not attempt to custom lower non-power-of-2 vectors
744 if (!isPowerOf2_32(VT.getVectorNumElements()))
746 // Do not attempt to custom lower non-128-bit vectors
747 if (!VT.is128BitVector())
749 setOperationAction(ISD::BUILD_VECTOR,
750 VT.getSimpleVT().SimpleTy, Custom);
751 setOperationAction(ISD::VECTOR_SHUFFLE,
752 VT.getSimpleVT().SimpleTy, Custom);
753 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
754 VT.getSimpleVT().SimpleTy, Custom);
757 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
758 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
759 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
760 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
761 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
762 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
764 if (Subtarget->is64Bit()) {
765 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
766 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
769 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
770 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
771 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
774 // Do not attempt to promote non-128-bit vectors
775 if (!VT.is128BitVector()) {
778 setOperationAction(ISD::AND, SVT, Promote);
779 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
780 setOperationAction(ISD::OR, SVT, Promote);
781 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
782 setOperationAction(ISD::XOR, SVT, Promote);
783 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
784 setOperationAction(ISD::LOAD, SVT, Promote);
785 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
786 setOperationAction(ISD::SELECT, SVT, Promote);
787 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
790 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
792 // Custom lower v2i64 and v2f64 selects.
793 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
794 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
795 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
796 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
798 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
799 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
800 if (!DisableMMX && Subtarget->hasMMX()) {
801 setOperationAction(ISD::FP_TO_SINT, MVT::v2i32, Custom);
802 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
806 if (Subtarget->hasSSE41()) {
807 // FIXME: Do we need to handle scalar-to-vector here?
808 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
810 // i8 and i16 vectors are custom , because the source register and source
811 // source memory operand types are not the same width. f32 vectors are
812 // custom since the immediate controlling the insert encodes additional
814 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
815 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
816 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
817 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
819 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
820 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
821 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
822 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
824 if (Subtarget->is64Bit()) {
825 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
826 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
830 if (Subtarget->hasSSE42()) {
831 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
834 if (!UseSoftFloat && Subtarget->hasAVX()) {
835 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
836 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
837 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
838 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
840 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
841 setOperationAction(ISD::LOAD, MVT::v8i32, Legal);
842 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
843 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
844 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
845 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
846 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
847 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
848 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
849 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
850 //setOperationAction(ISD::BUILD_VECTOR, MVT::v8f32, Custom);
851 //setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Custom);
852 //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
853 //setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
854 //setOperationAction(ISD::VSETCC, MVT::v8f32, Custom);
856 // Operations to consider commented out -v16i16 v32i8
857 //setOperationAction(ISD::ADD, MVT::v16i16, Legal);
858 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
859 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
860 //setOperationAction(ISD::SUB, MVT::v32i8, Legal);
861 //setOperationAction(ISD::SUB, MVT::v16i16, Legal);
862 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
863 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
864 //setOperationAction(ISD::MUL, MVT::v16i16, Legal);
865 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
866 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
867 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
868 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
869 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
870 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
872 setOperationAction(ISD::VSETCC, MVT::v4f64, Custom);
873 // setOperationAction(ISD::VSETCC, MVT::v32i8, Custom);
874 // setOperationAction(ISD::VSETCC, MVT::v16i16, Custom);
875 setOperationAction(ISD::VSETCC, MVT::v8i32, Custom);
877 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v32i8, Custom);
878 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i16, Custom);
879 // setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i16, Custom);
880 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i32, Custom);
881 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8f32, Custom);
883 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
884 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i64, Custom);
885 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f64, Custom);
886 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i64, Custom);
887 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f64, Custom);
888 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
891 // Not sure we want to do this since there are no 256-bit integer
894 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
895 // This includes 256-bit vectors
896 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
897 EVT VT = (MVT::SimpleValueType)i;
899 // Do not attempt to custom lower non-power-of-2 vectors
900 if (!isPowerOf2_32(VT.getVectorNumElements()))
903 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
904 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
905 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
908 if (Subtarget->is64Bit()) {
909 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i64, Custom);
910 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
915 // Not sure we want to do this since there are no 256-bit integer
918 // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
919 // Including 256-bit vectors
920 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
921 EVT VT = (MVT::SimpleValueType)i;
923 if (!VT.is256BitVector()) {
926 setOperationAction(ISD::AND, VT, Promote);
927 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
928 setOperationAction(ISD::OR, VT, Promote);
929 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
930 setOperationAction(ISD::XOR, VT, Promote);
931 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
932 setOperationAction(ISD::LOAD, VT, Promote);
933 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
934 setOperationAction(ISD::SELECT, VT, Promote);
935 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
938 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
942 // We want to custom lower some of our intrinsics.
943 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
945 // Add/Sub/Mul with overflow operations are custom lowered.
946 setOperationAction(ISD::SADDO, MVT::i32, Custom);
947 setOperationAction(ISD::SADDO, MVT::i64, Custom);
948 setOperationAction(ISD::UADDO, MVT::i32, Custom);
949 setOperationAction(ISD::UADDO, MVT::i64, Custom);
950 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
951 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
952 setOperationAction(ISD::USUBO, MVT::i32, Custom);
953 setOperationAction(ISD::USUBO, MVT::i64, Custom);
954 setOperationAction(ISD::SMULO, MVT::i32, Custom);
955 setOperationAction(ISD::SMULO, MVT::i64, Custom);
957 if (!Subtarget->is64Bit()) {
958 // These libcalls are not available in 32-bit.
959 setLibcallName(RTLIB::SHL_I128, 0);
960 setLibcallName(RTLIB::SRL_I128, 0);
961 setLibcallName(RTLIB::SRA_I128, 0);
964 // We have target-specific dag combine patterns for the following nodes:
965 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
966 setTargetDAGCombine(ISD::BUILD_VECTOR);
967 setTargetDAGCombine(ISD::SELECT);
968 setTargetDAGCombine(ISD::SHL);
969 setTargetDAGCombine(ISD::SRA);
970 setTargetDAGCombine(ISD::SRL);
971 setTargetDAGCombine(ISD::STORE);
972 setTargetDAGCombine(ISD::MEMBARRIER);
973 if (Subtarget->is64Bit())
974 setTargetDAGCombine(ISD::MUL);
976 computeRegisterProperties();
978 // FIXME: These should be based on subtarget info. Plus, the values should
979 // be smaller when we are in optimizing for size mode.
980 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
981 maxStoresPerMemcpy = 16; // For @llvm.memcpy -> sequence of stores
982 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
983 setPrefLoopAlignment(16);
984 benefitFromCodePlacementOpt = true;
988 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
993 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
994 /// the desired ByVal argument alignment.
995 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
998 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
999 if (VTy->getBitWidth() == 128)
1001 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1002 unsigned EltAlign = 0;
1003 getMaxByValAlign(ATy->getElementType(), EltAlign);
1004 if (EltAlign > MaxAlign)
1005 MaxAlign = EltAlign;
1006 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1007 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1008 unsigned EltAlign = 0;
1009 getMaxByValAlign(STy->getElementType(i), EltAlign);
1010 if (EltAlign > MaxAlign)
1011 MaxAlign = EltAlign;
1019 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1020 /// function arguments in the caller parameter area. For X86, aggregates
1021 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1022 /// are at 4-byte boundaries.
1023 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1024 if (Subtarget->is64Bit()) {
1025 // Max of 8 and alignment of type.
1026 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1033 if (Subtarget->hasSSE1())
1034 getMaxByValAlign(Ty, Align);
1038 /// getOptimalMemOpType - Returns the target specific optimal type for load
1039 /// and store operations as a result of memset, memcpy, and memmove
1040 /// lowering. It returns MVT::iAny if SelectionDAG should be responsible for
1043 X86TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned Align,
1044 bool isSrcConst, bool isSrcStr,
1045 SelectionDAG &DAG) const {
1046 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1047 // linux. This is because the stack realignment code can't handle certain
1048 // cases like PR2962. This should be removed when PR2962 is fixed.
1049 const Function *F = DAG.getMachineFunction().getFunction();
1050 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
1051 if (!NoImplicitFloatOps && Subtarget->getStackAlignment() >= 16) {
1052 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE2() && Size >= 16)
1054 if ((isSrcConst || isSrcStr) && Subtarget->hasSSE1() && Size >= 16)
1057 if (Subtarget->is64Bit() && Size >= 8)
1062 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1064 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1065 SelectionDAG &DAG) const {
1066 if (usesGlobalOffsetTable())
1067 return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy());
1068 if (!Subtarget->is64Bit())
1069 // This doesn't have DebugLoc associated with it, but is not really the
1070 // same as a Register.
1071 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc::getUnknownLoc(),
1076 /// getFunctionAlignment - Return the Log2 alignment of this function.
1077 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1078 return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1081 //===----------------------------------------------------------------------===//
1082 // Return Value Calling Convention Implementation
1083 //===----------------------------------------------------------------------===//
1085 #include "X86GenCallingConv.inc"
1088 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1089 const SmallVectorImpl<EVT> &OutTys,
1090 const SmallVectorImpl<ISD::ArgFlagsTy> &ArgsFlags,
1091 SelectionDAG &DAG) {
1092 SmallVector<CCValAssign, 16> RVLocs;
1093 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1094 RVLocs, *DAG.getContext());
1095 return CCInfo.CheckReturn(OutTys, ArgsFlags, RetCC_X86);
1099 X86TargetLowering::LowerReturn(SDValue Chain,
1100 CallingConv::ID CallConv, bool isVarArg,
1101 const SmallVectorImpl<ISD::OutputArg> &Outs,
1102 DebugLoc dl, SelectionDAG &DAG) {
1104 SmallVector<CCValAssign, 16> RVLocs;
1105 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1106 RVLocs, *DAG.getContext());
1107 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1109 // If this is the first return lowered for this function, add the regs to the
1110 // liveout set for the function.
1111 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
1112 for (unsigned i = 0; i != RVLocs.size(); ++i)
1113 if (RVLocs[i].isRegLoc())
1114 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
1119 SmallVector<SDValue, 6> RetOps;
1120 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1121 // Operand #1 = Bytes To Pop
1122 RetOps.push_back(DAG.getTargetConstant(getBytesToPopOnReturn(), MVT::i16));
1124 // Copy the result values into the output registers.
1125 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1126 CCValAssign &VA = RVLocs[i];
1127 assert(VA.isRegLoc() && "Can only return in registers!");
1128 SDValue ValToCopy = Outs[i].Val;
1130 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1131 // the RET instruction and handled by the FP Stackifier.
1132 if (VA.getLocReg() == X86::ST0 ||
1133 VA.getLocReg() == X86::ST1) {
1134 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1135 // change the value to the FP stack register class.
1136 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1137 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1138 RetOps.push_back(ValToCopy);
1139 // Don't emit a copytoreg.
1143 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1144 // which is returned in RAX / RDX.
1145 if (Subtarget->is64Bit()) {
1146 EVT ValVT = ValToCopy.getValueType();
1147 if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1148 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1149 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1150 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1154 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1155 Flag = Chain.getValue(1);
1158 // The x86-64 ABI for returning structs by value requires that we copy
1159 // the sret argument into %rax for the return. We saved the argument into
1160 // a virtual register in the entry block, so now we copy the value out
1162 if (Subtarget->is64Bit() &&
1163 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1164 MachineFunction &MF = DAG.getMachineFunction();
1165 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1166 unsigned Reg = FuncInfo->getSRetReturnReg();
1168 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1169 FuncInfo->setSRetReturnReg(Reg);
1171 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1173 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1174 Flag = Chain.getValue(1);
1176 // RAX now acts like a return value.
1177 MF.getRegInfo().addLiveOut(X86::RAX);
1180 RetOps[0] = Chain; // Update chain.
1182 // Add the flag if we have it.
1184 RetOps.push_back(Flag);
1186 return DAG.getNode(X86ISD::RET_FLAG, dl,
1187 MVT::Other, &RetOps[0], RetOps.size());
1190 /// LowerCallResult - Lower the result values of a call into the
1191 /// appropriate copies out of appropriate physical registers.
1194 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1195 CallingConv::ID CallConv, bool isVarArg,
1196 const SmallVectorImpl<ISD::InputArg> &Ins,
1197 DebugLoc dl, SelectionDAG &DAG,
1198 SmallVectorImpl<SDValue> &InVals) {
1200 // Assign locations to each value returned by this call.
1201 SmallVector<CCValAssign, 16> RVLocs;
1202 bool Is64Bit = Subtarget->is64Bit();
1203 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1204 RVLocs, *DAG.getContext());
1205 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1207 // Copy all of the result registers out of their specified physreg.
1208 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1209 CCValAssign &VA = RVLocs[i];
1210 EVT CopyVT = VA.getValVT();
1212 // If this is x86-64, and we disabled SSE, we can't return FP values
1213 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1214 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1215 llvm_report_error("SSE register return with SSE disabled");
1218 // If this is a call to a function that returns an fp value on the floating
1219 // point stack, but where we prefer to use the value in xmm registers, copy
1220 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1221 if ((VA.getLocReg() == X86::ST0 ||
1222 VA.getLocReg() == X86::ST1) &&
1223 isScalarFPTypeInSSEReg(VA.getValVT())) {
1228 if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1229 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1230 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1231 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1232 MVT::v2i64, InFlag).getValue(1);
1233 Val = Chain.getValue(0);
1234 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1235 Val, DAG.getConstant(0, MVT::i64));
1237 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1238 MVT::i64, InFlag).getValue(1);
1239 Val = Chain.getValue(0);
1241 Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1243 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1244 CopyVT, InFlag).getValue(1);
1245 Val = Chain.getValue(0);
1247 InFlag = Chain.getValue(2);
1249 if (CopyVT != VA.getValVT()) {
1250 // Round the F80 the right size, which also moves to the appropriate xmm
1252 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1253 // This truncation won't change the value.
1254 DAG.getIntPtrConstant(1));
1257 InVals.push_back(Val);
1264 //===----------------------------------------------------------------------===//
1265 // C & StdCall & Fast Calling Convention implementation
1266 //===----------------------------------------------------------------------===//
1267 // StdCall calling convention seems to be standard for many Windows' API
1268 // routines and around. It differs from C calling convention just a little:
1269 // callee should clean up the stack, not caller. Symbols should be also
1270 // decorated in some fancy way :) It doesn't support any vector arguments.
1271 // For info on fast calling convention see Fast Calling Convention (tail call)
1272 // implementation LowerX86_32FastCCCallTo.
1274 /// CallIsStructReturn - Determines whether a call uses struct return
1276 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1280 return Outs[0].Flags.isSRet();
1283 /// ArgsAreStructReturn - Determines whether a function uses struct
1284 /// return semantics.
1286 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1290 return Ins[0].Flags.isSRet();
1293 /// IsCalleePop - Determines whether the callee is required to pop its
1294 /// own arguments. Callee pop is necessary to support tail calls.
1295 bool X86TargetLowering::IsCalleePop(bool IsVarArg, CallingConv::ID CallingConv){
1299 switch (CallingConv) {
1302 case CallingConv::X86_StdCall:
1303 return !Subtarget->is64Bit();
1304 case CallingConv::X86_FastCall:
1305 return !Subtarget->is64Bit();
1306 case CallingConv::Fast:
1307 return PerformTailCallOpt;
1311 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1312 /// given CallingConvention value.
1313 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1314 if (Subtarget->is64Bit()) {
1315 if (Subtarget->isTargetWin64())
1316 return CC_X86_Win64_C;
1321 if (CC == CallingConv::X86_FastCall)
1322 return CC_X86_32_FastCall;
1323 else if (CC == CallingConv::Fast)
1324 return CC_X86_32_FastCC;
1329 /// NameDecorationForCallConv - Selects the appropriate decoration to
1330 /// apply to a MachineFunction containing a given calling convention.
1332 X86TargetLowering::NameDecorationForCallConv(CallingConv::ID CallConv) {
1333 if (CallConv == CallingConv::X86_FastCall)
1335 else if (CallConv == CallingConv::X86_StdCall)
1341 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1342 /// by "Src" to address "Dst" with size and alignment information specified by
1343 /// the specific parameter attribute. The copy will be passed as a byval
1344 /// function parameter.
1346 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1347 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1349 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1350 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1351 /*AlwaysInline=*/true, NULL, 0, NULL, 0);
1355 X86TargetLowering::LowerMemArgument(SDValue Chain,
1356 CallingConv::ID CallConv,
1357 const SmallVectorImpl<ISD::InputArg> &Ins,
1358 DebugLoc dl, SelectionDAG &DAG,
1359 const CCValAssign &VA,
1360 MachineFrameInfo *MFI,
1363 // Create the nodes corresponding to a load from this parameter slot.
1364 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1365 bool AlwaysUseMutable = (CallConv==CallingConv::Fast) && PerformTailCallOpt;
1366 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1369 // If value is passed by pointer we have address passed instead of the value
1371 if (VA.getLocInfo() == CCValAssign::Indirect)
1372 ValVT = VA.getLocVT();
1374 ValVT = VA.getValVT();
1376 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1377 // changed with more analysis.
1378 // In case of tail call optimization mark all arguments mutable. Since they
1379 // could be overwritten by lowering of arguments in case of a tail call.
1380 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1381 VA.getLocMemOffset(), isImmutable, false);
1382 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1383 if (Flags.isByVal())
1385 return DAG.getLoad(ValVT, dl, Chain, FIN,
1386 PseudoSourceValue::getFixedStack(FI), 0);
1390 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1391 CallingConv::ID CallConv,
1393 const SmallVectorImpl<ISD::InputArg> &Ins,
1396 SmallVectorImpl<SDValue> &InVals) {
1398 MachineFunction &MF = DAG.getMachineFunction();
1399 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1401 const Function* Fn = MF.getFunction();
1402 if (Fn->hasExternalLinkage() &&
1403 Subtarget->isTargetCygMing() &&
1404 Fn->getName() == "main")
1405 FuncInfo->setForceFramePointer(true);
1407 // Decorate the function name.
1408 FuncInfo->setDecorationStyle(NameDecorationForCallConv(CallConv));
1410 MachineFrameInfo *MFI = MF.getFrameInfo();
1411 bool Is64Bit = Subtarget->is64Bit();
1412 bool IsWin64 = Subtarget->isTargetWin64();
1414 assert(!(isVarArg && CallConv == CallingConv::Fast) &&
1415 "Var args not supported with calling convention fastcc");
1417 // Assign locations to all of the incoming arguments.
1418 SmallVector<CCValAssign, 16> ArgLocs;
1419 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1420 ArgLocs, *DAG.getContext());
1421 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1423 unsigned LastVal = ~0U;
1425 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1426 CCValAssign &VA = ArgLocs[i];
1427 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1429 assert(VA.getValNo() != LastVal &&
1430 "Don't support value assigned to multiple locs yet");
1431 LastVal = VA.getValNo();
1433 if (VA.isRegLoc()) {
1434 EVT RegVT = VA.getLocVT();
1435 TargetRegisterClass *RC = NULL;
1436 if (RegVT == MVT::i32)
1437 RC = X86::GR32RegisterClass;
1438 else if (Is64Bit && RegVT == MVT::i64)
1439 RC = X86::GR64RegisterClass;
1440 else if (RegVT == MVT::f32)
1441 RC = X86::FR32RegisterClass;
1442 else if (RegVT == MVT::f64)
1443 RC = X86::FR64RegisterClass;
1444 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1445 RC = X86::VR128RegisterClass;
1446 else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1447 RC = X86::VR64RegisterClass;
1449 llvm_unreachable("Unknown argument type!");
1451 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1452 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1454 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1455 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1457 if (VA.getLocInfo() == CCValAssign::SExt)
1458 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1459 DAG.getValueType(VA.getValVT()));
1460 else if (VA.getLocInfo() == CCValAssign::ZExt)
1461 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1462 DAG.getValueType(VA.getValVT()));
1463 else if (VA.getLocInfo() == CCValAssign::BCvt)
1464 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1466 if (VA.isExtInLoc()) {
1467 // Handle MMX values passed in XMM regs.
1468 if (RegVT.isVector()) {
1469 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1470 ArgValue, DAG.getConstant(0, MVT::i64));
1471 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1473 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1476 assert(VA.isMemLoc());
1477 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1480 // If value is passed via pointer - do a load.
1481 if (VA.getLocInfo() == CCValAssign::Indirect)
1482 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0);
1484 InVals.push_back(ArgValue);
1487 // The x86-64 ABI for returning structs by value requires that we copy
1488 // the sret argument into %rax for the return. Save the argument into
1489 // a virtual register so that we can access it from the return points.
1490 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1491 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1492 unsigned Reg = FuncInfo->getSRetReturnReg();
1494 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1495 FuncInfo->setSRetReturnReg(Reg);
1497 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1498 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1501 unsigned StackSize = CCInfo.getNextStackOffset();
1502 // align stack specially for tail calls
1503 if (PerformTailCallOpt && CallConv == CallingConv::Fast)
1504 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1506 // If the function takes variable number of arguments, make a frame index for
1507 // the start of the first vararg value... for expansion of llvm.va_start.
1509 if (Is64Bit || CallConv != CallingConv::X86_FastCall) {
1510 VarArgsFrameIndex = MFI->CreateFixedObject(1, StackSize, true, false);
1513 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1515 // FIXME: We should really autogenerate these arrays
1516 static const unsigned GPR64ArgRegsWin64[] = {
1517 X86::RCX, X86::RDX, X86::R8, X86::R9
1519 static const unsigned XMMArgRegsWin64[] = {
1520 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1522 static const unsigned GPR64ArgRegs64Bit[] = {
1523 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1525 static const unsigned XMMArgRegs64Bit[] = {
1526 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1527 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1529 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1532 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1533 GPR64ArgRegs = GPR64ArgRegsWin64;
1534 XMMArgRegs = XMMArgRegsWin64;
1536 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1537 GPR64ArgRegs = GPR64ArgRegs64Bit;
1538 XMMArgRegs = XMMArgRegs64Bit;
1540 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1542 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1545 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1546 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1547 "SSE register cannot be used when SSE is disabled!");
1548 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1549 "SSE register cannot be used when SSE is disabled!");
1550 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1551 // Kernel mode asks for SSE to be disabled, so don't push them
1553 TotalNumXMMRegs = 0;
1555 // For X86-64, if there are vararg parameters that are passed via
1556 // registers, then we must store them to their spots on the stack so they
1557 // may be loaded by deferencing the result of va_next.
1558 VarArgsGPOffset = NumIntRegs * 8;
1559 VarArgsFPOffset = TotalNumIntRegs * 8 + NumXMMRegs * 16;
1560 RegSaveFrameIndex = MFI->CreateStackObject(TotalNumIntRegs * 8 +
1561 TotalNumXMMRegs * 16, 16,
1564 // Store the integer parameter registers.
1565 SmallVector<SDValue, 8> MemOps;
1566 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
1567 unsigned Offset = VarArgsGPOffset;
1568 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1569 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1570 DAG.getIntPtrConstant(Offset));
1571 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1572 X86::GR64RegisterClass);
1573 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1575 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1576 PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
1578 MemOps.push_back(Store);
1582 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1583 // Now store the XMM (fp + vector) parameter registers.
1584 SmallVector<SDValue, 11> SaveXMMOps;
1585 SaveXMMOps.push_back(Chain);
1587 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1588 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1589 SaveXMMOps.push_back(ALVal);
1591 SaveXMMOps.push_back(DAG.getIntPtrConstant(RegSaveFrameIndex));
1592 SaveXMMOps.push_back(DAG.getIntPtrConstant(VarArgsFPOffset));
1594 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1595 unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1596 X86::VR128RegisterClass);
1597 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1598 SaveXMMOps.push_back(Val);
1600 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1602 &SaveXMMOps[0], SaveXMMOps.size()));
1605 if (!MemOps.empty())
1606 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1607 &MemOps[0], MemOps.size());
1611 // Some CCs need callee pop.
1612 if (IsCalleePop(isVarArg, CallConv)) {
1613 BytesToPopOnReturn = StackSize; // Callee pops everything.
1614 BytesCallerReserves = 0;
1616 BytesToPopOnReturn = 0; // Callee pops nothing.
1617 // If this is an sret function, the return should pop the hidden pointer.
1618 if (!Is64Bit && CallConv != CallingConv::Fast && ArgsAreStructReturn(Ins))
1619 BytesToPopOnReturn = 4;
1620 BytesCallerReserves = StackSize;
1624 RegSaveFrameIndex = 0xAAAAAAA; // RegSaveFrameIndex is X86-64 only.
1625 if (CallConv == CallingConv::X86_FastCall)
1626 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
1629 FuncInfo->setBytesToPopOnReturn(BytesToPopOnReturn);
1635 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1636 SDValue StackPtr, SDValue Arg,
1637 DebugLoc dl, SelectionDAG &DAG,
1638 const CCValAssign &VA,
1639 ISD::ArgFlagsTy Flags) {
1640 const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1641 unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1642 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1643 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1644 if (Flags.isByVal()) {
1645 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1647 return DAG.getStore(Chain, dl, Arg, PtrOff,
1648 PseudoSourceValue::getStack(), LocMemOffset);
1651 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1652 /// optimization is performed and it is required.
1654 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1655 SDValue &OutRetAddr,
1661 if (!IsTailCall || FPDiff==0) return Chain;
1663 // Adjust the Return address stack slot.
1664 EVT VT = getPointerTy();
1665 OutRetAddr = getReturnAddressFrameIndex(DAG);
1667 // Load the "old" Return address.
1668 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0);
1669 return SDValue(OutRetAddr.getNode(), 1);
1672 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1673 /// optimization is performed and it is required (FPDiff!=0).
1675 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1676 SDValue Chain, SDValue RetAddrFrIdx,
1677 bool Is64Bit, int FPDiff, DebugLoc dl) {
1678 // Store the return address to the appropriate stack slot.
1679 if (!FPDiff) return Chain;
1680 // Calculate the new stack slot for the return address.
1681 int SlotSize = Is64Bit ? 8 : 4;
1682 int NewReturnAddrFI =
1683 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize,
1685 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1686 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1687 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1688 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0);
1693 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1694 CallingConv::ID CallConv, bool isVarArg,
1696 const SmallVectorImpl<ISD::OutputArg> &Outs,
1697 const SmallVectorImpl<ISD::InputArg> &Ins,
1698 DebugLoc dl, SelectionDAG &DAG,
1699 SmallVectorImpl<SDValue> &InVals) {
1701 MachineFunction &MF = DAG.getMachineFunction();
1702 bool Is64Bit = Subtarget->is64Bit();
1703 bool IsStructRet = CallIsStructReturn(Outs);
1705 assert((!isTailCall ||
1706 (CallConv == CallingConv::Fast && PerformTailCallOpt)) &&
1707 "IsEligibleForTailCallOptimization missed a case!");
1708 assert(!(isVarArg && CallConv == CallingConv::Fast) &&
1709 "Var args not supported with calling convention fastcc");
1711 // Analyze operands of the call, assigning locations to each operand.
1712 SmallVector<CCValAssign, 16> ArgLocs;
1713 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1714 ArgLocs, *DAG.getContext());
1715 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1717 // Get a count of how many bytes are to be pushed on the stack.
1718 unsigned NumBytes = CCInfo.getNextStackOffset();
1719 if (PerformTailCallOpt && CallConv == CallingConv::Fast)
1720 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1724 // Lower arguments at fp - stackoffset + fpdiff.
1725 unsigned NumBytesCallerPushed =
1726 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1727 FPDiff = NumBytesCallerPushed - NumBytes;
1729 // Set the delta of movement of the returnaddr stackslot.
1730 // But only set if delta is greater than previous delta.
1731 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1732 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1735 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1737 SDValue RetAddrFrIdx;
1738 // Load return adress for tail calls.
1739 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall, Is64Bit,
1742 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1743 SmallVector<SDValue, 8> MemOpChains;
1746 // Walk the register/memloc assignments, inserting copies/loads. In the case
1747 // of tail call optimization arguments are handle later.
1748 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1749 CCValAssign &VA = ArgLocs[i];
1750 EVT RegVT = VA.getLocVT();
1751 SDValue Arg = Outs[i].Val;
1752 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1753 bool isByVal = Flags.isByVal();
1755 // Promote the value if needed.
1756 switch (VA.getLocInfo()) {
1757 default: llvm_unreachable("Unknown loc info!");
1758 case CCValAssign::Full: break;
1759 case CCValAssign::SExt:
1760 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1762 case CCValAssign::ZExt:
1763 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1765 case CCValAssign::AExt:
1766 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1767 // Special case: passing MMX values in XMM registers.
1768 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1769 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1770 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1772 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1774 case CCValAssign::BCvt:
1775 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1777 case CCValAssign::Indirect: {
1778 // Store the argument.
1779 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1780 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1781 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1782 PseudoSourceValue::getFixedStack(FI), 0);
1788 if (VA.isRegLoc()) {
1789 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1791 if (!isTailCall || (isTailCall && isByVal)) {
1792 assert(VA.isMemLoc());
1793 if (StackPtr.getNode() == 0)
1794 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1796 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1797 dl, DAG, VA, Flags));
1802 if (!MemOpChains.empty())
1803 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1804 &MemOpChains[0], MemOpChains.size());
1806 // Build a sequence of copy-to-reg nodes chained together with token chain
1807 // and flag operands which copy the outgoing args into registers.
1809 // Tail call byval lowering might overwrite argument registers so in case of
1810 // tail call optimization the copies to registers are lowered later.
1812 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1813 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1814 RegsToPass[i].second, InFlag);
1815 InFlag = Chain.getValue(1);
1819 if (Subtarget->isPICStyleGOT()) {
1820 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1823 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1824 DAG.getNode(X86ISD::GlobalBaseReg,
1825 DebugLoc::getUnknownLoc(),
1828 InFlag = Chain.getValue(1);
1830 // If we are tail calling and generating PIC/GOT style code load the
1831 // address of the callee into ECX. The value in ecx is used as target of
1832 // the tail jump. This is done to circumvent the ebx/callee-saved problem
1833 // for tail calls on PIC/GOT architectures. Normally we would just put the
1834 // address of GOT into ebx and then call target@PLT. But for tail calls
1835 // ebx would be restored (since ebx is callee saved) before jumping to the
1838 // Note: The actual moving to ECX is done further down.
1839 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1840 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1841 !G->getGlobal()->hasProtectedVisibility())
1842 Callee = LowerGlobalAddress(Callee, DAG);
1843 else if (isa<ExternalSymbolSDNode>(Callee))
1844 Callee = LowerExternalSymbol(Callee, DAG);
1848 if (Is64Bit && isVarArg) {
1849 // From AMD64 ABI document:
1850 // For calls that may call functions that use varargs or stdargs
1851 // (prototype-less calls or calls to functions containing ellipsis (...) in
1852 // the declaration) %al is used as hidden argument to specify the number
1853 // of SSE registers used. The contents of %al do not need to match exactly
1854 // the number of registers, but must be an ubound on the number of SSE
1855 // registers used and is in the range 0 - 8 inclusive.
1857 // FIXME: Verify this on Win64
1858 // Count the number of XMM registers allocated.
1859 static const unsigned XMMArgRegs[] = {
1860 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1861 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1863 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1864 assert((Subtarget->hasSSE1() || !NumXMMRegs)
1865 && "SSE registers cannot be used when SSE is disabled");
1867 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1868 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1869 InFlag = Chain.getValue(1);
1873 // For tail calls lower the arguments to the 'real' stack slot.
1875 // Force all the incoming stack arguments to be loaded from the stack
1876 // before any new outgoing arguments are stored to the stack, because the
1877 // outgoing stack slots may alias the incoming argument stack slots, and
1878 // the alias isn't otherwise explicit. This is slightly more conservative
1879 // than necessary, because it means that each store effectively depends
1880 // on every argument instead of just those arguments it would clobber.
1881 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
1883 SmallVector<SDValue, 8> MemOpChains2;
1886 // Do not flag preceeding copytoreg stuff together with the following stuff.
1888 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1889 CCValAssign &VA = ArgLocs[i];
1890 if (!VA.isRegLoc()) {
1891 assert(VA.isMemLoc());
1892 SDValue Arg = Outs[i].Val;
1893 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1894 // Create frame index.
1895 int32_t Offset = VA.getLocMemOffset()+FPDiff;
1896 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
1897 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true, false);
1898 FIN = DAG.getFrameIndex(FI, getPointerTy());
1900 if (Flags.isByVal()) {
1901 // Copy relative to framepointer.
1902 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
1903 if (StackPtr.getNode() == 0)
1904 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
1906 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
1908 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
1912 // Store relative to framepointer.
1913 MemOpChains2.push_back(
1914 DAG.getStore(ArgChain, dl, Arg, FIN,
1915 PseudoSourceValue::getFixedStack(FI), 0));
1920 if (!MemOpChains2.empty())
1921 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1922 &MemOpChains2[0], MemOpChains2.size());
1924 // Copy arguments to their registers.
1925 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1926 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1927 RegsToPass[i].second, InFlag);
1928 InFlag = Chain.getValue(1);
1932 // Store the return address to the appropriate stack slot.
1933 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
1937 bool WasGlobalOrExternal = false;
1938 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
1939 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
1940 // In the 64-bit large code model, we have to make all calls
1941 // through a register, since the call instruction's 32-bit
1942 // pc-relative offset may not be large enough to hold the whole
1944 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
1945 WasGlobalOrExternal = true;
1946 // If the callee is a GlobalAddress node (quite common, every direct call
1947 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
1950 // We should use extra load for direct calls to dllimported functions in
1952 GlobalValue *GV = G->getGlobal();
1953 if (!GV->hasDLLImportLinkage()) {
1954 unsigned char OpFlags = 0;
1956 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
1957 // external symbols most go through the PLT in PIC mode. If the symbol
1958 // has hidden or protected visibility, or if it is static or local, then
1959 // we don't need to use the PLT - we can directly call it.
1960 if (Subtarget->isTargetELF() &&
1961 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1962 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
1963 OpFlags = X86II::MO_PLT;
1964 } else if (Subtarget->isPICStyleStubAny() &&
1965 (GV->isDeclaration() || GV->isWeakForLinker()) &&
1966 Subtarget->getDarwinVers() < 9) {
1967 // PC-relative references to external symbols should go through $stub,
1968 // unless we're building with the leopard linker or later, which
1969 // automatically synthesizes these stubs.
1970 OpFlags = X86II::MO_DARWIN_STUB;
1973 Callee = DAG.getTargetGlobalAddress(GV, getPointerTy(),
1974 G->getOffset(), OpFlags);
1976 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
1977 WasGlobalOrExternal = true;
1978 unsigned char OpFlags = 0;
1980 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
1981 // symbols should go through the PLT.
1982 if (Subtarget->isTargetELF() &&
1983 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1984 OpFlags = X86II::MO_PLT;
1985 } else if (Subtarget->isPICStyleStubAny() &&
1986 Subtarget->getDarwinVers() < 9) {
1987 // PC-relative references to external symbols should go through $stub,
1988 // unless we're building with the leopard linker or later, which
1989 // automatically synthesizes these stubs.
1990 OpFlags = X86II::MO_DARWIN_STUB;
1993 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
1997 if (isTailCall && !WasGlobalOrExternal) {
1998 unsigned Opc = Is64Bit ? X86::R11 : X86::EAX;
2000 Chain = DAG.getCopyToReg(Chain, dl,
2001 DAG.getRegister(Opc, getPointerTy()),
2003 Callee = DAG.getRegister(Opc, getPointerTy());
2004 // Add register as live out.
2005 MF.getRegInfo().addLiveOut(Opc);
2008 // Returns a chain & a flag for retval copy to use.
2009 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2010 SmallVector<SDValue, 8> Ops;
2013 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2014 DAG.getIntPtrConstant(0, true), InFlag);
2015 InFlag = Chain.getValue(1);
2018 Ops.push_back(Chain);
2019 Ops.push_back(Callee);
2022 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2024 // Add argument registers to the end of the list so that they are known live
2026 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2027 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2028 RegsToPass[i].second.getValueType()));
2030 // Add an implicit use GOT pointer in EBX.
2031 if (!isTailCall && Subtarget->isPICStyleGOT())
2032 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2034 // Add an implicit use of AL for x86 vararg functions.
2035 if (Is64Bit && isVarArg)
2036 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2038 if (InFlag.getNode())
2039 Ops.push_back(InFlag);
2042 // If this is the first return lowered for this function, add the regs
2043 // to the liveout set for the function.
2044 if (MF.getRegInfo().liveout_empty()) {
2045 SmallVector<CCValAssign, 16> RVLocs;
2046 CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
2048 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2049 for (unsigned i = 0; i != RVLocs.size(); ++i)
2050 if (RVLocs[i].isRegLoc())
2051 MF.getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2054 assert(((Callee.getOpcode() == ISD::Register &&
2055 (cast<RegisterSDNode>(Callee)->getReg() == X86::EAX ||
2056 cast<RegisterSDNode>(Callee)->getReg() == X86::R9)) ||
2057 Callee.getOpcode() == ISD::TargetExternalSymbol ||
2058 Callee.getOpcode() == ISD::TargetGlobalAddress) &&
2059 "Expecting an global address, external symbol, or register");
2061 return DAG.getNode(X86ISD::TC_RETURN, dl,
2062 NodeTys, &Ops[0], Ops.size());
2065 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2066 InFlag = Chain.getValue(1);
2068 // Create the CALLSEQ_END node.
2069 unsigned NumBytesForCalleeToPush;
2070 if (IsCalleePop(isVarArg, CallConv))
2071 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2072 else if (!Is64Bit && CallConv != CallingConv::Fast && IsStructRet)
2073 // If this is is a call to a struct-return function, the callee
2074 // pops the hidden struct pointer, so we have to push it back.
2075 // This is common for Darwin/X86, Linux & Mingw32 targets.
2076 NumBytesForCalleeToPush = 4;
2078 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2080 // Returns a flag for retval copy to use.
2081 Chain = DAG.getCALLSEQ_END(Chain,
2082 DAG.getIntPtrConstant(NumBytes, true),
2083 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2086 InFlag = Chain.getValue(1);
2088 // Handle result values, copying them out of physregs into vregs that we
2090 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2091 Ins, dl, DAG, InVals);
2095 //===----------------------------------------------------------------------===//
2096 // Fast Calling Convention (tail call) implementation
2097 //===----------------------------------------------------------------------===//
2099 // Like std call, callee cleans arguments, convention except that ECX is
2100 // reserved for storing the tail called function address. Only 2 registers are
2101 // free for argument passing (inreg). Tail call optimization is performed
2103 // * tailcallopt is enabled
2104 // * caller/callee are fastcc
2105 // On X86_64 architecture with GOT-style position independent code only local
2106 // (within module) calls are supported at the moment.
2107 // To keep the stack aligned according to platform abi the function
2108 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2109 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2110 // If a tail called function callee has more arguments than the caller the
2111 // caller needs to make sure that there is room to move the RETADDR to. This is
2112 // achieved by reserving an area the size of the argument delta right after the
2113 // original REtADDR, but before the saved framepointer or the spilled registers
2114 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2126 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2127 /// for a 16 byte align requirement.
2128 unsigned X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2129 SelectionDAG& DAG) {
2130 MachineFunction &MF = DAG.getMachineFunction();
2131 const TargetMachine &TM = MF.getTarget();
2132 const TargetFrameInfo &TFI = *TM.getFrameInfo();
2133 unsigned StackAlignment = TFI.getStackAlignment();
2134 uint64_t AlignMask = StackAlignment - 1;
2135 int64_t Offset = StackSize;
2136 uint64_t SlotSize = TD->getPointerSize();
2137 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2138 // Number smaller than 12 so just add the difference.
2139 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2141 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2142 Offset = ((~AlignMask) & Offset) + StackAlignment +
2143 (StackAlignment-SlotSize);
2148 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2149 /// for tail call optimization. Targets which want to do tail call
2150 /// optimization should implement this function.
2152 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2153 CallingConv::ID CalleeCC,
2155 const SmallVectorImpl<ISD::InputArg> &Ins,
2156 SelectionDAG& DAG) const {
2157 MachineFunction &MF = DAG.getMachineFunction();
2158 CallingConv::ID CallerCC = MF.getFunction()->getCallingConv();
2159 return CalleeCC == CallingConv::Fast && CallerCC == CalleeCC;
2163 X86TargetLowering::createFastISel(MachineFunction &mf,
2164 MachineModuleInfo *mmo,
2166 DenseMap<const Value *, unsigned> &vm,
2167 DenseMap<const BasicBlock *,
2168 MachineBasicBlock *> &bm,
2169 DenseMap<const AllocaInst *, int> &am
2171 , SmallSet<Instruction*, 8> &cil
2174 return X86::createFastISel(mf, mmo, dw, vm, bm, am
2182 //===----------------------------------------------------------------------===//
2183 // Other Lowering Hooks
2184 //===----------------------------------------------------------------------===//
2187 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
2188 MachineFunction &MF = DAG.getMachineFunction();
2189 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2190 int ReturnAddrIndex = FuncInfo->getRAIndex();
2192 if (ReturnAddrIndex == 0) {
2193 // Set up a frame object for the return address.
2194 uint64_t SlotSize = TD->getPointerSize();
2195 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2197 FuncInfo->setRAIndex(ReturnAddrIndex);
2200 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2204 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2205 bool hasSymbolicDisplacement) {
2206 // Offset should fit into 32 bit immediate field.
2207 if (!isInt32(Offset))
2210 // If we don't have a symbolic displacement - we don't have any extra
2212 if (!hasSymbolicDisplacement)
2215 // FIXME: Some tweaks might be needed for medium code model.
2216 if (M != CodeModel::Small && M != CodeModel::Kernel)
2219 // For small code model we assume that latest object is 16MB before end of 31
2220 // bits boundary. We may also accept pretty large negative constants knowing
2221 // that all objects are in the positive half of address space.
2222 if (M == CodeModel::Small && Offset < 16*1024*1024)
2225 // For kernel code model we know that all object resist in the negative half
2226 // of 32bits address space. We may not accept negative offsets, since they may
2227 // be just off and we may accept pretty large positive ones.
2228 if (M == CodeModel::Kernel && Offset > 0)
2234 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2235 /// specific condition code, returning the condition code and the LHS/RHS of the
2236 /// comparison to make.
2237 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2238 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2240 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2241 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2242 // X > -1 -> X == 0, jump !sign.
2243 RHS = DAG.getConstant(0, RHS.getValueType());
2244 return X86::COND_NS;
2245 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2246 // X < 0 -> X == 0, jump on sign.
2248 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2250 RHS = DAG.getConstant(0, RHS.getValueType());
2251 return X86::COND_LE;
2255 switch (SetCCOpcode) {
2256 default: llvm_unreachable("Invalid integer condition!");
2257 case ISD::SETEQ: return X86::COND_E;
2258 case ISD::SETGT: return X86::COND_G;
2259 case ISD::SETGE: return X86::COND_GE;
2260 case ISD::SETLT: return X86::COND_L;
2261 case ISD::SETLE: return X86::COND_LE;
2262 case ISD::SETNE: return X86::COND_NE;
2263 case ISD::SETULT: return X86::COND_B;
2264 case ISD::SETUGT: return X86::COND_A;
2265 case ISD::SETULE: return X86::COND_BE;
2266 case ISD::SETUGE: return X86::COND_AE;
2270 // First determine if it is required or is profitable to flip the operands.
2272 // If LHS is a foldable load, but RHS is not, flip the condition.
2273 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2274 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2275 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2276 std::swap(LHS, RHS);
2279 switch (SetCCOpcode) {
2285 std::swap(LHS, RHS);
2289 // On a floating point condition, the flags are set as follows:
2291 // 0 | 0 | 0 | X > Y
2292 // 0 | 0 | 1 | X < Y
2293 // 1 | 0 | 0 | X == Y
2294 // 1 | 1 | 1 | unordered
2295 switch (SetCCOpcode) {
2296 default: llvm_unreachable("Condcode should be pre-legalized away");
2298 case ISD::SETEQ: return X86::COND_E;
2299 case ISD::SETOLT: // flipped
2301 case ISD::SETGT: return X86::COND_A;
2302 case ISD::SETOLE: // flipped
2304 case ISD::SETGE: return X86::COND_AE;
2305 case ISD::SETUGT: // flipped
2307 case ISD::SETLT: return X86::COND_B;
2308 case ISD::SETUGE: // flipped
2310 case ISD::SETLE: return X86::COND_BE;
2312 case ISD::SETNE: return X86::COND_NE;
2313 case ISD::SETUO: return X86::COND_P;
2314 case ISD::SETO: return X86::COND_NP;
2316 case ISD::SETUNE: return X86::COND_INVALID;
2320 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2321 /// code. Current x86 isa includes the following FP cmov instructions:
2322 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2323 static bool hasFPCMov(unsigned X86CC) {
2339 /// isFPImmLegal - Returns true if the target can instruction select the
2340 /// specified FP immediate natively. If false, the legalizer will
2341 /// materialize the FP immediate as a load from a constant pool.
2342 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2343 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2344 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2350 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2351 /// the specified range (L, H].
2352 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2353 return (Val < 0) || (Val >= Low && Val < Hi);
2356 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2357 /// specified value.
2358 static bool isUndefOrEqual(int Val, int CmpVal) {
2359 if (Val < 0 || Val == CmpVal)
2364 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2365 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2366 /// the second operand.
2367 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2368 if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2369 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2370 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2371 return (Mask[0] < 2 && Mask[1] < 2);
2375 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2376 SmallVector<int, 8> M;
2378 return ::isPSHUFDMask(M, N->getValueType(0));
2381 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2382 /// is suitable for input to PSHUFHW.
2383 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2384 if (VT != MVT::v8i16)
2387 // Lower quadword copied in order or undef.
2388 for (int i = 0; i != 4; ++i)
2389 if (Mask[i] >= 0 && Mask[i] != i)
2392 // Upper quadword shuffled.
2393 for (int i = 4; i != 8; ++i)
2394 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2400 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2401 SmallVector<int, 8> M;
2403 return ::isPSHUFHWMask(M, N->getValueType(0));
2406 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2407 /// is suitable for input to PSHUFLW.
2408 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2409 if (VT != MVT::v8i16)
2412 // Upper quadword copied in order.
2413 for (int i = 4; i != 8; ++i)
2414 if (Mask[i] >= 0 && Mask[i] != i)
2417 // Lower quadword shuffled.
2418 for (int i = 0; i != 4; ++i)
2425 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2426 SmallVector<int, 8> M;
2428 return ::isPSHUFLWMask(M, N->getValueType(0));
2431 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2432 /// is suitable for input to PALIGNR.
2433 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2435 int i, e = VT.getVectorNumElements();
2437 // Do not handle v2i64 / v2f64 shuffles with palignr.
2438 if (e < 4 || !hasSSSE3)
2441 for (i = 0; i != e; ++i)
2445 // All undef, not a palignr.
2449 // Determine if it's ok to perform a palignr with only the LHS, since we
2450 // don't have access to the actual shuffle elements to see if RHS is undef.
2451 bool Unary = Mask[i] < (int)e;
2452 bool NeedsUnary = false;
2454 int s = Mask[i] - i;
2456 // Check the rest of the elements to see if they are consecutive.
2457 for (++i; i != e; ++i) {
2462 Unary = Unary && (m < (int)e);
2463 NeedsUnary = NeedsUnary || (m < s);
2465 if (NeedsUnary && !Unary)
2467 if (Unary && m != ((s+i) & (e-1)))
2469 if (!Unary && m != (s+i))
2475 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2476 SmallVector<int, 8> M;
2478 return ::isPALIGNRMask(M, N->getValueType(0), true);
2481 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2482 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2483 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2484 int NumElems = VT.getVectorNumElements();
2485 if (NumElems != 2 && NumElems != 4)
2488 int Half = NumElems / 2;
2489 for (int i = 0; i < Half; ++i)
2490 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2492 for (int i = Half; i < NumElems; ++i)
2493 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2499 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2500 SmallVector<int, 8> M;
2502 return ::isSHUFPMask(M, N->getValueType(0));
2505 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2506 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2507 /// half elements to come from vector 1 (which would equal the dest.) and
2508 /// the upper half to come from vector 2.
2509 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2510 int NumElems = VT.getVectorNumElements();
2512 if (NumElems != 2 && NumElems != 4)
2515 int Half = NumElems / 2;
2516 for (int i = 0; i < Half; ++i)
2517 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2519 for (int i = Half; i < NumElems; ++i)
2520 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2525 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2526 SmallVector<int, 8> M;
2528 return isCommutedSHUFPMask(M, N->getValueType(0));
2531 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2532 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2533 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2534 if (N->getValueType(0).getVectorNumElements() != 4)
2537 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2538 return isUndefOrEqual(N->getMaskElt(0), 6) &&
2539 isUndefOrEqual(N->getMaskElt(1), 7) &&
2540 isUndefOrEqual(N->getMaskElt(2), 2) &&
2541 isUndefOrEqual(N->getMaskElt(3), 3);
2544 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2545 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2547 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2548 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2553 return isUndefOrEqual(N->getMaskElt(0), 2) &&
2554 isUndefOrEqual(N->getMaskElt(1), 3) &&
2555 isUndefOrEqual(N->getMaskElt(2), 2) &&
2556 isUndefOrEqual(N->getMaskElt(3), 3);
2559 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2560 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2561 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2562 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2564 if (NumElems != 2 && NumElems != 4)
2567 for (unsigned i = 0; i < NumElems/2; ++i)
2568 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2571 for (unsigned i = NumElems/2; i < NumElems; ++i)
2572 if (!isUndefOrEqual(N->getMaskElt(i), i))
2578 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
2579 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
2580 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
2581 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2583 if (NumElems != 2 && NumElems != 4)
2586 for (unsigned i = 0; i < NumElems/2; ++i)
2587 if (!isUndefOrEqual(N->getMaskElt(i), i))
2590 for (unsigned i = 0; i < NumElems/2; ++i)
2591 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2597 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2598 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2599 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2600 bool V2IsSplat = false) {
2601 int NumElts = VT.getVectorNumElements();
2602 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2605 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2607 int BitI1 = Mask[i+1];
2608 if (!isUndefOrEqual(BitI, j))
2611 if (!isUndefOrEqual(BitI1, NumElts))
2614 if (!isUndefOrEqual(BitI1, j + NumElts))
2621 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2622 SmallVector<int, 8> M;
2624 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2627 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2628 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2629 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
2630 bool V2IsSplat = false) {
2631 int NumElts = VT.getVectorNumElements();
2632 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2635 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2637 int BitI1 = Mask[i+1];
2638 if (!isUndefOrEqual(BitI, j + NumElts/2))
2641 if (isUndefOrEqual(BitI1, NumElts))
2644 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2651 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2652 SmallVector<int, 8> M;
2654 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2657 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2658 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2660 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2661 int NumElems = VT.getVectorNumElements();
2662 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2665 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2667 int BitI1 = Mask[i+1];
2668 if (!isUndefOrEqual(BitI, j))
2670 if (!isUndefOrEqual(BitI1, j))
2676 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2677 SmallVector<int, 8> M;
2679 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2682 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2683 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2685 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2686 int NumElems = VT.getVectorNumElements();
2687 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2690 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2692 int BitI1 = Mask[i+1];
2693 if (!isUndefOrEqual(BitI, j))
2695 if (!isUndefOrEqual(BitI1, j))
2701 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2702 SmallVector<int, 8> M;
2704 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2707 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2708 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2709 /// MOVSD, and MOVD, i.e. setting the lowest element.
2710 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2711 if (VT.getVectorElementType().getSizeInBits() < 32)
2714 int NumElts = VT.getVectorNumElements();
2716 if (!isUndefOrEqual(Mask[0], NumElts))
2719 for (int i = 1; i < NumElts; ++i)
2720 if (!isUndefOrEqual(Mask[i], i))
2726 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
2727 SmallVector<int, 8> M;
2729 return ::isMOVLMask(M, N->getValueType(0));
2732 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
2733 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
2734 /// element of vector 2 and the other elements to come from vector 1 in order.
2735 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2736 bool V2IsSplat = false, bool V2IsUndef = false) {
2737 int NumOps = VT.getVectorNumElements();
2738 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
2741 if (!isUndefOrEqual(Mask[0], 0))
2744 for (int i = 1; i < NumOps; ++i)
2745 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
2746 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
2747 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
2753 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
2754 bool V2IsUndef = false) {
2755 SmallVector<int, 8> M;
2757 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
2760 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2761 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
2762 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
2763 if (N->getValueType(0).getVectorNumElements() != 4)
2766 // Expect 1, 1, 3, 3
2767 for (unsigned i = 0; i < 2; ++i) {
2768 int Elt = N->getMaskElt(i);
2769 if (Elt >= 0 && Elt != 1)
2774 for (unsigned i = 2; i < 4; ++i) {
2775 int Elt = N->getMaskElt(i);
2776 if (Elt >= 0 && Elt != 3)
2781 // Don't use movshdup if it can be done with a shufps.
2782 // FIXME: verify that matching u, u, 3, 3 is what we want.
2786 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2787 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
2788 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
2789 if (N->getValueType(0).getVectorNumElements() != 4)
2792 // Expect 0, 0, 2, 2
2793 for (unsigned i = 0; i < 2; ++i)
2794 if (N->getMaskElt(i) > 0)
2798 for (unsigned i = 2; i < 4; ++i) {
2799 int Elt = N->getMaskElt(i);
2800 if (Elt >= 0 && Elt != 2)
2805 // Don't use movsldup if it can be done with a shufps.
2809 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
2810 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
2811 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
2812 int e = N->getValueType(0).getVectorNumElements() / 2;
2814 for (int i = 0; i < e; ++i)
2815 if (!isUndefOrEqual(N->getMaskElt(i), i))
2817 for (int i = 0; i < e; ++i)
2818 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
2823 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
2824 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
2825 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
2826 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2827 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
2829 unsigned Shift = (NumOperands == 4) ? 2 : 1;
2831 for (int i = 0; i < NumOperands; ++i) {
2832 int Val = SVOp->getMaskElt(NumOperands-i-1);
2833 if (Val < 0) Val = 0;
2834 if (Val >= NumOperands) Val -= NumOperands;
2836 if (i != NumOperands - 1)
2842 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
2843 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
2844 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
2845 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2847 // 8 nodes, but we only care about the last 4.
2848 for (unsigned i = 7; i >= 4; --i) {
2849 int Val = SVOp->getMaskElt(i);
2858 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
2859 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
2860 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
2861 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2863 // 8 nodes, but we only care about the first 4.
2864 for (int i = 3; i >= 0; --i) {
2865 int Val = SVOp->getMaskElt(i);
2874 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
2875 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
2876 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
2877 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
2878 EVT VVT = N->getValueType(0);
2879 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
2883 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
2884 Val = SVOp->getMaskElt(i);
2888 return (Val - i) * EltSize;
2891 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
2893 bool X86::isZeroNode(SDValue Elt) {
2894 return ((isa<ConstantSDNode>(Elt) &&
2895 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
2896 (isa<ConstantFPSDNode>(Elt) &&
2897 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
2900 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
2901 /// their permute mask.
2902 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
2903 SelectionDAG &DAG) {
2904 EVT VT = SVOp->getValueType(0);
2905 unsigned NumElems = VT.getVectorNumElements();
2906 SmallVector<int, 8> MaskVec;
2908 for (unsigned i = 0; i != NumElems; ++i) {
2909 int idx = SVOp->getMaskElt(i);
2911 MaskVec.push_back(idx);
2912 else if (idx < (int)NumElems)
2913 MaskVec.push_back(idx + NumElems);
2915 MaskVec.push_back(idx - NumElems);
2917 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
2918 SVOp->getOperand(0), &MaskVec[0]);
2921 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
2922 /// the two vector operands have swapped position.
2923 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
2924 unsigned NumElems = VT.getVectorNumElements();
2925 for (unsigned i = 0; i != NumElems; ++i) {
2929 else if (idx < (int)NumElems)
2930 Mask[i] = idx + NumElems;
2932 Mask[i] = idx - NumElems;
2936 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
2937 /// match movhlps. The lower half elements should come from upper half of
2938 /// V1 (and in order), and the upper half elements should come from the upper
2939 /// half of V2 (and in order).
2940 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
2941 if (Op->getValueType(0).getVectorNumElements() != 4)
2943 for (unsigned i = 0, e = 2; i != e; ++i)
2944 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
2946 for (unsigned i = 2; i != 4; ++i)
2947 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
2952 /// isScalarLoadToVector - Returns true if the node is a scalar load that
2953 /// is promoted to a vector. It also returns the LoadSDNode by reference if
2955 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
2956 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
2958 N = N->getOperand(0).getNode();
2959 if (!ISD::isNON_EXTLoad(N))
2962 *LD = cast<LoadSDNode>(N);
2966 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
2967 /// match movlp{s|d}. The lower half elements should come from lower half of
2968 /// V1 (and in order), and the upper half elements should come from the upper
2969 /// half of V2 (and in order). And since V1 will become the source of the
2970 /// MOVLP, it must be either a vector load or a scalar load to vector.
2971 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
2972 ShuffleVectorSDNode *Op) {
2973 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
2975 // Is V2 is a vector load, don't do this transformation. We will try to use
2976 // load folding shufps op.
2977 if (ISD::isNON_EXTLoad(V2))
2980 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
2982 if (NumElems != 2 && NumElems != 4)
2984 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
2985 if (!isUndefOrEqual(Op->getMaskElt(i), i))
2987 for (unsigned i = NumElems/2; i != NumElems; ++i)
2988 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
2993 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
2995 static bool isSplatVector(SDNode *N) {
2996 if (N->getOpcode() != ISD::BUILD_VECTOR)
2999 SDValue SplatValue = N->getOperand(0);
3000 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3001 if (N->getOperand(i) != SplatValue)
3006 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3007 /// to an zero vector.
3008 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3009 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3010 SDValue V1 = N->getOperand(0);
3011 SDValue V2 = N->getOperand(1);
3012 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3013 for (unsigned i = 0; i != NumElems; ++i) {
3014 int Idx = N->getMaskElt(i);
3015 if (Idx >= (int)NumElems) {
3016 unsigned Opc = V2.getOpcode();
3017 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3019 if (Opc != ISD::BUILD_VECTOR ||
3020 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3022 } else if (Idx >= 0) {
3023 unsigned Opc = V1.getOpcode();
3024 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3026 if (Opc != ISD::BUILD_VECTOR ||
3027 !X86::isZeroNode(V1.getOperand(Idx)))
3034 /// getZeroVector - Returns a vector of specified type with all zero elements.
3036 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3038 assert(VT.isVector() && "Expected a vector type");
3040 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3041 // type. This ensures they get CSE'd.
3043 if (VT.getSizeInBits() == 64) { // MMX
3044 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3045 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3046 } else if (HasSSE2) { // SSE2
3047 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3048 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3050 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3051 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3053 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3056 /// getOnesVector - Returns a vector of specified type with all bits set.
3058 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3059 assert(VT.isVector() && "Expected a vector type");
3061 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3062 // type. This ensures they get CSE'd.
3063 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3065 if (VT.getSizeInBits() == 64) // MMX
3066 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3068 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3069 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3073 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3074 /// that point to V2 points to its first element.
3075 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3076 EVT VT = SVOp->getValueType(0);
3077 unsigned NumElems = VT.getVectorNumElements();
3079 bool Changed = false;
3080 SmallVector<int, 8> MaskVec;
3081 SVOp->getMask(MaskVec);
3083 for (unsigned i = 0; i != NumElems; ++i) {
3084 if (MaskVec[i] > (int)NumElems) {
3085 MaskVec[i] = NumElems;
3090 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3091 SVOp->getOperand(1), &MaskVec[0]);
3092 return SDValue(SVOp, 0);
3095 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3096 /// operation of specified width.
3097 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3099 unsigned NumElems = VT.getVectorNumElements();
3100 SmallVector<int, 8> Mask;
3101 Mask.push_back(NumElems);
3102 for (unsigned i = 1; i != NumElems; ++i)
3104 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3107 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3108 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3110 unsigned NumElems = VT.getVectorNumElements();
3111 SmallVector<int, 8> Mask;
3112 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3114 Mask.push_back(i + NumElems);
3116 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3119 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3120 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3122 unsigned NumElems = VT.getVectorNumElements();
3123 unsigned Half = NumElems/2;
3124 SmallVector<int, 8> Mask;
3125 for (unsigned i = 0; i != Half; ++i) {
3126 Mask.push_back(i + Half);
3127 Mask.push_back(i + NumElems + Half);
3129 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3132 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3133 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3135 if (SV->getValueType(0).getVectorNumElements() <= 4)
3136 return SDValue(SV, 0);
3138 EVT PVT = MVT::v4f32;
3139 EVT VT = SV->getValueType(0);
3140 DebugLoc dl = SV->getDebugLoc();
3141 SDValue V1 = SV->getOperand(0);
3142 int NumElems = VT.getVectorNumElements();
3143 int EltNo = SV->getSplatIndex();
3145 // unpack elements to the correct location
3146 while (NumElems > 4) {
3147 if (EltNo < NumElems/2) {
3148 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3150 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3151 EltNo -= NumElems/2;
3156 // Perform the splat.
3157 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3158 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3159 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3160 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3163 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3164 /// vector of zero or undef vector. This produces a shuffle where the low
3165 /// element of V2 is swizzled into the zero/undef vector, landing at element
3166 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3167 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3168 bool isZero, bool HasSSE2,
3169 SelectionDAG &DAG) {
3170 EVT VT = V2.getValueType();
3172 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3173 unsigned NumElems = VT.getVectorNumElements();
3174 SmallVector<int, 16> MaskVec;
3175 for (unsigned i = 0; i != NumElems; ++i)
3176 // If this is the insertion idx, put the low elt of V2 here.
3177 MaskVec.push_back(i == Idx ? NumElems : i);
3178 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3181 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3182 /// a shuffle that is zero.
3184 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3185 bool Low, SelectionDAG &DAG) {
3186 unsigned NumZeros = 0;
3187 for (int i = 0; i < NumElems; ++i) {
3188 unsigned Index = Low ? i : NumElems-i-1;
3189 int Idx = SVOp->getMaskElt(Index);
3194 SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3195 if (Elt.getNode() && X86::isZeroNode(Elt))
3203 /// isVectorShift - Returns true if the shuffle can be implemented as a
3204 /// logical left or right shift of a vector.
3205 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3206 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3207 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3208 int NumElems = SVOp->getValueType(0).getVectorNumElements();
3211 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3214 NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3218 bool SeenV1 = false;
3219 bool SeenV2 = false;
3220 for (int i = NumZeros; i < NumElems; ++i) {
3221 int Val = isLeft ? (i - NumZeros) : i;
3222 int Idx = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3234 if (SeenV1 && SeenV2)
3237 ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3243 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3245 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3246 unsigned NumNonZero, unsigned NumZero,
3247 SelectionDAG &DAG, TargetLowering &TLI) {
3251 DebugLoc dl = Op.getDebugLoc();
3254 for (unsigned i = 0; i < 16; ++i) {
3255 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3256 if (ThisIsNonZero && First) {
3258 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3260 V = DAG.getUNDEF(MVT::v8i16);
3265 SDValue ThisElt(0, 0), LastElt(0, 0);
3266 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3267 if (LastIsNonZero) {
3268 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3269 MVT::i16, Op.getOperand(i-1));
3271 if (ThisIsNonZero) {
3272 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3273 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3274 ThisElt, DAG.getConstant(8, MVT::i8));
3276 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3280 if (ThisElt.getNode())
3281 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3282 DAG.getIntPtrConstant(i/2));
3286 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3289 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3291 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3292 unsigned NumNonZero, unsigned NumZero,
3293 SelectionDAG &DAG, TargetLowering &TLI) {
3297 DebugLoc dl = Op.getDebugLoc();
3300 for (unsigned i = 0; i < 8; ++i) {
3301 bool isNonZero = (NonZeros & (1 << i)) != 0;
3305 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3307 V = DAG.getUNDEF(MVT::v8i16);
3310 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3311 MVT::v8i16, V, Op.getOperand(i),
3312 DAG.getIntPtrConstant(i));
3319 /// getVShift - Return a vector logical shift node.
3321 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3322 unsigned NumBits, SelectionDAG &DAG,
3323 const TargetLowering &TLI, DebugLoc dl) {
3324 bool isMMX = VT.getSizeInBits() == 64;
3325 EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3326 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3327 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3328 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3329 DAG.getNode(Opc, dl, ShVT, SrcOp,
3330 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3334 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) {
3335 DebugLoc dl = Op.getDebugLoc();
3336 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3337 if (ISD::isBuildVectorAllZeros(Op.getNode())
3338 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3339 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3340 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3341 // eliminated on x86-32 hosts.
3342 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3345 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3346 return getOnesVector(Op.getValueType(), DAG, dl);
3347 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3350 EVT VT = Op.getValueType();
3351 EVT ExtVT = VT.getVectorElementType();
3352 unsigned EVTBits = ExtVT.getSizeInBits();
3354 unsigned NumElems = Op.getNumOperands();
3355 unsigned NumZero = 0;
3356 unsigned NumNonZero = 0;
3357 unsigned NonZeros = 0;
3358 bool IsAllConstants = true;
3359 SmallSet<SDValue, 8> Values;
3360 for (unsigned i = 0; i < NumElems; ++i) {
3361 SDValue Elt = Op.getOperand(i);
3362 if (Elt.getOpcode() == ISD::UNDEF)
3365 if (Elt.getOpcode() != ISD::Constant &&
3366 Elt.getOpcode() != ISD::ConstantFP)
3367 IsAllConstants = false;
3368 if (X86::isZeroNode(Elt))
3371 NonZeros |= (1 << i);
3376 if (NumNonZero == 0) {
3377 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3378 return DAG.getUNDEF(VT);
3381 // Special case for single non-zero, non-undef, element.
3382 if (NumNonZero == 1) {
3383 unsigned Idx = CountTrailingZeros_32(NonZeros);
3384 SDValue Item = Op.getOperand(Idx);
3386 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3387 // the value are obviously zero, truncate the value to i32 and do the
3388 // insertion that way. Only do this if the value is non-constant or if the
3389 // value is a constant being inserted into element 0. It is cheaper to do
3390 // a constant pool load than it is to do a movd + shuffle.
3391 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3392 (!IsAllConstants || Idx == 0)) {
3393 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3394 // Handle MMX and SSE both.
3395 EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3396 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3398 // Truncate the value (which may itself be a constant) to i32, and
3399 // convert it to a vector with movd (S2V+shuffle to zero extend).
3400 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3401 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3402 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3403 Subtarget->hasSSE2(), DAG);
3405 // Now we have our 32-bit value zero extended in the low element of
3406 // a vector. If Idx != 0, swizzle it into place.
3408 SmallVector<int, 4> Mask;
3409 Mask.push_back(Idx);
3410 for (unsigned i = 1; i != VecElts; ++i)
3412 Item = DAG.getVectorShuffle(VecVT, dl, Item,
3413 DAG.getUNDEF(Item.getValueType()),
3416 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3420 // If we have a constant or non-constant insertion into the low element of
3421 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3422 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3423 // depending on what the source datatype is.
3426 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3427 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3428 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3429 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3430 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3431 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3433 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3434 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3435 EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3436 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3437 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3438 Subtarget->hasSSE2(), DAG);
3439 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3443 // Is it a vector logical left shift?
3444 if (NumElems == 2 && Idx == 1 &&
3445 X86::isZeroNode(Op.getOperand(0)) &&
3446 !X86::isZeroNode(Op.getOperand(1))) {
3447 unsigned NumBits = VT.getSizeInBits();
3448 return getVShift(true, VT,
3449 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3450 VT, Op.getOperand(1)),
3451 NumBits/2, DAG, *this, dl);
3454 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3457 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3458 // is a non-constant being inserted into an element other than the low one,
3459 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3460 // movd/movss) to move this into the low element, then shuffle it into
3462 if (EVTBits == 32) {
3463 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3465 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3466 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3467 Subtarget->hasSSE2(), DAG);
3468 SmallVector<int, 8> MaskVec;
3469 for (unsigned i = 0; i < NumElems; i++)
3470 MaskVec.push_back(i == Idx ? 0 : 1);
3471 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3475 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3476 if (Values.size() == 1)
3479 // A vector full of immediates; various special cases are already
3480 // handled, so this is best done with a single constant-pool load.
3484 // Let legalizer expand 2-wide build_vectors.
3485 if (EVTBits == 64) {
3486 if (NumNonZero == 1) {
3487 // One half is zero or undef.
3488 unsigned Idx = CountTrailingZeros_32(NonZeros);
3489 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3490 Op.getOperand(Idx));
3491 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3492 Subtarget->hasSSE2(), DAG);
3497 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3498 if (EVTBits == 8 && NumElems == 16) {
3499 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3501 if (V.getNode()) return V;
3504 if (EVTBits == 16 && NumElems == 8) {
3505 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3507 if (V.getNode()) return V;
3510 // If element VT is == 32 bits, turn it into a number of shuffles.
3511 SmallVector<SDValue, 8> V;
3513 if (NumElems == 4 && NumZero > 0) {
3514 for (unsigned i = 0; i < 4; ++i) {
3515 bool isZero = !(NonZeros & (1 << i));
3517 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3519 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3522 for (unsigned i = 0; i < 2; ++i) {
3523 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3526 V[i] = V[i*2]; // Must be a zero vector.
3529 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3532 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3535 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3540 SmallVector<int, 8> MaskVec;
3541 bool Reverse = (NonZeros & 0x3) == 2;
3542 for (unsigned i = 0; i < 2; ++i)
3543 MaskVec.push_back(Reverse ? 1-i : i);
3544 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3545 for (unsigned i = 0; i < 2; ++i)
3546 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3547 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3550 if (Values.size() > 2) {
3551 // If we have SSE 4.1, Expand into a number of inserts unless the number of
3552 // values to be inserted is equal to the number of elements, in which case
3553 // use the unpack code below in the hopes of matching the consecutive elts
3554 // load merge pattern for shuffles.
3555 // FIXME: We could probably just check that here directly.
3556 if (Values.size() < NumElems && VT.getSizeInBits() == 128 &&
3557 getSubtarget()->hasSSE41()) {
3558 V[0] = DAG.getUNDEF(VT);
3559 for (unsigned i = 0; i < NumElems; ++i)
3560 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3561 V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3562 Op.getOperand(i), DAG.getIntPtrConstant(i));
3565 // Expand into a number of unpckl*.
3567 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3568 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3569 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3570 for (unsigned i = 0; i < NumElems; ++i)
3571 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3573 while (NumElems != 0) {
3574 for (unsigned i = 0; i < NumElems; ++i)
3575 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
3584 // v8i16 shuffles - Prefer shuffles in the following order:
3585 // 1. [all] pshuflw, pshufhw, optional move
3586 // 2. [ssse3] 1 x pshufb
3587 // 3. [ssse3] 2 x pshufb + 1 x por
3588 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
3590 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
3591 SelectionDAG &DAG, X86TargetLowering &TLI) {
3592 SDValue V1 = SVOp->getOperand(0);
3593 SDValue V2 = SVOp->getOperand(1);
3594 DebugLoc dl = SVOp->getDebugLoc();
3595 SmallVector<int, 8> MaskVals;
3597 // Determine if more than 1 of the words in each of the low and high quadwords
3598 // of the result come from the same quadword of one of the two inputs. Undef
3599 // mask values count as coming from any quadword, for better codegen.
3600 SmallVector<unsigned, 4> LoQuad(4);
3601 SmallVector<unsigned, 4> HiQuad(4);
3602 BitVector InputQuads(4);
3603 for (unsigned i = 0; i < 8; ++i) {
3604 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
3605 int EltIdx = SVOp->getMaskElt(i);
3606 MaskVals.push_back(EltIdx);
3615 InputQuads.set(EltIdx / 4);
3618 int BestLoQuad = -1;
3619 unsigned MaxQuad = 1;
3620 for (unsigned i = 0; i < 4; ++i) {
3621 if (LoQuad[i] > MaxQuad) {
3623 MaxQuad = LoQuad[i];
3627 int BestHiQuad = -1;
3629 for (unsigned i = 0; i < 4; ++i) {
3630 if (HiQuad[i] > MaxQuad) {
3632 MaxQuad = HiQuad[i];
3636 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
3637 // of the two input vectors, shuffle them into one input vector so only a
3638 // single pshufb instruction is necessary. If There are more than 2 input
3639 // quads, disable the next transformation since it does not help SSSE3.
3640 bool V1Used = InputQuads[0] || InputQuads[1];
3641 bool V2Used = InputQuads[2] || InputQuads[3];
3642 if (TLI.getSubtarget()->hasSSSE3()) {
3643 if (InputQuads.count() == 2 && V1Used && V2Used) {
3644 BestLoQuad = InputQuads.find_first();
3645 BestHiQuad = InputQuads.find_next(BestLoQuad);
3647 if (InputQuads.count() > 2) {
3653 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
3654 // the shuffle mask. If a quad is scored as -1, that means that it contains
3655 // words from all 4 input quadwords.
3657 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
3658 SmallVector<int, 8> MaskV;
3659 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
3660 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
3661 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
3662 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
3663 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
3664 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
3666 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
3667 // source words for the shuffle, to aid later transformations.
3668 bool AllWordsInNewV = true;
3669 bool InOrder[2] = { true, true };
3670 for (unsigned i = 0; i != 8; ++i) {
3671 int idx = MaskVals[i];
3673 InOrder[i/4] = false;
3674 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
3676 AllWordsInNewV = false;
3680 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
3681 if (AllWordsInNewV) {
3682 for (int i = 0; i != 8; ++i) {
3683 int idx = MaskVals[i];
3686 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
3687 if ((idx != i) && idx < 4)
3689 if ((idx != i) && idx > 3)
3698 // If we've eliminated the use of V2, and the new mask is a pshuflw or
3699 // pshufhw, that's as cheap as it gets. Return the new shuffle.
3700 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
3701 return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
3702 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
3706 // If we have SSSE3, and all words of the result are from 1 input vector,
3707 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
3708 // is present, fall back to case 4.
3709 if (TLI.getSubtarget()->hasSSSE3()) {
3710 SmallVector<SDValue,16> pshufbMask;
3712 // If we have elements from both input vectors, set the high bit of the
3713 // shuffle mask element to zero out elements that come from V2 in the V1
3714 // mask, and elements that come from V1 in the V2 mask, so that the two
3715 // results can be OR'd together.
3716 bool TwoInputs = V1Used && V2Used;
3717 for (unsigned i = 0; i != 8; ++i) {
3718 int EltIdx = MaskVals[i] * 2;
3719 if (TwoInputs && (EltIdx >= 16)) {
3720 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3721 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3724 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3725 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
3727 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
3728 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3729 DAG.getNode(ISD::BUILD_VECTOR, dl,
3730 MVT::v16i8, &pshufbMask[0], 16));
3732 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3734 // Calculate the shuffle mask for the second input, shuffle it, and
3735 // OR it with the first shuffled input.
3737 for (unsigned i = 0; i != 8; ++i) {
3738 int EltIdx = MaskVals[i] * 2;
3740 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3741 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3744 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3745 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
3747 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
3748 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3749 DAG.getNode(ISD::BUILD_VECTOR, dl,
3750 MVT::v16i8, &pshufbMask[0], 16));
3751 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3752 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3755 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
3756 // and update MaskVals with new element order.
3757 BitVector InOrder(8);
3758 if (BestLoQuad >= 0) {
3759 SmallVector<int, 8> MaskV;
3760 for (int i = 0; i != 4; ++i) {
3761 int idx = MaskVals[i];
3763 MaskV.push_back(-1);
3765 } else if ((idx / 4) == BestLoQuad) {
3766 MaskV.push_back(idx & 3);
3769 MaskV.push_back(-1);
3772 for (unsigned i = 4; i != 8; ++i)
3774 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3778 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
3779 // and update MaskVals with the new element order.
3780 if (BestHiQuad >= 0) {
3781 SmallVector<int, 8> MaskV;
3782 for (unsigned i = 0; i != 4; ++i)
3784 for (unsigned i = 4; i != 8; ++i) {
3785 int idx = MaskVals[i];
3787 MaskV.push_back(-1);
3789 } else if ((idx / 4) == BestHiQuad) {
3790 MaskV.push_back((idx & 3) + 4);
3793 MaskV.push_back(-1);
3796 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
3800 // In case BestHi & BestLo were both -1, which means each quadword has a word
3801 // from each of the four input quadwords, calculate the InOrder bitvector now
3802 // before falling through to the insert/extract cleanup.
3803 if (BestLoQuad == -1 && BestHiQuad == -1) {
3805 for (int i = 0; i != 8; ++i)
3806 if (MaskVals[i] < 0 || MaskVals[i] == i)
3810 // The other elements are put in the right place using pextrw and pinsrw.
3811 for (unsigned i = 0; i != 8; ++i) {
3814 int EltIdx = MaskVals[i];
3817 SDValue ExtOp = (EltIdx < 8)
3818 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
3819 DAG.getIntPtrConstant(EltIdx))
3820 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
3821 DAG.getIntPtrConstant(EltIdx - 8));
3822 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
3823 DAG.getIntPtrConstant(i));
3828 // v16i8 shuffles - Prefer shuffles in the following order:
3829 // 1. [ssse3] 1 x pshufb
3830 // 2. [ssse3] 2 x pshufb + 1 x por
3831 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
3833 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
3834 SelectionDAG &DAG, X86TargetLowering &TLI) {
3835 SDValue V1 = SVOp->getOperand(0);
3836 SDValue V2 = SVOp->getOperand(1);
3837 DebugLoc dl = SVOp->getDebugLoc();
3838 SmallVector<int, 16> MaskVals;
3839 SVOp->getMask(MaskVals);
3841 // If we have SSSE3, case 1 is generated when all result bytes come from
3842 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
3843 // present, fall back to case 3.
3844 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
3847 for (unsigned i = 0; i < 16; ++i) {
3848 int EltIdx = MaskVals[i];
3857 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
3858 if (TLI.getSubtarget()->hasSSSE3()) {
3859 SmallVector<SDValue,16> pshufbMask;
3861 // If all result elements are from one input vector, then only translate
3862 // undef mask values to 0x80 (zero out result) in the pshufb mask.
3864 // Otherwise, we have elements from both input vectors, and must zero out
3865 // elements that come from V2 in the first mask, and V1 in the second mask
3866 // so that we can OR them together.
3867 bool TwoInputs = !(V1Only || V2Only);
3868 for (unsigned i = 0; i != 16; ++i) {
3869 int EltIdx = MaskVals[i];
3870 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
3871 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3874 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
3876 // If all the elements are from V2, assign it to V1 and return after
3877 // building the first pshufb.
3880 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
3881 DAG.getNode(ISD::BUILD_VECTOR, dl,
3882 MVT::v16i8, &pshufbMask[0], 16));
3886 // Calculate the shuffle mask for the second input, shuffle it, and
3887 // OR it with the first shuffled input.
3889 for (unsigned i = 0; i != 16; ++i) {
3890 int EltIdx = MaskVals[i];
3892 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
3895 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
3897 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
3898 DAG.getNode(ISD::BUILD_VECTOR, dl,
3899 MVT::v16i8, &pshufbMask[0], 16));
3900 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
3903 // No SSSE3 - Calculate in place words and then fix all out of place words
3904 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
3905 // the 16 different words that comprise the two doublequadword input vectors.
3906 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
3907 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
3908 SDValue NewV = V2Only ? V2 : V1;
3909 for (int i = 0; i != 8; ++i) {
3910 int Elt0 = MaskVals[i*2];
3911 int Elt1 = MaskVals[i*2+1];
3913 // This word of the result is all undef, skip it.
3914 if (Elt0 < 0 && Elt1 < 0)
3917 // This word of the result is already in the correct place, skip it.
3918 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
3920 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
3923 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
3924 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
3927 // If Elt0 and Elt1 are defined, are consecutive, and can be load
3928 // using a single extract together, load it and store it.
3929 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
3930 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3931 DAG.getIntPtrConstant(Elt1 / 2));
3932 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3933 DAG.getIntPtrConstant(i));
3937 // If Elt1 is defined, extract it from the appropriate source. If the
3938 // source byte is not also odd, shift the extracted word left 8 bits
3939 // otherwise clear the bottom 8 bits if we need to do an or.
3941 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
3942 DAG.getIntPtrConstant(Elt1 / 2));
3943 if ((Elt1 & 1) == 0)
3944 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
3945 DAG.getConstant(8, TLI.getShiftAmountTy()));
3947 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
3948 DAG.getConstant(0xFF00, MVT::i16));
3950 // If Elt0 is defined, extract it from the appropriate source. If the
3951 // source byte is not also even, shift the extracted word right 8 bits. If
3952 // Elt1 was also defined, OR the extracted values together before
3953 // inserting them in the result.
3955 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
3956 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
3957 if ((Elt0 & 1) != 0)
3958 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
3959 DAG.getConstant(8, TLI.getShiftAmountTy()));
3961 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
3962 DAG.getConstant(0x00FF, MVT::i16));
3963 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
3966 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
3967 DAG.getIntPtrConstant(i));
3969 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
3972 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
3973 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
3974 /// done when every pair / quad of shuffle mask elements point to elements in
3975 /// the right sequence. e.g.
3976 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
3978 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
3980 TargetLowering &TLI, DebugLoc dl) {
3981 EVT VT = SVOp->getValueType(0);
3982 SDValue V1 = SVOp->getOperand(0);
3983 SDValue V2 = SVOp->getOperand(1);
3984 unsigned NumElems = VT.getVectorNumElements();
3985 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
3986 EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
3987 EVT MaskEltVT = MaskVT.getVectorElementType();
3989 switch (VT.getSimpleVT().SimpleTy) {
3990 default: assert(false && "Unexpected!");
3991 case MVT::v4f32: NewVT = MVT::v2f64; break;
3992 case MVT::v4i32: NewVT = MVT::v2i64; break;
3993 case MVT::v8i16: NewVT = MVT::v4i32; break;
3994 case MVT::v16i8: NewVT = MVT::v4i32; break;
3997 if (NewWidth == 2) {
4003 int Scale = NumElems / NewWidth;
4004 SmallVector<int, 8> MaskVec;
4005 for (unsigned i = 0; i < NumElems; i += Scale) {
4007 for (int j = 0; j < Scale; ++j) {
4008 int EltIdx = SVOp->getMaskElt(i+j);
4012 StartIdx = EltIdx - (EltIdx % Scale);
4013 if (EltIdx != StartIdx + j)
4017 MaskVec.push_back(-1);
4019 MaskVec.push_back(StartIdx / Scale);
4022 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4023 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4024 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4027 /// getVZextMovL - Return a zero-extending vector move low node.
4029 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4030 SDValue SrcOp, SelectionDAG &DAG,
4031 const X86Subtarget *Subtarget, DebugLoc dl) {
4032 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4033 LoadSDNode *LD = NULL;
4034 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4035 LD = dyn_cast<LoadSDNode>(SrcOp);
4037 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4039 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4040 if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4041 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4042 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4043 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4045 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4046 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4047 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4048 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4056 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4057 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4058 DAG.getNode(ISD::BIT_CONVERT, dl,
4062 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4065 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4066 SDValue V1 = SVOp->getOperand(0);
4067 SDValue V2 = SVOp->getOperand(1);
4068 DebugLoc dl = SVOp->getDebugLoc();
4069 EVT VT = SVOp->getValueType(0);
4071 SmallVector<std::pair<int, int>, 8> Locs;
4073 SmallVector<int, 8> Mask1(4U, -1);
4074 SmallVector<int, 8> PermMask;
4075 SVOp->getMask(PermMask);
4079 for (unsigned i = 0; i != 4; ++i) {
4080 int Idx = PermMask[i];
4082 Locs[i] = std::make_pair(-1, -1);
4084 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4086 Locs[i] = std::make_pair(0, NumLo);
4090 Locs[i] = std::make_pair(1, NumHi);
4092 Mask1[2+NumHi] = Idx;
4098 if (NumLo <= 2 && NumHi <= 2) {
4099 // If no more than two elements come from either vector. This can be
4100 // implemented with two shuffles. First shuffle gather the elements.
4101 // The second shuffle, which takes the first shuffle as both of its
4102 // vector operands, put the elements into the right order.
4103 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4105 SmallVector<int, 8> Mask2(4U, -1);
4107 for (unsigned i = 0; i != 4; ++i) {
4108 if (Locs[i].first == -1)
4111 unsigned Idx = (i < 2) ? 0 : 4;
4112 Idx += Locs[i].first * 2 + Locs[i].second;
4117 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4118 } else if (NumLo == 3 || NumHi == 3) {
4119 // Otherwise, we must have three elements from one vector, call it X, and
4120 // one element from the other, call it Y. First, use a shufps to build an
4121 // intermediate vector with the one element from Y and the element from X
4122 // that will be in the same half in the final destination (the indexes don't
4123 // matter). Then, use a shufps to build the final vector, taking the half
4124 // containing the element from Y from the intermediate, and the other half
4127 // Normalize it so the 3 elements come from V1.
4128 CommuteVectorShuffleMask(PermMask, VT);
4132 // Find the element from V2.
4134 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4135 int Val = PermMask[HiIndex];
4142 Mask1[0] = PermMask[HiIndex];
4144 Mask1[2] = PermMask[HiIndex^1];
4146 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4149 Mask1[0] = PermMask[0];
4150 Mask1[1] = PermMask[1];
4151 Mask1[2] = HiIndex & 1 ? 6 : 4;
4152 Mask1[3] = HiIndex & 1 ? 4 : 6;
4153 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4155 Mask1[0] = HiIndex & 1 ? 2 : 0;
4156 Mask1[1] = HiIndex & 1 ? 0 : 2;
4157 Mask1[2] = PermMask[2];
4158 Mask1[3] = PermMask[3];
4163 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4167 // Break it into (shuffle shuffle_hi, shuffle_lo).
4169 SmallVector<int,8> LoMask(4U, -1);
4170 SmallVector<int,8> HiMask(4U, -1);
4172 SmallVector<int,8> *MaskPtr = &LoMask;
4173 unsigned MaskIdx = 0;
4176 for (unsigned i = 0; i != 4; ++i) {
4183 int Idx = PermMask[i];
4185 Locs[i] = std::make_pair(-1, -1);
4186 } else if (Idx < 4) {
4187 Locs[i] = std::make_pair(MaskIdx, LoIdx);
4188 (*MaskPtr)[LoIdx] = Idx;
4191 Locs[i] = std::make_pair(MaskIdx, HiIdx);
4192 (*MaskPtr)[HiIdx] = Idx;
4197 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4198 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4199 SmallVector<int, 8> MaskOps;
4200 for (unsigned i = 0; i != 4; ++i) {
4201 if (Locs[i].first == -1) {
4202 MaskOps.push_back(-1);
4204 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4205 MaskOps.push_back(Idx);
4208 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4212 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
4213 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4214 SDValue V1 = Op.getOperand(0);
4215 SDValue V2 = Op.getOperand(1);
4216 EVT VT = Op.getValueType();
4217 DebugLoc dl = Op.getDebugLoc();
4218 unsigned NumElems = VT.getVectorNumElements();
4219 bool isMMX = VT.getSizeInBits() == 64;
4220 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4221 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4222 bool V1IsSplat = false;
4223 bool V2IsSplat = false;
4225 if (isZeroShuffle(SVOp))
4226 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4228 // Promote splats to v4f32.
4229 if (SVOp->isSplat()) {
4230 if (isMMX || NumElems < 4)
4232 return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4235 // If the shuffle can be profitably rewritten as a narrower shuffle, then
4237 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4238 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4239 if (NewOp.getNode())
4240 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4241 LowerVECTOR_SHUFFLE(NewOp, DAG));
4242 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4243 // FIXME: Figure out a cleaner way to do this.
4244 // Try to make use of movq to zero out the top part.
4245 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4246 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4247 if (NewOp.getNode()) {
4248 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4249 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4250 DAG, Subtarget, dl);
4252 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4253 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4254 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4255 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4256 DAG, Subtarget, dl);
4260 if (X86::isPSHUFDMask(SVOp))
4263 // Check if this can be converted into a logical shift.
4264 bool isLeft = false;
4267 bool isShift = getSubtarget()->hasSSE2() &&
4268 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4269 if (isShift && ShVal.hasOneUse()) {
4270 // If the shifted value has multiple uses, it may be cheaper to use
4271 // v_set0 + movlhps or movhlps, etc.
4272 EVT EltVT = VT.getVectorElementType();
4273 ShAmt *= EltVT.getSizeInBits();
4274 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4277 if (X86::isMOVLMask(SVOp)) {
4280 if (ISD::isBuildVectorAllZeros(V1.getNode()))
4281 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4286 // FIXME: fold these into legal mask.
4287 if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4288 X86::isMOVSLDUPMask(SVOp) ||
4289 X86::isMOVHLPSMask(SVOp) ||
4290 X86::isMOVLHPSMask(SVOp) ||
4291 X86::isMOVLPMask(SVOp)))
4294 if (ShouldXformToMOVHLPS(SVOp) ||
4295 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4296 return CommuteVectorShuffle(SVOp, DAG);
4299 // No better options. Use a vshl / vsrl.
4300 EVT EltVT = VT.getVectorElementType();
4301 ShAmt *= EltVT.getSizeInBits();
4302 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4305 bool Commuted = false;
4306 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4307 // 1,1,1,1 -> v8i16 though.
4308 V1IsSplat = isSplatVector(V1.getNode());
4309 V2IsSplat = isSplatVector(V2.getNode());
4311 // Canonicalize the splat or undef, if present, to be on the RHS.
4312 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4313 Op = CommuteVectorShuffle(SVOp, DAG);
4314 SVOp = cast<ShuffleVectorSDNode>(Op);
4315 V1 = SVOp->getOperand(0);
4316 V2 = SVOp->getOperand(1);
4317 std::swap(V1IsSplat, V2IsSplat);
4318 std::swap(V1IsUndef, V2IsUndef);
4322 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4323 // Shuffling low element of v1 into undef, just return v1.
4326 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4327 // the instruction selector will not match, so get a canonical MOVL with
4328 // swapped operands to undo the commute.
4329 return getMOVL(DAG, dl, VT, V2, V1);
4332 if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4333 X86::isUNPCKH_v_undef_Mask(SVOp) ||
4334 X86::isUNPCKLMask(SVOp) ||
4335 X86::isUNPCKHMask(SVOp))
4339 // Normalize mask so all entries that point to V2 points to its first
4340 // element then try to match unpck{h|l} again. If match, return a
4341 // new vector_shuffle with the corrected mask.
4342 SDValue NewMask = NormalizeMask(SVOp, DAG);
4343 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4344 if (NSVOp != SVOp) {
4345 if (X86::isUNPCKLMask(NSVOp, true)) {
4347 } else if (X86::isUNPCKHMask(NSVOp, true)) {
4354 // Commute is back and try unpck* again.
4355 // FIXME: this seems wrong.
4356 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4357 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4358 if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4359 X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4360 X86::isUNPCKLMask(NewSVOp) ||
4361 X86::isUNPCKHMask(NewSVOp))
4365 // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4367 // Normalize the node to match x86 shuffle ops if needed
4368 if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4369 return CommuteVectorShuffle(SVOp, DAG);
4371 // Check for legal shuffle and return?
4372 SmallVector<int, 16> PermMask;
4373 SVOp->getMask(PermMask);
4374 if (isShuffleMaskLegal(PermMask, VT))
4377 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4378 if (VT == MVT::v8i16) {
4379 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4380 if (NewOp.getNode())
4384 if (VT == MVT::v16i8) {
4385 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4386 if (NewOp.getNode())
4390 // Handle all 4 wide cases with a number of shuffles except for MMX.
4391 if (NumElems == 4 && !isMMX)
4392 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4398 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4399 SelectionDAG &DAG) {
4400 EVT VT = Op.getValueType();
4401 DebugLoc dl = Op.getDebugLoc();
4402 if (VT.getSizeInBits() == 8) {
4403 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4404 Op.getOperand(0), Op.getOperand(1));
4405 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4406 DAG.getValueType(VT));
4407 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4408 } else if (VT.getSizeInBits() == 16) {
4409 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4410 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4412 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4413 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4414 DAG.getNode(ISD::BIT_CONVERT, dl,
4418 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4419 Op.getOperand(0), Op.getOperand(1));
4420 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4421 DAG.getValueType(VT));
4422 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4423 } else if (VT == MVT::f32) {
4424 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4425 // the result back to FR32 register. It's only worth matching if the
4426 // result has a single use which is a store or a bitcast to i32. And in
4427 // the case of a store, it's not worth it if the index is a constant 0,
4428 // because a MOVSSmr can be used instead, which is smaller and faster.
4429 if (!Op.hasOneUse())
4431 SDNode *User = *Op.getNode()->use_begin();
4432 if ((User->getOpcode() != ISD::STORE ||
4433 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4434 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4435 (User->getOpcode() != ISD::BIT_CONVERT ||
4436 User->getValueType(0) != MVT::i32))
4438 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4439 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4442 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4443 } else if (VT == MVT::i32) {
4444 // ExtractPS works with constant index.
4445 if (isa<ConstantSDNode>(Op.getOperand(1)))
4453 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4454 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4457 if (Subtarget->hasSSE41()) {
4458 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4463 EVT VT = Op.getValueType();
4464 DebugLoc dl = Op.getDebugLoc();
4465 // TODO: handle v16i8.
4466 if (VT.getSizeInBits() == 16) {
4467 SDValue Vec = Op.getOperand(0);
4468 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4470 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4471 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4472 DAG.getNode(ISD::BIT_CONVERT, dl,
4475 // Transform it so it match pextrw which produces a 32-bit result.
4476 EVT EltVT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy+1);
4477 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
4478 Op.getOperand(0), Op.getOperand(1));
4479 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
4480 DAG.getValueType(VT));
4481 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4482 } else if (VT.getSizeInBits() == 32) {
4483 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4487 // SHUFPS the element to the lowest double word, then movss.
4488 int Mask[4] = { Idx, -1, -1, -1 };
4489 EVT VVT = Op.getOperand(0).getValueType();
4490 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4491 DAG.getUNDEF(VVT), Mask);
4492 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4493 DAG.getIntPtrConstant(0));
4494 } else if (VT.getSizeInBits() == 64) {
4495 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4496 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4497 // to match extract_elt for f64.
4498 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4502 // UNPCKHPD the element to the lowest double word, then movsd.
4503 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4504 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4505 int Mask[2] = { 1, -1 };
4506 EVT VVT = Op.getOperand(0).getValueType();
4507 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4508 DAG.getUNDEF(VVT), Mask);
4509 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4510 DAG.getIntPtrConstant(0));
4517 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG){
4518 EVT VT = Op.getValueType();
4519 EVT EltVT = VT.getVectorElementType();
4520 DebugLoc dl = Op.getDebugLoc();
4522 SDValue N0 = Op.getOperand(0);
4523 SDValue N1 = Op.getOperand(1);
4524 SDValue N2 = Op.getOperand(2);
4526 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
4527 isa<ConstantSDNode>(N2)) {
4528 unsigned Opc = (EltVT.getSizeInBits() == 8) ? X86ISD::PINSRB
4530 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4532 if (N1.getValueType() != MVT::i32)
4533 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4534 if (N2.getValueType() != MVT::i32)
4535 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4536 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
4537 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
4538 // Bits [7:6] of the constant are the source select. This will always be
4539 // zero here. The DAG Combiner may combine an extract_elt index into these
4540 // bits. For example (insert (extract, 3), 2) could be matched by putting
4541 // the '3' into bits [7:6] of X86ISD::INSERTPS.
4542 // Bits [5:4] of the constant are the destination select. This is the
4543 // value of the incoming immediate.
4544 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
4545 // combine either bitwise AND or insert of float 0.0 to set these bits.
4546 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
4547 // Create this as a scalar to vector..
4548 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
4549 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
4550 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
4551 // PINSR* works with constant index.
4558 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
4559 EVT VT = Op.getValueType();
4560 EVT EltVT = VT.getVectorElementType();
4562 if (Subtarget->hasSSE41())
4563 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
4565 if (EltVT == MVT::i8)
4568 DebugLoc dl = Op.getDebugLoc();
4569 SDValue N0 = Op.getOperand(0);
4570 SDValue N1 = Op.getOperand(1);
4571 SDValue N2 = Op.getOperand(2);
4573 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
4574 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
4575 // as its second argument.
4576 if (N1.getValueType() != MVT::i32)
4577 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4578 if (N2.getValueType() != MVT::i32)
4579 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4580 return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
4586 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
4587 DebugLoc dl = Op.getDebugLoc();
4588 if (Op.getValueType() == MVT::v2f32)
4589 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
4590 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
4591 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
4592 Op.getOperand(0))));
4594 if (Op.getValueType() == MVT::v1i64 && Op.getOperand(0).getValueType() == MVT::i64)
4595 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
4597 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
4598 EVT VT = MVT::v2i32;
4599 switch (Op.getValueType().getSimpleVT().SimpleTy) {
4606 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
4607 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
4610 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
4611 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
4612 // one of the above mentioned nodes. It has to be wrapped because otherwise
4613 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
4614 // be used to form addressing mode. These wrapped nodes will be selected
4617 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
4618 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4620 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4622 unsigned char OpFlag = 0;
4623 unsigned WrapperKind = X86ISD::Wrapper;
4624 CodeModel::Model M = getTargetMachine().getCodeModel();
4626 if (Subtarget->isPICStyleRIPRel() &&
4627 (M == CodeModel::Small || M == CodeModel::Kernel))
4628 WrapperKind = X86ISD::WrapperRIP;
4629 else if (Subtarget->isPICStyleGOT())
4630 OpFlag = X86II::MO_GOTOFF;
4631 else if (Subtarget->isPICStyleStubPIC())
4632 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4634 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
4636 CP->getOffset(), OpFlag);
4637 DebugLoc DL = CP->getDebugLoc();
4638 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4639 // With PIC, the address is actually $g + Offset.
4641 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4642 DAG.getNode(X86ISD::GlobalBaseReg,
4643 DebugLoc::getUnknownLoc(), getPointerTy()),
4650 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) {
4651 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4653 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4655 unsigned char OpFlag = 0;
4656 unsigned WrapperKind = X86ISD::Wrapper;
4657 CodeModel::Model M = getTargetMachine().getCodeModel();
4659 if (Subtarget->isPICStyleRIPRel() &&
4660 (M == CodeModel::Small || M == CodeModel::Kernel))
4661 WrapperKind = X86ISD::WrapperRIP;
4662 else if (Subtarget->isPICStyleGOT())
4663 OpFlag = X86II::MO_GOTOFF;
4664 else if (Subtarget->isPICStyleStubPIC())
4665 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4667 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
4669 DebugLoc DL = JT->getDebugLoc();
4670 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4672 // With PIC, the address is actually $g + Offset.
4674 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4675 DAG.getNode(X86ISD::GlobalBaseReg,
4676 DebugLoc::getUnknownLoc(), getPointerTy()),
4684 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) {
4685 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
4687 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
4689 unsigned char OpFlag = 0;
4690 unsigned WrapperKind = X86ISD::Wrapper;
4691 CodeModel::Model M = getTargetMachine().getCodeModel();
4693 if (Subtarget->isPICStyleRIPRel() &&
4694 (M == CodeModel::Small || M == CodeModel::Kernel))
4695 WrapperKind = X86ISD::WrapperRIP;
4696 else if (Subtarget->isPICStyleGOT())
4697 OpFlag = X86II::MO_GOTOFF;
4698 else if (Subtarget->isPICStyleStubPIC())
4699 OpFlag = X86II::MO_PIC_BASE_OFFSET;
4701 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
4703 DebugLoc DL = Op.getDebugLoc();
4704 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
4707 // With PIC, the address is actually $g + Offset.
4708 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
4709 !Subtarget->is64Bit()) {
4710 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
4711 DAG.getNode(X86ISD::GlobalBaseReg,
4712 DebugLoc::getUnknownLoc(),
4721 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) {
4722 // Create the TargetBlockAddressAddress node.
4723 unsigned char OpFlags =
4724 Subtarget->ClassifyBlockAddressReference();
4725 CodeModel::Model M = getTargetMachine().getCodeModel();
4726 BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
4727 DebugLoc dl = Op.getDebugLoc();
4728 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
4729 /*isTarget=*/true, OpFlags);
4731 if (Subtarget->isPICStyleRIPRel() &&
4732 (M == CodeModel::Small || M == CodeModel::Kernel))
4733 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
4735 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4737 // With PIC, the address is actually $g + Offset.
4738 if (isGlobalRelativeToPICBase(OpFlags)) {
4739 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4740 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4748 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
4750 SelectionDAG &DAG) const {
4751 // Create the TargetGlobalAddress node, folding in the constant
4752 // offset if it is legal.
4753 unsigned char OpFlags =
4754 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
4755 CodeModel::Model M = getTargetMachine().getCodeModel();
4757 if (OpFlags == X86II::MO_NO_FLAG &&
4758 X86::isOffsetSuitableForCodeModel(Offset, M)) {
4759 // A direct static reference to a global.
4760 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
4763 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
4766 if (Subtarget->isPICStyleRIPRel() &&
4767 (M == CodeModel::Small || M == CodeModel::Kernel))
4768 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
4770 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
4772 // With PIC, the address is actually $g + Offset.
4773 if (isGlobalRelativeToPICBase(OpFlags)) {
4774 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
4775 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
4779 // For globals that require a load from a stub to get the address, emit the
4781 if (isGlobalStubReference(OpFlags))
4782 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
4783 PseudoSourceValue::getGOT(), 0);
4785 // If there was a non-zero offset that we didn't fold, create an explicit
4788 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
4789 DAG.getConstant(Offset, getPointerTy()));
4795 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) {
4796 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
4797 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
4798 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
4802 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
4803 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
4804 unsigned char OperandFlags) {
4805 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
4806 DebugLoc dl = GA->getDebugLoc();
4807 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
4808 GA->getValueType(0),
4812 SDValue Ops[] = { Chain, TGA, *InFlag };
4813 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
4815 SDValue Ops[] = { Chain, TGA };
4816 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
4818 SDValue Flag = Chain.getValue(1);
4819 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
4822 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
4824 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4827 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
4828 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
4829 DAG.getNode(X86ISD::GlobalBaseReg,
4830 DebugLoc::getUnknownLoc(),
4832 InFlag = Chain.getValue(1);
4834 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
4837 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
4839 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4841 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
4842 X86::RAX, X86II::MO_TLSGD);
4845 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
4846 // "local exec" model.
4847 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
4848 const EVT PtrVT, TLSModel::Model model,
4850 DebugLoc dl = GA->getDebugLoc();
4851 // Get the Thread Pointer
4852 SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
4853 DebugLoc::getUnknownLoc(), PtrVT,
4854 DAG.getRegister(is64Bit? X86::FS : X86::GS,
4857 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
4860 unsigned char OperandFlags = 0;
4861 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
4863 unsigned WrapperKind = X86ISD::Wrapper;
4864 if (model == TLSModel::LocalExec) {
4865 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
4866 } else if (is64Bit) {
4867 assert(model == TLSModel::InitialExec);
4868 OperandFlags = X86II::MO_GOTTPOFF;
4869 WrapperKind = X86ISD::WrapperRIP;
4871 assert(model == TLSModel::InitialExec);
4872 OperandFlags = X86II::MO_INDNTPOFF;
4875 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
4877 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
4878 GA->getOffset(), OperandFlags);
4879 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
4881 if (model == TLSModel::InitialExec)
4882 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
4883 PseudoSourceValue::getGOT(), 0);
4885 // The address of the thread local variable is the add of the thread
4886 // pointer with the offset of the variable.
4887 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
4891 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) {
4892 // TODO: implement the "local dynamic" model
4893 // TODO: implement the "initial exec"model for pic executables
4894 assert(Subtarget->isTargetELF() &&
4895 "TLS not implemented for non-ELF targets");
4896 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
4897 const GlobalValue *GV = GA->getGlobal();
4899 // If GV is an alias then use the aliasee for determining
4900 // thread-localness.
4901 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
4902 GV = GA->resolveAliasedGlobal(false);
4904 TLSModel::Model model = getTLSModel(GV,
4905 getTargetMachine().getRelocationModel());
4908 case TLSModel::GeneralDynamic:
4909 case TLSModel::LocalDynamic: // not implemented
4910 if (Subtarget->is64Bit())
4911 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
4912 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
4914 case TLSModel::InitialExec:
4915 case TLSModel::LocalExec:
4916 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
4917 Subtarget->is64Bit());
4920 llvm_unreachable("Unreachable");
4925 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
4926 /// take a 2 x i32 value to shift plus a shift amount.
4927 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) {
4928 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4929 EVT VT = Op.getValueType();
4930 unsigned VTBits = VT.getSizeInBits();
4931 DebugLoc dl = Op.getDebugLoc();
4932 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
4933 SDValue ShOpLo = Op.getOperand(0);
4934 SDValue ShOpHi = Op.getOperand(1);
4935 SDValue ShAmt = Op.getOperand(2);
4936 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
4937 DAG.getConstant(VTBits - 1, MVT::i8))
4938 : DAG.getConstant(0, VT);
4941 if (Op.getOpcode() == ISD::SHL_PARTS) {
4942 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
4943 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4945 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
4946 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
4949 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
4950 DAG.getConstant(VTBits, MVT::i8));
4951 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, VT,
4952 AndNode, DAG.getConstant(0, MVT::i8));
4955 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
4956 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
4957 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
4959 if (Op.getOpcode() == ISD::SHL_PARTS) {
4960 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4961 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4963 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
4964 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
4967 SDValue Ops[2] = { Lo, Hi };
4968 return DAG.getMergeValues(Ops, 2, dl);
4971 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4972 EVT SrcVT = Op.getOperand(0).getValueType();
4974 if (SrcVT.isVector()) {
4975 if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
4981 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
4982 "Unknown SINT_TO_FP to lower!");
4984 // These are really Legal; return the operand so the caller accepts it as
4986 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
4988 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
4989 Subtarget->is64Bit()) {
4993 DebugLoc dl = Op.getDebugLoc();
4994 unsigned Size = SrcVT.getSizeInBits()/8;
4995 MachineFunction &MF = DAG.getMachineFunction();
4996 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
4997 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
4998 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5000 PseudoSourceValue::getFixedStack(SSFI), 0);
5001 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
5004 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
5006 SelectionDAG &DAG) {
5008 DebugLoc dl = Op.getDebugLoc();
5010 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
5012 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
5014 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
5015 SmallVector<SDValue, 8> Ops;
5016 Ops.push_back(Chain);
5017 Ops.push_back(StackSlot);
5018 Ops.push_back(DAG.getValueType(SrcVT));
5019 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
5020 Tys, &Ops[0], Ops.size());
5023 Chain = Result.getValue(1);
5024 SDValue InFlag = Result.getValue(2);
5026 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5027 // shouldn't be necessary except that RFP cannot be live across
5028 // multiple blocks. When stackifier is fixed, they can be uncoupled.
5029 MachineFunction &MF = DAG.getMachineFunction();
5030 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5031 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5032 Tys = DAG.getVTList(MVT::Other);
5033 SmallVector<SDValue, 8> Ops;
5034 Ops.push_back(Chain);
5035 Ops.push_back(Result);
5036 Ops.push_back(StackSlot);
5037 Ops.push_back(DAG.getValueType(Op.getValueType()));
5038 Ops.push_back(InFlag);
5039 Chain = DAG.getNode(X86ISD::FST, dl, Tys, &Ops[0], Ops.size());
5040 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5041 PseudoSourceValue::getFixedStack(SSFI), 0);
5047 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5048 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op, SelectionDAG &DAG) {
5049 // This algorithm is not obvious. Here it is in C code, more or less:
5051 double uint64_to_double( uint32_t hi, uint32_t lo ) {
5052 static const __m128i exp = { 0x4330000045300000ULL, 0 };
5053 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5055 // Copy ints to xmm registers.
5056 __m128i xh = _mm_cvtsi32_si128( hi );
5057 __m128i xl = _mm_cvtsi32_si128( lo );
5059 // Combine into low half of a single xmm register.
5060 __m128i x = _mm_unpacklo_epi32( xh, xl );
5064 // Merge in appropriate exponents to give the integer bits the right
5066 x = _mm_unpacklo_epi32( x, exp );
5068 // Subtract away the biases to deal with the IEEE-754 double precision
5070 d = _mm_sub_pd( (__m128d) x, bias );
5072 // All conversions up to here are exact. The correctly rounded result is
5073 // calculated using the current rounding mode using the following
5075 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5076 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
5077 // store doesn't really need to be here (except
5078 // maybe to zero the other double)
5083 DebugLoc dl = Op.getDebugLoc();
5084 LLVMContext *Context = DAG.getContext();
5086 // Build some magic constants.
5087 std::vector<Constant*> CV0;
5088 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
5089 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
5090 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5091 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5092 Constant *C0 = ConstantVector::get(CV0);
5093 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5095 std::vector<Constant*> CV1;
5097 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
5099 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
5100 Constant *C1 = ConstantVector::get(CV1);
5101 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5103 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5104 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5106 DAG.getIntPtrConstant(1)));
5107 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5108 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5110 DAG.getIntPtrConstant(0)));
5111 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
5112 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5113 PseudoSourceValue::getConstantPool(), 0,
5115 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
5116 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5117 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5118 PseudoSourceValue::getConstantPool(), 0,
5120 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5122 // Add the halves; easiest way is to swap them into another reg first.
5123 int ShufMask[2] = { 1, -1 };
5124 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
5125 DAG.getUNDEF(MVT::v2f64), ShufMask);
5126 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5127 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5128 DAG.getIntPtrConstant(0));
5131 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5132 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op, SelectionDAG &DAG) {
5133 DebugLoc dl = Op.getDebugLoc();
5134 // FP constant to bias correct the final result.
5135 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5138 // Load the 32-bit value into an XMM register.
5139 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5140 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5142 DAG.getIntPtrConstant(0)));
5144 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5145 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5146 DAG.getIntPtrConstant(0));
5148 // Or the load with the bias.
5149 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5150 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5151 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5153 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5154 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5155 MVT::v2f64, Bias)));
5156 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5157 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5158 DAG.getIntPtrConstant(0));
5160 // Subtract the bias.
5161 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5163 // Handle final rounding.
5164 EVT DestVT = Op.getValueType();
5166 if (DestVT.bitsLT(MVT::f64)) {
5167 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5168 DAG.getIntPtrConstant(0));
5169 } else if (DestVT.bitsGT(MVT::f64)) {
5170 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5173 // Handle final rounding.
5177 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
5178 SDValue N0 = Op.getOperand(0);
5179 DebugLoc dl = Op.getDebugLoc();
5181 // Now not UINT_TO_FP is legal (it's marked custom), dag combiner won't
5182 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5183 // the optimization here.
5184 if (DAG.SignBitIsZero(N0))
5185 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5187 EVT SrcVT = N0.getValueType();
5188 if (SrcVT == MVT::i64) {
5189 // We only handle SSE2 f64 target here; caller can expand the rest.
5190 if (Op.getValueType() != MVT::f64 || !X86ScalarSSEf64)
5193 return LowerUINT_TO_FP_i64(Op, DAG);
5194 } else if (SrcVT == MVT::i32 && X86ScalarSSEf64) {
5195 return LowerUINT_TO_FP_i32(Op, DAG);
5198 assert(SrcVT == MVT::i32 && "Unknown UINT_TO_FP to lower!");
5200 // Make a 64-bit buffer, and use it to build an FILD.
5201 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5202 SDValue WordOff = DAG.getConstant(4, getPointerTy());
5203 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5204 getPointerTy(), StackSlot, WordOff);
5205 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5206 StackSlot, NULL, 0);
5207 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5208 OffsetSlot, NULL, 0);
5209 return BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5212 std::pair<SDValue,SDValue> X86TargetLowering::
5213 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) {
5214 DebugLoc dl = Op.getDebugLoc();
5216 EVT DstTy = Op.getValueType();
5219 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5223 assert(DstTy.getSimpleVT() <= MVT::i64 &&
5224 DstTy.getSimpleVT() >= MVT::i16 &&
5225 "Unknown FP_TO_SINT to lower!");
5227 // These are really Legal.
5228 if (DstTy == MVT::i32 &&
5229 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5230 return std::make_pair(SDValue(), SDValue());
5231 if (Subtarget->is64Bit() &&
5232 DstTy == MVT::i64 &&
5233 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5234 return std::make_pair(SDValue(), SDValue());
5236 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5238 MachineFunction &MF = DAG.getMachineFunction();
5239 unsigned MemSize = DstTy.getSizeInBits()/8;
5240 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5241 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5244 switch (DstTy.getSimpleVT().SimpleTy) {
5245 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5246 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5247 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5248 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5251 SDValue Chain = DAG.getEntryNode();
5252 SDValue Value = Op.getOperand(0);
5253 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5254 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5255 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5256 PseudoSourceValue::getFixedStack(SSFI), 0);
5257 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5259 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5261 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5262 Chain = Value.getValue(1);
5263 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5264 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5267 // Build the FP_TO_INT*_IN_MEM
5268 SDValue Ops[] = { Chain, Value, StackSlot };
5269 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5271 return std::make_pair(FIST, StackSlot);
5274 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
5275 if (Op.getValueType().isVector()) {
5276 if (Op.getValueType() == MVT::v2i32 &&
5277 Op.getOperand(0).getValueType() == MVT::v2f64) {
5283 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5284 SDValue FIST = Vals.first, StackSlot = Vals.second;
5285 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5286 if (FIST.getNode() == 0) return Op;
5289 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5290 FIST, StackSlot, NULL, 0);
5293 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op, SelectionDAG &DAG) {
5294 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5295 SDValue FIST = Vals.first, StackSlot = Vals.second;
5296 assert(FIST.getNode() && "Unexpected failure");
5299 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5300 FIST, StackSlot, NULL, 0);
5303 SDValue X86TargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) {
5304 LLVMContext *Context = DAG.getContext();
5305 DebugLoc dl = Op.getDebugLoc();
5306 EVT VT = Op.getValueType();
5309 EltVT = VT.getVectorElementType();
5310 std::vector<Constant*> CV;
5311 if (EltVT == MVT::f64) {
5312 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5316 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5322 Constant *C = ConstantVector::get(CV);
5323 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5324 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5325 PseudoSourceValue::getConstantPool(), 0,
5327 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5330 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) {
5331 LLVMContext *Context = DAG.getContext();
5332 DebugLoc dl = Op.getDebugLoc();
5333 EVT VT = Op.getValueType();
5336 EltVT = VT.getVectorElementType();
5337 std::vector<Constant*> CV;
5338 if (EltVT == MVT::f64) {
5339 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5343 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5349 Constant *C = ConstantVector::get(CV);
5350 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5351 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5352 PseudoSourceValue::getConstantPool(), 0,
5354 if (VT.isVector()) {
5355 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5356 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5357 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5359 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5361 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5365 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
5366 LLVMContext *Context = DAG.getContext();
5367 SDValue Op0 = Op.getOperand(0);
5368 SDValue Op1 = Op.getOperand(1);
5369 DebugLoc dl = Op.getDebugLoc();
5370 EVT VT = Op.getValueType();
5371 EVT SrcVT = Op1.getValueType();
5373 // If second operand is smaller, extend it first.
5374 if (SrcVT.bitsLT(VT)) {
5375 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5378 // And if it is bigger, shrink it first.
5379 if (SrcVT.bitsGT(VT)) {
5380 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5384 // At this point the operands and the result should have the same
5385 // type, and that won't be f80 since that is not custom lowered.
5387 // First get the sign bit of second operand.
5388 std::vector<Constant*> CV;
5389 if (SrcVT == MVT::f64) {
5390 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
5391 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5393 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
5394 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5395 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5396 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5398 Constant *C = ConstantVector::get(CV);
5399 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5400 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5401 PseudoSourceValue::getConstantPool(), 0,
5403 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5405 // Shift sign bit right or left if the two operands have different types.
5406 if (SrcVT.bitsGT(VT)) {
5407 // Op0 is MVT::f32, Op1 is MVT::f64.
5408 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5409 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5410 DAG.getConstant(32, MVT::i32));
5411 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5412 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5413 DAG.getIntPtrConstant(0));
5416 // Clear first operand sign bit.
5418 if (VT == MVT::f64) {
5419 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
5420 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5422 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
5423 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5424 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5425 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5427 C = ConstantVector::get(CV);
5428 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5429 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5430 PseudoSourceValue::getConstantPool(), 0,
5432 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5434 // Or the value with the sign bit.
5435 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5438 /// Emit nodes that will be selected as "test Op0,Op0", or something
5440 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5441 SelectionDAG &DAG) {
5442 DebugLoc dl = Op.getDebugLoc();
5444 // CF and OF aren't always set the way we want. Determine which
5445 // of these we need.
5446 bool NeedCF = false;
5447 bool NeedOF = false;
5449 case X86::COND_A: case X86::COND_AE:
5450 case X86::COND_B: case X86::COND_BE:
5453 case X86::COND_G: case X86::COND_GE:
5454 case X86::COND_L: case X86::COND_LE:
5455 case X86::COND_O: case X86::COND_NO:
5461 // See if we can use the EFLAGS value from the operand instead of
5462 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5463 // we prove that the arithmetic won't overflow, we can't use OF or CF.
5464 if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5465 unsigned Opcode = 0;
5466 unsigned NumOperands = 0;
5467 switch (Op.getNode()->getOpcode()) {
5469 // Due to an isel shortcoming, be conservative if this add is likely to
5470 // be selected as part of a load-modify-store instruction. When the root
5471 // node in a match is a store, isel doesn't know how to remap non-chain
5472 // non-flag uses of other nodes in the match, such as the ADD in this
5473 // case. This leads to the ADD being left around and reselected, with
5474 // the result being two adds in the output.
5475 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5476 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5477 if (UI->getOpcode() == ISD::STORE)
5479 if (ConstantSDNode *C =
5480 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5481 // An add of one will be selected as an INC.
5482 if (C->getAPIntValue() == 1) {
5483 Opcode = X86ISD::INC;
5487 // An add of negative one (subtract of one) will be selected as a DEC.
5488 if (C->getAPIntValue().isAllOnesValue()) {
5489 Opcode = X86ISD::DEC;
5494 // Otherwise use a regular EFLAGS-setting add.
5495 Opcode = X86ISD::ADD;
5499 // If the primary and result isn't used, don't bother using X86ISD::AND,
5500 // because a TEST instruction will be better.
5501 bool NonFlagUse = false;
5502 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5503 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5504 if (UI->getOpcode() != ISD::BRCOND &&
5505 UI->getOpcode() != ISD::SELECT &&
5506 UI->getOpcode() != ISD::SETCC) {
5517 // Due to the ISEL shortcoming noted above, be conservative if this op is
5518 // likely to be selected as part of a load-modify-store instruction.
5519 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5520 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5521 if (UI->getOpcode() == ISD::STORE)
5523 // Otherwise use a regular EFLAGS-setting instruction.
5524 switch (Op.getNode()->getOpcode()) {
5525 case ISD::SUB: Opcode = X86ISD::SUB; break;
5526 case ISD::OR: Opcode = X86ISD::OR; break;
5527 case ISD::XOR: Opcode = X86ISD::XOR; break;
5528 case ISD::AND: Opcode = X86ISD::AND; break;
5529 default: llvm_unreachable("unexpected operator!");
5540 return SDValue(Op.getNode(), 1);
5546 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
5547 SmallVector<SDValue, 4> Ops;
5548 for (unsigned i = 0; i != NumOperands; ++i)
5549 Ops.push_back(Op.getOperand(i));
5550 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
5551 DAG.ReplaceAllUsesWith(Op, New);
5552 return SDValue(New.getNode(), 1);
5556 // Otherwise just emit a CMP with 0, which is the TEST pattern.
5557 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
5558 DAG.getConstant(0, Op.getValueType()));
5561 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
5563 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
5564 SelectionDAG &DAG) {
5565 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
5566 if (C->getAPIntValue() == 0)
5567 return EmitTest(Op0, X86CC, DAG);
5569 DebugLoc dl = Op0.getDebugLoc();
5570 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
5573 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) {
5574 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
5575 SDValue Op0 = Op.getOperand(0);
5576 SDValue Op1 = Op.getOperand(1);
5577 DebugLoc dl = Op.getDebugLoc();
5578 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5580 // Lower (X & (1 << N)) == 0 to BT(X, N).
5581 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
5582 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
5583 if (Op0.getOpcode() == ISD::AND &&
5585 Op1.getOpcode() == ISD::Constant &&
5586 cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
5587 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
5589 if (Op0.getOperand(1).getOpcode() == ISD::SHL) {
5590 if (ConstantSDNode *Op010C =
5591 dyn_cast<ConstantSDNode>(Op0.getOperand(1).getOperand(0)))
5592 if (Op010C->getZExtValue() == 1) {
5593 LHS = Op0.getOperand(0);
5594 RHS = Op0.getOperand(1).getOperand(1);
5596 } else if (Op0.getOperand(0).getOpcode() == ISD::SHL) {
5597 if (ConstantSDNode *Op000C =
5598 dyn_cast<ConstantSDNode>(Op0.getOperand(0).getOperand(0)))
5599 if (Op000C->getZExtValue() == 1) {
5600 LHS = Op0.getOperand(1);
5601 RHS = Op0.getOperand(0).getOperand(1);
5603 } else if (Op0.getOperand(1).getOpcode() == ISD::Constant) {
5604 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op0.getOperand(1));
5605 SDValue AndLHS = Op0.getOperand(0);
5606 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
5607 LHS = AndLHS.getOperand(0);
5608 RHS = AndLHS.getOperand(1);
5612 if (LHS.getNode()) {
5613 // If LHS is i8, promote it to i16 with any_extend. There is no i8 BT
5614 // instruction. Since the shift amount is in-range-or-undefined, we know
5615 // that doing a bittest on the i16 value is ok. We extend to i32 because
5616 // the encoding for the i16 version is larger than the i32 version.
5617 if (LHS.getValueType() == MVT::i8)
5618 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
5620 // If the operand types disagree, extend the shift amount to match. Since
5621 // BT ignores high bits (like shifts) we can use anyextend.
5622 if (LHS.getValueType() != RHS.getValueType())
5623 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
5625 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
5626 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
5627 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5628 DAG.getConstant(Cond, MVT::i8), BT);
5632 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5633 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
5634 if (X86CC == X86::COND_INVALID)
5637 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
5638 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
5639 DAG.getConstant(X86CC, MVT::i8), Cond);
5642 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5644 SDValue Op0 = Op.getOperand(0);
5645 SDValue Op1 = Op.getOperand(1);
5646 SDValue CC = Op.getOperand(2);
5647 EVT VT = Op.getValueType();
5648 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5649 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
5650 DebugLoc dl = Op.getDebugLoc();
5654 EVT VT0 = Op0.getValueType();
5655 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
5656 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
5659 switch (SetCCOpcode) {
5662 case ISD::SETEQ: SSECC = 0; break;
5664 case ISD::SETGT: Swap = true; // Fallthrough
5666 case ISD::SETOLT: SSECC = 1; break;
5668 case ISD::SETGE: Swap = true; // Fallthrough
5670 case ISD::SETOLE: SSECC = 2; break;
5671 case ISD::SETUO: SSECC = 3; break;
5673 case ISD::SETNE: SSECC = 4; break;
5674 case ISD::SETULE: Swap = true;
5675 case ISD::SETUGE: SSECC = 5; break;
5676 case ISD::SETULT: Swap = true;
5677 case ISD::SETUGT: SSECC = 6; break;
5678 case ISD::SETO: SSECC = 7; break;
5681 std::swap(Op0, Op1);
5683 // In the two special cases we can't handle, emit two comparisons.
5685 if (SetCCOpcode == ISD::SETUEQ) {
5687 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
5688 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
5689 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
5691 else if (SetCCOpcode == ISD::SETONE) {
5693 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
5694 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
5695 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
5697 llvm_unreachable("Illegal FP comparison");
5699 // Handle all other FP comparisons here.
5700 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
5703 // We are handling one of the integer comparisons here. Since SSE only has
5704 // GT and EQ comparisons for integer, swapping operands and multiple
5705 // operations may be required for some comparisons.
5706 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
5707 bool Swap = false, Invert = false, FlipSigns = false;
5709 switch (VT.getSimpleVT().SimpleTy) {
5712 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
5714 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
5716 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
5717 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
5720 switch (SetCCOpcode) {
5722 case ISD::SETNE: Invert = true;
5723 case ISD::SETEQ: Opc = EQOpc; break;
5724 case ISD::SETLT: Swap = true;
5725 case ISD::SETGT: Opc = GTOpc; break;
5726 case ISD::SETGE: Swap = true;
5727 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
5728 case ISD::SETULT: Swap = true;
5729 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
5730 case ISD::SETUGE: Swap = true;
5731 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
5734 std::swap(Op0, Op1);
5736 // Since SSE has no unsigned integer comparisons, we need to flip the sign
5737 // bits of the inputs before performing those operations.
5739 EVT EltVT = VT.getVectorElementType();
5740 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
5742 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
5743 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
5745 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
5746 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
5749 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
5751 // If the logical-not of the result is required, perform that now.
5753 Result = DAG.getNOT(dl, Result, VT);
5758 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
5759 static bool isX86LogicalCmp(SDValue Op) {
5760 unsigned Opc = Op.getNode()->getOpcode();
5761 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
5763 if (Op.getResNo() == 1 &&
5764 (Opc == X86ISD::ADD ||
5765 Opc == X86ISD::SUB ||
5766 Opc == X86ISD::SMUL ||
5767 Opc == X86ISD::UMUL ||
5768 Opc == X86ISD::INC ||
5769 Opc == X86ISD::DEC ||
5770 Opc == X86ISD::OR ||
5771 Opc == X86ISD::XOR ||
5772 Opc == X86ISD::AND))
5778 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) {
5779 bool addTest = true;
5780 SDValue Cond = Op.getOperand(0);
5781 DebugLoc dl = Op.getDebugLoc();
5784 if (Cond.getOpcode() == ISD::SETCC) {
5785 SDValue NewCond = LowerSETCC(Cond, DAG);
5786 if (NewCond.getNode())
5790 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5791 // setting operand in place of the X86ISD::SETCC.
5792 if (Cond.getOpcode() == X86ISD::SETCC) {
5793 CC = Cond.getOperand(0);
5795 SDValue Cmp = Cond.getOperand(1);
5796 unsigned Opc = Cmp.getOpcode();
5797 EVT VT = Op.getValueType();
5799 bool IllegalFPCMov = false;
5800 if (VT.isFloatingPoint() && !VT.isVector() &&
5801 !isScalarFPTypeInSSEReg(VT)) // FPStack?
5802 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
5804 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
5805 Opc == X86ISD::BT) { // FIXME
5812 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5813 Cond = EmitTest(Cond, X86::COND_NE, DAG);
5816 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
5817 SmallVector<SDValue, 4> Ops;
5818 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
5819 // condition is true.
5820 Ops.push_back(Op.getOperand(2));
5821 Ops.push_back(Op.getOperand(1));
5823 Ops.push_back(Cond);
5824 return DAG.getNode(X86ISD::CMOV, dl, VTs, &Ops[0], Ops.size());
5827 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
5828 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
5829 // from the AND / OR.
5830 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
5831 Opc = Op.getOpcode();
5832 if (Opc != ISD::OR && Opc != ISD::AND)
5834 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5835 Op.getOperand(0).hasOneUse() &&
5836 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
5837 Op.getOperand(1).hasOneUse());
5840 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
5841 // 1 and that the SETCC node has a single use.
5842 static bool isXor1OfSetCC(SDValue Op) {
5843 if (Op.getOpcode() != ISD::XOR)
5845 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5846 if (N1C && N1C->getAPIntValue() == 1) {
5847 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
5848 Op.getOperand(0).hasOneUse();
5853 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) {
5854 bool addTest = true;
5855 SDValue Chain = Op.getOperand(0);
5856 SDValue Cond = Op.getOperand(1);
5857 SDValue Dest = Op.getOperand(2);
5858 DebugLoc dl = Op.getDebugLoc();
5861 if (Cond.getOpcode() == ISD::SETCC) {
5862 SDValue NewCond = LowerSETCC(Cond, DAG);
5863 if (NewCond.getNode())
5867 // FIXME: LowerXALUO doesn't handle these!!
5868 else if (Cond.getOpcode() == X86ISD::ADD ||
5869 Cond.getOpcode() == X86ISD::SUB ||
5870 Cond.getOpcode() == X86ISD::SMUL ||
5871 Cond.getOpcode() == X86ISD::UMUL)
5872 Cond = LowerXALUO(Cond, DAG);
5875 // If condition flag is set by a X86ISD::CMP, then use it as the condition
5876 // setting operand in place of the X86ISD::SETCC.
5877 if (Cond.getOpcode() == X86ISD::SETCC) {
5878 CC = Cond.getOperand(0);
5880 SDValue Cmp = Cond.getOperand(1);
5881 unsigned Opc = Cmp.getOpcode();
5882 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
5883 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
5887 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
5891 // These can only come from an arithmetic instruction with overflow,
5892 // e.g. SADDO, UADDO.
5893 Cond = Cond.getNode()->getOperand(1);
5900 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
5901 SDValue Cmp = Cond.getOperand(0).getOperand(1);
5902 if (CondOpc == ISD::OR) {
5903 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
5904 // two branches instead of an explicit OR instruction with a
5906 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5907 isX86LogicalCmp(Cmp)) {
5908 CC = Cond.getOperand(0).getOperand(0);
5909 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5910 Chain, Dest, CC, Cmp);
5911 CC = Cond.getOperand(1).getOperand(0);
5915 } else { // ISD::AND
5916 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
5917 // two branches instead of an explicit AND instruction with a
5918 // separate test. However, we only do this if this block doesn't
5919 // have a fall-through edge, because this requires an explicit
5920 // jmp when the condition is false.
5921 if (Cmp == Cond.getOperand(1).getOperand(1) &&
5922 isX86LogicalCmp(Cmp) &&
5923 Op.getNode()->hasOneUse()) {
5924 X86::CondCode CCode =
5925 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5926 CCode = X86::GetOppositeBranchCondition(CCode);
5927 CC = DAG.getConstant(CCode, MVT::i8);
5928 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
5929 // Look for an unconditional branch following this conditional branch.
5930 // We need this because we need to reverse the successors in order
5931 // to implement FCMP_OEQ.
5932 if (User.getOpcode() == ISD::BR) {
5933 SDValue FalseBB = User.getOperand(1);
5935 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
5936 assert(NewBR == User);
5939 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5940 Chain, Dest, CC, Cmp);
5941 X86::CondCode CCode =
5942 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
5943 CCode = X86::GetOppositeBranchCondition(CCode);
5944 CC = DAG.getConstant(CCode, MVT::i8);
5950 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
5951 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
5952 // It should be transformed during dag combiner except when the condition
5953 // is set by a arithmetics with overflow node.
5954 X86::CondCode CCode =
5955 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
5956 CCode = X86::GetOppositeBranchCondition(CCode);
5957 CC = DAG.getConstant(CCode, MVT::i8);
5958 Cond = Cond.getOperand(0).getOperand(1);
5964 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5965 Cond = EmitTest(Cond, X86::COND_NE, DAG);
5967 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
5968 Chain, Dest, CC, Cond);
5972 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
5973 // Calls to _alloca is needed to probe the stack when allocating more than 4k
5974 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
5975 // that the guard pages used by the OS virtual memory manager are allocated in
5976 // correct sequence.
5978 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
5979 SelectionDAG &DAG) {
5980 assert(Subtarget->isTargetCygMing() &&
5981 "This should be used only on Cygwin/Mingw targets");
5982 DebugLoc dl = Op.getDebugLoc();
5985 SDValue Chain = Op.getOperand(0);
5986 SDValue Size = Op.getOperand(1);
5987 // FIXME: Ensure alignment here
5991 EVT IntPtr = getPointerTy();
5992 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
5994 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
5996 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
5997 Flag = Chain.getValue(1);
5999 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6000 SDValue Ops[] = { Chain,
6001 DAG.getTargetExternalSymbol("_alloca", IntPtr),
6002 DAG.getRegister(X86::EAX, IntPtr),
6003 DAG.getRegister(X86StackPtr, SPTy),
6005 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops, 5);
6006 Flag = Chain.getValue(1);
6008 Chain = DAG.getCALLSEQ_END(Chain,
6009 DAG.getIntPtrConstant(0, true),
6010 DAG.getIntPtrConstant(0, true),
6013 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
6015 SDValue Ops1[2] = { Chain.getValue(0), Chain };
6016 return DAG.getMergeValues(Ops1, 2, dl);
6020 X86TargetLowering::EmitTargetCodeForMemset(SelectionDAG &DAG, DebugLoc dl,
6022 SDValue Dst, SDValue Src,
6023 SDValue Size, unsigned Align,
6025 uint64_t DstSVOff) {
6026 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6028 // If not DWORD aligned or size is more than the threshold, call the library.
6029 // The libc version is likely to be faster for these cases. It can use the
6030 // address value and run time information about the CPU.
6031 if ((Align & 3) != 0 ||
6033 ConstantSize->getZExtValue() >
6034 getSubtarget()->getMaxInlineSizeThreshold()) {
6035 SDValue InFlag(0, 0);
6037 // Check to see if there is a specialized entry-point for memory zeroing.
6038 ConstantSDNode *V = dyn_cast<ConstantSDNode>(Src);
6040 if (const char *bzeroEntry = V &&
6041 V->isNullValue() ? Subtarget->getBZeroEntry() : 0) {
6042 EVT IntPtr = getPointerTy();
6043 const Type *IntPtrTy = TD->getIntPtrType(*DAG.getContext());
6044 TargetLowering::ArgListTy Args;
6045 TargetLowering::ArgListEntry Entry;
6047 Entry.Ty = IntPtrTy;
6048 Args.push_back(Entry);
6050 Args.push_back(Entry);
6051 std::pair<SDValue,SDValue> CallResult =
6052 LowerCallTo(Chain, Type::getVoidTy(*DAG.getContext()),
6053 false, false, false, false,
6054 0, CallingConv::C, false, /*isReturnValueUsed=*/false,
6055 DAG.getExternalSymbol(bzeroEntry, IntPtr), Args, DAG, dl);
6056 return CallResult.second;
6059 // Otherwise have the target-independent code call memset.
6063 uint64_t SizeVal = ConstantSize->getZExtValue();
6064 SDValue InFlag(0, 0);
6067 ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Src);
6068 unsigned BytesLeft = 0;
6069 bool TwoRepStos = false;
6072 uint64_t Val = ValC->getZExtValue() & 255;
6074 // If the value is a constant, then we can potentially use larger sets.
6075 switch (Align & 3) {
6076 case 2: // WORD aligned
6079 Val = (Val << 8) | Val;
6081 case 0: // DWORD aligned
6084 Val = (Val << 8) | Val;
6085 Val = (Val << 16) | Val;
6086 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) { // QWORD aligned
6089 Val = (Val << 32) | Val;
6092 default: // Byte aligned
6095 Count = DAG.getIntPtrConstant(SizeVal);
6099 if (AVT.bitsGT(MVT::i8)) {
6100 unsigned UBytes = AVT.getSizeInBits() / 8;
6101 Count = DAG.getIntPtrConstant(SizeVal / UBytes);
6102 BytesLeft = SizeVal % UBytes;
6105 Chain = DAG.getCopyToReg(Chain, dl, ValReg, DAG.getConstant(Val, AVT),
6107 InFlag = Chain.getValue(1);
6110 Count = DAG.getIntPtrConstant(SizeVal);
6111 Chain = DAG.getCopyToReg(Chain, dl, X86::AL, Src, InFlag);
6112 InFlag = Chain.getValue(1);
6115 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6118 InFlag = Chain.getValue(1);
6119 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6122 InFlag = Chain.getValue(1);
6124 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6125 SmallVector<SDValue, 8> Ops;
6126 Ops.push_back(Chain);
6127 Ops.push_back(DAG.getValueType(AVT));
6128 Ops.push_back(InFlag);
6129 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
6132 InFlag = Chain.getValue(1);
6134 EVT CVT = Count.getValueType();
6135 SDValue Left = DAG.getNode(ISD::AND, dl, CVT, Count,
6136 DAG.getConstant((AVT == MVT::i64) ? 7 : 3, CVT));
6137 Chain = DAG.getCopyToReg(Chain, dl, (CVT == MVT::i64) ? X86::RCX :
6140 InFlag = Chain.getValue(1);
6141 Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6143 Ops.push_back(Chain);
6144 Ops.push_back(DAG.getValueType(MVT::i8));
6145 Ops.push_back(InFlag);
6146 Chain = DAG.getNode(X86ISD::REP_STOS, dl, Tys, &Ops[0], Ops.size());
6147 } else if (BytesLeft) {
6148 // Handle the last 1 - 7 bytes.
6149 unsigned Offset = SizeVal - BytesLeft;
6150 EVT AddrVT = Dst.getValueType();
6151 EVT SizeVT = Size.getValueType();
6153 Chain = DAG.getMemset(Chain, dl,
6154 DAG.getNode(ISD::ADD, dl, AddrVT, Dst,
6155 DAG.getConstant(Offset, AddrVT)),
6157 DAG.getConstant(BytesLeft, SizeVT),
6158 Align, DstSV, DstSVOff + Offset);
6161 // TODO: Use a Tokenfactor, as in memcpy, instead of a single chain.
6166 X86TargetLowering::EmitTargetCodeForMemcpy(SelectionDAG &DAG, DebugLoc dl,
6167 SDValue Chain, SDValue Dst, SDValue Src,
6168 SDValue Size, unsigned Align,
6170 const Value *DstSV, uint64_t DstSVOff,
6171 const Value *SrcSV, uint64_t SrcSVOff) {
6172 // This requires the copy size to be a constant, preferrably
6173 // within a subtarget-specific limit.
6174 ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6177 uint64_t SizeVal = ConstantSize->getZExtValue();
6178 if (!AlwaysInline && SizeVal > getSubtarget()->getMaxInlineSizeThreshold())
6181 /// If not DWORD aligned, call the library.
6182 if ((Align & 3) != 0)
6187 if (Subtarget->is64Bit() && ((Align & 0x7) == 0)) // QWORD aligned
6190 unsigned UBytes = AVT.getSizeInBits() / 8;
6191 unsigned CountVal = SizeVal / UBytes;
6192 SDValue Count = DAG.getIntPtrConstant(CountVal);
6193 unsigned BytesLeft = SizeVal % UBytes;
6195 SDValue InFlag(0, 0);
6196 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RCX :
6199 InFlag = Chain.getValue(1);
6200 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RDI :
6203 InFlag = Chain.getValue(1);
6204 Chain = DAG.getCopyToReg(Chain, dl, Subtarget->is64Bit() ? X86::RSI :
6207 InFlag = Chain.getValue(1);
6209 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
6210 SmallVector<SDValue, 8> Ops;
6211 Ops.push_back(Chain);
6212 Ops.push_back(DAG.getValueType(AVT));
6213 Ops.push_back(InFlag);
6214 SDValue RepMovs = DAG.getNode(X86ISD::REP_MOVS, dl, Tys, &Ops[0], Ops.size());
6216 SmallVector<SDValue, 4> Results;
6217 Results.push_back(RepMovs);
6219 // Handle the last 1 - 7 bytes.
6220 unsigned Offset = SizeVal - BytesLeft;
6221 EVT DstVT = Dst.getValueType();
6222 EVT SrcVT = Src.getValueType();
6223 EVT SizeVT = Size.getValueType();
6224 Results.push_back(DAG.getMemcpy(Chain, dl,
6225 DAG.getNode(ISD::ADD, dl, DstVT, Dst,
6226 DAG.getConstant(Offset, DstVT)),
6227 DAG.getNode(ISD::ADD, dl, SrcVT, Src,
6228 DAG.getConstant(Offset, SrcVT)),
6229 DAG.getConstant(BytesLeft, SizeVT),
6230 Align, AlwaysInline,
6231 DstSV, DstSVOff + Offset,
6232 SrcSV, SrcSVOff + Offset));
6235 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6236 &Results[0], Results.size());
6239 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) {
6240 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6241 DebugLoc dl = Op.getDebugLoc();
6243 if (!Subtarget->is64Bit()) {
6244 // vastart just stores the address of the VarArgsFrameIndex slot into the
6245 // memory location argument.
6246 SDValue FR = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6247 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0);
6251 // gp_offset (0 - 6 * 8)
6252 // fp_offset (48 - 48 + 8 * 16)
6253 // overflow_arg_area (point to parameters coming in memory).
6255 SmallVector<SDValue, 8> MemOps;
6256 SDValue FIN = Op.getOperand(1);
6258 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6259 DAG.getConstant(VarArgsGPOffset, MVT::i32),
6261 MemOps.push_back(Store);
6264 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6265 FIN, DAG.getIntPtrConstant(4));
6266 Store = DAG.getStore(Op.getOperand(0), dl,
6267 DAG.getConstant(VarArgsFPOffset, MVT::i32),
6269 MemOps.push_back(Store);
6271 // Store ptr to overflow_arg_area
6272 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6273 FIN, DAG.getIntPtrConstant(4));
6274 SDValue OVFIN = DAG.getFrameIndex(VarArgsFrameIndex, getPointerTy());
6275 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0);
6276 MemOps.push_back(Store);
6278 // Store ptr to reg_save_area.
6279 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6280 FIN, DAG.getIntPtrConstant(8));
6281 SDValue RSFIN = DAG.getFrameIndex(RegSaveFrameIndex, getPointerTy());
6282 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0);
6283 MemOps.push_back(Store);
6284 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6285 &MemOps[0], MemOps.size());
6288 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) {
6289 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6290 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6291 SDValue Chain = Op.getOperand(0);
6292 SDValue SrcPtr = Op.getOperand(1);
6293 SDValue SrcSV = Op.getOperand(2);
6295 llvm_report_error("VAArgInst is not yet implemented for x86-64!");
6299 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) {
6300 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6301 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6302 SDValue Chain = Op.getOperand(0);
6303 SDValue DstPtr = Op.getOperand(1);
6304 SDValue SrcPtr = Op.getOperand(2);
6305 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6306 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6307 DebugLoc dl = Op.getDebugLoc();
6309 return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6310 DAG.getIntPtrConstant(24), 8, false,
6311 DstSV, 0, SrcSV, 0);
6315 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
6316 DebugLoc dl = Op.getDebugLoc();
6317 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6319 default: return SDValue(); // Don't custom lower most intrinsics.
6320 // Comparison intrinsics.
6321 case Intrinsic::x86_sse_comieq_ss:
6322 case Intrinsic::x86_sse_comilt_ss:
6323 case Intrinsic::x86_sse_comile_ss:
6324 case Intrinsic::x86_sse_comigt_ss:
6325 case Intrinsic::x86_sse_comige_ss:
6326 case Intrinsic::x86_sse_comineq_ss:
6327 case Intrinsic::x86_sse_ucomieq_ss:
6328 case Intrinsic::x86_sse_ucomilt_ss:
6329 case Intrinsic::x86_sse_ucomile_ss:
6330 case Intrinsic::x86_sse_ucomigt_ss:
6331 case Intrinsic::x86_sse_ucomige_ss:
6332 case Intrinsic::x86_sse_ucomineq_ss:
6333 case Intrinsic::x86_sse2_comieq_sd:
6334 case Intrinsic::x86_sse2_comilt_sd:
6335 case Intrinsic::x86_sse2_comile_sd:
6336 case Intrinsic::x86_sse2_comigt_sd:
6337 case Intrinsic::x86_sse2_comige_sd:
6338 case Intrinsic::x86_sse2_comineq_sd:
6339 case Intrinsic::x86_sse2_ucomieq_sd:
6340 case Intrinsic::x86_sse2_ucomilt_sd:
6341 case Intrinsic::x86_sse2_ucomile_sd:
6342 case Intrinsic::x86_sse2_ucomigt_sd:
6343 case Intrinsic::x86_sse2_ucomige_sd:
6344 case Intrinsic::x86_sse2_ucomineq_sd: {
6346 ISD::CondCode CC = ISD::SETCC_INVALID;
6349 case Intrinsic::x86_sse_comieq_ss:
6350 case Intrinsic::x86_sse2_comieq_sd:
6354 case Intrinsic::x86_sse_comilt_ss:
6355 case Intrinsic::x86_sse2_comilt_sd:
6359 case Intrinsic::x86_sse_comile_ss:
6360 case Intrinsic::x86_sse2_comile_sd:
6364 case Intrinsic::x86_sse_comigt_ss:
6365 case Intrinsic::x86_sse2_comigt_sd:
6369 case Intrinsic::x86_sse_comige_ss:
6370 case Intrinsic::x86_sse2_comige_sd:
6374 case Intrinsic::x86_sse_comineq_ss:
6375 case Intrinsic::x86_sse2_comineq_sd:
6379 case Intrinsic::x86_sse_ucomieq_ss:
6380 case Intrinsic::x86_sse2_ucomieq_sd:
6381 Opc = X86ISD::UCOMI;
6384 case Intrinsic::x86_sse_ucomilt_ss:
6385 case Intrinsic::x86_sse2_ucomilt_sd:
6386 Opc = X86ISD::UCOMI;
6389 case Intrinsic::x86_sse_ucomile_ss:
6390 case Intrinsic::x86_sse2_ucomile_sd:
6391 Opc = X86ISD::UCOMI;
6394 case Intrinsic::x86_sse_ucomigt_ss:
6395 case Intrinsic::x86_sse2_ucomigt_sd:
6396 Opc = X86ISD::UCOMI;
6399 case Intrinsic::x86_sse_ucomige_ss:
6400 case Intrinsic::x86_sse2_ucomige_sd:
6401 Opc = X86ISD::UCOMI;
6404 case Intrinsic::x86_sse_ucomineq_ss:
6405 case Intrinsic::x86_sse2_ucomineq_sd:
6406 Opc = X86ISD::UCOMI;
6411 SDValue LHS = Op.getOperand(1);
6412 SDValue RHS = Op.getOperand(2);
6413 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6414 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
6415 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6416 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6417 DAG.getConstant(X86CC, MVT::i8), Cond);
6418 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6420 // ptest intrinsics. The intrinsic these come from are designed to return
6421 // an integer value, not just an instruction so lower it to the ptest
6422 // pattern and a setcc for the result.
6423 case Intrinsic::x86_sse41_ptestz:
6424 case Intrinsic::x86_sse41_ptestc:
6425 case Intrinsic::x86_sse41_ptestnzc:{
6428 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
6429 case Intrinsic::x86_sse41_ptestz:
6431 X86CC = X86::COND_E;
6433 case Intrinsic::x86_sse41_ptestc:
6435 X86CC = X86::COND_B;
6437 case Intrinsic::x86_sse41_ptestnzc:
6439 X86CC = X86::COND_A;
6443 SDValue LHS = Op.getOperand(1);
6444 SDValue RHS = Op.getOperand(2);
6445 SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
6446 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
6447 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
6448 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6451 // Fix vector shift instructions where the last operand is a non-immediate
6453 case Intrinsic::x86_sse2_pslli_w:
6454 case Intrinsic::x86_sse2_pslli_d:
6455 case Intrinsic::x86_sse2_pslli_q:
6456 case Intrinsic::x86_sse2_psrli_w:
6457 case Intrinsic::x86_sse2_psrli_d:
6458 case Intrinsic::x86_sse2_psrli_q:
6459 case Intrinsic::x86_sse2_psrai_w:
6460 case Intrinsic::x86_sse2_psrai_d:
6461 case Intrinsic::x86_mmx_pslli_w:
6462 case Intrinsic::x86_mmx_pslli_d:
6463 case Intrinsic::x86_mmx_pslli_q:
6464 case Intrinsic::x86_mmx_psrli_w:
6465 case Intrinsic::x86_mmx_psrli_d:
6466 case Intrinsic::x86_mmx_psrli_q:
6467 case Intrinsic::x86_mmx_psrai_w:
6468 case Intrinsic::x86_mmx_psrai_d: {
6469 SDValue ShAmt = Op.getOperand(2);
6470 if (isa<ConstantSDNode>(ShAmt))
6473 unsigned NewIntNo = 0;
6474 EVT ShAmtVT = MVT::v4i32;
6476 case Intrinsic::x86_sse2_pslli_w:
6477 NewIntNo = Intrinsic::x86_sse2_psll_w;
6479 case Intrinsic::x86_sse2_pslli_d:
6480 NewIntNo = Intrinsic::x86_sse2_psll_d;
6482 case Intrinsic::x86_sse2_pslli_q:
6483 NewIntNo = Intrinsic::x86_sse2_psll_q;
6485 case Intrinsic::x86_sse2_psrli_w:
6486 NewIntNo = Intrinsic::x86_sse2_psrl_w;
6488 case Intrinsic::x86_sse2_psrli_d:
6489 NewIntNo = Intrinsic::x86_sse2_psrl_d;
6491 case Intrinsic::x86_sse2_psrli_q:
6492 NewIntNo = Intrinsic::x86_sse2_psrl_q;
6494 case Intrinsic::x86_sse2_psrai_w:
6495 NewIntNo = Intrinsic::x86_sse2_psra_w;
6497 case Intrinsic::x86_sse2_psrai_d:
6498 NewIntNo = Intrinsic::x86_sse2_psra_d;
6501 ShAmtVT = MVT::v2i32;
6503 case Intrinsic::x86_mmx_pslli_w:
6504 NewIntNo = Intrinsic::x86_mmx_psll_w;
6506 case Intrinsic::x86_mmx_pslli_d:
6507 NewIntNo = Intrinsic::x86_mmx_psll_d;
6509 case Intrinsic::x86_mmx_pslli_q:
6510 NewIntNo = Intrinsic::x86_mmx_psll_q;
6512 case Intrinsic::x86_mmx_psrli_w:
6513 NewIntNo = Intrinsic::x86_mmx_psrl_w;
6515 case Intrinsic::x86_mmx_psrli_d:
6516 NewIntNo = Intrinsic::x86_mmx_psrl_d;
6518 case Intrinsic::x86_mmx_psrli_q:
6519 NewIntNo = Intrinsic::x86_mmx_psrl_q;
6521 case Intrinsic::x86_mmx_psrai_w:
6522 NewIntNo = Intrinsic::x86_mmx_psra_w;
6524 case Intrinsic::x86_mmx_psrai_d:
6525 NewIntNo = Intrinsic::x86_mmx_psra_d;
6527 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
6533 // The vector shift intrinsics with scalars uses 32b shift amounts but
6534 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
6538 ShOps[1] = DAG.getConstant(0, MVT::i32);
6539 if (ShAmtVT == MVT::v4i32) {
6540 ShOps[2] = DAG.getUNDEF(MVT::i32);
6541 ShOps[3] = DAG.getUNDEF(MVT::i32);
6542 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
6544 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
6547 EVT VT = Op.getValueType();
6548 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
6549 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6550 DAG.getConstant(NewIntNo, MVT::i32),
6551 Op.getOperand(1), ShAmt);
6556 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
6557 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6558 DebugLoc dl = Op.getDebugLoc();
6561 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6563 DAG.getConstant(TD->getPointerSize(),
6564 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6565 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6566 DAG.getNode(ISD::ADD, dl, getPointerTy(),
6571 // Just load the return address.
6572 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6573 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6574 RetAddrFI, NULL, 0);
6577 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
6578 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6579 MFI->setFrameAddressIsTaken(true);
6580 EVT VT = Op.getValueType();
6581 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
6582 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6583 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6584 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
6586 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0);
6590 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
6591 SelectionDAG &DAG) {
6592 return DAG.getIntPtrConstant(2*TD->getPointerSize());
6595 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
6597 MachineFunction &MF = DAG.getMachineFunction();
6598 SDValue Chain = Op.getOperand(0);
6599 SDValue Offset = Op.getOperand(1);
6600 SDValue Handler = Op.getOperand(2);
6601 DebugLoc dl = Op.getDebugLoc();
6603 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
6605 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
6607 SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
6608 DAG.getIntPtrConstant(-TD->getPointerSize()));
6609 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
6610 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0);
6611 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
6612 MF.getRegInfo().addLiveOut(StoreAddrReg);
6614 return DAG.getNode(X86ISD::EH_RETURN, dl,
6616 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
6619 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
6620 SelectionDAG &DAG) {
6621 SDValue Root = Op.getOperand(0);
6622 SDValue Trmp = Op.getOperand(1); // trampoline
6623 SDValue FPtr = Op.getOperand(2); // nested function
6624 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
6625 DebugLoc dl = Op.getDebugLoc();
6627 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6629 const X86InstrInfo *TII =
6630 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
6632 if (Subtarget->is64Bit()) {
6633 SDValue OutChains[6];
6635 // Large code-model.
6637 const unsigned char JMP64r = TII->getBaseOpcodeFor(X86::JMP64r);
6638 const unsigned char MOV64ri = TII->getBaseOpcodeFor(X86::MOV64ri);
6640 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
6641 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
6643 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
6645 // Load the pointer to the nested function into R11.
6646 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
6647 SDValue Addr = Trmp;
6648 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6651 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6652 DAG.getConstant(2, MVT::i64));
6653 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2, false, 2);
6655 // Load the 'nest' parameter value into R10.
6656 // R10 is specified in X86CallingConv.td
6657 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
6658 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6659 DAG.getConstant(10, MVT::i64));
6660 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6661 Addr, TrmpAddr, 10);
6663 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6664 DAG.getConstant(12, MVT::i64));
6665 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12, false, 2);
6667 // Jump to the nested function.
6668 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
6669 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6670 DAG.getConstant(20, MVT::i64));
6671 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
6672 Addr, TrmpAddr, 20);
6674 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
6675 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
6676 DAG.getConstant(22, MVT::i64));
6677 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
6681 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
6682 return DAG.getMergeValues(Ops, 2, dl);
6684 const Function *Func =
6685 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
6686 CallingConv::ID CC = Func->getCallingConv();
6691 llvm_unreachable("Unsupported calling convention");
6692 case CallingConv::C:
6693 case CallingConv::X86_StdCall: {
6694 // Pass 'nest' parameter in ECX.
6695 // Must be kept in sync with X86CallingConv.td
6698 // Check that ECX wasn't needed by an 'inreg' parameter.
6699 const FunctionType *FTy = Func->getFunctionType();
6700 const AttrListPtr &Attrs = Func->getAttributes();
6702 if (!Attrs.isEmpty() && !Func->isVarArg()) {
6703 unsigned InRegCount = 0;
6706 for (FunctionType::param_iterator I = FTy->param_begin(),
6707 E = FTy->param_end(); I != E; ++I, ++Idx)
6708 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
6709 // FIXME: should only count parameters that are lowered to integers.
6710 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
6712 if (InRegCount > 2) {
6713 llvm_report_error("Nest register in use - reduce number of inreg parameters!");
6718 case CallingConv::X86_FastCall:
6719 case CallingConv::Fast:
6720 // Pass 'nest' parameter in EAX.
6721 // Must be kept in sync with X86CallingConv.td
6726 SDValue OutChains[4];
6729 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6730 DAG.getConstant(10, MVT::i32));
6731 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
6733 const unsigned char MOV32ri = TII->getBaseOpcodeFor(X86::MOV32ri);
6734 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
6735 OutChains[0] = DAG.getStore(Root, dl,
6736 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
6739 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6740 DAG.getConstant(1, MVT::i32));
6741 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1, false, 1);
6743 const unsigned char JMP = TII->getBaseOpcodeFor(X86::JMP);
6744 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6745 DAG.getConstant(5, MVT::i32));
6746 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
6747 TrmpAddr, 5, false, 1);
6749 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
6750 DAG.getConstant(6, MVT::i32));
6751 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6, false, 1);
6754 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
6755 return DAG.getMergeValues(Ops, 2, dl);
6759 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op, SelectionDAG &DAG) {
6761 The rounding mode is in bits 11:10 of FPSR, and has the following
6768 FLT_ROUNDS, on the other hand, expects the following:
6775 To perform the conversion, we do:
6776 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
6779 MachineFunction &MF = DAG.getMachineFunction();
6780 const TargetMachine &TM = MF.getTarget();
6781 const TargetFrameInfo &TFI = *TM.getFrameInfo();
6782 unsigned StackAlignment = TFI.getStackAlignment();
6783 EVT VT = Op.getValueType();
6784 DebugLoc dl = Op.getDebugLoc();
6786 // Save FP Control Word to stack slot
6787 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
6788 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
6790 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
6791 DAG.getEntryNode(), StackSlot);
6793 // Load FP Control Word from stack slot
6794 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0);
6796 // Transform as necessary
6798 DAG.getNode(ISD::SRL, dl, MVT::i16,
6799 DAG.getNode(ISD::AND, dl, MVT::i16,
6800 CWD, DAG.getConstant(0x800, MVT::i16)),
6801 DAG.getConstant(11, MVT::i8));
6803 DAG.getNode(ISD::SRL, dl, MVT::i16,
6804 DAG.getNode(ISD::AND, dl, MVT::i16,
6805 CWD, DAG.getConstant(0x400, MVT::i16)),
6806 DAG.getConstant(9, MVT::i8));
6809 DAG.getNode(ISD::AND, dl, MVT::i16,
6810 DAG.getNode(ISD::ADD, dl, MVT::i16,
6811 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
6812 DAG.getConstant(1, MVT::i16)),
6813 DAG.getConstant(3, MVT::i16));
6816 return DAG.getNode((VT.getSizeInBits() < 16 ?
6817 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
6820 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
6821 EVT VT = Op.getValueType();
6823 unsigned NumBits = VT.getSizeInBits();
6824 DebugLoc dl = Op.getDebugLoc();
6826 Op = Op.getOperand(0);
6827 if (VT == MVT::i8) {
6828 // Zero extend to i32 since there is not an i8 bsr.
6830 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6833 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
6834 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6835 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
6837 // If src is zero (i.e. bsr sets ZF), returns NumBits.
6838 SmallVector<SDValue, 4> Ops;
6840 Ops.push_back(DAG.getConstant(NumBits+NumBits-1, OpVT));
6841 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6842 Ops.push_back(Op.getValue(1));
6843 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6845 // Finally xor with NumBits-1.
6846 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
6849 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6853 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
6854 EVT VT = Op.getValueType();
6856 unsigned NumBits = VT.getSizeInBits();
6857 DebugLoc dl = Op.getDebugLoc();
6859 Op = Op.getOperand(0);
6860 if (VT == MVT::i8) {
6862 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
6865 // Issue a bsf (scan bits forward) which also sets EFLAGS.
6866 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
6867 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
6869 // If src is zero (i.e. bsf sets ZF), returns NumBits.
6870 SmallVector<SDValue, 4> Ops;
6872 Ops.push_back(DAG.getConstant(NumBits, OpVT));
6873 Ops.push_back(DAG.getConstant(X86::COND_E, MVT::i8));
6874 Ops.push_back(Op.getValue(1));
6875 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, &Ops[0], 4);
6878 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
6882 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) {
6883 EVT VT = Op.getValueType();
6884 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
6885 DebugLoc dl = Op.getDebugLoc();
6887 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
6888 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
6889 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
6890 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
6891 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
6893 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
6894 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
6895 // return AloBlo + AloBhi + AhiBlo;
6897 SDValue A = Op.getOperand(0);
6898 SDValue B = Op.getOperand(1);
6900 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6901 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6902 A, DAG.getConstant(32, MVT::i32));
6903 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6904 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
6905 B, DAG.getConstant(32, MVT::i32));
6906 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6907 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6909 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6910 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6912 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6913 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
6915 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6916 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6917 AloBhi, DAG.getConstant(32, MVT::i32));
6918 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6919 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
6920 AhiBlo, DAG.getConstant(32, MVT::i32));
6921 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
6922 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
6927 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) {
6928 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
6929 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
6930 // looks for this combo and may remove the "setcc" instruction if the "setcc"
6931 // has only one use.
6932 SDNode *N = Op.getNode();
6933 SDValue LHS = N->getOperand(0);
6934 SDValue RHS = N->getOperand(1);
6935 unsigned BaseOp = 0;
6937 DebugLoc dl = Op.getDebugLoc();
6939 switch (Op.getOpcode()) {
6940 default: llvm_unreachable("Unknown ovf instruction!");
6942 // A subtract of one will be selected as a INC. Note that INC doesn't
6943 // set CF, so we can't do this for UADDO.
6944 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6945 if (C->getAPIntValue() == 1) {
6946 BaseOp = X86ISD::INC;
6950 BaseOp = X86ISD::ADD;
6954 BaseOp = X86ISD::ADD;
6958 // A subtract of one will be selected as a DEC. Note that DEC doesn't
6959 // set CF, so we can't do this for USUBO.
6960 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
6961 if (C->getAPIntValue() == 1) {
6962 BaseOp = X86ISD::DEC;
6966 BaseOp = X86ISD::SUB;
6970 BaseOp = X86ISD::SUB;
6974 BaseOp = X86ISD::SMUL;
6978 BaseOp = X86ISD::UMUL;
6983 // Also sets EFLAGS.
6984 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
6985 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
6988 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
6989 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
6991 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
6995 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) {
6996 EVT T = Op.getValueType();
6997 DebugLoc dl = Op.getDebugLoc();
7000 switch(T.getSimpleVT().SimpleTy) {
7002 assert(false && "Invalid value type!");
7003 case MVT::i8: Reg = X86::AL; size = 1; break;
7004 case MVT::i16: Reg = X86::AX; size = 2; break;
7005 case MVT::i32: Reg = X86::EAX; size = 4; break;
7007 assert(Subtarget->is64Bit() && "Node not type legal!");
7008 Reg = X86::RAX; size = 8;
7011 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
7012 Op.getOperand(2), SDValue());
7013 SDValue Ops[] = { cpIn.getValue(0),
7016 DAG.getTargetConstant(size, MVT::i8),
7018 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7019 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
7021 DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
7025 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
7026 SelectionDAG &DAG) {
7027 assert(Subtarget->is64Bit() && "Result not type legalized?");
7028 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7029 SDValue TheChain = Op.getOperand(0);
7030 DebugLoc dl = Op.getDebugLoc();
7031 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7032 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
7033 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
7035 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
7036 DAG.getConstant(32, MVT::i8));
7038 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
7041 return DAG.getMergeValues(Ops, 2, dl);
7044 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
7045 SDNode *Node = Op.getNode();
7046 DebugLoc dl = Node->getDebugLoc();
7047 EVT T = Node->getValueType(0);
7048 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
7049 DAG.getConstant(0, T), Node->getOperand(2));
7050 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
7051 cast<AtomicSDNode>(Node)->getMemoryVT(),
7052 Node->getOperand(0),
7053 Node->getOperand(1), negOp,
7054 cast<AtomicSDNode>(Node)->getSrcValue(),
7055 cast<AtomicSDNode>(Node)->getAlignment());
7058 /// LowerOperation - Provide custom lowering hooks for some operations.
7060 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
7061 switch (Op.getOpcode()) {
7062 default: llvm_unreachable("Should not custom lower this!");
7063 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
7064 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
7065 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
7066 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7067 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7068 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7069 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
7070 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
7071 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
7072 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7073 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
7074 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
7075 case ISD::SHL_PARTS:
7076 case ISD::SRA_PARTS:
7077 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
7078 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
7079 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
7080 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
7081 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
7082 case ISD::FABS: return LowerFABS(Op, DAG);
7083 case ISD::FNEG: return LowerFNEG(Op, DAG);
7084 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
7085 case ISD::SETCC: return LowerSETCC(Op, DAG);
7086 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
7087 case ISD::SELECT: return LowerSELECT(Op, DAG);
7088 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
7089 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
7090 case ISD::VASTART: return LowerVASTART(Op, DAG);
7091 case ISD::VAARG: return LowerVAARG(Op, DAG);
7092 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
7093 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7094 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
7095 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
7096 case ISD::FRAME_TO_ARGS_OFFSET:
7097 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
7098 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
7099 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
7100 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
7101 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
7102 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
7103 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
7104 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
7110 case ISD::UMULO: return LowerXALUO(Op, DAG);
7111 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
7115 void X86TargetLowering::
7116 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
7117 SelectionDAG &DAG, unsigned NewOp) {
7118 EVT T = Node->getValueType(0);
7119 DebugLoc dl = Node->getDebugLoc();
7120 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
7122 SDValue Chain = Node->getOperand(0);
7123 SDValue In1 = Node->getOperand(1);
7124 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7125 Node->getOperand(2), DAG.getIntPtrConstant(0));
7126 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7127 Node->getOperand(2), DAG.getIntPtrConstant(1));
7128 SDValue Ops[] = { Chain, In1, In2L, In2H };
7129 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7131 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
7132 cast<MemSDNode>(Node)->getMemOperand());
7133 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7134 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7135 Results.push_back(Result.getValue(2));
7138 /// ReplaceNodeResults - Replace a node with an illegal result type
7139 /// with a new node built out of custom code.
7140 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7141 SmallVectorImpl<SDValue>&Results,
7142 SelectionDAG &DAG) {
7143 DebugLoc dl = N->getDebugLoc();
7144 switch (N->getOpcode()) {
7146 assert(false && "Do not know how to custom type legalize this operation!");
7148 case ISD::FP_TO_SINT: {
7149 std::pair<SDValue,SDValue> Vals =
7150 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
7151 SDValue FIST = Vals.first, StackSlot = Vals.second;
7152 if (FIST.getNode() != 0) {
7153 EVT VT = N->getValueType(0);
7154 // Return a load from the stack slot.
7155 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0));
7159 case ISD::READCYCLECOUNTER: {
7160 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7161 SDValue TheChain = N->getOperand(0);
7162 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7163 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7165 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7167 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7168 SDValue Ops[] = { eax, edx };
7169 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7170 Results.push_back(edx.getValue(1));
7173 case ISD::ATOMIC_CMP_SWAP: {
7174 EVT T = N->getValueType(0);
7175 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7176 SDValue cpInL, cpInH;
7177 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7178 DAG.getConstant(0, MVT::i32));
7179 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7180 DAG.getConstant(1, MVT::i32));
7181 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7182 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7184 SDValue swapInL, swapInH;
7185 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7186 DAG.getConstant(0, MVT::i32));
7187 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7188 DAG.getConstant(1, MVT::i32));
7189 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7191 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7192 swapInL.getValue(1));
7193 SDValue Ops[] = { swapInH.getValue(0),
7195 swapInH.getValue(1) };
7196 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7197 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7198 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7199 MVT::i32, Result.getValue(1));
7200 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7201 MVT::i32, cpOutL.getValue(2));
7202 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7203 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7204 Results.push_back(cpOutH.getValue(1));
7207 case ISD::ATOMIC_LOAD_ADD:
7208 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7210 case ISD::ATOMIC_LOAD_AND:
7211 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7213 case ISD::ATOMIC_LOAD_NAND:
7214 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7216 case ISD::ATOMIC_LOAD_OR:
7217 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7219 case ISD::ATOMIC_LOAD_SUB:
7220 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7222 case ISD::ATOMIC_LOAD_XOR:
7223 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7225 case ISD::ATOMIC_SWAP:
7226 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7231 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7233 default: return NULL;
7234 case X86ISD::BSF: return "X86ISD::BSF";
7235 case X86ISD::BSR: return "X86ISD::BSR";
7236 case X86ISD::SHLD: return "X86ISD::SHLD";
7237 case X86ISD::SHRD: return "X86ISD::SHRD";
7238 case X86ISD::FAND: return "X86ISD::FAND";
7239 case X86ISD::FOR: return "X86ISD::FOR";
7240 case X86ISD::FXOR: return "X86ISD::FXOR";
7241 case X86ISD::FSRL: return "X86ISD::FSRL";
7242 case X86ISD::FILD: return "X86ISD::FILD";
7243 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
7244 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7245 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7246 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7247 case X86ISD::FLD: return "X86ISD::FLD";
7248 case X86ISD::FST: return "X86ISD::FST";
7249 case X86ISD::CALL: return "X86ISD::CALL";
7250 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
7251 case X86ISD::BT: return "X86ISD::BT";
7252 case X86ISD::CMP: return "X86ISD::CMP";
7253 case X86ISD::COMI: return "X86ISD::COMI";
7254 case X86ISD::UCOMI: return "X86ISD::UCOMI";
7255 case X86ISD::SETCC: return "X86ISD::SETCC";
7256 case X86ISD::CMOV: return "X86ISD::CMOV";
7257 case X86ISD::BRCOND: return "X86ISD::BRCOND";
7258 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
7259 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
7260 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
7261 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
7262 case X86ISD::Wrapper: return "X86ISD::Wrapper";
7263 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
7264 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
7265 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
7266 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
7267 case X86ISD::PINSRB: return "X86ISD::PINSRB";
7268 case X86ISD::PINSRW: return "X86ISD::PINSRW";
7269 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
7270 case X86ISD::FMAX: return "X86ISD::FMAX";
7271 case X86ISD::FMIN: return "X86ISD::FMIN";
7272 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
7273 case X86ISD::FRCP: return "X86ISD::FRCP";
7274 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
7275 case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7276 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
7277 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
7278 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
7279 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
7280 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
7281 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
7282 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
7283 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
7284 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
7285 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
7286 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
7287 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
7288 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
7289 case X86ISD::VSHL: return "X86ISD::VSHL";
7290 case X86ISD::VSRL: return "X86ISD::VSRL";
7291 case X86ISD::CMPPD: return "X86ISD::CMPPD";
7292 case X86ISD::CMPPS: return "X86ISD::CMPPS";
7293 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
7294 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
7295 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
7296 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
7297 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
7298 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
7299 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
7300 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
7301 case X86ISD::ADD: return "X86ISD::ADD";
7302 case X86ISD::SUB: return "X86ISD::SUB";
7303 case X86ISD::SMUL: return "X86ISD::SMUL";
7304 case X86ISD::UMUL: return "X86ISD::UMUL";
7305 case X86ISD::INC: return "X86ISD::INC";
7306 case X86ISD::DEC: return "X86ISD::DEC";
7307 case X86ISD::OR: return "X86ISD::OR";
7308 case X86ISD::XOR: return "X86ISD::XOR";
7309 case X86ISD::AND: return "X86ISD::AND";
7310 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
7311 case X86ISD::PTEST: return "X86ISD::PTEST";
7312 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
7316 // isLegalAddressingMode - Return true if the addressing mode represented
7317 // by AM is legal for this target, for a load/store of the specified type.
7318 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7319 const Type *Ty) const {
7320 // X86 supports extremely general addressing modes.
7321 CodeModel::Model M = getTargetMachine().getCodeModel();
7323 // X86 allows a sign-extended 32-bit immediate field as a displacement.
7324 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
7329 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7331 // If a reference to this global requires an extra load, we can't fold it.
7332 if (isGlobalStubReference(GVFlags))
7335 // If BaseGV requires a register for the PIC base, we cannot also have a
7336 // BaseReg specified.
7337 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
7340 // If lower 4G is not available, then we must use rip-relative addressing.
7341 if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
7351 // These scales always work.
7356 // These scales are formed with basereg+scalereg. Only accept if there is
7361 default: // Other stuff never works.
7369 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7370 if (!Ty1->isInteger() || !Ty2->isInteger())
7372 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7373 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7374 if (NumBits1 <= NumBits2)
7376 return Subtarget->is64Bit() || NumBits1 < 64;
7379 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7380 if (!VT1.isInteger() || !VT2.isInteger())
7382 unsigned NumBits1 = VT1.getSizeInBits();
7383 unsigned NumBits2 = VT2.getSizeInBits();
7384 if (NumBits1 <= NumBits2)
7386 return Subtarget->is64Bit() || NumBits1 < 64;
7389 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7390 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7391 return Ty1 == Type::getInt32Ty(Ty1->getContext()) &&
7392 Ty2 == Type::getInt64Ty(Ty1->getContext()) && Subtarget->is64Bit();
7395 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7396 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7397 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7400 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
7401 // i16 instructions are longer (0x66 prefix) and potentially slower.
7402 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7405 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7406 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7407 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7408 /// are assumed to be legal.
7410 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
7412 // Only do shuffles on 128-bit vector types for now.
7413 if (VT.getSizeInBits() == 64)
7416 // FIXME: pshufb, blends, shifts.
7417 return (VT.getVectorNumElements() == 2 ||
7418 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7419 isMOVLMask(M, VT) ||
7420 isSHUFPMask(M, VT) ||
7421 isPSHUFDMask(M, VT) ||
7422 isPSHUFHWMask(M, VT) ||
7423 isPSHUFLWMask(M, VT) ||
7424 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
7425 isUNPCKLMask(M, VT) ||
7426 isUNPCKHMask(M, VT) ||
7427 isUNPCKL_v_undef_Mask(M, VT) ||
7428 isUNPCKH_v_undef_Mask(M, VT));
7432 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
7434 unsigned NumElts = VT.getVectorNumElements();
7435 // FIXME: This collection of masks seems suspect.
7438 if (NumElts == 4 && VT.getSizeInBits() == 128) {
7439 return (isMOVLMask(Mask, VT) ||
7440 isCommutedMOVLMask(Mask, VT, true) ||
7441 isSHUFPMask(Mask, VT) ||
7442 isCommutedSHUFPMask(Mask, VT));
7447 //===----------------------------------------------------------------------===//
7448 // X86 Scheduler Hooks
7449 //===----------------------------------------------------------------------===//
7451 // private utility function
7453 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7454 MachineBasicBlock *MBB,
7462 TargetRegisterClass *RC,
7463 bool invSrc) const {
7464 // For the atomic bitwise operator, we generate
7467 // ld t1 = [bitinstr.addr]
7468 // op t2 = t1, [bitinstr.val]
7470 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7472 // fallthrough -->nextMBB
7473 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7474 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7475 MachineFunction::iterator MBBIter = MBB;
7478 /// First build the CFG
7479 MachineFunction *F = MBB->getParent();
7480 MachineBasicBlock *thisMBB = MBB;
7481 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7482 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7483 F->insert(MBBIter, newMBB);
7484 F->insert(MBBIter, nextMBB);
7486 // Move all successors to thisMBB to nextMBB
7487 nextMBB->transferSuccessors(thisMBB);
7489 // Update thisMBB to fall through to newMBB
7490 thisMBB->addSuccessor(newMBB);
7492 // newMBB jumps to itself and fall through to nextMBB
7493 newMBB->addSuccessor(nextMBB);
7494 newMBB->addSuccessor(newMBB);
7496 // Insert instructions into newMBB based on incoming instruction
7497 assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7498 "unexpected number of operands");
7499 DebugLoc dl = bInstr->getDebugLoc();
7500 MachineOperand& destOper = bInstr->getOperand(0);
7501 MachineOperand* argOpers[2 + X86AddrNumOperands];
7502 int numArgs = bInstr->getNumOperands() - 1;
7503 for (int i=0; i < numArgs; ++i)
7504 argOpers[i] = &bInstr->getOperand(i+1);
7506 // x86 address has 4 operands: base, index, scale, and displacement
7507 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7508 int valArgIndx = lastAddrIndx + 1;
7510 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7511 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7512 for (int i=0; i <= lastAddrIndx; ++i)
7513 (*MIB).addOperand(*argOpers[i]);
7515 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7517 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7522 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7523 assert((argOpers[valArgIndx]->isReg() ||
7524 argOpers[valArgIndx]->isImm()) &&
7526 if (argOpers[valArgIndx]->isReg())
7527 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7529 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7531 (*MIB).addOperand(*argOpers[valArgIndx]);
7533 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7536 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7537 for (int i=0; i <= lastAddrIndx; ++i)
7538 (*MIB).addOperand(*argOpers[i]);
7540 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7541 (*MIB).setMemRefs(bInstr->memoperands_begin(),
7542 bInstr->memoperands_end());
7544 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7548 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7550 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7554 // private utility function: 64 bit atomics on 32 bit host.
7556 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7557 MachineBasicBlock *MBB,
7562 bool invSrc) const {
7563 // For the atomic bitwise operator, we generate
7564 // thisMBB (instructions are in pairs, except cmpxchg8b)
7565 // ld t1,t2 = [bitinstr.addr]
7567 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7568 // op t5, t6 <- out1, out2, [bitinstr.val]
7569 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
7570 // mov ECX, EBX <- t5, t6
7571 // mov EAX, EDX <- t1, t2
7572 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
7573 // mov t3, t4 <- EAX, EDX
7575 // result in out1, out2
7576 // fallthrough -->nextMBB
7578 const TargetRegisterClass *RC = X86::GR32RegisterClass;
7579 const unsigned LoadOpc = X86::MOV32rm;
7580 const unsigned copyOpc = X86::MOV32rr;
7581 const unsigned NotOpc = X86::NOT32r;
7582 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7583 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7584 MachineFunction::iterator MBBIter = MBB;
7587 /// First build the CFG
7588 MachineFunction *F = MBB->getParent();
7589 MachineBasicBlock *thisMBB = MBB;
7590 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7591 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7592 F->insert(MBBIter, newMBB);
7593 F->insert(MBBIter, nextMBB);
7595 // Move all successors to thisMBB to nextMBB
7596 nextMBB->transferSuccessors(thisMBB);
7598 // Update thisMBB to fall through to newMBB
7599 thisMBB->addSuccessor(newMBB);
7601 // newMBB jumps to itself and fall through to nextMBB
7602 newMBB->addSuccessor(nextMBB);
7603 newMBB->addSuccessor(newMBB);
7605 DebugLoc dl = bInstr->getDebugLoc();
7606 // Insert instructions into newMBB based on incoming instruction
7607 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
7608 assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
7609 "unexpected number of operands");
7610 MachineOperand& dest1Oper = bInstr->getOperand(0);
7611 MachineOperand& dest2Oper = bInstr->getOperand(1);
7612 MachineOperand* argOpers[2 + X86AddrNumOperands];
7613 for (int i=0; i < 2 + X86AddrNumOperands; ++i)
7614 argOpers[i] = &bInstr->getOperand(i+2);
7616 // x86 address has 4 operands: base, index, scale, and displacement
7617 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7619 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7620 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
7621 for (int i=0; i <= lastAddrIndx; ++i)
7622 (*MIB).addOperand(*argOpers[i]);
7623 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7624 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
7625 // add 4 to displacement.
7626 for (int i=0; i <= lastAddrIndx-2; ++i)
7627 (*MIB).addOperand(*argOpers[i]);
7628 MachineOperand newOp3 = *(argOpers[3]);
7630 newOp3.setImm(newOp3.getImm()+4);
7632 newOp3.setOffset(newOp3.getOffset()+4);
7633 (*MIB).addOperand(newOp3);
7634 (*MIB).addOperand(*argOpers[lastAddrIndx]);
7636 // t3/4 are defined later, at the bottom of the loop
7637 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
7638 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
7639 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
7640 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
7641 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
7642 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
7644 unsigned tt1 = F->getRegInfo().createVirtualRegister(RC);
7645 unsigned tt2 = F->getRegInfo().createVirtualRegister(RC);
7647 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt1).addReg(t1);
7648 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), tt2).addReg(t2);
7654 int valArgIndx = lastAddrIndx + 1;
7655 assert((argOpers[valArgIndx]->isReg() ||
7656 argOpers[valArgIndx]->isImm()) &&
7658 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
7659 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
7660 if (argOpers[valArgIndx]->isReg())
7661 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
7663 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
7664 if (regOpcL != X86::MOV32rr)
7666 (*MIB).addOperand(*argOpers[valArgIndx]);
7667 assert(argOpers[valArgIndx + 1]->isReg() ==
7668 argOpers[valArgIndx]->isReg());
7669 assert(argOpers[valArgIndx + 1]->isImm() ==
7670 argOpers[valArgIndx]->isImm());
7671 if (argOpers[valArgIndx + 1]->isReg())
7672 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
7674 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
7675 if (regOpcH != X86::MOV32rr)
7677 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
7679 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
7681 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
7684 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
7686 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
7689 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
7690 for (int i=0; i <= lastAddrIndx; ++i)
7691 (*MIB).addOperand(*argOpers[i]);
7693 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7694 (*MIB).setMemRefs(bInstr->memoperands_begin(),
7695 bInstr->memoperands_end());
7697 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
7698 MIB.addReg(X86::EAX);
7699 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
7700 MIB.addReg(X86::EDX);
7703 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7705 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7709 // private utility function
7711 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
7712 MachineBasicBlock *MBB,
7713 unsigned cmovOpc) const {
7714 // For the atomic min/max operator, we generate
7717 // ld t1 = [min/max.addr]
7718 // mov t2 = [min/max.val]
7720 // cmov[cond] t2 = t1
7722 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7724 // fallthrough -->nextMBB
7726 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7727 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7728 MachineFunction::iterator MBBIter = MBB;
7731 /// First build the CFG
7732 MachineFunction *F = MBB->getParent();
7733 MachineBasicBlock *thisMBB = MBB;
7734 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7735 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7736 F->insert(MBBIter, newMBB);
7737 F->insert(MBBIter, nextMBB);
7739 // Move all successors of thisMBB to nextMBB
7740 nextMBB->transferSuccessors(thisMBB);
7742 // Update thisMBB to fall through to newMBB
7743 thisMBB->addSuccessor(newMBB);
7745 // newMBB jumps to newMBB and fall through to nextMBB
7746 newMBB->addSuccessor(nextMBB);
7747 newMBB->addSuccessor(newMBB);
7749 DebugLoc dl = mInstr->getDebugLoc();
7750 // Insert instructions into newMBB based on incoming instruction
7751 assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7752 "unexpected number of operands");
7753 MachineOperand& destOper = mInstr->getOperand(0);
7754 MachineOperand* argOpers[2 + X86AddrNumOperands];
7755 int numArgs = mInstr->getNumOperands() - 1;
7756 for (int i=0; i < numArgs; ++i)
7757 argOpers[i] = &mInstr->getOperand(i+1);
7759 // x86 address has 4 operands: base, index, scale, and displacement
7760 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7761 int valArgIndx = lastAddrIndx + 1;
7763 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7764 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
7765 for (int i=0; i <= lastAddrIndx; ++i)
7766 (*MIB).addOperand(*argOpers[i]);
7768 // We only support register and immediate values
7769 assert((argOpers[valArgIndx]->isReg() ||
7770 argOpers[valArgIndx]->isImm()) &&
7773 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7774 if (argOpers[valArgIndx]->isReg())
7775 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7777 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
7778 (*MIB).addOperand(*argOpers[valArgIndx]);
7780 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
7783 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
7788 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
7789 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
7793 // Cmp and exchange if none has modified the memory location
7794 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
7795 for (int i=0; i <= lastAddrIndx; ++i)
7796 (*MIB).addOperand(*argOpers[i]);
7798 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7799 (*MIB).setMemRefs(mInstr->memoperands_begin(),
7800 mInstr->memoperands_end());
7802 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
7803 MIB.addReg(X86::EAX);
7806 BuildMI(newMBB, dl, TII->get(X86::JNE)).addMBB(newMBB);
7808 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
7812 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
7813 // all of this code can be replaced with that in the .td file.
7815 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
7816 unsigned numArgs, bool memArg) const {
7818 MachineFunction *F = BB->getParent();
7819 DebugLoc dl = MI->getDebugLoc();
7820 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7824 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
7826 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
7828 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
7830 for (unsigned i = 0; i < numArgs; ++i) {
7831 MachineOperand &Op = MI->getOperand(i+1);
7833 if (!(Op.isReg() && Op.isImplicit()))
7837 BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
7840 F->DeleteMachineInstr(MI);
7846 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
7848 MachineBasicBlock *MBB) const {
7849 // Emit code to save XMM registers to the stack. The ABI says that the
7850 // number of registers to save is given in %al, so it's theoretically
7851 // possible to do an indirect jump trick to avoid saving all of them,
7852 // however this code takes a simpler approach and just executes all
7853 // of the stores if %al is non-zero. It's less code, and it's probably
7854 // easier on the hardware branch predictor, and stores aren't all that
7855 // expensive anyway.
7857 // Create the new basic blocks. One block contains all the XMM stores,
7858 // and one block is the final destination regardless of whether any
7859 // stores were performed.
7860 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7861 MachineFunction *F = MBB->getParent();
7862 MachineFunction::iterator MBBIter = MBB;
7864 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
7865 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
7866 F->insert(MBBIter, XMMSaveMBB);
7867 F->insert(MBBIter, EndMBB);
7870 // Move any original successors of MBB to the end block.
7871 EndMBB->transferSuccessors(MBB);
7872 // The original block will now fall through to the XMM save block.
7873 MBB->addSuccessor(XMMSaveMBB);
7874 // The XMMSaveMBB will fall through to the end block.
7875 XMMSaveMBB->addSuccessor(EndMBB);
7877 // Now add the instructions.
7878 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7879 DebugLoc DL = MI->getDebugLoc();
7881 unsigned CountReg = MI->getOperand(0).getReg();
7882 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
7883 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
7885 if (!Subtarget->isTargetWin64()) {
7886 // If %al is 0, branch around the XMM save block.
7887 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
7888 BuildMI(MBB, DL, TII->get(X86::JE)).addMBB(EndMBB);
7889 MBB->addSuccessor(EndMBB);
7892 // In the XMM save block, save all the XMM argument registers.
7893 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
7894 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
7895 MachineMemOperand *MMO =
7896 F->getMachineMemOperand(
7897 PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
7898 MachineMemOperand::MOStore, Offset,
7899 /*Size=*/16, /*Align=*/16);
7900 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
7901 .addFrameIndex(RegSaveFrameIndex)
7902 .addImm(/*Scale=*/1)
7903 .addReg(/*IndexReg=*/0)
7904 .addImm(/*Disp=*/Offset)
7905 .addReg(/*Segment=*/0)
7906 .addReg(MI->getOperand(i).getReg())
7907 .addMemOperand(MMO);
7910 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7916 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
7917 MachineBasicBlock *BB,
7918 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
7919 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7920 DebugLoc DL = MI->getDebugLoc();
7922 // To "insert" a SELECT_CC instruction, we actually have to insert the
7923 // diamond control-flow pattern. The incoming instruction knows the
7924 // destination vreg to set, the condition code register to branch on, the
7925 // true/false values to select between, and a branch opcode to use.
7926 const BasicBlock *LLVM_BB = BB->getBasicBlock();
7927 MachineFunction::iterator It = BB;
7933 // cmpTY ccX, r1, r2
7935 // fallthrough --> copy0MBB
7936 MachineBasicBlock *thisMBB = BB;
7937 MachineFunction *F = BB->getParent();
7938 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
7939 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
7941 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
7942 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
7943 F->insert(It, copy0MBB);
7944 F->insert(It, sinkMBB);
7945 // Update machine-CFG edges by first adding all successors of the current
7946 // block to the new block which will contain the Phi node for the select.
7947 // Also inform sdisel of the edge changes.
7948 for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
7949 E = BB->succ_end(); I != E; ++I) {
7950 EM->insert(std::make_pair(*I, sinkMBB));
7951 sinkMBB->addSuccessor(*I);
7953 // Next, remove all successors of the current block, and add the true
7954 // and fallthrough blocks as its successors.
7955 while (!BB->succ_empty())
7956 BB->removeSuccessor(BB->succ_begin());
7957 // Add the true and fallthrough blocks as its successors.
7958 BB->addSuccessor(copy0MBB);
7959 BB->addSuccessor(sinkMBB);
7962 // %FalseValue = ...
7963 // # fallthrough to sinkMBB
7966 // Update machine-CFG edges
7967 BB->addSuccessor(sinkMBB);
7970 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
7973 BuildMI(BB, DL, TII->get(X86::PHI), MI->getOperand(0).getReg())
7974 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
7975 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
7977 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
7983 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
7984 MachineBasicBlock *BB,
7985 DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
7986 switch (MI->getOpcode()) {
7987 default: assert(false && "Unexpected instr type to insert");
7989 case X86::CMOV_V1I64:
7990 case X86::CMOV_FR32:
7991 case X86::CMOV_FR64:
7992 case X86::CMOV_V4F32:
7993 case X86::CMOV_V2F64:
7994 case X86::CMOV_V2I64:
7995 return EmitLoweredSelect(MI, BB, EM);
7997 case X86::FP32_TO_INT16_IN_MEM:
7998 case X86::FP32_TO_INT32_IN_MEM:
7999 case X86::FP32_TO_INT64_IN_MEM:
8000 case X86::FP64_TO_INT16_IN_MEM:
8001 case X86::FP64_TO_INT32_IN_MEM:
8002 case X86::FP64_TO_INT64_IN_MEM:
8003 case X86::FP80_TO_INT16_IN_MEM:
8004 case X86::FP80_TO_INT32_IN_MEM:
8005 case X86::FP80_TO_INT64_IN_MEM: {
8006 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8007 DebugLoc DL = MI->getDebugLoc();
8009 // Change the floating point control register to use "round towards zero"
8010 // mode when truncating to an integer value.
8011 MachineFunction *F = BB->getParent();
8012 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
8013 addFrameReference(BuildMI(BB, DL, TII->get(X86::FNSTCW16m)), CWFrameIdx);
8015 // Load the old value of the high byte of the control word...
8017 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
8018 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16rm), OldCW),
8021 // Set the high part to be round to zero...
8022 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
8025 // Reload the modified control word now...
8026 addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8028 // Restore the memory image of control word to original value
8029 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
8032 // Get the X86 opcode to use.
8034 switch (MI->getOpcode()) {
8035 default: llvm_unreachable("illegal opcode!");
8036 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
8037 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
8038 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
8039 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
8040 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
8041 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
8042 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
8043 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
8044 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
8048 MachineOperand &Op = MI->getOperand(0);
8050 AM.BaseType = X86AddressMode::RegBase;
8051 AM.Base.Reg = Op.getReg();
8053 AM.BaseType = X86AddressMode::FrameIndexBase;
8054 AM.Base.FrameIndex = Op.getIndex();
8056 Op = MI->getOperand(1);
8058 AM.Scale = Op.getImm();
8059 Op = MI->getOperand(2);
8061 AM.IndexReg = Op.getImm();
8062 Op = MI->getOperand(3);
8063 if (Op.isGlobal()) {
8064 AM.GV = Op.getGlobal();
8066 AM.Disp = Op.getImm();
8068 addFullAddress(BuildMI(BB, DL, TII->get(Opc)), AM)
8069 .addReg(MI->getOperand(X86AddrNumOperands).getReg());
8071 // Reload the original control word now.
8072 addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8074 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8077 // String/text processing lowering.
8078 case X86::PCMPISTRM128REG:
8079 return EmitPCMP(MI, BB, 3, false /* in-mem */);
8080 case X86::PCMPISTRM128MEM:
8081 return EmitPCMP(MI, BB, 3, true /* in-mem */);
8082 case X86::PCMPESTRM128REG:
8083 return EmitPCMP(MI, BB, 5, false /* in mem */);
8084 case X86::PCMPESTRM128MEM:
8085 return EmitPCMP(MI, BB, 5, true /* in mem */);
8088 case X86::ATOMAND32:
8089 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8090 X86::AND32ri, X86::MOV32rm,
8091 X86::LCMPXCHG32, X86::MOV32rr,
8092 X86::NOT32r, X86::EAX,
8093 X86::GR32RegisterClass);
8095 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
8096 X86::OR32ri, X86::MOV32rm,
8097 X86::LCMPXCHG32, X86::MOV32rr,
8098 X86::NOT32r, X86::EAX,
8099 X86::GR32RegisterClass);
8100 case X86::ATOMXOR32:
8101 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
8102 X86::XOR32ri, X86::MOV32rm,
8103 X86::LCMPXCHG32, X86::MOV32rr,
8104 X86::NOT32r, X86::EAX,
8105 X86::GR32RegisterClass);
8106 case X86::ATOMNAND32:
8107 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8108 X86::AND32ri, X86::MOV32rm,
8109 X86::LCMPXCHG32, X86::MOV32rr,
8110 X86::NOT32r, X86::EAX,
8111 X86::GR32RegisterClass, true);
8112 case X86::ATOMMIN32:
8113 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
8114 case X86::ATOMMAX32:
8115 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
8116 case X86::ATOMUMIN32:
8117 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
8118 case X86::ATOMUMAX32:
8119 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
8121 case X86::ATOMAND16:
8122 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8123 X86::AND16ri, X86::MOV16rm,
8124 X86::LCMPXCHG16, X86::MOV16rr,
8125 X86::NOT16r, X86::AX,
8126 X86::GR16RegisterClass);
8128 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
8129 X86::OR16ri, X86::MOV16rm,
8130 X86::LCMPXCHG16, X86::MOV16rr,
8131 X86::NOT16r, X86::AX,
8132 X86::GR16RegisterClass);
8133 case X86::ATOMXOR16:
8134 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
8135 X86::XOR16ri, X86::MOV16rm,
8136 X86::LCMPXCHG16, X86::MOV16rr,
8137 X86::NOT16r, X86::AX,
8138 X86::GR16RegisterClass);
8139 case X86::ATOMNAND16:
8140 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8141 X86::AND16ri, X86::MOV16rm,
8142 X86::LCMPXCHG16, X86::MOV16rr,
8143 X86::NOT16r, X86::AX,
8144 X86::GR16RegisterClass, true);
8145 case X86::ATOMMIN16:
8146 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
8147 case X86::ATOMMAX16:
8148 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
8149 case X86::ATOMUMIN16:
8150 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
8151 case X86::ATOMUMAX16:
8152 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
8155 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8156 X86::AND8ri, X86::MOV8rm,
8157 X86::LCMPXCHG8, X86::MOV8rr,
8158 X86::NOT8r, X86::AL,
8159 X86::GR8RegisterClass);
8161 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
8162 X86::OR8ri, X86::MOV8rm,
8163 X86::LCMPXCHG8, X86::MOV8rr,
8164 X86::NOT8r, X86::AL,
8165 X86::GR8RegisterClass);
8167 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
8168 X86::XOR8ri, X86::MOV8rm,
8169 X86::LCMPXCHG8, X86::MOV8rr,
8170 X86::NOT8r, X86::AL,
8171 X86::GR8RegisterClass);
8172 case X86::ATOMNAND8:
8173 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8174 X86::AND8ri, X86::MOV8rm,
8175 X86::LCMPXCHG8, X86::MOV8rr,
8176 X86::NOT8r, X86::AL,
8177 X86::GR8RegisterClass, true);
8178 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
8179 // This group is for 64-bit host.
8180 case X86::ATOMAND64:
8181 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8182 X86::AND64ri32, X86::MOV64rm,
8183 X86::LCMPXCHG64, X86::MOV64rr,
8184 X86::NOT64r, X86::RAX,
8185 X86::GR64RegisterClass);
8187 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
8188 X86::OR64ri32, X86::MOV64rm,
8189 X86::LCMPXCHG64, X86::MOV64rr,
8190 X86::NOT64r, X86::RAX,
8191 X86::GR64RegisterClass);
8192 case X86::ATOMXOR64:
8193 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
8194 X86::XOR64ri32, X86::MOV64rm,
8195 X86::LCMPXCHG64, X86::MOV64rr,
8196 X86::NOT64r, X86::RAX,
8197 X86::GR64RegisterClass);
8198 case X86::ATOMNAND64:
8199 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8200 X86::AND64ri32, X86::MOV64rm,
8201 X86::LCMPXCHG64, X86::MOV64rr,
8202 X86::NOT64r, X86::RAX,
8203 X86::GR64RegisterClass, true);
8204 case X86::ATOMMIN64:
8205 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
8206 case X86::ATOMMAX64:
8207 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
8208 case X86::ATOMUMIN64:
8209 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
8210 case X86::ATOMUMAX64:
8211 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
8213 // This group does 64-bit operations on a 32-bit host.
8214 case X86::ATOMAND6432:
8215 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8216 X86::AND32rr, X86::AND32rr,
8217 X86::AND32ri, X86::AND32ri,
8219 case X86::ATOMOR6432:
8220 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8221 X86::OR32rr, X86::OR32rr,
8222 X86::OR32ri, X86::OR32ri,
8224 case X86::ATOMXOR6432:
8225 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8226 X86::XOR32rr, X86::XOR32rr,
8227 X86::XOR32ri, X86::XOR32ri,
8229 case X86::ATOMNAND6432:
8230 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8231 X86::AND32rr, X86::AND32rr,
8232 X86::AND32ri, X86::AND32ri,
8234 case X86::ATOMADD6432:
8235 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8236 X86::ADD32rr, X86::ADC32rr,
8237 X86::ADD32ri, X86::ADC32ri,
8239 case X86::ATOMSUB6432:
8240 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8241 X86::SUB32rr, X86::SBB32rr,
8242 X86::SUB32ri, X86::SBB32ri,
8244 case X86::ATOMSWAP6432:
8245 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8246 X86::MOV32rr, X86::MOV32rr,
8247 X86::MOV32ri, X86::MOV32ri,
8249 case X86::VASTART_SAVE_XMM_REGS:
8250 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
8254 //===----------------------------------------------------------------------===//
8255 // X86 Optimization Hooks
8256 //===----------------------------------------------------------------------===//
8258 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8262 const SelectionDAG &DAG,
8263 unsigned Depth) const {
8264 unsigned Opc = Op.getOpcode();
8265 assert((Opc >= ISD::BUILTIN_OP_END ||
8266 Opc == ISD::INTRINSIC_WO_CHAIN ||
8267 Opc == ISD::INTRINSIC_W_CHAIN ||
8268 Opc == ISD::INTRINSIC_VOID) &&
8269 "Should use MaskedValueIsZero if you don't know whether Op"
8270 " is a target node!");
8272 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
8284 // These nodes' second result is a boolean.
8285 if (Op.getResNo() == 0)
8289 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
8290 Mask.getBitWidth() - 1);
8295 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
8296 /// node is a GlobalAddress + offset.
8297 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
8298 GlobalValue* &GA, int64_t &Offset) const{
8299 if (N->getOpcode() == X86ISD::Wrapper) {
8300 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
8301 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
8302 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
8306 return TargetLowering::isGAPlusOffset(N, GA, Offset);
8309 static bool isBaseAlignmentOfN(unsigned N, SDNode *Base,
8310 const TargetLowering &TLI) {
8313 if (TLI.isGAPlusOffset(Base, GV, Offset))
8314 return (GV->getAlignment() >= N && (Offset % N) == 0);
8315 // DAG combine handles the stack object case.
8319 static bool EltsFromConsecutiveLoads(ShuffleVectorSDNode *N, unsigned NumElems,
8320 EVT EltVT, LoadSDNode *&LDBase,
8321 unsigned &LastLoadedElt,
8322 SelectionDAG &DAG, MachineFrameInfo *MFI,
8323 const TargetLowering &TLI) {
8325 LastLoadedElt = -1U;
8326 for (unsigned i = 0; i < NumElems; ++i) {
8327 if (N->getMaskElt(i) < 0) {
8333 SDValue Elt = DAG.getShuffleScalarElt(N, i);
8334 if (!Elt.getNode() ||
8335 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
8338 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
8340 LDBase = cast<LoadSDNode>(Elt.getNode());
8344 if (Elt.getOpcode() == ISD::UNDEF)
8347 LoadSDNode *LD = cast<LoadSDNode>(Elt);
8348 if (!TLI.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i, MFI))
8355 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8356 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8357 /// if the load addresses are consecutive, non-overlapping, and in the right
8358 /// order. In the case of v2i64, it will see if it can rewrite the
8359 /// shuffle to be an appropriate build vector so it can take advantage of
8360 // performBuildVectorCombine.
8361 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8362 const TargetLowering &TLI) {
8363 DebugLoc dl = N->getDebugLoc();
8364 EVT VT = N->getValueType(0);
8365 EVT EltVT = VT.getVectorElementType();
8366 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8367 unsigned NumElems = VT.getVectorNumElements();
8369 if (VT.getSizeInBits() != 128)
8372 // Try to combine a vector_shuffle into a 128-bit load.
8373 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8374 LoadSDNode *LD = NULL;
8375 unsigned LastLoadedElt;
8376 if (!EltsFromConsecutiveLoads(SVN, NumElems, EltVT, LD, LastLoadedElt, DAG,
8380 if (LastLoadedElt == NumElems - 1) {
8381 if (isBaseAlignmentOfN(16, LD->getBasePtr().getNode(), TLI))
8382 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8383 LD->getSrcValue(), LD->getSrcValueOffset(),
8385 return DAG.getLoad(VT, dl, LD->getChain(), LD->getBasePtr(),
8386 LD->getSrcValue(), LD->getSrcValueOffset(),
8387 LD->isVolatile(), LD->getAlignment());
8388 } else if (NumElems == 4 && LastLoadedElt == 1) {
8389 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
8390 SDValue Ops[] = { LD->getChain(), LD->getBasePtr() };
8391 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
8392 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
8397 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
8398 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
8399 const X86Subtarget *Subtarget) {
8400 DebugLoc DL = N->getDebugLoc();
8401 SDValue Cond = N->getOperand(0);
8402 // Get the LHS/RHS of the select.
8403 SDValue LHS = N->getOperand(1);
8404 SDValue RHS = N->getOperand(2);
8406 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
8407 // instructions have the peculiarity that if either operand is a NaN,
8408 // they chose what we call the RHS operand (and as such are not symmetric).
8409 // It happens that this matches the semantics of the common C idiom
8410 // x<y?x:y and related forms, so we can recognize these cases.
8411 if (Subtarget->hasSSE2() &&
8412 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
8413 Cond.getOpcode() == ISD::SETCC) {
8414 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
8416 unsigned Opcode = 0;
8417 // Check for x CC y ? x : y.
8418 if (LHS == Cond.getOperand(0) && RHS == Cond.getOperand(1)) {
8422 // This can be a min if we can prove that at least one of the operands
8424 if (!FiniteOnlyFPMath()) {
8425 if (DAG.isKnownNeverNaN(RHS)) {
8426 // Put the potential NaN in the RHS so that SSE will preserve it.
8427 std::swap(LHS, RHS);
8428 } else if (!DAG.isKnownNeverNaN(LHS))
8431 Opcode = X86ISD::FMIN;
8434 // This can be a min if we can prove that at least one of the operands
8436 if (!FiniteOnlyFPMath()) {
8437 if (DAG.isKnownNeverNaN(LHS)) {
8438 // Put the potential NaN in the RHS so that SSE will preserve it.
8439 std::swap(LHS, RHS);
8440 } else if (!DAG.isKnownNeverNaN(RHS))
8443 Opcode = X86ISD::FMIN;
8446 // This can be a min, but if either operand is a NaN we need it to
8447 // preserve the original LHS.
8448 std::swap(LHS, RHS);
8452 Opcode = X86ISD::FMIN;
8456 // This can be a max if we can prove that at least one of the operands
8458 if (!FiniteOnlyFPMath()) {
8459 if (DAG.isKnownNeverNaN(LHS)) {
8460 // Put the potential NaN in the RHS so that SSE will preserve it.
8461 std::swap(LHS, RHS);
8462 } else if (!DAG.isKnownNeverNaN(RHS))
8465 Opcode = X86ISD::FMAX;
8468 // This can be a max if we can prove that at least one of the operands
8470 if (!FiniteOnlyFPMath()) {
8471 if (DAG.isKnownNeverNaN(RHS)) {
8472 // Put the potential NaN in the RHS so that SSE will preserve it.
8473 std::swap(LHS, RHS);
8474 } else if (!DAG.isKnownNeverNaN(LHS))
8477 Opcode = X86ISD::FMAX;
8480 // This can be a max, but if either operand is a NaN we need it to
8481 // preserve the original LHS.
8482 std::swap(LHS, RHS);
8486 Opcode = X86ISD::FMAX;
8489 // Check for x CC y ? y : x -- a min/max with reversed arms.
8490 } else if (LHS == Cond.getOperand(1) && RHS == Cond.getOperand(0)) {
8494 // This can be a min if we can prove that at least one of the operands
8496 if (!FiniteOnlyFPMath()) {
8497 if (DAG.isKnownNeverNaN(RHS)) {
8498 // Put the potential NaN in the RHS so that SSE will preserve it.
8499 std::swap(LHS, RHS);
8500 } else if (!DAG.isKnownNeverNaN(LHS))
8503 Opcode = X86ISD::FMIN;
8506 // This can be a min if we can prove that at least one of the operands
8508 if (!FiniteOnlyFPMath()) {
8509 if (DAG.isKnownNeverNaN(LHS)) {
8510 // Put the potential NaN in the RHS so that SSE will preserve it.
8511 std::swap(LHS, RHS);
8512 } else if (!DAG.isKnownNeverNaN(RHS))
8515 Opcode = X86ISD::FMIN;
8518 // This can be a min, but if either operand is a NaN we need it to
8519 // preserve the original LHS.
8520 std::swap(LHS, RHS);
8524 Opcode = X86ISD::FMIN;
8528 // This can be a max if we can prove that at least one of the operands
8530 if (!FiniteOnlyFPMath()) {
8531 if (DAG.isKnownNeverNaN(LHS)) {
8532 // Put the potential NaN in the RHS so that SSE will preserve it.
8533 std::swap(LHS, RHS);
8534 } else if (!DAG.isKnownNeverNaN(RHS))
8537 Opcode = X86ISD::FMAX;
8540 // This can be a max if we can prove that at least one of the operands
8542 if (!FiniteOnlyFPMath()) {
8543 if (DAG.isKnownNeverNaN(RHS)) {
8544 // Put the potential NaN in the RHS so that SSE will preserve it.
8545 std::swap(LHS, RHS);
8546 } else if (!DAG.isKnownNeverNaN(LHS))
8549 Opcode = X86ISD::FMAX;
8552 // This can be a max, but if either operand is a NaN we need it to
8553 // preserve the original LHS.
8554 std::swap(LHS, RHS);
8558 Opcode = X86ISD::FMAX;
8564 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
8567 // If this is a select between two integer constants, try to do some
8569 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
8570 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
8571 // Don't do this for crazy integer types.
8572 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
8573 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
8574 // so that TrueC (the true value) is larger than FalseC.
8575 bool NeedsCondInvert = false;
8577 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
8578 // Efficiently invertible.
8579 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
8580 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
8581 isa<ConstantSDNode>(Cond.getOperand(1))))) {
8582 NeedsCondInvert = true;
8583 std::swap(TrueC, FalseC);
8586 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
8587 if (FalseC->getAPIntValue() == 0 &&
8588 TrueC->getAPIntValue().isPowerOf2()) {
8589 if (NeedsCondInvert) // Invert the condition if needed.
8590 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8591 DAG.getConstant(1, Cond.getValueType()));
8593 // Zero extend the condition if needed.
8594 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
8596 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8597 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
8598 DAG.getConstant(ShAmt, MVT::i8));
8601 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
8602 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8603 if (NeedsCondInvert) // Invert the condition if needed.
8604 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8605 DAG.getConstant(1, Cond.getValueType()));
8607 // Zero extend the condition if needed.
8608 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8609 FalseC->getValueType(0), Cond);
8610 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8611 SDValue(FalseC, 0));
8614 // Optimize cases that will turn into an LEA instruction. This requires
8615 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8616 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8617 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8618 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8620 bool isFastMultiplier = false;
8622 switch ((unsigned char)Diff) {
8624 case 1: // result = add base, cond
8625 case 2: // result = lea base( , cond*2)
8626 case 3: // result = lea base(cond, cond*2)
8627 case 4: // result = lea base( , cond*4)
8628 case 5: // result = lea base(cond, cond*4)
8629 case 8: // result = lea base( , cond*8)
8630 case 9: // result = lea base(cond, cond*8)
8631 isFastMultiplier = true;
8636 if (isFastMultiplier) {
8637 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8638 if (NeedsCondInvert) // Invert the condition if needed.
8639 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
8640 DAG.getConstant(1, Cond.getValueType()));
8642 // Zero extend the condition if needed.
8643 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8645 // Scale the condition by the difference.
8647 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8648 DAG.getConstant(Diff, Cond.getValueType()));
8650 // Add the base if non-zero.
8651 if (FalseC->getAPIntValue() != 0)
8652 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8653 SDValue(FalseC, 0));
8663 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
8664 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
8665 TargetLowering::DAGCombinerInfo &DCI) {
8666 DebugLoc DL = N->getDebugLoc();
8668 // If the flag operand isn't dead, don't touch this CMOV.
8669 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
8672 // If this is a select between two integer constants, try to do some
8673 // optimizations. Note that the operands are ordered the opposite of SELECT
8675 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
8676 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
8677 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
8678 // larger than FalseC (the false value).
8679 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
8681 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
8682 CC = X86::GetOppositeBranchCondition(CC);
8683 std::swap(TrueC, FalseC);
8686 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
8687 // This is efficient for any integer data type (including i8/i16) and
8689 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
8690 SDValue Cond = N->getOperand(3);
8691 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8692 DAG.getConstant(CC, MVT::i8), Cond);
8694 // Zero extend the condition if needed.
8695 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
8697 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
8698 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
8699 DAG.getConstant(ShAmt, MVT::i8));
8700 if (N->getNumValues() == 2) // Dead flag value?
8701 return DCI.CombineTo(N, Cond, SDValue());
8705 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
8706 // for any integer data type, including i8/i16.
8707 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
8708 SDValue Cond = N->getOperand(3);
8709 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8710 DAG.getConstant(CC, MVT::i8), Cond);
8712 // Zero extend the condition if needed.
8713 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
8714 FalseC->getValueType(0), Cond);
8715 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8716 SDValue(FalseC, 0));
8718 if (N->getNumValues() == 2) // Dead flag value?
8719 return DCI.CombineTo(N, Cond, SDValue());
8723 // Optimize cases that will turn into an LEA instruction. This requires
8724 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
8725 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
8726 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
8727 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
8729 bool isFastMultiplier = false;
8731 switch ((unsigned char)Diff) {
8733 case 1: // result = add base, cond
8734 case 2: // result = lea base( , cond*2)
8735 case 3: // result = lea base(cond, cond*2)
8736 case 4: // result = lea base( , cond*4)
8737 case 5: // result = lea base(cond, cond*4)
8738 case 8: // result = lea base( , cond*8)
8739 case 9: // result = lea base(cond, cond*8)
8740 isFastMultiplier = true;
8745 if (isFastMultiplier) {
8746 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
8747 SDValue Cond = N->getOperand(3);
8748 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
8749 DAG.getConstant(CC, MVT::i8), Cond);
8750 // Zero extend the condition if needed.
8751 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
8753 // Scale the condition by the difference.
8755 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
8756 DAG.getConstant(Diff, Cond.getValueType()));
8758 // Add the base if non-zero.
8759 if (FalseC->getAPIntValue() != 0)
8760 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
8761 SDValue(FalseC, 0));
8762 if (N->getNumValues() == 2) // Dead flag value?
8763 return DCI.CombineTo(N, Cond, SDValue());
8773 /// PerformMulCombine - Optimize a single multiply with constant into two
8774 /// in order to implement it with two cheaper instructions, e.g.
8775 /// LEA + SHL, LEA + LEA.
8776 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
8777 TargetLowering::DAGCombinerInfo &DCI) {
8778 if (DAG.getMachineFunction().
8779 getFunction()->hasFnAttr(Attribute::OptimizeForSize))
8782 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8785 EVT VT = N->getValueType(0);
8789 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
8792 uint64_t MulAmt = C->getZExtValue();
8793 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
8796 uint64_t MulAmt1 = 0;
8797 uint64_t MulAmt2 = 0;
8798 if ((MulAmt % 9) == 0) {
8800 MulAmt2 = MulAmt / 9;
8801 } else if ((MulAmt % 5) == 0) {
8803 MulAmt2 = MulAmt / 5;
8804 } else if ((MulAmt % 3) == 0) {
8806 MulAmt2 = MulAmt / 3;
8809 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
8810 DebugLoc DL = N->getDebugLoc();
8812 if (isPowerOf2_64(MulAmt2) &&
8813 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
8814 // If second multiplifer is pow2, issue it first. We want the multiply by
8815 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
8817 std::swap(MulAmt1, MulAmt2);
8820 if (isPowerOf2_64(MulAmt1))
8821 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
8822 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
8824 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
8825 DAG.getConstant(MulAmt1, VT));
8827 if (isPowerOf2_64(MulAmt2))
8828 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
8829 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
8831 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
8832 DAG.getConstant(MulAmt2, VT));
8834 // Do not add new nodes to DAG combiner worklist.
8835 DCI.CombineTo(N, NewMul, false);
8841 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
8843 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
8844 const X86Subtarget *Subtarget) {
8845 // On X86 with SSE2 support, we can transform this to a vector shift if
8846 // all elements are shifted by the same amount. We can't do this in legalize
8847 // because the a constant vector is typically transformed to a constant pool
8848 // so we have no knowledge of the shift amount.
8849 if (!Subtarget->hasSSE2())
8852 EVT VT = N->getValueType(0);
8853 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
8856 SDValue ShAmtOp = N->getOperand(1);
8857 EVT EltVT = VT.getVectorElementType();
8858 DebugLoc DL = N->getDebugLoc();
8859 SDValue BaseShAmt = SDValue();
8860 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
8861 unsigned NumElts = VT.getVectorNumElements();
8863 for (; i != NumElts; ++i) {
8864 SDValue Arg = ShAmtOp.getOperand(i);
8865 if (Arg.getOpcode() == ISD::UNDEF) continue;
8869 for (; i != NumElts; ++i) {
8870 SDValue Arg = ShAmtOp.getOperand(i);
8871 if (Arg.getOpcode() == ISD::UNDEF) continue;
8872 if (Arg != BaseShAmt) {
8876 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
8877 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
8878 SDValue InVec = ShAmtOp.getOperand(0);
8879 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
8880 unsigned NumElts = InVec.getValueType().getVectorNumElements();
8882 for (; i != NumElts; ++i) {
8883 SDValue Arg = InVec.getOperand(i);
8884 if (Arg.getOpcode() == ISD::UNDEF) continue;
8888 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
8889 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
8890 unsigned SplatIdx = cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
8891 if (C->getZExtValue() == SplatIdx)
8892 BaseShAmt = InVec.getOperand(1);
8895 if (BaseShAmt.getNode() == 0)
8896 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
8897 DAG.getIntPtrConstant(0));
8901 // The shift amount is an i32.
8902 if (EltVT.bitsGT(MVT::i32))
8903 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
8904 else if (EltVT.bitsLT(MVT::i32))
8905 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
8907 // The shift amount is identical so we can do a vector shift.
8908 SDValue ValOp = N->getOperand(0);
8909 switch (N->getOpcode()) {
8911 llvm_unreachable("Unknown shift opcode!");
8914 if (VT == MVT::v2i64)
8915 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8916 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
8918 if (VT == MVT::v4i32)
8919 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8920 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
8922 if (VT == MVT::v8i16)
8923 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8924 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
8928 if (VT == MVT::v4i32)
8929 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8930 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
8932 if (VT == MVT::v8i16)
8933 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8934 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
8938 if (VT == MVT::v2i64)
8939 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8940 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
8942 if (VT == MVT::v4i32)
8943 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8944 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
8946 if (VT == MVT::v8i16)
8947 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
8948 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
8955 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
8956 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
8957 const X86Subtarget *Subtarget) {
8958 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
8959 // the FP state in cases where an emms may be missing.
8960 // A preferable solution to the general problem is to figure out the right
8961 // places to insert EMMS. This qualifies as a quick hack.
8963 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
8964 StoreSDNode *St = cast<StoreSDNode>(N);
8965 EVT VT = St->getValue().getValueType();
8966 if (VT.getSizeInBits() != 64)
8969 const Function *F = DAG.getMachineFunction().getFunction();
8970 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
8971 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
8972 && Subtarget->hasSSE2();
8973 if ((VT.isVector() ||
8974 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
8975 isa<LoadSDNode>(St->getValue()) &&
8976 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
8977 St->getChain().hasOneUse() && !St->isVolatile()) {
8978 SDNode* LdVal = St->getValue().getNode();
8980 int TokenFactorIndex = -1;
8981 SmallVector<SDValue, 8> Ops;
8982 SDNode* ChainVal = St->getChain().getNode();
8983 // Must be a store of a load. We currently handle two cases: the load
8984 // is a direct child, and it's under an intervening TokenFactor. It is
8985 // possible to dig deeper under nested TokenFactors.
8986 if (ChainVal == LdVal)
8987 Ld = cast<LoadSDNode>(St->getChain());
8988 else if (St->getValue().hasOneUse() &&
8989 ChainVal->getOpcode() == ISD::TokenFactor) {
8990 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
8991 if (ChainVal->getOperand(i).getNode() == LdVal) {
8992 TokenFactorIndex = i;
8993 Ld = cast<LoadSDNode>(St->getValue());
8995 Ops.push_back(ChainVal->getOperand(i));
8999 if (!Ld || !ISD::isNormalLoad(Ld))
9002 // If this is not the MMX case, i.e. we are just turning i64 load/store
9003 // into f64 load/store, avoid the transformation if there are multiple
9004 // uses of the loaded value.
9005 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
9008 DebugLoc LdDL = Ld->getDebugLoc();
9009 DebugLoc StDL = N->getDebugLoc();
9010 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
9011 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
9013 if (Subtarget->is64Bit() || F64IsLegal) {
9014 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
9015 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
9016 Ld->getBasePtr(), Ld->getSrcValue(),
9017 Ld->getSrcValueOffset(), Ld->isVolatile(),
9018 Ld->getAlignment());
9019 SDValue NewChain = NewLd.getValue(1);
9020 if (TokenFactorIndex != -1) {
9021 Ops.push_back(NewChain);
9022 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9025 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
9026 St->getSrcValue(), St->getSrcValueOffset(),
9027 St->isVolatile(), St->getAlignment());
9030 // Otherwise, lower to two pairs of 32-bit loads / stores.
9031 SDValue LoAddr = Ld->getBasePtr();
9032 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
9033 DAG.getConstant(4, MVT::i32));
9035 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
9036 Ld->getSrcValue(), Ld->getSrcValueOffset(),
9037 Ld->isVolatile(), Ld->getAlignment());
9038 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
9039 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
9041 MinAlign(Ld->getAlignment(), 4));
9043 SDValue NewChain = LoLd.getValue(1);
9044 if (TokenFactorIndex != -1) {
9045 Ops.push_back(LoLd);
9046 Ops.push_back(HiLd);
9047 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9051 LoAddr = St->getBasePtr();
9052 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
9053 DAG.getConstant(4, MVT::i32));
9055 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
9056 St->getSrcValue(), St->getSrcValueOffset(),
9057 St->isVolatile(), St->getAlignment());
9058 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
9060 St->getSrcValueOffset() + 4,
9062 MinAlign(St->getAlignment(), 4));
9063 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
9068 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
9069 /// X86ISD::FXOR nodes.
9070 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
9071 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
9072 // F[X]OR(0.0, x) -> x
9073 // F[X]OR(x, 0.0) -> x
9074 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9075 if (C->getValueAPF().isPosZero())
9076 return N->getOperand(1);
9077 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9078 if (C->getValueAPF().isPosZero())
9079 return N->getOperand(0);
9083 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
9084 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
9085 // FAND(0.0, x) -> 0.0
9086 // FAND(x, 0.0) -> 0.0
9087 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9088 if (C->getValueAPF().isPosZero())
9089 return N->getOperand(0);
9090 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9091 if (C->getValueAPF().isPosZero())
9092 return N->getOperand(1);
9096 static SDValue PerformBTCombine(SDNode *N,
9098 TargetLowering::DAGCombinerInfo &DCI) {
9099 // BT ignores high bits in the bit index operand.
9100 SDValue Op1 = N->getOperand(1);
9101 if (Op1.hasOneUse()) {
9102 unsigned BitWidth = Op1.getValueSizeInBits();
9103 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
9104 APInt KnownZero, KnownOne;
9105 TargetLowering::TargetLoweringOpt TLO(DAG);
9106 TargetLowering &TLI = DAG.getTargetLoweringInfo();
9107 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
9108 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
9109 DCI.CommitTargetLoweringOpt(TLO);
9114 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
9115 SDValue Op = N->getOperand(0);
9116 if (Op.getOpcode() == ISD::BIT_CONVERT)
9117 Op = Op.getOperand(0);
9118 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
9119 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
9120 VT.getVectorElementType().getSizeInBits() ==
9121 OpVT.getVectorElementType().getSizeInBits()) {
9122 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
9127 // On X86 and X86-64, atomic operations are lowered to locked instructions.
9128 // Locked instructions, in turn, have implicit fence semantics (all memory
9129 // operations are flushed before issuing the locked instruction, and the
9130 // are not buffered), so we can fold away the common pattern of
9131 // fence-atomic-fence.
9132 static SDValue PerformMEMBARRIERCombine(SDNode* N, SelectionDAG &DAG) {
9133 SDValue atomic = N->getOperand(0);
9134 switch (atomic.getOpcode()) {
9135 case ISD::ATOMIC_CMP_SWAP:
9136 case ISD::ATOMIC_SWAP:
9137 case ISD::ATOMIC_LOAD_ADD:
9138 case ISD::ATOMIC_LOAD_SUB:
9139 case ISD::ATOMIC_LOAD_AND:
9140 case ISD::ATOMIC_LOAD_OR:
9141 case ISD::ATOMIC_LOAD_XOR:
9142 case ISD::ATOMIC_LOAD_NAND:
9143 case ISD::ATOMIC_LOAD_MIN:
9144 case ISD::ATOMIC_LOAD_MAX:
9145 case ISD::ATOMIC_LOAD_UMIN:
9146 case ISD::ATOMIC_LOAD_UMAX:
9152 SDValue fence = atomic.getOperand(0);
9153 if (fence.getOpcode() != ISD::MEMBARRIER)
9156 switch (atomic.getOpcode()) {
9157 case ISD::ATOMIC_CMP_SWAP:
9158 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9159 atomic.getOperand(1), atomic.getOperand(2),
9160 atomic.getOperand(3));
9161 case ISD::ATOMIC_SWAP:
9162 case ISD::ATOMIC_LOAD_ADD:
9163 case ISD::ATOMIC_LOAD_SUB:
9164 case ISD::ATOMIC_LOAD_AND:
9165 case ISD::ATOMIC_LOAD_OR:
9166 case ISD::ATOMIC_LOAD_XOR:
9167 case ISD::ATOMIC_LOAD_NAND:
9168 case ISD::ATOMIC_LOAD_MIN:
9169 case ISD::ATOMIC_LOAD_MAX:
9170 case ISD::ATOMIC_LOAD_UMIN:
9171 case ISD::ATOMIC_LOAD_UMAX:
9172 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9173 atomic.getOperand(1), atomic.getOperand(2));
9179 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
9180 DAGCombinerInfo &DCI) const {
9181 SelectionDAG &DAG = DCI.DAG;
9182 switch (N->getOpcode()) {
9184 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
9185 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
9186 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
9187 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
9190 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
9191 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
9193 case X86ISD::FOR: return PerformFORCombine(N, DAG);
9194 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
9195 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
9196 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
9197 case ISD::MEMBARRIER: return PerformMEMBARRIERCombine(N, DAG);
9203 //===----------------------------------------------------------------------===//
9204 // X86 Inline Assembly Support
9205 //===----------------------------------------------------------------------===//
9207 static bool LowerToBSwap(CallInst *CI) {
9208 // FIXME: this should verify that we are targetting a 486 or better. If not,
9209 // we will turn this bswap into something that will be lowered to logical ops
9210 // instead of emitting the bswap asm. For now, we don't support 486 or lower
9211 // so don't worry about this.
9213 // Verify this is a simple bswap.
9214 if (CI->getNumOperands() != 2 ||
9215 CI->getType() != CI->getOperand(1)->getType() ||
9216 !CI->getType()->isInteger())
9219 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9220 if (!Ty || Ty->getBitWidth() % 16 != 0)
9223 // Okay, we can do this xform, do so now.
9224 const Type *Tys[] = { Ty };
9225 Module *M = CI->getParent()->getParent()->getParent();
9226 Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
9228 Value *Op = CI->getOperand(1);
9229 Op = CallInst::Create(Int, Op, CI->getName(), CI);
9231 CI->replaceAllUsesWith(Op);
9232 CI->eraseFromParent();
9236 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
9237 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9238 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
9240 std::string AsmStr = IA->getAsmString();
9242 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
9243 std::vector<std::string> AsmPieces;
9244 SplitString(AsmStr, AsmPieces, "\n"); // ; as separator?
9246 switch (AsmPieces.size()) {
9247 default: return false;
9249 AsmStr = AsmPieces[0];
9251 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
9254 if (AsmPieces.size() == 2 &&
9255 (AsmPieces[0] == "bswap" ||
9256 AsmPieces[0] == "bswapq" ||
9257 AsmPieces[0] == "bswapl") &&
9258 (AsmPieces[1] == "$0" ||
9259 AsmPieces[1] == "${0:q}")) {
9260 // No need to check constraints, nothing other than the equivalent of
9261 // "=r,0" would be valid here.
9262 return LowerToBSwap(CI);
9264 // rorw $$8, ${0:w} --> llvm.bswap.i16
9265 if (CI->getType() == Type::getInt16Ty(CI->getContext()) &&
9266 AsmPieces.size() == 3 &&
9267 AsmPieces[0] == "rorw" &&
9268 AsmPieces[1] == "$$8," &&
9269 AsmPieces[2] == "${0:w}" &&
9270 IA->getConstraintString() == "=r,0,~{dirflag},~{fpsr},~{flags},~{cc}") {
9271 return LowerToBSwap(CI);
9275 if (CI->getType() == Type::getInt64Ty(CI->getContext()) &&
9276 Constraints.size() >= 2 &&
9277 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
9278 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
9279 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
9280 std::vector<std::string> Words;
9281 SplitString(AsmPieces[0], Words, " \t");
9282 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
9284 SplitString(AsmPieces[1], Words, " \t");
9285 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
9287 SplitString(AsmPieces[2], Words, " \t,");
9288 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
9289 Words[2] == "%edx") {
9290 return LowerToBSwap(CI);
9302 /// getConstraintType - Given a constraint letter, return the type of
9303 /// constraint it is for this target.
9304 X86TargetLowering::ConstraintType
9305 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
9306 if (Constraint.size() == 1) {
9307 switch (Constraint[0]) {
9319 return C_RegisterClass;
9327 return TargetLowering::getConstraintType(Constraint);
9330 /// LowerXConstraint - try to replace an X constraint, which matches anything,
9331 /// with another that has more specific requirements based on the type of the
9332 /// corresponding operand.
9333 const char *X86TargetLowering::
9334 LowerXConstraint(EVT ConstraintVT) const {
9335 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
9336 // 'f' like normal targets.
9337 if (ConstraintVT.isFloatingPoint()) {
9338 if (Subtarget->hasSSE2())
9340 if (Subtarget->hasSSE1())
9344 return TargetLowering::LowerXConstraint(ConstraintVT);
9347 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
9348 /// vector. If it is invalid, don't add anything to Ops.
9349 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
9352 std::vector<SDValue>&Ops,
9353 SelectionDAG &DAG) const {
9354 SDValue Result(0, 0);
9356 switch (Constraint) {
9359 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9360 if (C->getZExtValue() <= 31) {
9361 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9367 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9368 if (C->getZExtValue() <= 63) {
9369 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9375 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9376 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
9377 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9383 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9384 if (C->getZExtValue() <= 255) {
9385 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9391 // 32-bit signed value
9392 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9393 const ConstantInt *CI = C->getConstantIntValue();
9394 if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
9395 C->getSExtValue())) {
9396 // Widen to 64 bits here to get it sign extended.
9397 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
9400 // FIXME gcc accepts some relocatable values here too, but only in certain
9401 // memory models; it's complicated.
9406 // 32-bit unsigned value
9407 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
9408 const ConstantInt *CI = C->getConstantIntValue();
9409 if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
9410 C->getZExtValue())) {
9411 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
9415 // FIXME gcc accepts some relocatable values here too, but only in certain
9416 // memory models; it's complicated.
9420 // Literal immediates are always ok.
9421 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
9422 // Widen to 64 bits here to get it sign extended.
9423 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
9427 // If we are in non-pic codegen mode, we allow the address of a global (with
9428 // an optional displacement) to be used with 'i'.
9429 GlobalAddressSDNode *GA = 0;
9432 // Match either (GA), (GA+C), (GA+C1+C2), etc.
9434 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
9435 Offset += GA->getOffset();
9437 } else if (Op.getOpcode() == ISD::ADD) {
9438 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9439 Offset += C->getZExtValue();
9440 Op = Op.getOperand(0);
9443 } else if (Op.getOpcode() == ISD::SUB) {
9444 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
9445 Offset += -C->getZExtValue();
9446 Op = Op.getOperand(0);
9451 // Otherwise, this isn't something we can handle, reject it.
9455 GlobalValue *GV = GA->getGlobal();
9456 // If we require an extra load to get this address, as in PIC mode, we
9458 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
9459 getTargetMachine())))
9463 Op = LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
9465 Op = DAG.getTargetGlobalAddress(GV, GA->getValueType(0), Offset);
9471 if (Result.getNode()) {
9472 Ops.push_back(Result);
9475 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
9479 std::vector<unsigned> X86TargetLowering::
9480 getRegClassForInlineAsmConstraint(const std::string &Constraint,
9482 if (Constraint.size() == 1) {
9483 // FIXME: not handling fp-stack yet!
9484 switch (Constraint[0]) { // GCC X86 Constraint Letters
9485 default: break; // Unknown constraint letter
9486 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
9487 if (Subtarget->is64Bit()) {
9489 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
9490 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
9491 X86::R10D,X86::R11D,X86::R12D,
9492 X86::R13D,X86::R14D,X86::R15D,
9493 X86::EBP, X86::ESP, 0);
9494 else if (VT == MVT::i16)
9495 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
9496 X86::SI, X86::DI, X86::R8W,X86::R9W,
9497 X86::R10W,X86::R11W,X86::R12W,
9498 X86::R13W,X86::R14W,X86::R15W,
9499 X86::BP, X86::SP, 0);
9500 else if (VT == MVT::i8)
9501 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
9502 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
9503 X86::R10B,X86::R11B,X86::R12B,
9504 X86::R13B,X86::R14B,X86::R15B,
9505 X86::BPL, X86::SPL, 0);
9507 else if (VT == MVT::i64)
9508 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
9509 X86::RSI, X86::RDI, X86::R8, X86::R9,
9510 X86::R10, X86::R11, X86::R12,
9511 X86::R13, X86::R14, X86::R15,
9512 X86::RBP, X86::RSP, 0);
9516 // 32-bit fallthrough
9519 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
9520 else if (VT == MVT::i16)
9521 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
9522 else if (VT == MVT::i8)
9523 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
9524 else if (VT == MVT::i64)
9525 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
9530 return std::vector<unsigned>();
9533 std::pair<unsigned, const TargetRegisterClass*>
9534 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
9536 // First, see if this is a constraint that directly corresponds to an LLVM
9538 if (Constraint.size() == 1) {
9539 // GCC Constraint Letters
9540 switch (Constraint[0]) {
9542 case 'r': // GENERAL_REGS
9543 case 'l': // INDEX_REGS
9545 return std::make_pair(0U, X86::GR8RegisterClass);
9547 return std::make_pair(0U, X86::GR16RegisterClass);
9548 if (VT == MVT::i32 || !Subtarget->is64Bit())
9549 return std::make_pair(0U, X86::GR32RegisterClass);
9550 return std::make_pair(0U, X86::GR64RegisterClass);
9551 case 'R': // LEGACY_REGS
9553 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
9555 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
9556 if (VT == MVT::i32 || !Subtarget->is64Bit())
9557 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
9558 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
9559 case 'f': // FP Stack registers.
9560 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
9561 // value to the correct fpstack register class.
9562 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
9563 return std::make_pair(0U, X86::RFP32RegisterClass);
9564 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
9565 return std::make_pair(0U, X86::RFP64RegisterClass);
9566 return std::make_pair(0U, X86::RFP80RegisterClass);
9567 case 'y': // MMX_REGS if MMX allowed.
9568 if (!Subtarget->hasMMX()) break;
9569 return std::make_pair(0U, X86::VR64RegisterClass);
9570 case 'Y': // SSE_REGS if SSE2 allowed
9571 if (!Subtarget->hasSSE2()) break;
9573 case 'x': // SSE_REGS if SSE1 allowed
9574 if (!Subtarget->hasSSE1()) break;
9576 switch (VT.getSimpleVT().SimpleTy) {
9578 // Scalar SSE types.
9581 return std::make_pair(0U, X86::FR32RegisterClass);
9584 return std::make_pair(0U, X86::FR64RegisterClass);
9592 return std::make_pair(0U, X86::VR128RegisterClass);
9598 // Use the default implementation in TargetLowering to convert the register
9599 // constraint into a member of a register class.
9600 std::pair<unsigned, const TargetRegisterClass*> Res;
9601 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
9603 // Not found as a standard register?
9604 if (Res.second == 0) {
9605 // Map st(0) -> st(7) -> ST0
9606 if (Constraint.size() == 7 && Constraint[0] == '{' &&
9607 tolower(Constraint[1]) == 's' &&
9608 tolower(Constraint[2]) == 't' &&
9609 Constraint[3] == '(' &&
9610 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
9611 Constraint[5] == ')' &&
9612 Constraint[6] == '}') {
9614 Res.first = X86::ST0+Constraint[4]-'0';
9615 Res.second = X86::RFP80RegisterClass;
9619 // GCC allows "st(0)" to be called just plain "st".
9620 if (StringRef("{st}").equals_lower(Constraint)) {
9621 Res.first = X86::ST0;
9622 Res.second = X86::RFP80RegisterClass;
9627 if (StringRef("{flags}").equals_lower(Constraint)) {
9628 Res.first = X86::EFLAGS;
9629 Res.second = X86::CCRRegisterClass;
9633 // 'A' means EAX + EDX.
9634 if (Constraint == "A") {
9635 Res.first = X86::EAX;
9636 Res.second = X86::GR32_ADRegisterClass;
9642 // Otherwise, check to see if this is a register class of the wrong value
9643 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
9644 // turn into {ax},{dx}.
9645 if (Res.second->hasType(VT))
9646 return Res; // Correct type already, nothing to do.
9648 // All of the single-register GCC register classes map their values onto
9649 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
9650 // really want an 8-bit or 32-bit register, map to the appropriate register
9651 // class and return the appropriate register.
9652 if (Res.second == X86::GR16RegisterClass) {
9653 if (VT == MVT::i8) {
9654 unsigned DestReg = 0;
9655 switch (Res.first) {
9657 case X86::AX: DestReg = X86::AL; break;
9658 case X86::DX: DestReg = X86::DL; break;
9659 case X86::CX: DestReg = X86::CL; break;
9660 case X86::BX: DestReg = X86::BL; break;
9663 Res.first = DestReg;
9664 Res.second = X86::GR8RegisterClass;
9666 } else if (VT == MVT::i32) {
9667 unsigned DestReg = 0;
9668 switch (Res.first) {
9670 case X86::AX: DestReg = X86::EAX; break;
9671 case X86::DX: DestReg = X86::EDX; break;
9672 case X86::CX: DestReg = X86::ECX; break;
9673 case X86::BX: DestReg = X86::EBX; break;
9674 case X86::SI: DestReg = X86::ESI; break;
9675 case X86::DI: DestReg = X86::EDI; break;
9676 case X86::BP: DestReg = X86::EBP; break;
9677 case X86::SP: DestReg = X86::ESP; break;
9680 Res.first = DestReg;
9681 Res.second = X86::GR32RegisterClass;
9683 } else if (VT == MVT::i64) {
9684 unsigned DestReg = 0;
9685 switch (Res.first) {
9687 case X86::AX: DestReg = X86::RAX; break;
9688 case X86::DX: DestReg = X86::RDX; break;
9689 case X86::CX: DestReg = X86::RCX; break;
9690 case X86::BX: DestReg = X86::RBX; break;
9691 case X86::SI: DestReg = X86::RSI; break;
9692 case X86::DI: DestReg = X86::RDI; break;
9693 case X86::BP: DestReg = X86::RBP; break;
9694 case X86::SP: DestReg = X86::RSP; break;
9697 Res.first = DestReg;
9698 Res.second = X86::GR64RegisterClass;
9701 } else if (Res.second == X86::FR32RegisterClass ||
9702 Res.second == X86::FR64RegisterClass ||
9703 Res.second == X86::VR128RegisterClass) {
9704 // Handle references to XMM physical registers that got mapped into the
9705 // wrong class. This can happen with constraints like {xmm0} where the
9706 // target independent register mapper will just pick the first match it can
9707 // find, ignoring the required type.
9709 Res.second = X86::FR32RegisterClass;
9710 else if (VT == MVT::f64)
9711 Res.second = X86::FR64RegisterClass;
9712 else if (X86::VR128RegisterClass->hasType(VT))
9713 Res.second = X86::VR128RegisterClass;
9719 //===----------------------------------------------------------------------===//
9720 // X86 Widen vector type
9721 //===----------------------------------------------------------------------===//
9723 /// getWidenVectorType: given a vector type, returns the type to widen
9724 /// to (e.g., v7i8 to v8i8). If the vector type is legal, it returns itself.
9725 /// If there is no vector type that we want to widen to, returns MVT::Other
9726 /// When and where to widen is target dependent based on the cost of
9727 /// scalarizing vs using the wider vector type.
9729 EVT X86TargetLowering::getWidenVectorType(EVT VT) const {
9730 assert(VT.isVector());
9731 if (isTypeLegal(VT))
9734 // TODO: In computeRegisterProperty, we can compute the list of legal vector
9735 // type based on element type. This would speed up our search (though
9736 // it may not be worth it since the size of the list is relatively
9738 EVT EltVT = VT.getVectorElementType();
9739 unsigned NElts = VT.getVectorNumElements();
9741 // On X86, it make sense to widen any vector wider than 1
9745 for (unsigned nVT = MVT::FIRST_VECTOR_VALUETYPE;
9746 nVT <= MVT::LAST_VECTOR_VALUETYPE; ++nVT) {
9747 EVT SVT = (MVT::SimpleValueType)nVT;
9749 if (isTypeLegal(SVT) &&
9750 SVT.getVectorElementType() == EltVT &&
9751 SVT.getVectorNumElements() > NElts)