1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "x86-isel"
17 #include "X86InstrBuilder.h"
18 #include "X86ISelLowering.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetObjectFile.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/GlobalAlias.h"
25 #include "llvm/GlobalVariable.h"
26 #include "llvm/Function.h"
27 #include "llvm/Instructions.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/LLVMContext.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/PseudoSourceValue.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/MC/MCContext.h"
39 #include "llvm/MC/MCExpr.h"
40 #include "llvm/MC/MCSymbol.h"
41 #include "llvm/ADT/BitVector.h"
42 #include "llvm/ADT/SmallSet.h"
43 #include "llvm/ADT/Statistic.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/ADT/VectorExtras.h"
46 #include "llvm/Support/CommandLine.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/Dwarf.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Support/raw_ostream.h"
53 using namespace dwarf;
55 STATISTIC(NumTailCalls, "Number of tail calls");
58 DisableMMX("disable-mmx", cl::Hidden, cl::desc("Disable use of MMX"));
60 // Forward declarations.
61 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
64 static TargetLoweringObjectFile *createTLOF(X86TargetMachine &TM) {
65 switch (TM.getSubtarget<X86Subtarget>().TargetType) {
66 default: llvm_unreachable("unknown subtarget type");
67 case X86Subtarget::isDarwin:
68 if (TM.getSubtarget<X86Subtarget>().is64Bit())
69 return new X8664_MachoTargetObjectFile();
70 return new TargetLoweringObjectFileMachO();
71 case X86Subtarget::isELF:
72 if (TM.getSubtarget<X86Subtarget>().is64Bit())
73 return new X8664_ELFTargetObjectFile(TM);
74 return new X8632_ELFTargetObjectFile(TM);
75 case X86Subtarget::isMingw:
76 case X86Subtarget::isCygwin:
77 case X86Subtarget::isWindows:
78 return new TargetLoweringObjectFileCOFF();
82 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
83 : TargetLowering(TM, createTLOF(TM)) {
84 Subtarget = &TM.getSubtarget<X86Subtarget>();
85 X86ScalarSSEf64 = Subtarget->hasSSE2();
86 X86ScalarSSEf32 = Subtarget->hasSSE1();
87 X86StackPtr = Subtarget->is64Bit() ? X86::RSP : X86::ESP;
89 RegInfo = TM.getRegisterInfo();
92 // Set up the TargetLowering object.
94 // X86 is weird, it always uses i8 for shift amounts and setcc results.
95 setShiftAmountType(MVT::i8);
96 setBooleanContents(ZeroOrOneBooleanContent);
97 setSchedulingPreference(SchedulingForRegPressure);
98 setStackPointerRegisterToSaveRestore(X86StackPtr);
100 if (Subtarget->isTargetDarwin()) {
101 // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
102 setUseUnderscoreSetJmp(false);
103 setUseUnderscoreLongJmp(false);
104 } else if (Subtarget->isTargetMingw()) {
105 // MS runtime is weird: it exports _setjmp, but longjmp!
106 setUseUnderscoreSetJmp(true);
107 setUseUnderscoreLongJmp(false);
109 setUseUnderscoreSetJmp(true);
110 setUseUnderscoreLongJmp(true);
113 // Set up the register classes.
114 addRegisterClass(MVT::i8, X86::GR8RegisterClass);
115 addRegisterClass(MVT::i16, X86::GR16RegisterClass);
116 addRegisterClass(MVT::i32, X86::GR32RegisterClass);
117 if (Subtarget->is64Bit())
118 addRegisterClass(MVT::i64, X86::GR64RegisterClass);
120 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
122 // We don't accept any truncstore of integer registers.
123 setTruncStoreAction(MVT::i64, MVT::i32, Expand);
124 setTruncStoreAction(MVT::i64, MVT::i16, Expand);
125 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 // We have an algorithm for SSE2->double, and we turn this into a
149 // 64-bit FILD followed by conditional FADD for other targets.
150 setOperationAction(ISD::UINT_TO_FP , MVT::i64 , Custom);
151 // We have an algorithm for SSE2, and we turn this into a 64-bit
152 // FILD for other targets.
153 setOperationAction(ISD::UINT_TO_FP , MVT::i32 , Custom);
156 // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
158 setOperationAction(ISD::SINT_TO_FP , MVT::i1 , Promote);
159 setOperationAction(ISD::SINT_TO_FP , MVT::i8 , Promote);
162 // SSE has no i16 to fp conversion, only i32
163 if (X86ScalarSSEf32) {
164 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
165 // f32 and f64 cases are Legal, f80 case is not
166 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
168 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Custom);
169 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Custom);
172 setOperationAction(ISD::SINT_TO_FP , MVT::i16 , Promote);
173 setOperationAction(ISD::SINT_TO_FP , MVT::i32 , Promote);
176 // In 32-bit mode these are custom lowered. In 64-bit mode F32 and F64
177 // are Legal, f80 is custom lowered.
178 setOperationAction(ISD::FP_TO_SINT , MVT::i64 , Custom);
179 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
181 // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
183 setOperationAction(ISD::FP_TO_SINT , MVT::i1 , Promote);
184 setOperationAction(ISD::FP_TO_SINT , MVT::i8 , Promote);
186 if (X86ScalarSSEf32) {
187 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Promote);
188 // f32 and f64 cases are Legal, f80 case is not
189 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
191 setOperationAction(ISD::FP_TO_SINT , MVT::i16 , Custom);
192 setOperationAction(ISD::FP_TO_SINT , MVT::i32 , Custom);
195 // Handle FP_TO_UINT by promoting the destination to a larger signed
197 setOperationAction(ISD::FP_TO_UINT , MVT::i1 , Promote);
198 setOperationAction(ISD::FP_TO_UINT , MVT::i8 , Promote);
199 setOperationAction(ISD::FP_TO_UINT , MVT::i16 , Promote);
201 if (Subtarget->is64Bit()) {
202 setOperationAction(ISD::FP_TO_UINT , MVT::i64 , Expand);
203 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Promote);
204 } else if (!UseSoftFloat) {
205 if (X86ScalarSSEf32 && !Subtarget->hasSSE3())
206 // Expand FP_TO_UINT into a select.
207 // FIXME: We would like to use a Custom expander here eventually to do
208 // the optimal thing for SSE vs. the default expansion in the legalizer.
209 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Expand);
211 // With SSE3 we can use fisttpll to convert to a signed i64; without
212 // SSE, we're stuck with a fistpll.
213 setOperationAction(ISD::FP_TO_UINT , MVT::i32 , Custom);
216 // TODO: when we have SSE, these could be more efficient, by using movd/movq.
217 if (!X86ScalarSSEf64) {
218 setOperationAction(ISD::BIT_CONVERT , MVT::f32 , Expand);
219 setOperationAction(ISD::BIT_CONVERT , MVT::i32 , Expand);
220 if (Subtarget->is64Bit()) {
221 setOperationAction(ISD::BIT_CONVERT , MVT::f64 , Expand);
222 setOperationAction(ISD::BIT_CONVERT , MVT::i64 , Expand);
226 // Scalar integer divide and remainder are lowered to use operations that
227 // produce two results, to match the available instructions. This exposes
228 // the two-result form to trivial CSE, which is able to combine x/y and x%y
229 // into a single instruction.
231 // Scalar integer multiply-high is also lowered to use two-result
232 // operations, to match the available instructions. However, plain multiply
233 // (low) operations are left as Legal, as there are single-result
234 // instructions for this in x86. Using the two-result multiply instructions
235 // when both high and low results are needed must be arranged by dagcombine.
236 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
237 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
238 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
239 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
240 setOperationAction(ISD::SREM , MVT::i8 , Expand);
241 setOperationAction(ISD::UREM , MVT::i8 , Expand);
242 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
243 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
244 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
245 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
246 setOperationAction(ISD::SREM , MVT::i16 , Expand);
247 setOperationAction(ISD::UREM , MVT::i16 , Expand);
248 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
249 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
250 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
251 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
252 setOperationAction(ISD::SREM , MVT::i32 , Expand);
253 setOperationAction(ISD::UREM , MVT::i32 , Expand);
254 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
255 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
256 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
257 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
258 setOperationAction(ISD::SREM , MVT::i64 , Expand);
259 setOperationAction(ISD::UREM , MVT::i64 , Expand);
261 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
262 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
263 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
264 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
265 if (Subtarget->is64Bit())
266 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
267 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
268 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
269 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
270 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
271 setOperationAction(ISD::FREM , MVT::f32 , Expand);
272 setOperationAction(ISD::FREM , MVT::f64 , Expand);
273 setOperationAction(ISD::FREM , MVT::f80 , Expand);
274 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
276 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
277 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
278 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
279 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
280 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
281 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
282 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
283 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
284 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
285 if (Subtarget->is64Bit()) {
286 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
287 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
288 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
291 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
292 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
294 // These should be promoted to a larger select which is supported.
295 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
296 // X86 wants to expand cmov itself.
297 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
298 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
299 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
300 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
301 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
302 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
303 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
304 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
305 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
306 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
307 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
308 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
309 if (Subtarget->is64Bit()) {
310 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
311 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
313 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
316 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
317 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
318 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
319 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
320 if (Subtarget->is64Bit())
321 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
322 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
323 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
324 if (Subtarget->is64Bit()) {
325 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
326 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
327 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
328 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
329 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
331 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
332 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
333 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
334 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
335 if (Subtarget->is64Bit()) {
336 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
337 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
338 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
341 if (Subtarget->hasSSE1())
342 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
344 if (!Subtarget->hasSSE2())
345 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
347 // Expand certain atomics
348 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
349 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
350 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
351 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
353 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
354 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
355 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
356 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
358 if (!Subtarget->is64Bit()) {
359 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
360 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
361 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
362 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
363 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
364 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
365 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
368 // FIXME - use subtarget debug flags
369 if (!Subtarget->isTargetDarwin() &&
370 !Subtarget->isTargetELF() &&
371 !Subtarget->isTargetCygMing()) {
372 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
375 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
376 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
377 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
378 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
379 if (Subtarget->is64Bit()) {
380 setExceptionPointerRegister(X86::RAX);
381 setExceptionSelectorRegister(X86::RDX);
383 setExceptionPointerRegister(X86::EAX);
384 setExceptionSelectorRegister(X86::EDX);
386 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
387 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
389 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
391 setOperationAction(ISD::TRAP, MVT::Other, Legal);
393 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
394 setOperationAction(ISD::VASTART , MVT::Other, Custom);
395 setOperationAction(ISD::VAEND , MVT::Other, Expand);
396 if (Subtarget->is64Bit()) {
397 setOperationAction(ISD::VAARG , MVT::Other, Custom);
398 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
400 setOperationAction(ISD::VAARG , MVT::Other, Expand);
401 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
404 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
405 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
406 if (Subtarget->is64Bit())
407 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
408 if (Subtarget->isTargetCygMing())
409 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
411 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
413 if (!UseSoftFloat && X86ScalarSSEf64) {
414 // f32 and f64 use SSE.
415 // Set up the FP register classes.
416 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
417 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
419 // Use ANDPD to simulate FABS.
420 setOperationAction(ISD::FABS , MVT::f64, Custom);
421 setOperationAction(ISD::FABS , MVT::f32, Custom);
423 // Use XORP to simulate FNEG.
424 setOperationAction(ISD::FNEG , MVT::f64, Custom);
425 setOperationAction(ISD::FNEG , MVT::f32, Custom);
427 // Use ANDPD and ORPD to simulate FCOPYSIGN.
428 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
429 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
431 // We don't support sin/cos/fmod
432 setOperationAction(ISD::FSIN , MVT::f64, Expand);
433 setOperationAction(ISD::FCOS , MVT::f64, Expand);
434 setOperationAction(ISD::FSIN , MVT::f32, Expand);
435 setOperationAction(ISD::FCOS , MVT::f32, Expand);
437 // Expand FP immediates into loads from the stack, except for the special
439 addLegalFPImmediate(APFloat(+0.0)); // xorpd
440 addLegalFPImmediate(APFloat(+0.0f)); // xorps
441 } else if (!UseSoftFloat && X86ScalarSSEf32) {
442 // Use SSE for f32, x87 for f64.
443 // Set up the FP register classes.
444 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
445 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
447 // Use ANDPS to simulate FABS.
448 setOperationAction(ISD::FABS , MVT::f32, Custom);
450 // Use XORP to simulate FNEG.
451 setOperationAction(ISD::FNEG , MVT::f32, Custom);
453 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
455 // Use ANDPS and ORPS to simulate FCOPYSIGN.
456 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
457 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
459 // We don't support sin/cos/fmod
460 setOperationAction(ISD::FSIN , MVT::f32, Expand);
461 setOperationAction(ISD::FCOS , MVT::f32, Expand);
463 // Special cases we handle for FP constants.
464 addLegalFPImmediate(APFloat(+0.0f)); // xorps
465 addLegalFPImmediate(APFloat(+0.0)); // FLD0
466 addLegalFPImmediate(APFloat(+1.0)); // FLD1
467 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
468 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
471 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
472 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
474 } else if (!UseSoftFloat) {
475 // f32 and f64 in x87.
476 // Set up the FP register classes.
477 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
478 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
480 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
481 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
482 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
483 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
486 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
487 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
489 addLegalFPImmediate(APFloat(+0.0)); // FLD0
490 addLegalFPImmediate(APFloat(+1.0)); // FLD1
491 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
492 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
493 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
494 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
495 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
496 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
499 // Long double always uses X87.
501 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
502 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
503 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
506 APFloat TmpFlt(+0.0);
507 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
509 addLegalFPImmediate(TmpFlt); // FLD0
511 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
512 APFloat TmpFlt2(+1.0);
513 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
515 addLegalFPImmediate(TmpFlt2); // FLD1
516 TmpFlt2.changeSign();
517 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
521 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
522 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
526 // Always use a library call for pow.
527 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
528 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
529 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
531 setOperationAction(ISD::FLOG, MVT::f80, Expand);
532 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
533 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
534 setOperationAction(ISD::FEXP, MVT::f80, Expand);
535 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
537 // First set operation action for all vector types to either promote
538 // (for widening) or expand (for scalarization). Then we will selectively
539 // turn on ones that can be effectively codegen'd.
540 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
541 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
542 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
543 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
544 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
545 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
546 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
547 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
548 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
549 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
550 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
551 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
552 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
553 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
554 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
555 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
556 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
557 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
558 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
559 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
560 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
561 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
562 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
563 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
564 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
565 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
566 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
567 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
568 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
569 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
570 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
571 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
572 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
573 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
574 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
575 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
576 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
577 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
578 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
579 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
580 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
581 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
582 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
583 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
584 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
585 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
586 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
587 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
588 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
589 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
590 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
591 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
592 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
593 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
594 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
595 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
596 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
597 setTruncStoreAction((MVT::SimpleValueType)VT,
598 (MVT::SimpleValueType)InnerVT, Expand);
599 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
600 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
601 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
604 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
605 // with -msoft-float, disable use of MMX as well.
606 if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
607 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass, false);
608 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass, false);
609 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass, false);
610 addRegisterClass(MVT::v2f32, X86::VR64RegisterClass, false);
611 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass, false);
613 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
614 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
615 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
616 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
618 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
619 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
620 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
621 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
623 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
624 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
626 setOperationAction(ISD::AND, MVT::v8i8, Promote);
627 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
628 setOperationAction(ISD::AND, MVT::v4i16, Promote);
629 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
630 setOperationAction(ISD::AND, MVT::v2i32, Promote);
631 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
632 setOperationAction(ISD::AND, MVT::v1i64, Legal);
634 setOperationAction(ISD::OR, MVT::v8i8, Promote);
635 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
636 setOperationAction(ISD::OR, MVT::v4i16, Promote);
637 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
638 setOperationAction(ISD::OR, MVT::v2i32, Promote);
639 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
640 setOperationAction(ISD::OR, MVT::v1i64, Legal);
642 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
643 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
644 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
645 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
646 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
647 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
648 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
650 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
651 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
652 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
653 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
654 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
655 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
656 setOperationAction(ISD::LOAD, MVT::v2f32, Promote);
657 AddPromotedToType (ISD::LOAD, MVT::v2f32, MVT::v1i64);
658 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
660 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
661 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
662 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
663 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f32, Custom);
664 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
666 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
667 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
668 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
669 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
671 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v2f32, Custom);
672 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
673 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
674 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
676 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
678 setOperationAction(ISD::SELECT, MVT::v8i8, Promote);
679 setOperationAction(ISD::SELECT, MVT::v4i16, Promote);
680 setOperationAction(ISD::SELECT, MVT::v2i32, Promote);
681 setOperationAction(ISD::SELECT, MVT::v1i64, Custom);
682 setOperationAction(ISD::VSETCC, MVT::v8i8, Custom);
683 setOperationAction(ISD::VSETCC, MVT::v4i16, Custom);
684 setOperationAction(ISD::VSETCC, MVT::v2i32, Custom);
687 if (!UseSoftFloat && Subtarget->hasSSE1()) {
688 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
690 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
691 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
692 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
693 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
694 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
695 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
696 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
697 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
698 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
699 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
700 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
701 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
704 if (!UseSoftFloat && Subtarget->hasSSE2()) {
705 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
707 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
708 // registers cannot be used even for integer operations.
709 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
710 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
711 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
712 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
714 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
715 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
716 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
717 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
718 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
719 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
720 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
721 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
722 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
723 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
724 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
725 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
726 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
727 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
728 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
729 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
731 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
732 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
733 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
734 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
736 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
737 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
738 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
739 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
740 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
742 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
743 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
744 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
745 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
746 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
748 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
749 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
750 EVT VT = (MVT::SimpleValueType)i;
751 // Do not attempt to custom lower non-power-of-2 vectors
752 if (!isPowerOf2_32(VT.getVectorNumElements()))
754 // Do not attempt to custom lower non-128-bit vectors
755 if (!VT.is128BitVector())
757 setOperationAction(ISD::BUILD_VECTOR,
758 VT.getSimpleVT().SimpleTy, Custom);
759 setOperationAction(ISD::VECTOR_SHUFFLE,
760 VT.getSimpleVT().SimpleTy, Custom);
761 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
762 VT.getSimpleVT().SimpleTy, Custom);
765 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
766 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
767 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
768 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
769 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
770 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
772 if (Subtarget->is64Bit()) {
773 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
774 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
777 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
778 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
779 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
782 // Do not attempt to promote non-128-bit vectors
783 if (!VT.is128BitVector()) {
787 setOperationAction(ISD::AND, SVT, Promote);
788 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
789 setOperationAction(ISD::OR, SVT, Promote);
790 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
791 setOperationAction(ISD::XOR, SVT, Promote);
792 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
793 setOperationAction(ISD::LOAD, SVT, Promote);
794 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
795 setOperationAction(ISD::SELECT, SVT, Promote);
796 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
799 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
801 // Custom lower v2i64 and v2f64 selects.
802 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
803 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
804 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
805 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
807 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
808 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
809 if (!DisableMMX && Subtarget->hasMMX()) {
810 setOperationAction(ISD::FP_TO_SINT, MVT::v2i32, Custom);
811 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
815 if (Subtarget->hasSSE41()) {
816 // FIXME: Do we need to handle scalar-to-vector here?
817 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
819 // i8 and i16 vectors are custom , because the source register and source
820 // source memory operand types are not the same width. f32 vectors are
821 // custom since the immediate controlling the insert encodes additional
823 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
824 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
825 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
826 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
828 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
829 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
830 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
831 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
833 if (Subtarget->is64Bit()) {
834 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
835 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
839 if (Subtarget->hasSSE42()) {
840 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
843 if (!UseSoftFloat && Subtarget->hasAVX()) {
844 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
845 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
846 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
847 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
849 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
850 setOperationAction(ISD::LOAD, MVT::v8i32, Legal);
851 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
852 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
853 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
854 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
855 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
856 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
857 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
858 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
859 //setOperationAction(ISD::BUILD_VECTOR, MVT::v8f32, Custom);
860 //setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Custom);
861 //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
862 //setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
863 //setOperationAction(ISD::VSETCC, MVT::v8f32, Custom);
865 // Operations to consider commented out -v16i16 v32i8
866 //setOperationAction(ISD::ADD, MVT::v16i16, Legal);
867 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
868 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
869 //setOperationAction(ISD::SUB, MVT::v32i8, Legal);
870 //setOperationAction(ISD::SUB, MVT::v16i16, Legal);
871 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
872 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
873 //setOperationAction(ISD::MUL, MVT::v16i16, Legal);
874 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
875 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
876 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
877 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
878 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
879 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
881 setOperationAction(ISD::VSETCC, MVT::v4f64, Custom);
882 // setOperationAction(ISD::VSETCC, MVT::v32i8, Custom);
883 // setOperationAction(ISD::VSETCC, MVT::v16i16, Custom);
884 setOperationAction(ISD::VSETCC, MVT::v8i32, Custom);
886 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v32i8, Custom);
887 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i16, Custom);
888 // setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i16, Custom);
889 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i32, Custom);
890 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8f32, Custom);
892 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
893 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i64, Custom);
894 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f64, Custom);
895 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i64, Custom);
896 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f64, Custom);
897 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
900 // Not sure we want to do this since there are no 256-bit integer
903 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
904 // This includes 256-bit vectors
905 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
906 EVT VT = (MVT::SimpleValueType)i;
908 // Do not attempt to custom lower non-power-of-2 vectors
909 if (!isPowerOf2_32(VT.getVectorNumElements()))
912 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
913 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
914 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
917 if (Subtarget->is64Bit()) {
918 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i64, Custom);
919 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
924 // Not sure we want to do this since there are no 256-bit integer
927 // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
928 // Including 256-bit vectors
929 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
930 EVT VT = (MVT::SimpleValueType)i;
932 if (!VT.is256BitVector()) {
935 setOperationAction(ISD::AND, VT, Promote);
936 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
937 setOperationAction(ISD::OR, VT, Promote);
938 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
939 setOperationAction(ISD::XOR, VT, Promote);
940 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
941 setOperationAction(ISD::LOAD, VT, Promote);
942 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
943 setOperationAction(ISD::SELECT, VT, Promote);
944 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
947 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
951 // We want to custom lower some of our intrinsics.
952 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
954 // Add/Sub/Mul with overflow operations are custom lowered.
955 setOperationAction(ISD::SADDO, MVT::i32, Custom);
956 setOperationAction(ISD::SADDO, MVT::i64, Custom);
957 setOperationAction(ISD::UADDO, MVT::i32, Custom);
958 setOperationAction(ISD::UADDO, MVT::i64, Custom);
959 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
960 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
961 setOperationAction(ISD::USUBO, MVT::i32, Custom);
962 setOperationAction(ISD::USUBO, MVT::i64, Custom);
963 setOperationAction(ISD::SMULO, MVT::i32, Custom);
964 setOperationAction(ISD::SMULO, MVT::i64, Custom);
966 if (!Subtarget->is64Bit()) {
967 // These libcalls are not available in 32-bit.
968 setLibcallName(RTLIB::SHL_I128, 0);
969 setLibcallName(RTLIB::SRL_I128, 0);
970 setLibcallName(RTLIB::SRA_I128, 0);
973 // We have target-specific dag combine patterns for the following nodes:
974 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
975 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
976 setTargetDAGCombine(ISD::BUILD_VECTOR);
977 setTargetDAGCombine(ISD::SELECT);
978 setTargetDAGCombine(ISD::SHL);
979 setTargetDAGCombine(ISD::SRA);
980 setTargetDAGCombine(ISD::SRL);
981 setTargetDAGCombine(ISD::OR);
982 setTargetDAGCombine(ISD::STORE);
983 setTargetDAGCombine(ISD::MEMBARRIER);
984 setTargetDAGCombine(ISD::ZERO_EXTEND);
985 if (Subtarget->is64Bit())
986 setTargetDAGCombine(ISD::MUL);
988 computeRegisterProperties();
990 // FIXME: These should be based on subtarget info. Plus, the values should
991 // be smaller when we are in optimizing for size mode.
992 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
993 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
994 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
995 setPrefLoopAlignment(16);
996 benefitFromCodePlacementOpt = true;
1000 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1005 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1006 /// the desired ByVal argument alignment.
1007 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1010 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1011 if (VTy->getBitWidth() == 128)
1013 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1014 unsigned EltAlign = 0;
1015 getMaxByValAlign(ATy->getElementType(), EltAlign);
1016 if (EltAlign > MaxAlign)
1017 MaxAlign = EltAlign;
1018 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1019 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1020 unsigned EltAlign = 0;
1021 getMaxByValAlign(STy->getElementType(i), EltAlign);
1022 if (EltAlign > MaxAlign)
1023 MaxAlign = EltAlign;
1031 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1032 /// function arguments in the caller parameter area. For X86, aggregates
1033 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1034 /// are at 4-byte boundaries.
1035 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1036 if (Subtarget->is64Bit()) {
1037 // Max of 8 and alignment of type.
1038 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1045 if (Subtarget->hasSSE1())
1046 getMaxByValAlign(Ty, Align);
1050 /// getOptimalMemOpType - Returns the target specific optimal type for load
1051 /// and store operations as a result of memset, memcpy, and memmove
1052 /// lowering. If DstAlign is zero that means it's safe to destination
1053 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1054 /// means there isn't a need to check it against alignment requirement,
1055 /// probably because the source does not need to be loaded. If
1056 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1057 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1058 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1059 /// constant so it does not need to be loaded.
1060 /// It returns EVT::Other if the type should be determined using generic
1061 /// target-independent logic.
1063 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1064 unsigned DstAlign, unsigned SrcAlign,
1065 bool NonScalarIntSafe,
1067 MachineFunction &MF) const {
1068 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1069 // linux. This is because the stack realignment code can't handle certain
1070 // cases like PR2962. This should be removed when PR2962 is fixed.
1071 const Function *F = MF.getFunction();
1072 if (NonScalarIntSafe &&
1073 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1075 (Subtarget->isUnalignedMemAccessFast() ||
1076 ((DstAlign == 0 || DstAlign >= 16) &&
1077 (SrcAlign == 0 || SrcAlign >= 16))) &&
1078 Subtarget->getStackAlignment() >= 16) {
1079 if (Subtarget->hasSSE2())
1081 if (Subtarget->hasSSE1())
1083 } else if (!MemcpyStrSrc && Size >= 8 &&
1084 !Subtarget->is64Bit() &&
1085 Subtarget->getStackAlignment() >= 8 &&
1086 Subtarget->hasSSE2()) {
1087 // Do not use f64 to lower memcpy if source is string constant. It's
1088 // better to use i32 to avoid the loads.
1092 if (Subtarget->is64Bit() && Size >= 8)
1097 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1098 /// current function. The returned value is a member of the
1099 /// MachineJumpTableInfo::JTEntryKind enum.
1100 unsigned X86TargetLowering::getJumpTableEncoding() const {
1101 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1103 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1104 Subtarget->isPICStyleGOT())
1105 return MachineJumpTableInfo::EK_Custom32;
1107 // Otherwise, use the normal jump table encoding heuristics.
1108 return TargetLowering::getJumpTableEncoding();
1111 /// getPICBaseSymbol - Return the X86-32 PIC base.
1113 X86TargetLowering::getPICBaseSymbol(const MachineFunction *MF,
1114 MCContext &Ctx) const {
1115 const MCAsmInfo &MAI = *getTargetMachine().getMCAsmInfo();
1116 return Ctx.GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix())+
1117 Twine(MF->getFunctionNumber())+"$pb");
1122 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1123 const MachineBasicBlock *MBB,
1124 unsigned uid,MCContext &Ctx) const{
1125 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1126 Subtarget->isPICStyleGOT());
1127 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1129 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1130 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1133 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1135 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1136 SelectionDAG &DAG) const {
1137 if (!Subtarget->is64Bit())
1138 // This doesn't have DebugLoc associated with it, but is not really the
1139 // same as a Register.
1140 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1144 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1145 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1147 const MCExpr *X86TargetLowering::
1148 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1149 MCContext &Ctx) const {
1150 // X86-64 uses RIP relative addressing based on the jump table label.
1151 if (Subtarget->isPICStyleRIPRel())
1152 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1154 // Otherwise, the reference is relative to the PIC base.
1155 return MCSymbolRefExpr::Create(getPICBaseSymbol(MF, Ctx), Ctx);
1158 /// getFunctionAlignment - Return the Log2 alignment of this function.
1159 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1160 return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1163 //===----------------------------------------------------------------------===//
1164 // Return Value Calling Convention Implementation
1165 //===----------------------------------------------------------------------===//
1167 #include "X86GenCallingConv.inc"
1170 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1171 const SmallVectorImpl<EVT> &OutTys,
1172 const SmallVectorImpl<ISD::ArgFlagsTy> &ArgsFlags,
1173 SelectionDAG &DAG) const {
1174 SmallVector<CCValAssign, 16> RVLocs;
1175 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1176 RVLocs, *DAG.getContext());
1177 return CCInfo.CheckReturn(OutTys, ArgsFlags, RetCC_X86);
1181 X86TargetLowering::LowerReturn(SDValue Chain,
1182 CallingConv::ID CallConv, bool isVarArg,
1183 const SmallVectorImpl<ISD::OutputArg> &Outs,
1184 DebugLoc dl, SelectionDAG &DAG) const {
1185 MachineFunction &MF = DAG.getMachineFunction();
1186 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1188 SmallVector<CCValAssign, 16> RVLocs;
1189 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1190 RVLocs, *DAG.getContext());
1191 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1193 // Add the regs to the liveout set for the function.
1194 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1195 for (unsigned i = 0; i != RVLocs.size(); ++i)
1196 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1197 MRI.addLiveOut(RVLocs[i].getLocReg());
1201 SmallVector<SDValue, 6> RetOps;
1202 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1203 // Operand #1 = Bytes To Pop
1204 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1207 // Copy the result values into the output registers.
1208 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1209 CCValAssign &VA = RVLocs[i];
1210 assert(VA.isRegLoc() && "Can only return in registers!");
1211 SDValue ValToCopy = Outs[i].Val;
1213 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1214 // the RET instruction and handled by the FP Stackifier.
1215 if (VA.getLocReg() == X86::ST0 ||
1216 VA.getLocReg() == X86::ST1) {
1217 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1218 // change the value to the FP stack register class.
1219 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1220 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1221 RetOps.push_back(ValToCopy);
1222 // Don't emit a copytoreg.
1226 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1227 // which is returned in RAX / RDX.
1228 if (Subtarget->is64Bit()) {
1229 EVT ValVT = ValToCopy.getValueType();
1230 if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1231 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1232 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1233 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1237 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1238 Flag = Chain.getValue(1);
1241 // The x86-64 ABI for returning structs by value requires that we copy
1242 // the sret argument into %rax for the return. We saved the argument into
1243 // a virtual register in the entry block, so now we copy the value out
1245 if (Subtarget->is64Bit() &&
1246 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1247 MachineFunction &MF = DAG.getMachineFunction();
1248 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1249 unsigned Reg = FuncInfo->getSRetReturnReg();
1251 Reg = MRI.createVirtualRegister(getRegClassFor(MVT::i64));
1252 FuncInfo->setSRetReturnReg(Reg);
1254 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1256 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1257 Flag = Chain.getValue(1);
1259 // RAX now acts like a return value.
1260 MRI.addLiveOut(X86::RAX);
1263 RetOps[0] = Chain; // Update chain.
1265 // Add the flag if we have it.
1267 RetOps.push_back(Flag);
1269 return DAG.getNode(X86ISD::RET_FLAG, dl,
1270 MVT::Other, &RetOps[0], RetOps.size());
1273 /// LowerCallResult - Lower the result values of a call into the
1274 /// appropriate copies out of appropriate physical registers.
1277 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1278 CallingConv::ID CallConv, bool isVarArg,
1279 const SmallVectorImpl<ISD::InputArg> &Ins,
1280 DebugLoc dl, SelectionDAG &DAG,
1281 SmallVectorImpl<SDValue> &InVals) const {
1283 // Assign locations to each value returned by this call.
1284 SmallVector<CCValAssign, 16> RVLocs;
1285 bool Is64Bit = Subtarget->is64Bit();
1286 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1287 RVLocs, *DAG.getContext());
1288 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1290 // Copy all of the result registers out of their specified physreg.
1291 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1292 CCValAssign &VA = RVLocs[i];
1293 EVT CopyVT = VA.getValVT();
1295 // If this is x86-64, and we disabled SSE, we can't return FP values
1296 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1297 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1298 report_fatal_error("SSE register return with SSE disabled");
1301 // If this is a call to a function that returns an fp value on the floating
1302 // point stack, but where we prefer to use the value in xmm registers, copy
1303 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1304 if ((VA.getLocReg() == X86::ST0 ||
1305 VA.getLocReg() == X86::ST1) &&
1306 isScalarFPTypeInSSEReg(VA.getValVT())) {
1311 if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1312 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1313 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1314 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1315 MVT::v2i64, InFlag).getValue(1);
1316 Val = Chain.getValue(0);
1317 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1318 Val, DAG.getConstant(0, MVT::i64));
1320 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1321 MVT::i64, InFlag).getValue(1);
1322 Val = Chain.getValue(0);
1324 Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1326 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1327 CopyVT, InFlag).getValue(1);
1328 Val = Chain.getValue(0);
1330 InFlag = Chain.getValue(2);
1332 if (CopyVT != VA.getValVT()) {
1333 // Round the F80 the right size, which also moves to the appropriate xmm
1335 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1336 // This truncation won't change the value.
1337 DAG.getIntPtrConstant(1));
1340 InVals.push_back(Val);
1347 //===----------------------------------------------------------------------===//
1348 // C & StdCall & Fast Calling Convention implementation
1349 //===----------------------------------------------------------------------===//
1350 // StdCall calling convention seems to be standard for many Windows' API
1351 // routines and around. It differs from C calling convention just a little:
1352 // callee should clean up the stack, not caller. Symbols should be also
1353 // decorated in some fancy way :) It doesn't support any vector arguments.
1354 // For info on fast calling convention see Fast Calling Convention (tail call)
1355 // implementation LowerX86_32FastCCCallTo.
1357 /// CallIsStructReturn - Determines whether a call uses struct return
1359 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1363 return Outs[0].Flags.isSRet();
1366 /// ArgsAreStructReturn - Determines whether a function uses struct
1367 /// return semantics.
1369 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1373 return Ins[0].Flags.isSRet();
1376 /// IsCalleePop - Determines whether the callee is required to pop its
1377 /// own arguments. Callee pop is necessary to support tail calls.
1378 bool X86TargetLowering::IsCalleePop(bool IsVarArg,
1379 CallingConv::ID CallingConv) const {
1383 switch (CallingConv) {
1386 case CallingConv::X86_StdCall:
1387 return !Subtarget->is64Bit();
1388 case CallingConv::X86_FastCall:
1389 return !Subtarget->is64Bit();
1390 case CallingConv::X86_ThisCall:
1391 return !Subtarget->is64Bit();
1392 case CallingConv::Fast:
1393 return GuaranteedTailCallOpt;
1394 case CallingConv::GHC:
1395 return GuaranteedTailCallOpt;
1399 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1400 /// given CallingConvention value.
1401 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1402 if (Subtarget->is64Bit()) {
1403 if (CC == CallingConv::GHC)
1404 return CC_X86_64_GHC;
1405 else if (Subtarget->isTargetWin64())
1406 return CC_X86_Win64_C;
1411 if (CC == CallingConv::X86_FastCall)
1412 return CC_X86_32_FastCall;
1413 else if (CC == CallingConv::X86_ThisCall)
1414 return CC_X86_32_ThisCall;
1415 else if (CC == CallingConv::Fast)
1416 return CC_X86_32_FastCC;
1417 else if (CC == CallingConv::GHC)
1418 return CC_X86_32_GHC;
1423 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1424 /// by "Src" to address "Dst" with size and alignment information specified by
1425 /// the specific parameter attribute. The copy will be passed as a byval
1426 /// function parameter.
1428 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1429 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1431 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1432 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1433 /*isVolatile*/false, /*AlwaysInline=*/true,
1437 /// IsTailCallConvention - Return true if the calling convention is one that
1438 /// supports tail call optimization.
1439 static bool IsTailCallConvention(CallingConv::ID CC) {
1440 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1443 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1444 /// a tailcall target by changing its ABI.
1445 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1446 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1450 X86TargetLowering::LowerMemArgument(SDValue Chain,
1451 CallingConv::ID CallConv,
1452 const SmallVectorImpl<ISD::InputArg> &Ins,
1453 DebugLoc dl, SelectionDAG &DAG,
1454 const CCValAssign &VA,
1455 MachineFrameInfo *MFI,
1457 // Create the nodes corresponding to a load from this parameter slot.
1458 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1459 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1460 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1463 // If value is passed by pointer we have address passed instead of the value
1465 if (VA.getLocInfo() == CCValAssign::Indirect)
1466 ValVT = VA.getLocVT();
1468 ValVT = VA.getValVT();
1470 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1471 // changed with more analysis.
1472 // In case of tail call optimization mark all arguments mutable. Since they
1473 // could be overwritten by lowering of arguments in case of a tail call.
1474 if (Flags.isByVal()) {
1475 int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1476 VA.getLocMemOffset(), isImmutable, false);
1477 return DAG.getFrameIndex(FI, getPointerTy());
1479 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1480 VA.getLocMemOffset(), isImmutable, false);
1481 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1482 return DAG.getLoad(ValVT, dl, Chain, FIN,
1483 PseudoSourceValue::getFixedStack(FI), 0,
1489 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1490 CallingConv::ID CallConv,
1492 const SmallVectorImpl<ISD::InputArg> &Ins,
1495 SmallVectorImpl<SDValue> &InVals)
1497 MachineFunction &MF = DAG.getMachineFunction();
1498 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1500 const Function* Fn = MF.getFunction();
1501 if (Fn->hasExternalLinkage() &&
1502 Subtarget->isTargetCygMing() &&
1503 Fn->getName() == "main")
1504 FuncInfo->setForceFramePointer(true);
1506 MachineFrameInfo *MFI = MF.getFrameInfo();
1507 bool Is64Bit = Subtarget->is64Bit();
1508 bool IsWin64 = Subtarget->isTargetWin64();
1510 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1511 "Var args not supported with calling convention fastcc or ghc");
1513 // Assign locations to all of the incoming arguments.
1514 SmallVector<CCValAssign, 16> ArgLocs;
1515 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1516 ArgLocs, *DAG.getContext());
1517 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1519 unsigned LastVal = ~0U;
1521 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1522 CCValAssign &VA = ArgLocs[i];
1523 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1525 assert(VA.getValNo() != LastVal &&
1526 "Don't support value assigned to multiple locs yet");
1527 LastVal = VA.getValNo();
1529 if (VA.isRegLoc()) {
1530 EVT RegVT = VA.getLocVT();
1531 TargetRegisterClass *RC = NULL;
1532 if (RegVT == MVT::i32)
1533 RC = X86::GR32RegisterClass;
1534 else if (Is64Bit && RegVT == MVT::i64)
1535 RC = X86::GR64RegisterClass;
1536 else if (RegVT == MVT::f32)
1537 RC = X86::FR32RegisterClass;
1538 else if (RegVT == MVT::f64)
1539 RC = X86::FR64RegisterClass;
1540 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1541 RC = X86::VR128RegisterClass;
1542 else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1543 RC = X86::VR64RegisterClass;
1545 llvm_unreachable("Unknown argument type!");
1547 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1548 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1550 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1551 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1553 if (VA.getLocInfo() == CCValAssign::SExt)
1554 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1555 DAG.getValueType(VA.getValVT()));
1556 else if (VA.getLocInfo() == CCValAssign::ZExt)
1557 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1558 DAG.getValueType(VA.getValVT()));
1559 else if (VA.getLocInfo() == CCValAssign::BCvt)
1560 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1562 if (VA.isExtInLoc()) {
1563 // Handle MMX values passed in XMM regs.
1564 if (RegVT.isVector()) {
1565 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1566 ArgValue, DAG.getConstant(0, MVT::i64));
1567 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1569 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1572 assert(VA.isMemLoc());
1573 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1576 // If value is passed via pointer - do a load.
1577 if (VA.getLocInfo() == CCValAssign::Indirect)
1578 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0,
1581 InVals.push_back(ArgValue);
1584 // The x86-64 ABI for returning structs by value requires that we copy
1585 // the sret argument into %rax for the return. Save the argument into
1586 // a virtual register so that we can access it from the return points.
1587 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1588 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1589 unsigned Reg = FuncInfo->getSRetReturnReg();
1591 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1592 FuncInfo->setSRetReturnReg(Reg);
1594 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1595 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1598 unsigned StackSize = CCInfo.getNextStackOffset();
1599 // Align stack specially for tail calls.
1600 if (FuncIsMadeTailCallSafe(CallConv))
1601 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1603 // If the function takes variable number of arguments, make a frame index for
1604 // the start of the first vararg value... for expansion of llvm.va_start.
1606 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1607 CallConv != CallingConv::X86_ThisCall)) {
1608 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,
1612 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1614 // FIXME: We should really autogenerate these arrays
1615 static const unsigned GPR64ArgRegsWin64[] = {
1616 X86::RCX, X86::RDX, X86::R8, X86::R9
1618 static const unsigned XMMArgRegsWin64[] = {
1619 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1621 static const unsigned GPR64ArgRegs64Bit[] = {
1622 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1624 static const unsigned XMMArgRegs64Bit[] = {
1625 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1626 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1628 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1631 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1632 GPR64ArgRegs = GPR64ArgRegsWin64;
1633 XMMArgRegs = XMMArgRegsWin64;
1635 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1636 GPR64ArgRegs = GPR64ArgRegs64Bit;
1637 XMMArgRegs = XMMArgRegs64Bit;
1639 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1641 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1644 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1645 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1646 "SSE register cannot be used when SSE is disabled!");
1647 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1648 "SSE register cannot be used when SSE is disabled!");
1649 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1650 // Kernel mode asks for SSE to be disabled, so don't push them
1652 TotalNumXMMRegs = 0;
1654 // For X86-64, if there are vararg parameters that are passed via
1655 // registers, then we must store them to their spots on the stack so they
1656 // may be loaded by deferencing the result of va_next.
1657 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1658 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1659 FuncInfo->setRegSaveFrameIndex(
1660 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1663 // Store the integer parameter registers.
1664 SmallVector<SDValue, 8> MemOps;
1665 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1667 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1668 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1669 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1670 DAG.getIntPtrConstant(Offset));
1671 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1672 X86::GR64RegisterClass);
1673 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1675 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1676 PseudoSourceValue::getFixedStack(
1677 FuncInfo->getRegSaveFrameIndex()),
1678 Offset, false, false, 0);
1679 MemOps.push_back(Store);
1683 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1684 // Now store the XMM (fp + vector) parameter registers.
1685 SmallVector<SDValue, 11> SaveXMMOps;
1686 SaveXMMOps.push_back(Chain);
1688 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1689 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1690 SaveXMMOps.push_back(ALVal);
1692 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1693 FuncInfo->getRegSaveFrameIndex()));
1694 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1695 FuncInfo->getVarArgsFPOffset()));
1697 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1698 unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1699 X86::VR128RegisterClass);
1700 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1701 SaveXMMOps.push_back(Val);
1703 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1705 &SaveXMMOps[0], SaveXMMOps.size()));
1708 if (!MemOps.empty())
1709 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1710 &MemOps[0], MemOps.size());
1714 // Some CCs need callee pop.
1715 if (IsCalleePop(isVarArg, CallConv)) {
1716 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1718 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1719 // If this is an sret function, the return should pop the hidden pointer.
1720 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1721 FuncInfo->setBytesToPopOnReturn(4);
1725 // RegSaveFrameIndex is X86-64 only.
1726 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1727 if (CallConv == CallingConv::X86_FastCall ||
1728 CallConv == CallingConv::X86_ThisCall)
1729 // fastcc functions can't have varargs.
1730 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1737 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1738 SDValue StackPtr, SDValue Arg,
1739 DebugLoc dl, SelectionDAG &DAG,
1740 const CCValAssign &VA,
1741 ISD::ArgFlagsTy Flags) const {
1742 const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1743 unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1744 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1745 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1746 if (Flags.isByVal()) {
1747 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1749 return DAG.getStore(Chain, dl, Arg, PtrOff,
1750 PseudoSourceValue::getStack(), LocMemOffset,
1754 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1755 /// optimization is performed and it is required.
1757 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1758 SDValue &OutRetAddr, SDValue Chain,
1759 bool IsTailCall, bool Is64Bit,
1760 int FPDiff, DebugLoc dl) const {
1761 // Adjust the Return address stack slot.
1762 EVT VT = getPointerTy();
1763 OutRetAddr = getReturnAddressFrameIndex(DAG);
1765 // Load the "old" Return address.
1766 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0, false, false, 0);
1767 return SDValue(OutRetAddr.getNode(), 1);
1770 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1771 /// optimization is performed and it is required (FPDiff!=0).
1773 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1774 SDValue Chain, SDValue RetAddrFrIdx,
1775 bool Is64Bit, int FPDiff, DebugLoc dl) {
1776 // Store the return address to the appropriate stack slot.
1777 if (!FPDiff) return Chain;
1778 // Calculate the new stack slot for the return address.
1779 int SlotSize = Is64Bit ? 8 : 4;
1780 int NewReturnAddrFI =
1781 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false, false);
1782 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1783 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1784 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1785 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0,
1791 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1792 CallingConv::ID CallConv, bool isVarArg,
1794 const SmallVectorImpl<ISD::OutputArg> &Outs,
1795 const SmallVectorImpl<ISD::InputArg> &Ins,
1796 DebugLoc dl, SelectionDAG &DAG,
1797 SmallVectorImpl<SDValue> &InVals) const {
1798 MachineFunction &MF = DAG.getMachineFunction();
1799 bool Is64Bit = Subtarget->is64Bit();
1800 bool IsStructRet = CallIsStructReturn(Outs);
1801 bool IsSibcall = false;
1804 // Check if it's really possible to do a tail call.
1805 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1806 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1809 // Sibcalls are automatically detected tailcalls which do not require
1811 if (!GuaranteedTailCallOpt && isTailCall)
1818 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1819 "Var args not supported with calling convention fastcc or ghc");
1821 // Analyze operands of the call, assigning locations to each operand.
1822 SmallVector<CCValAssign, 16> ArgLocs;
1823 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1824 ArgLocs, *DAG.getContext());
1825 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1827 // Get a count of how many bytes are to be pushed on the stack.
1828 unsigned NumBytes = CCInfo.getNextStackOffset();
1830 // This is a sibcall. The memory operands are available in caller's
1831 // own caller's stack.
1833 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1834 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1837 if (isTailCall && !IsSibcall) {
1838 // Lower arguments at fp - stackoffset + fpdiff.
1839 unsigned NumBytesCallerPushed =
1840 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1841 FPDiff = NumBytesCallerPushed - NumBytes;
1843 // Set the delta of movement of the returnaddr stackslot.
1844 // But only set if delta is greater than previous delta.
1845 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1846 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1850 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1852 SDValue RetAddrFrIdx;
1853 // Load return adress for tail calls.
1854 if (isTailCall && FPDiff)
1855 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1856 Is64Bit, FPDiff, dl);
1858 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1859 SmallVector<SDValue, 8> MemOpChains;
1862 // Walk the register/memloc assignments, inserting copies/loads. In the case
1863 // of tail call optimization arguments are handle later.
1864 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1865 CCValAssign &VA = ArgLocs[i];
1866 EVT RegVT = VA.getLocVT();
1867 SDValue Arg = Outs[i].Val;
1868 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1869 bool isByVal = Flags.isByVal();
1871 // Promote the value if needed.
1872 switch (VA.getLocInfo()) {
1873 default: llvm_unreachable("Unknown loc info!");
1874 case CCValAssign::Full: break;
1875 case CCValAssign::SExt:
1876 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1878 case CCValAssign::ZExt:
1879 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1881 case CCValAssign::AExt:
1882 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1883 // Special case: passing MMX values in XMM registers.
1884 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1885 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1886 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1888 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1890 case CCValAssign::BCvt:
1891 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1893 case CCValAssign::Indirect: {
1894 // Store the argument.
1895 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1896 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1897 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1898 PseudoSourceValue::getFixedStack(FI), 0,
1905 if (VA.isRegLoc()) {
1906 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1907 } else if (!IsSibcall && (!isTailCall || isByVal)) {
1908 assert(VA.isMemLoc());
1909 if (StackPtr.getNode() == 0)
1910 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1911 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1912 dl, DAG, VA, Flags));
1916 if (!MemOpChains.empty())
1917 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1918 &MemOpChains[0], MemOpChains.size());
1920 // Build a sequence of copy-to-reg nodes chained together with token chain
1921 // and flag operands which copy the outgoing args into registers.
1923 // Tail call byval lowering might overwrite argument registers so in case of
1924 // tail call optimization the copies to registers are lowered later.
1926 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1927 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1928 RegsToPass[i].second, InFlag);
1929 InFlag = Chain.getValue(1);
1932 if (Subtarget->isPICStyleGOT()) {
1933 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1936 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1937 DAG.getNode(X86ISD::GlobalBaseReg,
1938 DebugLoc(), getPointerTy()),
1940 InFlag = Chain.getValue(1);
1942 // If we are tail calling and generating PIC/GOT style code load the
1943 // address of the callee into ECX. The value in ecx is used as target of
1944 // the tail jump. This is done to circumvent the ebx/callee-saved problem
1945 // for tail calls on PIC/GOT architectures. Normally we would just put the
1946 // address of GOT into ebx and then call target@PLT. But for tail calls
1947 // ebx would be restored (since ebx is callee saved) before jumping to the
1950 // Note: The actual moving to ECX is done further down.
1951 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1952 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1953 !G->getGlobal()->hasProtectedVisibility())
1954 Callee = LowerGlobalAddress(Callee, DAG);
1955 else if (isa<ExternalSymbolSDNode>(Callee))
1956 Callee = LowerExternalSymbol(Callee, DAG);
1960 if (Is64Bit && isVarArg) {
1961 // From AMD64 ABI document:
1962 // For calls that may call functions that use varargs or stdargs
1963 // (prototype-less calls or calls to functions containing ellipsis (...) in
1964 // the declaration) %al is used as hidden argument to specify the number
1965 // of SSE registers used. The contents of %al do not need to match exactly
1966 // the number of registers, but must be an ubound on the number of SSE
1967 // registers used and is in the range 0 - 8 inclusive.
1969 // FIXME: Verify this on Win64
1970 // Count the number of XMM registers allocated.
1971 static const unsigned XMMArgRegs[] = {
1972 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1973 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1975 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1976 assert((Subtarget->hasSSE1() || !NumXMMRegs)
1977 && "SSE registers cannot be used when SSE is disabled");
1979 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1980 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1981 InFlag = Chain.getValue(1);
1985 // For tail calls lower the arguments to the 'real' stack slot.
1987 // Force all the incoming stack arguments to be loaded from the stack
1988 // before any new outgoing arguments are stored to the stack, because the
1989 // outgoing stack slots may alias the incoming argument stack slots, and
1990 // the alias isn't otherwise explicit. This is slightly more conservative
1991 // than necessary, because it means that each store effectively depends
1992 // on every argument instead of just those arguments it would clobber.
1993 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
1995 SmallVector<SDValue, 8> MemOpChains2;
1998 // Do not flag preceeding copytoreg stuff together with the following stuff.
2000 if (GuaranteedTailCallOpt) {
2001 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2002 CCValAssign &VA = ArgLocs[i];
2005 assert(VA.isMemLoc());
2006 SDValue Arg = Outs[i].Val;
2007 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2008 // Create frame index.
2009 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2010 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2011 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true, false);
2012 FIN = DAG.getFrameIndex(FI, getPointerTy());
2014 if (Flags.isByVal()) {
2015 // Copy relative to framepointer.
2016 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2017 if (StackPtr.getNode() == 0)
2018 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2020 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2022 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2026 // Store relative to framepointer.
2027 MemOpChains2.push_back(
2028 DAG.getStore(ArgChain, dl, Arg, FIN,
2029 PseudoSourceValue::getFixedStack(FI), 0,
2035 if (!MemOpChains2.empty())
2036 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2037 &MemOpChains2[0], MemOpChains2.size());
2039 // Copy arguments to their registers.
2040 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2041 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2042 RegsToPass[i].second, InFlag);
2043 InFlag = Chain.getValue(1);
2047 // Store the return address to the appropriate stack slot.
2048 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2052 bool WasGlobalOrExternal = false;
2053 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2054 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2055 // In the 64-bit large code model, we have to make all calls
2056 // through a register, since the call instruction's 32-bit
2057 // pc-relative offset may not be large enough to hold the whole
2059 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2060 WasGlobalOrExternal = true;
2061 // If the callee is a GlobalAddress node (quite common, every direct call
2062 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2065 // We should use extra load for direct calls to dllimported functions in
2067 const GlobalValue *GV = G->getGlobal();
2068 if (!GV->hasDLLImportLinkage()) {
2069 unsigned char OpFlags = 0;
2071 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2072 // external symbols most go through the PLT in PIC mode. If the symbol
2073 // has hidden or protected visibility, or if it is static or local, then
2074 // we don't need to use the PLT - we can directly call it.
2075 if (Subtarget->isTargetELF() &&
2076 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2077 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2078 OpFlags = X86II::MO_PLT;
2079 } else if (Subtarget->isPICStyleStubAny() &&
2080 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2081 Subtarget->getDarwinVers() < 9) {
2082 // PC-relative references to external symbols should go through $stub,
2083 // unless we're building with the leopard linker or later, which
2084 // automatically synthesizes these stubs.
2085 OpFlags = X86II::MO_DARWIN_STUB;
2088 Callee = DAG.getTargetGlobalAddress(GV, getPointerTy(),
2089 G->getOffset(), OpFlags);
2091 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2092 WasGlobalOrExternal = true;
2093 unsigned char OpFlags = 0;
2095 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2096 // symbols should go through the PLT.
2097 if (Subtarget->isTargetELF() &&
2098 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2099 OpFlags = X86II::MO_PLT;
2100 } else if (Subtarget->isPICStyleStubAny() &&
2101 Subtarget->getDarwinVers() < 9) {
2102 // PC-relative references to external symbols should go through $stub,
2103 // unless we're building with the leopard linker or later, which
2104 // automatically synthesizes these stubs.
2105 OpFlags = X86II::MO_DARWIN_STUB;
2108 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2112 // Returns a chain & a flag for retval copy to use.
2113 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2114 SmallVector<SDValue, 8> Ops;
2116 if (!IsSibcall && isTailCall) {
2117 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2118 DAG.getIntPtrConstant(0, true), InFlag);
2119 InFlag = Chain.getValue(1);
2122 Ops.push_back(Chain);
2123 Ops.push_back(Callee);
2126 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2128 // Add argument registers to the end of the list so that they are known live
2130 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2131 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2132 RegsToPass[i].second.getValueType()));
2134 // Add an implicit use GOT pointer in EBX.
2135 if (!isTailCall && Subtarget->isPICStyleGOT())
2136 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2138 // Add an implicit use of AL for x86 vararg functions.
2139 if (Is64Bit && isVarArg)
2140 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2142 if (InFlag.getNode())
2143 Ops.push_back(InFlag);
2146 // If this is the first return lowered for this function, add the regs
2147 // to the liveout set for the function.
2148 if (MF.getRegInfo().liveout_empty()) {
2149 SmallVector<CCValAssign, 16> RVLocs;
2150 CCState CCInfo(CallConv, isVarArg, getTargetMachine(), RVLocs,
2152 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2153 for (unsigned i = 0; i != RVLocs.size(); ++i)
2154 if (RVLocs[i].isRegLoc())
2155 MF.getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2157 return DAG.getNode(X86ISD::TC_RETURN, dl,
2158 NodeTys, &Ops[0], Ops.size());
2161 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2162 InFlag = Chain.getValue(1);
2164 // Create the CALLSEQ_END node.
2165 unsigned NumBytesForCalleeToPush;
2166 if (IsCalleePop(isVarArg, CallConv))
2167 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2168 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2169 // If this is a call to a struct-return function, the callee
2170 // pops the hidden struct pointer, so we have to push it back.
2171 // This is common for Darwin/X86, Linux & Mingw32 targets.
2172 NumBytesForCalleeToPush = 4;
2174 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2176 // Returns a flag for retval copy to use.
2178 Chain = DAG.getCALLSEQ_END(Chain,
2179 DAG.getIntPtrConstant(NumBytes, true),
2180 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2183 InFlag = Chain.getValue(1);
2186 // Handle result values, copying them out of physregs into vregs that we
2188 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2189 Ins, dl, DAG, InVals);
2193 //===----------------------------------------------------------------------===//
2194 // Fast Calling Convention (tail call) implementation
2195 //===----------------------------------------------------------------------===//
2197 // Like std call, callee cleans arguments, convention except that ECX is
2198 // reserved for storing the tail called function address. Only 2 registers are
2199 // free for argument passing (inreg). Tail call optimization is performed
2201 // * tailcallopt is enabled
2202 // * caller/callee are fastcc
2203 // On X86_64 architecture with GOT-style position independent code only local
2204 // (within module) calls are supported at the moment.
2205 // To keep the stack aligned according to platform abi the function
2206 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2207 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2208 // If a tail called function callee has more arguments than the caller the
2209 // caller needs to make sure that there is room to move the RETADDR to. This is
2210 // achieved by reserving an area the size of the argument delta right after the
2211 // original REtADDR, but before the saved framepointer or the spilled registers
2212 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2224 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2225 /// for a 16 byte align requirement.
2227 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2228 SelectionDAG& DAG) const {
2229 MachineFunction &MF = DAG.getMachineFunction();
2230 const TargetMachine &TM = MF.getTarget();
2231 const TargetFrameInfo &TFI = *TM.getFrameInfo();
2232 unsigned StackAlignment = TFI.getStackAlignment();
2233 uint64_t AlignMask = StackAlignment - 1;
2234 int64_t Offset = StackSize;
2235 uint64_t SlotSize = TD->getPointerSize();
2236 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2237 // Number smaller than 12 so just add the difference.
2238 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2240 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2241 Offset = ((~AlignMask) & Offset) + StackAlignment +
2242 (StackAlignment-SlotSize);
2247 /// MatchingStackOffset - Return true if the given stack call argument is
2248 /// already available in the same position (relatively) of the caller's
2249 /// incoming argument stack.
2251 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2252 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2253 const X86InstrInfo *TII) {
2254 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2256 if (Arg.getOpcode() == ISD::CopyFromReg) {
2257 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2258 if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2260 MachineInstr *Def = MRI->getVRegDef(VR);
2263 if (!Flags.isByVal()) {
2264 if (!TII->isLoadFromStackSlot(Def, FI))
2267 unsigned Opcode = Def->getOpcode();
2268 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2269 Def->getOperand(1).isFI()) {
2270 FI = Def->getOperand(1).getIndex();
2271 Bytes = Flags.getByValSize();
2275 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2276 if (Flags.isByVal())
2277 // ByVal argument is passed in as a pointer but it's now being
2278 // dereferenced. e.g.
2279 // define @foo(%struct.X* %A) {
2280 // tail call @bar(%struct.X* byval %A)
2283 SDValue Ptr = Ld->getBasePtr();
2284 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2287 FI = FINode->getIndex();
2291 assert(FI != INT_MAX);
2292 if (!MFI->isFixedObjectIndex(FI))
2294 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2297 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2298 /// for tail call optimization. Targets which want to do tail call
2299 /// optimization should implement this function.
2301 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2302 CallingConv::ID CalleeCC,
2304 bool isCalleeStructRet,
2305 bool isCallerStructRet,
2306 const SmallVectorImpl<ISD::OutputArg> &Outs,
2307 const SmallVectorImpl<ISD::InputArg> &Ins,
2308 SelectionDAG& DAG) const {
2309 if (!IsTailCallConvention(CalleeCC) &&
2310 CalleeCC != CallingConv::C)
2313 // If -tailcallopt is specified, make fastcc functions tail-callable.
2314 const MachineFunction &MF = DAG.getMachineFunction();
2315 const Function *CallerF = DAG.getMachineFunction().getFunction();
2316 CallingConv::ID CallerCC = CallerF->getCallingConv();
2317 bool CCMatch = CallerCC == CalleeCC;
2319 if (GuaranteedTailCallOpt) {
2320 if (IsTailCallConvention(CalleeCC) && CCMatch)
2325 // Look for obvious safe cases to perform tail call optimization that does not
2326 // requite ABI changes. This is what gcc calls sibcall.
2328 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2329 // emit a special epilogue.
2330 if (RegInfo->needsStackRealignment(MF))
2333 // Do not sibcall optimize vararg calls unless the call site is not passing any
2335 if (isVarArg && !Outs.empty())
2338 // Also avoid sibcall optimization if either caller or callee uses struct
2339 // return semantics.
2340 if (isCalleeStructRet || isCallerStructRet)
2343 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2344 // Therefore if it's not used by the call it is not safe to optimize this into
2346 bool Unused = false;
2347 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2354 SmallVector<CCValAssign, 16> RVLocs;
2355 CCState CCInfo(CalleeCC, false, getTargetMachine(),
2356 RVLocs, *DAG.getContext());
2357 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2358 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2359 CCValAssign &VA = RVLocs[i];
2360 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2365 // If the calling conventions do not match, then we'd better make sure the
2366 // results are returned in the same way as what the caller expects.
2368 SmallVector<CCValAssign, 16> RVLocs1;
2369 CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2370 RVLocs1, *DAG.getContext());
2371 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2373 SmallVector<CCValAssign, 16> RVLocs2;
2374 CCState CCInfo2(CallerCC, false, getTargetMachine(),
2375 RVLocs2, *DAG.getContext());
2376 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2378 if (RVLocs1.size() != RVLocs2.size())
2380 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2381 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2383 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2385 if (RVLocs1[i].isRegLoc()) {
2386 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2389 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2395 // If the callee takes no arguments then go on to check the results of the
2397 if (!Outs.empty()) {
2398 // Check if stack adjustment is needed. For now, do not do this if any
2399 // argument is passed on the stack.
2400 SmallVector<CCValAssign, 16> ArgLocs;
2401 CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2402 ArgLocs, *DAG.getContext());
2403 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
2404 if (CCInfo.getNextStackOffset()) {
2405 MachineFunction &MF = DAG.getMachineFunction();
2406 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2408 if (Subtarget->isTargetWin64())
2409 // Win64 ABI has additional complications.
2412 // Check if the arguments are already laid out in the right way as
2413 // the caller's fixed stack objects.
2414 MachineFrameInfo *MFI = MF.getFrameInfo();
2415 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2416 const X86InstrInfo *TII =
2417 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2418 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2419 CCValAssign &VA = ArgLocs[i];
2420 EVT RegVT = VA.getLocVT();
2421 SDValue Arg = Outs[i].Val;
2422 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2423 if (VA.getLocInfo() == CCValAssign::Indirect)
2425 if (!VA.isRegLoc()) {
2426 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2438 X86TargetLowering::createFastISel(MachineFunction &mf,
2439 DenseMap<const Value *, unsigned> &vm,
2440 DenseMap<const BasicBlock*, MachineBasicBlock*> &bm,
2441 DenseMap<const AllocaInst *, int> &am,
2442 std::vector<std::pair<MachineInstr*, unsigned> > &pn
2444 , SmallSet<const Instruction *, 8> &cil
2447 return X86::createFastISel(mf, vm, bm, am, pn
2455 //===----------------------------------------------------------------------===//
2456 // Other Lowering Hooks
2457 //===----------------------------------------------------------------------===//
2460 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2461 MachineFunction &MF = DAG.getMachineFunction();
2462 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2463 int ReturnAddrIndex = FuncInfo->getRAIndex();
2465 if (ReturnAddrIndex == 0) {
2466 // Set up a frame object for the return address.
2467 uint64_t SlotSize = TD->getPointerSize();
2468 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2470 FuncInfo->setRAIndex(ReturnAddrIndex);
2473 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2477 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2478 bool hasSymbolicDisplacement) {
2479 // Offset should fit into 32 bit immediate field.
2480 if (!isInt<32>(Offset))
2483 // If we don't have a symbolic displacement - we don't have any extra
2485 if (!hasSymbolicDisplacement)
2488 // FIXME: Some tweaks might be needed for medium code model.
2489 if (M != CodeModel::Small && M != CodeModel::Kernel)
2492 // For small code model we assume that latest object is 16MB before end of 31
2493 // bits boundary. We may also accept pretty large negative constants knowing
2494 // that all objects are in the positive half of address space.
2495 if (M == CodeModel::Small && Offset < 16*1024*1024)
2498 // For kernel code model we know that all object resist in the negative half
2499 // of 32bits address space. We may not accept negative offsets, since they may
2500 // be just off and we may accept pretty large positive ones.
2501 if (M == CodeModel::Kernel && Offset > 0)
2507 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2508 /// specific condition code, returning the condition code and the LHS/RHS of the
2509 /// comparison to make.
2510 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2511 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2513 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2514 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2515 // X > -1 -> X == 0, jump !sign.
2516 RHS = DAG.getConstant(0, RHS.getValueType());
2517 return X86::COND_NS;
2518 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2519 // X < 0 -> X == 0, jump on sign.
2521 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2523 RHS = DAG.getConstant(0, RHS.getValueType());
2524 return X86::COND_LE;
2528 switch (SetCCOpcode) {
2529 default: llvm_unreachable("Invalid integer condition!");
2530 case ISD::SETEQ: return X86::COND_E;
2531 case ISD::SETGT: return X86::COND_G;
2532 case ISD::SETGE: return X86::COND_GE;
2533 case ISD::SETLT: return X86::COND_L;
2534 case ISD::SETLE: return X86::COND_LE;
2535 case ISD::SETNE: return X86::COND_NE;
2536 case ISD::SETULT: return X86::COND_B;
2537 case ISD::SETUGT: return X86::COND_A;
2538 case ISD::SETULE: return X86::COND_BE;
2539 case ISD::SETUGE: return X86::COND_AE;
2543 // First determine if it is required or is profitable to flip the operands.
2545 // If LHS is a foldable load, but RHS is not, flip the condition.
2546 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2547 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2548 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2549 std::swap(LHS, RHS);
2552 switch (SetCCOpcode) {
2558 std::swap(LHS, RHS);
2562 // On a floating point condition, the flags are set as follows:
2564 // 0 | 0 | 0 | X > Y
2565 // 0 | 0 | 1 | X < Y
2566 // 1 | 0 | 0 | X == Y
2567 // 1 | 1 | 1 | unordered
2568 switch (SetCCOpcode) {
2569 default: llvm_unreachable("Condcode should be pre-legalized away");
2571 case ISD::SETEQ: return X86::COND_E;
2572 case ISD::SETOLT: // flipped
2574 case ISD::SETGT: return X86::COND_A;
2575 case ISD::SETOLE: // flipped
2577 case ISD::SETGE: return X86::COND_AE;
2578 case ISD::SETUGT: // flipped
2580 case ISD::SETLT: return X86::COND_B;
2581 case ISD::SETUGE: // flipped
2583 case ISD::SETLE: return X86::COND_BE;
2585 case ISD::SETNE: return X86::COND_NE;
2586 case ISD::SETUO: return X86::COND_P;
2587 case ISD::SETO: return X86::COND_NP;
2589 case ISD::SETUNE: return X86::COND_INVALID;
2593 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2594 /// code. Current x86 isa includes the following FP cmov instructions:
2595 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2596 static bool hasFPCMov(unsigned X86CC) {
2612 /// isFPImmLegal - Returns true if the target can instruction select the
2613 /// specified FP immediate natively. If false, the legalizer will
2614 /// materialize the FP immediate as a load from a constant pool.
2615 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2616 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2617 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2623 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2624 /// the specified range (L, H].
2625 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2626 return (Val < 0) || (Val >= Low && Val < Hi);
2629 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2630 /// specified value.
2631 static bool isUndefOrEqual(int Val, int CmpVal) {
2632 if (Val < 0 || Val == CmpVal)
2637 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2638 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2639 /// the second operand.
2640 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2641 if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2642 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2643 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2644 return (Mask[0] < 2 && Mask[1] < 2);
2648 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2649 SmallVector<int, 8> M;
2651 return ::isPSHUFDMask(M, N->getValueType(0));
2654 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2655 /// is suitable for input to PSHUFHW.
2656 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2657 if (VT != MVT::v8i16)
2660 // Lower quadword copied in order or undef.
2661 for (int i = 0; i != 4; ++i)
2662 if (Mask[i] >= 0 && Mask[i] != i)
2665 // Upper quadword shuffled.
2666 for (int i = 4; i != 8; ++i)
2667 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2673 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2674 SmallVector<int, 8> M;
2676 return ::isPSHUFHWMask(M, N->getValueType(0));
2679 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2680 /// is suitable for input to PSHUFLW.
2681 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2682 if (VT != MVT::v8i16)
2685 // Upper quadword copied in order.
2686 for (int i = 4; i != 8; ++i)
2687 if (Mask[i] >= 0 && Mask[i] != i)
2690 // Lower quadword shuffled.
2691 for (int i = 0; i != 4; ++i)
2698 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2699 SmallVector<int, 8> M;
2701 return ::isPSHUFLWMask(M, N->getValueType(0));
2704 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2705 /// is suitable for input to PALIGNR.
2706 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2708 int i, e = VT.getVectorNumElements();
2710 // Do not handle v2i64 / v2f64 shuffles with palignr.
2711 if (e < 4 || !hasSSSE3)
2714 for (i = 0; i != e; ++i)
2718 // All undef, not a palignr.
2722 // Determine if it's ok to perform a palignr with only the LHS, since we
2723 // don't have access to the actual shuffle elements to see if RHS is undef.
2724 bool Unary = Mask[i] < (int)e;
2725 bool NeedsUnary = false;
2727 int s = Mask[i] - i;
2729 // Check the rest of the elements to see if they are consecutive.
2730 for (++i; i != e; ++i) {
2735 Unary = Unary && (m < (int)e);
2736 NeedsUnary = NeedsUnary || (m < s);
2738 if (NeedsUnary && !Unary)
2740 if (Unary && m != ((s+i) & (e-1)))
2742 if (!Unary && m != (s+i))
2748 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2749 SmallVector<int, 8> M;
2751 return ::isPALIGNRMask(M, N->getValueType(0), true);
2754 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2755 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2756 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2757 int NumElems = VT.getVectorNumElements();
2758 if (NumElems != 2 && NumElems != 4)
2761 int Half = NumElems / 2;
2762 for (int i = 0; i < Half; ++i)
2763 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2765 for (int i = Half; i < NumElems; ++i)
2766 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2772 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2773 SmallVector<int, 8> M;
2775 return ::isSHUFPMask(M, N->getValueType(0));
2778 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2779 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2780 /// half elements to come from vector 1 (which would equal the dest.) and
2781 /// the upper half to come from vector 2.
2782 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2783 int NumElems = VT.getVectorNumElements();
2785 if (NumElems != 2 && NumElems != 4)
2788 int Half = NumElems / 2;
2789 for (int i = 0; i < Half; ++i)
2790 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2792 for (int i = Half; i < NumElems; ++i)
2793 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2798 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2799 SmallVector<int, 8> M;
2801 return isCommutedSHUFPMask(M, N->getValueType(0));
2804 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2805 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2806 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2807 if (N->getValueType(0).getVectorNumElements() != 4)
2810 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2811 return isUndefOrEqual(N->getMaskElt(0), 6) &&
2812 isUndefOrEqual(N->getMaskElt(1), 7) &&
2813 isUndefOrEqual(N->getMaskElt(2), 2) &&
2814 isUndefOrEqual(N->getMaskElt(3), 3);
2817 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2818 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2820 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2821 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2826 return isUndefOrEqual(N->getMaskElt(0), 2) &&
2827 isUndefOrEqual(N->getMaskElt(1), 3) &&
2828 isUndefOrEqual(N->getMaskElt(2), 2) &&
2829 isUndefOrEqual(N->getMaskElt(3), 3);
2832 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2833 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2834 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2835 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2837 if (NumElems != 2 && NumElems != 4)
2840 for (unsigned i = 0; i < NumElems/2; ++i)
2841 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2844 for (unsigned i = NumElems/2; i < NumElems; ++i)
2845 if (!isUndefOrEqual(N->getMaskElt(i), i))
2851 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
2852 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
2853 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
2854 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2856 if (NumElems != 2 && NumElems != 4)
2859 for (unsigned i = 0; i < NumElems/2; ++i)
2860 if (!isUndefOrEqual(N->getMaskElt(i), i))
2863 for (unsigned i = 0; i < NumElems/2; ++i)
2864 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2870 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2871 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2872 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2873 bool V2IsSplat = false) {
2874 int NumElts = VT.getVectorNumElements();
2875 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2878 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2880 int BitI1 = Mask[i+1];
2881 if (!isUndefOrEqual(BitI, j))
2884 if (!isUndefOrEqual(BitI1, NumElts))
2887 if (!isUndefOrEqual(BitI1, j + NumElts))
2894 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2895 SmallVector<int, 8> M;
2897 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2900 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2901 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2902 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
2903 bool V2IsSplat = false) {
2904 int NumElts = VT.getVectorNumElements();
2905 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2908 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2910 int BitI1 = Mask[i+1];
2911 if (!isUndefOrEqual(BitI, j + NumElts/2))
2914 if (isUndefOrEqual(BitI1, NumElts))
2917 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2924 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2925 SmallVector<int, 8> M;
2927 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2930 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2931 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2933 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2934 int NumElems = VT.getVectorNumElements();
2935 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2938 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2940 int BitI1 = Mask[i+1];
2941 if (!isUndefOrEqual(BitI, j))
2943 if (!isUndefOrEqual(BitI1, j))
2949 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2950 SmallVector<int, 8> M;
2952 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2955 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2956 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2958 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2959 int NumElems = VT.getVectorNumElements();
2960 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2963 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2965 int BitI1 = Mask[i+1];
2966 if (!isUndefOrEqual(BitI, j))
2968 if (!isUndefOrEqual(BitI1, j))
2974 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2975 SmallVector<int, 8> M;
2977 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2980 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2981 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2982 /// MOVSD, and MOVD, i.e. setting the lowest element.
2983 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2984 if (VT.getVectorElementType().getSizeInBits() < 32)
2987 int NumElts = VT.getVectorNumElements();
2989 if (!isUndefOrEqual(Mask[0], NumElts))
2992 for (int i = 1; i < NumElts; ++i)
2993 if (!isUndefOrEqual(Mask[i], i))
2999 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3000 SmallVector<int, 8> M;
3002 return ::isMOVLMask(M, N->getValueType(0));
3005 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3006 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3007 /// element of vector 2 and the other elements to come from vector 1 in order.
3008 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3009 bool V2IsSplat = false, bool V2IsUndef = false) {
3010 int NumOps = VT.getVectorNumElements();
3011 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3014 if (!isUndefOrEqual(Mask[0], 0))
3017 for (int i = 1; i < NumOps; ++i)
3018 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3019 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3020 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3026 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3027 bool V2IsUndef = false) {
3028 SmallVector<int, 8> M;
3030 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3033 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3034 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3035 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3036 if (N->getValueType(0).getVectorNumElements() != 4)
3039 // Expect 1, 1, 3, 3
3040 for (unsigned i = 0; i < 2; ++i) {
3041 int Elt = N->getMaskElt(i);
3042 if (Elt >= 0 && Elt != 1)
3047 for (unsigned i = 2; i < 4; ++i) {
3048 int Elt = N->getMaskElt(i);
3049 if (Elt >= 0 && Elt != 3)
3054 // Don't use movshdup if it can be done with a shufps.
3055 // FIXME: verify that matching u, u, 3, 3 is what we want.
3059 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3060 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3061 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3062 if (N->getValueType(0).getVectorNumElements() != 4)
3065 // Expect 0, 0, 2, 2
3066 for (unsigned i = 0; i < 2; ++i)
3067 if (N->getMaskElt(i) > 0)
3071 for (unsigned i = 2; i < 4; ++i) {
3072 int Elt = N->getMaskElt(i);
3073 if (Elt >= 0 && Elt != 2)
3078 // Don't use movsldup if it can be done with a shufps.
3082 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3083 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3084 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3085 int e = N->getValueType(0).getVectorNumElements() / 2;
3087 for (int i = 0; i < e; ++i)
3088 if (!isUndefOrEqual(N->getMaskElt(i), i))
3090 for (int i = 0; i < e; ++i)
3091 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3096 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3097 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3098 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3099 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3100 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3102 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3104 for (int i = 0; i < NumOperands; ++i) {
3105 int Val = SVOp->getMaskElt(NumOperands-i-1);
3106 if (Val < 0) Val = 0;
3107 if (Val >= NumOperands) Val -= NumOperands;
3109 if (i != NumOperands - 1)
3115 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3116 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3117 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3118 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3120 // 8 nodes, but we only care about the last 4.
3121 for (unsigned i = 7; i >= 4; --i) {
3122 int Val = SVOp->getMaskElt(i);
3131 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3132 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3133 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3134 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3136 // 8 nodes, but we only care about the first 4.
3137 for (int i = 3; i >= 0; --i) {
3138 int Val = SVOp->getMaskElt(i);
3147 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3148 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3149 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3150 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3151 EVT VVT = N->getValueType(0);
3152 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3156 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3157 Val = SVOp->getMaskElt(i);
3161 return (Val - i) * EltSize;
3164 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3166 bool X86::isZeroNode(SDValue Elt) {
3167 return ((isa<ConstantSDNode>(Elt) &&
3168 cast<ConstantSDNode>(Elt)->getZExtValue() == 0) ||
3169 (isa<ConstantFPSDNode>(Elt) &&
3170 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3173 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3174 /// their permute mask.
3175 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3176 SelectionDAG &DAG) {
3177 EVT VT = SVOp->getValueType(0);
3178 unsigned NumElems = VT.getVectorNumElements();
3179 SmallVector<int, 8> MaskVec;
3181 for (unsigned i = 0; i != NumElems; ++i) {
3182 int idx = SVOp->getMaskElt(i);
3184 MaskVec.push_back(idx);
3185 else if (idx < (int)NumElems)
3186 MaskVec.push_back(idx + NumElems);
3188 MaskVec.push_back(idx - NumElems);
3190 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3191 SVOp->getOperand(0), &MaskVec[0]);
3194 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3195 /// the two vector operands have swapped position.
3196 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3197 unsigned NumElems = VT.getVectorNumElements();
3198 for (unsigned i = 0; i != NumElems; ++i) {
3202 else if (idx < (int)NumElems)
3203 Mask[i] = idx + NumElems;
3205 Mask[i] = idx - NumElems;
3209 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3210 /// match movhlps. The lower half elements should come from upper half of
3211 /// V1 (and in order), and the upper half elements should come from the upper
3212 /// half of V2 (and in order).
3213 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3214 if (Op->getValueType(0).getVectorNumElements() != 4)
3216 for (unsigned i = 0, e = 2; i != e; ++i)
3217 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3219 for (unsigned i = 2; i != 4; ++i)
3220 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3225 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3226 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3228 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3229 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3231 N = N->getOperand(0).getNode();
3232 if (!ISD::isNON_EXTLoad(N))
3235 *LD = cast<LoadSDNode>(N);
3239 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3240 /// match movlp{s|d}. The lower half elements should come from lower half of
3241 /// V1 (and in order), and the upper half elements should come from the upper
3242 /// half of V2 (and in order). And since V1 will become the source of the
3243 /// MOVLP, it must be either a vector load or a scalar load to vector.
3244 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3245 ShuffleVectorSDNode *Op) {
3246 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3248 // Is V2 is a vector load, don't do this transformation. We will try to use
3249 // load folding shufps op.
3250 if (ISD::isNON_EXTLoad(V2))
3253 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3255 if (NumElems != 2 && NumElems != 4)
3257 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3258 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3260 for (unsigned i = NumElems/2; i != NumElems; ++i)
3261 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3266 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3268 static bool isSplatVector(SDNode *N) {
3269 if (N->getOpcode() != ISD::BUILD_VECTOR)
3272 SDValue SplatValue = N->getOperand(0);
3273 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3274 if (N->getOperand(i) != SplatValue)
3279 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3280 /// to an zero vector.
3281 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3282 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3283 SDValue V1 = N->getOperand(0);
3284 SDValue V2 = N->getOperand(1);
3285 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3286 for (unsigned i = 0; i != NumElems; ++i) {
3287 int Idx = N->getMaskElt(i);
3288 if (Idx >= (int)NumElems) {
3289 unsigned Opc = V2.getOpcode();
3290 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3292 if (Opc != ISD::BUILD_VECTOR ||
3293 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3295 } else if (Idx >= 0) {
3296 unsigned Opc = V1.getOpcode();
3297 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3299 if (Opc != ISD::BUILD_VECTOR ||
3300 !X86::isZeroNode(V1.getOperand(Idx)))
3307 /// getZeroVector - Returns a vector of specified type with all zero elements.
3309 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3311 assert(VT.isVector() && "Expected a vector type");
3313 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3314 // type. This ensures they get CSE'd.
3316 if (VT.getSizeInBits() == 64) { // MMX
3317 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3318 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3319 } else if (HasSSE2) { // SSE2
3320 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3321 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3323 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3324 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3326 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3329 /// getOnesVector - Returns a vector of specified type with all bits set.
3331 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3332 assert(VT.isVector() && "Expected a vector type");
3334 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3335 // type. This ensures they get CSE'd.
3336 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3338 if (VT.getSizeInBits() == 64) // MMX
3339 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3341 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3342 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3346 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3347 /// that point to V2 points to its first element.
3348 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3349 EVT VT = SVOp->getValueType(0);
3350 unsigned NumElems = VT.getVectorNumElements();
3352 bool Changed = false;
3353 SmallVector<int, 8> MaskVec;
3354 SVOp->getMask(MaskVec);
3356 for (unsigned i = 0; i != NumElems; ++i) {
3357 if (MaskVec[i] > (int)NumElems) {
3358 MaskVec[i] = NumElems;
3363 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3364 SVOp->getOperand(1), &MaskVec[0]);
3365 return SDValue(SVOp, 0);
3368 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3369 /// operation of specified width.
3370 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3372 unsigned NumElems = VT.getVectorNumElements();
3373 SmallVector<int, 8> Mask;
3374 Mask.push_back(NumElems);
3375 for (unsigned i = 1; i != NumElems; ++i)
3377 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3380 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3381 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3383 unsigned NumElems = VT.getVectorNumElements();
3384 SmallVector<int, 8> Mask;
3385 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3387 Mask.push_back(i + NumElems);
3389 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3392 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3393 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3395 unsigned NumElems = VT.getVectorNumElements();
3396 unsigned Half = NumElems/2;
3397 SmallVector<int, 8> Mask;
3398 for (unsigned i = 0; i != Half; ++i) {
3399 Mask.push_back(i + Half);
3400 Mask.push_back(i + NumElems + Half);
3402 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3405 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3406 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3408 if (SV->getValueType(0).getVectorNumElements() <= 4)
3409 return SDValue(SV, 0);
3411 EVT PVT = MVT::v4f32;
3412 EVT VT = SV->getValueType(0);
3413 DebugLoc dl = SV->getDebugLoc();
3414 SDValue V1 = SV->getOperand(0);
3415 int NumElems = VT.getVectorNumElements();
3416 int EltNo = SV->getSplatIndex();
3418 // unpack elements to the correct location
3419 while (NumElems > 4) {
3420 if (EltNo < NumElems/2) {
3421 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3423 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3424 EltNo -= NumElems/2;
3429 // Perform the splat.
3430 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3431 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3432 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3433 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3436 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3437 /// vector of zero or undef vector. This produces a shuffle where the low
3438 /// element of V2 is swizzled into the zero/undef vector, landing at element
3439 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3440 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3441 bool isZero, bool HasSSE2,
3442 SelectionDAG &DAG) {
3443 EVT VT = V2.getValueType();
3445 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3446 unsigned NumElems = VT.getVectorNumElements();
3447 SmallVector<int, 16> MaskVec;
3448 for (unsigned i = 0; i != NumElems; ++i)
3449 // If this is the insertion idx, put the low elt of V2 here.
3450 MaskVec.push_back(i == Idx ? NumElems : i);
3451 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3454 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3455 /// a shuffle that is zero.
3457 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3458 bool Low, SelectionDAG &DAG) {
3459 unsigned NumZeros = 0;
3460 for (int i = 0; i < NumElems; ++i) {
3461 unsigned Index = Low ? i : NumElems-i-1;
3462 int Idx = SVOp->getMaskElt(Index);
3467 SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3468 if (Elt.getNode() && X86::isZeroNode(Elt))
3476 /// isVectorShift - Returns true if the shuffle can be implemented as a
3477 /// logical left or right shift of a vector.
3478 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3479 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3480 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3481 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3484 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3487 NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3491 bool SeenV1 = false;
3492 bool SeenV2 = false;
3493 for (unsigned i = NumZeros; i < NumElems; ++i) {
3494 unsigned Val = isLeft ? (i - NumZeros) : i;
3495 int Idx_ = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3498 unsigned Idx = (unsigned) Idx_;
3508 if (SeenV1 && SeenV2)
3511 ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3517 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3519 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3520 unsigned NumNonZero, unsigned NumZero,
3522 const TargetLowering &TLI) {
3526 DebugLoc dl = Op.getDebugLoc();
3529 for (unsigned i = 0; i < 16; ++i) {
3530 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3531 if (ThisIsNonZero && First) {
3533 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3535 V = DAG.getUNDEF(MVT::v8i16);
3540 SDValue ThisElt(0, 0), LastElt(0, 0);
3541 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3542 if (LastIsNonZero) {
3543 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3544 MVT::i16, Op.getOperand(i-1));
3546 if (ThisIsNonZero) {
3547 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3548 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3549 ThisElt, DAG.getConstant(8, MVT::i8));
3551 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3555 if (ThisElt.getNode())
3556 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3557 DAG.getIntPtrConstant(i/2));
3561 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3564 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3566 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3567 unsigned NumNonZero, unsigned NumZero,
3569 const TargetLowering &TLI) {
3573 DebugLoc dl = Op.getDebugLoc();
3576 for (unsigned i = 0; i < 8; ++i) {
3577 bool isNonZero = (NonZeros & (1 << i)) != 0;
3581 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3583 V = DAG.getUNDEF(MVT::v8i16);
3586 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3587 MVT::v8i16, V, Op.getOperand(i),
3588 DAG.getIntPtrConstant(i));
3595 /// getVShift - Return a vector logical shift node.
3597 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3598 unsigned NumBits, SelectionDAG &DAG,
3599 const TargetLowering &TLI, DebugLoc dl) {
3600 bool isMMX = VT.getSizeInBits() == 64;
3601 EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3602 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3603 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3604 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3605 DAG.getNode(Opc, dl, ShVT, SrcOp,
3606 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3610 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3611 SelectionDAG &DAG) const {
3613 // Check if the scalar load can be widened into a vector load. And if
3614 // the address is "base + cst" see if the cst can be "absorbed" into
3615 // the shuffle mask.
3616 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3617 SDValue Ptr = LD->getBasePtr();
3618 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3620 EVT PVT = LD->getValueType(0);
3621 if (PVT != MVT::i32 && PVT != MVT::f32)
3626 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3627 FI = FINode->getIndex();
3629 } else if (Ptr.getOpcode() == ISD::ADD &&
3630 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
3631 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
3632 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
3633 Offset = Ptr.getConstantOperandVal(1);
3634 Ptr = Ptr.getOperand(0);
3639 SDValue Chain = LD->getChain();
3640 // Make sure the stack object alignment is at least 16.
3641 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3642 if (DAG.InferPtrAlignment(Ptr) < 16) {
3643 if (MFI->isFixedObjectIndex(FI)) {
3644 // Can't change the alignment. FIXME: It's possible to compute
3645 // the exact stack offset and reference FI + adjust offset instead.
3646 // If someone *really* cares about this. That's the way to implement it.
3649 MFI->setObjectAlignment(FI, 16);
3653 // (Offset % 16) must be multiple of 4. Then address is then
3654 // Ptr + (Offset & ~15).
3657 if ((Offset % 16) & 3)
3659 int64_t StartOffset = Offset & ~15;
3661 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
3662 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
3664 int EltNo = (Offset - StartOffset) >> 2;
3665 int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
3666 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
3667 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,LD->getSrcValue(),0,
3669 // Canonicalize it to a v4i32 shuffle.
3670 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
3671 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3672 DAG.getVectorShuffle(MVT::v4i32, dl, V1,
3673 DAG.getUNDEF(MVT::v4i32), &Mask[0]));
3679 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
3680 /// vector of type 'VT', see if the elements can be replaced by a single large
3681 /// load which has the same value as a build_vector whose operands are 'elts'.
3683 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
3685 /// FIXME: we'd also like to handle the case where the last elements are zero
3686 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
3687 /// There's even a handy isZeroNode for that purpose.
3688 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
3689 DebugLoc &dl, SelectionDAG &DAG) {
3690 EVT EltVT = VT.getVectorElementType();
3691 unsigned NumElems = Elts.size();
3693 LoadSDNode *LDBase = NULL;
3694 unsigned LastLoadedElt = -1U;
3696 // For each element in the initializer, see if we've found a load or an undef.
3697 // If we don't find an initial load element, or later load elements are
3698 // non-consecutive, bail out.
3699 for (unsigned i = 0; i < NumElems; ++i) {
3700 SDValue Elt = Elts[i];
3702 if (!Elt.getNode() ||
3703 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
3706 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
3708 LDBase = cast<LoadSDNode>(Elt.getNode());
3712 if (Elt.getOpcode() == ISD::UNDEF)
3715 LoadSDNode *LD = cast<LoadSDNode>(Elt);
3716 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
3721 // If we have found an entire vector of loads and undefs, then return a large
3722 // load of the entire vector width starting at the base pointer. If we found
3723 // consecutive loads for the low half, generate a vzext_load node.
3724 if (LastLoadedElt == NumElems - 1) {
3725 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
3726 return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3727 LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3728 LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
3729 return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3730 LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3731 LDBase->isVolatile(), LDBase->isNonTemporal(),
3732 LDBase->getAlignment());
3733 } else if (NumElems == 4 && LastLoadedElt == 1) {
3734 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
3735 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
3736 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
3737 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
3743 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
3744 DebugLoc dl = Op.getDebugLoc();
3745 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3746 if (ISD::isBuildVectorAllZeros(Op.getNode())
3747 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3748 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3749 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3750 // eliminated on x86-32 hosts.
3751 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3754 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3755 return getOnesVector(Op.getValueType(), DAG, dl);
3756 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3759 EVT VT = Op.getValueType();
3760 EVT ExtVT = VT.getVectorElementType();
3761 unsigned EVTBits = ExtVT.getSizeInBits();
3763 unsigned NumElems = Op.getNumOperands();
3764 unsigned NumZero = 0;
3765 unsigned NumNonZero = 0;
3766 unsigned NonZeros = 0;
3767 bool IsAllConstants = true;
3768 SmallSet<SDValue, 8> Values;
3769 for (unsigned i = 0; i < NumElems; ++i) {
3770 SDValue Elt = Op.getOperand(i);
3771 if (Elt.getOpcode() == ISD::UNDEF)
3774 if (Elt.getOpcode() != ISD::Constant &&
3775 Elt.getOpcode() != ISD::ConstantFP)
3776 IsAllConstants = false;
3777 if (X86::isZeroNode(Elt))
3780 NonZeros |= (1 << i);
3785 if (NumNonZero == 0) {
3786 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3787 return DAG.getUNDEF(VT);
3790 // Special case for single non-zero, non-undef, element.
3791 if (NumNonZero == 1) {
3792 unsigned Idx = CountTrailingZeros_32(NonZeros);
3793 SDValue Item = Op.getOperand(Idx);
3795 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3796 // the value are obviously zero, truncate the value to i32 and do the
3797 // insertion that way. Only do this if the value is non-constant or if the
3798 // value is a constant being inserted into element 0. It is cheaper to do
3799 // a constant pool load than it is to do a movd + shuffle.
3800 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3801 (!IsAllConstants || Idx == 0)) {
3802 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3803 // Handle MMX and SSE both.
3804 EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3805 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3807 // Truncate the value (which may itself be a constant) to i32, and
3808 // convert it to a vector with movd (S2V+shuffle to zero extend).
3809 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3810 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3811 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3812 Subtarget->hasSSE2(), DAG);
3814 // Now we have our 32-bit value zero extended in the low element of
3815 // a vector. If Idx != 0, swizzle it into place.
3817 SmallVector<int, 4> Mask;
3818 Mask.push_back(Idx);
3819 for (unsigned i = 1; i != VecElts; ++i)
3821 Item = DAG.getVectorShuffle(VecVT, dl, Item,
3822 DAG.getUNDEF(Item.getValueType()),
3825 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3829 // If we have a constant or non-constant insertion into the low element of
3830 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3831 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3832 // depending on what the source datatype is.
3835 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3836 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3837 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3838 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3839 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3840 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3842 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3843 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3844 EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3845 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3846 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3847 Subtarget->hasSSE2(), DAG);
3848 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3852 // Is it a vector logical left shift?
3853 if (NumElems == 2 && Idx == 1 &&
3854 X86::isZeroNode(Op.getOperand(0)) &&
3855 !X86::isZeroNode(Op.getOperand(1))) {
3856 unsigned NumBits = VT.getSizeInBits();
3857 return getVShift(true, VT,
3858 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3859 VT, Op.getOperand(1)),
3860 NumBits/2, DAG, *this, dl);
3863 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3866 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3867 // is a non-constant being inserted into an element other than the low one,
3868 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3869 // movd/movss) to move this into the low element, then shuffle it into
3871 if (EVTBits == 32) {
3872 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3874 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3875 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3876 Subtarget->hasSSE2(), DAG);
3877 SmallVector<int, 8> MaskVec;
3878 for (unsigned i = 0; i < NumElems; i++)
3879 MaskVec.push_back(i == Idx ? 0 : 1);
3880 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3884 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3885 if (Values.size() == 1) {
3886 if (EVTBits == 32) {
3887 // Instead of a shuffle like this:
3888 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
3889 // Check if it's possible to issue this instead.
3890 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
3891 unsigned Idx = CountTrailingZeros_32(NonZeros);
3892 SDValue Item = Op.getOperand(Idx);
3893 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
3894 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
3899 // A vector full of immediates; various special cases are already
3900 // handled, so this is best done with a single constant-pool load.
3904 // Let legalizer expand 2-wide build_vectors.
3905 if (EVTBits == 64) {
3906 if (NumNonZero == 1) {
3907 // One half is zero or undef.
3908 unsigned Idx = CountTrailingZeros_32(NonZeros);
3909 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3910 Op.getOperand(Idx));
3911 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3912 Subtarget->hasSSE2(), DAG);
3917 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3918 if (EVTBits == 8 && NumElems == 16) {
3919 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3921 if (V.getNode()) return V;
3924 if (EVTBits == 16 && NumElems == 8) {
3925 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3927 if (V.getNode()) return V;
3930 // If element VT is == 32 bits, turn it into a number of shuffles.
3931 SmallVector<SDValue, 8> V;
3933 if (NumElems == 4 && NumZero > 0) {
3934 for (unsigned i = 0; i < 4; ++i) {
3935 bool isZero = !(NonZeros & (1 << i));
3937 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3939 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3942 for (unsigned i = 0; i < 2; ++i) {
3943 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3946 V[i] = V[i*2]; // Must be a zero vector.
3949 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3952 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3955 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3960 SmallVector<int, 8> MaskVec;
3961 bool Reverse = (NonZeros & 0x3) == 2;
3962 for (unsigned i = 0; i < 2; ++i)
3963 MaskVec.push_back(Reverse ? 1-i : i);
3964 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3965 for (unsigned i = 0; i < 2; ++i)
3966 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3967 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3970 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
3971 // Check for a build vector of consecutive loads.
3972 for (unsigned i = 0; i < NumElems; ++i)
3973 V[i] = Op.getOperand(i);
3975 // Check for elements which are consecutive loads.
3976 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
3980 // For SSE 4.1, use inserts into undef.
3981 if (getSubtarget()->hasSSE41()) {
3982 V[0] = DAG.getUNDEF(VT);
3983 for (unsigned i = 0; i < NumElems; ++i)
3984 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3985 V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
3986 Op.getOperand(i), DAG.getIntPtrConstant(i));
3990 // Otherwise, expand into a number of unpckl*
3992 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
3993 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
3994 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
3995 for (unsigned i = 0; i < NumElems; ++i)
3996 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3998 while (NumElems != 0) {
3999 for (unsigned i = 0; i < NumElems; ++i)
4000 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
4009 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4010 // We support concatenate two MMX registers and place them in a MMX
4011 // register. This is better than doing a stack convert.
4012 DebugLoc dl = Op.getDebugLoc();
4013 EVT ResVT = Op.getValueType();
4014 assert(Op.getNumOperands() == 2);
4015 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4016 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4018 SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
4019 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4020 InVec = Op.getOperand(1);
4021 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4022 unsigned NumElts = ResVT.getVectorNumElements();
4023 VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4024 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4025 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4027 InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
4028 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4029 Mask[0] = 0; Mask[1] = 2;
4030 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4032 return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4035 // v8i16 shuffles - Prefer shuffles in the following order:
4036 // 1. [all] pshuflw, pshufhw, optional move
4037 // 2. [ssse3] 1 x pshufb
4038 // 3. [ssse3] 2 x pshufb + 1 x por
4039 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4041 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
4043 const X86TargetLowering &TLI) {
4044 SDValue V1 = SVOp->getOperand(0);
4045 SDValue V2 = SVOp->getOperand(1);
4046 DebugLoc dl = SVOp->getDebugLoc();
4047 SmallVector<int, 8> MaskVals;
4049 // Determine if more than 1 of the words in each of the low and high quadwords
4050 // of the result come from the same quadword of one of the two inputs. Undef
4051 // mask values count as coming from any quadword, for better codegen.
4052 SmallVector<unsigned, 4> LoQuad(4);
4053 SmallVector<unsigned, 4> HiQuad(4);
4054 BitVector InputQuads(4);
4055 for (unsigned i = 0; i < 8; ++i) {
4056 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4057 int EltIdx = SVOp->getMaskElt(i);
4058 MaskVals.push_back(EltIdx);
4067 InputQuads.set(EltIdx / 4);
4070 int BestLoQuad = -1;
4071 unsigned MaxQuad = 1;
4072 for (unsigned i = 0; i < 4; ++i) {
4073 if (LoQuad[i] > MaxQuad) {
4075 MaxQuad = LoQuad[i];
4079 int BestHiQuad = -1;
4081 for (unsigned i = 0; i < 4; ++i) {
4082 if (HiQuad[i] > MaxQuad) {
4084 MaxQuad = HiQuad[i];
4088 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4089 // of the two input vectors, shuffle them into one input vector so only a
4090 // single pshufb instruction is necessary. If There are more than 2 input
4091 // quads, disable the next transformation since it does not help SSSE3.
4092 bool V1Used = InputQuads[0] || InputQuads[1];
4093 bool V2Used = InputQuads[2] || InputQuads[3];
4094 if (TLI.getSubtarget()->hasSSSE3()) {
4095 if (InputQuads.count() == 2 && V1Used && V2Used) {
4096 BestLoQuad = InputQuads.find_first();
4097 BestHiQuad = InputQuads.find_next(BestLoQuad);
4099 if (InputQuads.count() > 2) {
4105 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4106 // the shuffle mask. If a quad is scored as -1, that means that it contains
4107 // words from all 4 input quadwords.
4109 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4110 SmallVector<int, 8> MaskV;
4111 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4112 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4113 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4114 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
4115 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
4116 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
4118 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4119 // source words for the shuffle, to aid later transformations.
4120 bool AllWordsInNewV = true;
4121 bool InOrder[2] = { true, true };
4122 for (unsigned i = 0; i != 8; ++i) {
4123 int idx = MaskVals[i];
4125 InOrder[i/4] = false;
4126 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4128 AllWordsInNewV = false;
4132 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4133 if (AllWordsInNewV) {
4134 for (int i = 0; i != 8; ++i) {
4135 int idx = MaskVals[i];
4138 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4139 if ((idx != i) && idx < 4)
4141 if ((idx != i) && idx > 3)
4150 // If we've eliminated the use of V2, and the new mask is a pshuflw or
4151 // pshufhw, that's as cheap as it gets. Return the new shuffle.
4152 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4153 return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4154 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4158 // If we have SSSE3, and all words of the result are from 1 input vector,
4159 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
4160 // is present, fall back to case 4.
4161 if (TLI.getSubtarget()->hasSSSE3()) {
4162 SmallVector<SDValue,16> pshufbMask;
4164 // If we have elements from both input vectors, set the high bit of the
4165 // shuffle mask element to zero out elements that come from V2 in the V1
4166 // mask, and elements that come from V1 in the V2 mask, so that the two
4167 // results can be OR'd together.
4168 bool TwoInputs = V1Used && V2Used;
4169 for (unsigned i = 0; i != 8; ++i) {
4170 int EltIdx = MaskVals[i] * 2;
4171 if (TwoInputs && (EltIdx >= 16)) {
4172 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4173 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4176 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4177 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4179 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
4180 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4181 DAG.getNode(ISD::BUILD_VECTOR, dl,
4182 MVT::v16i8, &pshufbMask[0], 16));
4184 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4186 // Calculate the shuffle mask for the second input, shuffle it, and
4187 // OR it with the first shuffled input.
4189 for (unsigned i = 0; i != 8; ++i) {
4190 int EltIdx = MaskVals[i] * 2;
4192 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4193 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4196 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4197 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4199 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
4200 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4201 DAG.getNode(ISD::BUILD_VECTOR, dl,
4202 MVT::v16i8, &pshufbMask[0], 16));
4203 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4204 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4207 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4208 // and update MaskVals with new element order.
4209 BitVector InOrder(8);
4210 if (BestLoQuad >= 0) {
4211 SmallVector<int, 8> MaskV;
4212 for (int i = 0; i != 4; ++i) {
4213 int idx = MaskVals[i];
4215 MaskV.push_back(-1);
4217 } else if ((idx / 4) == BestLoQuad) {
4218 MaskV.push_back(idx & 3);
4221 MaskV.push_back(-1);
4224 for (unsigned i = 4; i != 8; ++i)
4226 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4230 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4231 // and update MaskVals with the new element order.
4232 if (BestHiQuad >= 0) {
4233 SmallVector<int, 8> MaskV;
4234 for (unsigned i = 0; i != 4; ++i)
4236 for (unsigned i = 4; i != 8; ++i) {
4237 int idx = MaskVals[i];
4239 MaskV.push_back(-1);
4241 } else if ((idx / 4) == BestHiQuad) {
4242 MaskV.push_back((idx & 3) + 4);
4245 MaskV.push_back(-1);
4248 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4252 // In case BestHi & BestLo were both -1, which means each quadword has a word
4253 // from each of the four input quadwords, calculate the InOrder bitvector now
4254 // before falling through to the insert/extract cleanup.
4255 if (BestLoQuad == -1 && BestHiQuad == -1) {
4257 for (int i = 0; i != 8; ++i)
4258 if (MaskVals[i] < 0 || MaskVals[i] == i)
4262 // The other elements are put in the right place using pextrw and pinsrw.
4263 for (unsigned i = 0; i != 8; ++i) {
4266 int EltIdx = MaskVals[i];
4269 SDValue ExtOp = (EltIdx < 8)
4270 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4271 DAG.getIntPtrConstant(EltIdx))
4272 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4273 DAG.getIntPtrConstant(EltIdx - 8));
4274 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4275 DAG.getIntPtrConstant(i));
4280 // v16i8 shuffles - Prefer shuffles in the following order:
4281 // 1. [ssse3] 1 x pshufb
4282 // 2. [ssse3] 2 x pshufb + 1 x por
4283 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
4285 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4287 const X86TargetLowering &TLI) {
4288 SDValue V1 = SVOp->getOperand(0);
4289 SDValue V2 = SVOp->getOperand(1);
4290 DebugLoc dl = SVOp->getDebugLoc();
4291 SmallVector<int, 16> MaskVals;
4292 SVOp->getMask(MaskVals);
4294 // If we have SSSE3, case 1 is generated when all result bytes come from
4295 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
4296 // present, fall back to case 3.
4297 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4300 for (unsigned i = 0; i < 16; ++i) {
4301 int EltIdx = MaskVals[i];
4310 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4311 if (TLI.getSubtarget()->hasSSSE3()) {
4312 SmallVector<SDValue,16> pshufbMask;
4314 // If all result elements are from one input vector, then only translate
4315 // undef mask values to 0x80 (zero out result) in the pshufb mask.
4317 // Otherwise, we have elements from both input vectors, and must zero out
4318 // elements that come from V2 in the first mask, and V1 in the second mask
4319 // so that we can OR them together.
4320 bool TwoInputs = !(V1Only || V2Only);
4321 for (unsigned i = 0; i != 16; ++i) {
4322 int EltIdx = MaskVals[i];
4323 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4324 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4327 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4329 // If all the elements are from V2, assign it to V1 and return after
4330 // building the first pshufb.
4333 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4334 DAG.getNode(ISD::BUILD_VECTOR, dl,
4335 MVT::v16i8, &pshufbMask[0], 16));
4339 // Calculate the shuffle mask for the second input, shuffle it, and
4340 // OR it with the first shuffled input.
4342 for (unsigned i = 0; i != 16; ++i) {
4343 int EltIdx = MaskVals[i];
4345 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4348 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4350 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4351 DAG.getNode(ISD::BUILD_VECTOR, dl,
4352 MVT::v16i8, &pshufbMask[0], 16));
4353 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4356 // No SSSE3 - Calculate in place words and then fix all out of place words
4357 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
4358 // the 16 different words that comprise the two doublequadword input vectors.
4359 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4360 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4361 SDValue NewV = V2Only ? V2 : V1;
4362 for (int i = 0; i != 8; ++i) {
4363 int Elt0 = MaskVals[i*2];
4364 int Elt1 = MaskVals[i*2+1];
4366 // This word of the result is all undef, skip it.
4367 if (Elt0 < 0 && Elt1 < 0)
4370 // This word of the result is already in the correct place, skip it.
4371 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4373 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4376 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4377 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4380 // If Elt0 and Elt1 are defined, are consecutive, and can be load
4381 // using a single extract together, load it and store it.
4382 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4383 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4384 DAG.getIntPtrConstant(Elt1 / 2));
4385 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4386 DAG.getIntPtrConstant(i));
4390 // If Elt1 is defined, extract it from the appropriate source. If the
4391 // source byte is not also odd, shift the extracted word left 8 bits
4392 // otherwise clear the bottom 8 bits if we need to do an or.
4394 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4395 DAG.getIntPtrConstant(Elt1 / 2));
4396 if ((Elt1 & 1) == 0)
4397 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4398 DAG.getConstant(8, TLI.getShiftAmountTy()));
4400 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4401 DAG.getConstant(0xFF00, MVT::i16));
4403 // If Elt0 is defined, extract it from the appropriate source. If the
4404 // source byte is not also even, shift the extracted word right 8 bits. If
4405 // Elt1 was also defined, OR the extracted values together before
4406 // inserting them in the result.
4408 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4409 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4410 if ((Elt0 & 1) != 0)
4411 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4412 DAG.getConstant(8, TLI.getShiftAmountTy()));
4414 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4415 DAG.getConstant(0x00FF, MVT::i16));
4416 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4419 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4420 DAG.getIntPtrConstant(i));
4422 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4425 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4426 /// ones, or rewriting v4i32 / v2f32 as 2 wide ones if possible. This can be
4427 /// done when every pair / quad of shuffle mask elements point to elements in
4428 /// the right sequence. e.g.
4429 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
4431 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4433 const TargetLowering &TLI, DebugLoc dl) {
4434 EVT VT = SVOp->getValueType(0);
4435 SDValue V1 = SVOp->getOperand(0);
4436 SDValue V2 = SVOp->getOperand(1);
4437 unsigned NumElems = VT.getVectorNumElements();
4438 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4439 EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
4440 EVT MaskEltVT = MaskVT.getVectorElementType();
4442 switch (VT.getSimpleVT().SimpleTy) {
4443 default: assert(false && "Unexpected!");
4444 case MVT::v4f32: NewVT = MVT::v2f64; break;
4445 case MVT::v4i32: NewVT = MVT::v2i64; break;
4446 case MVT::v8i16: NewVT = MVT::v4i32; break;
4447 case MVT::v16i8: NewVT = MVT::v4i32; break;
4450 if (NewWidth == 2) {
4456 int Scale = NumElems / NewWidth;
4457 SmallVector<int, 8> MaskVec;
4458 for (unsigned i = 0; i < NumElems; i += Scale) {
4460 for (int j = 0; j < Scale; ++j) {
4461 int EltIdx = SVOp->getMaskElt(i+j);
4465 StartIdx = EltIdx - (EltIdx % Scale);
4466 if (EltIdx != StartIdx + j)
4470 MaskVec.push_back(-1);
4472 MaskVec.push_back(StartIdx / Scale);
4475 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4476 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4477 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4480 /// getVZextMovL - Return a zero-extending vector move low node.
4482 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4483 SDValue SrcOp, SelectionDAG &DAG,
4484 const X86Subtarget *Subtarget, DebugLoc dl) {
4485 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4486 LoadSDNode *LD = NULL;
4487 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4488 LD = dyn_cast<LoadSDNode>(SrcOp);
4490 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4492 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4493 if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4494 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4495 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4496 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4498 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4499 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4500 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4501 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4509 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4510 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4511 DAG.getNode(ISD::BIT_CONVERT, dl,
4515 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4518 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4519 SDValue V1 = SVOp->getOperand(0);
4520 SDValue V2 = SVOp->getOperand(1);
4521 DebugLoc dl = SVOp->getDebugLoc();
4522 EVT VT = SVOp->getValueType(0);
4524 SmallVector<std::pair<int, int>, 8> Locs;
4526 SmallVector<int, 8> Mask1(4U, -1);
4527 SmallVector<int, 8> PermMask;
4528 SVOp->getMask(PermMask);
4532 for (unsigned i = 0; i != 4; ++i) {
4533 int Idx = PermMask[i];
4535 Locs[i] = std::make_pair(-1, -1);
4537 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4539 Locs[i] = std::make_pair(0, NumLo);
4543 Locs[i] = std::make_pair(1, NumHi);
4545 Mask1[2+NumHi] = Idx;
4551 if (NumLo <= 2 && NumHi <= 2) {
4552 // If no more than two elements come from either vector. This can be
4553 // implemented with two shuffles. First shuffle gather the elements.
4554 // The second shuffle, which takes the first shuffle as both of its
4555 // vector operands, put the elements into the right order.
4556 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4558 SmallVector<int, 8> Mask2(4U, -1);
4560 for (unsigned i = 0; i != 4; ++i) {
4561 if (Locs[i].first == -1)
4564 unsigned Idx = (i < 2) ? 0 : 4;
4565 Idx += Locs[i].first * 2 + Locs[i].second;
4570 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4571 } else if (NumLo == 3 || NumHi == 3) {
4572 // Otherwise, we must have three elements from one vector, call it X, and
4573 // one element from the other, call it Y. First, use a shufps to build an
4574 // intermediate vector with the one element from Y and the element from X
4575 // that will be in the same half in the final destination (the indexes don't
4576 // matter). Then, use a shufps to build the final vector, taking the half
4577 // containing the element from Y from the intermediate, and the other half
4580 // Normalize it so the 3 elements come from V1.
4581 CommuteVectorShuffleMask(PermMask, VT);
4585 // Find the element from V2.
4587 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4588 int Val = PermMask[HiIndex];
4595 Mask1[0] = PermMask[HiIndex];
4597 Mask1[2] = PermMask[HiIndex^1];
4599 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4602 Mask1[0] = PermMask[0];
4603 Mask1[1] = PermMask[1];
4604 Mask1[2] = HiIndex & 1 ? 6 : 4;
4605 Mask1[3] = HiIndex & 1 ? 4 : 6;
4606 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4608 Mask1[0] = HiIndex & 1 ? 2 : 0;
4609 Mask1[1] = HiIndex & 1 ? 0 : 2;
4610 Mask1[2] = PermMask[2];
4611 Mask1[3] = PermMask[3];
4616 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4620 // Break it into (shuffle shuffle_hi, shuffle_lo).
4622 SmallVector<int,8> LoMask(4U, -1);
4623 SmallVector<int,8> HiMask(4U, -1);
4625 SmallVector<int,8> *MaskPtr = &LoMask;
4626 unsigned MaskIdx = 0;
4629 for (unsigned i = 0; i != 4; ++i) {
4636 int Idx = PermMask[i];
4638 Locs[i] = std::make_pair(-1, -1);
4639 } else if (Idx < 4) {
4640 Locs[i] = std::make_pair(MaskIdx, LoIdx);
4641 (*MaskPtr)[LoIdx] = Idx;
4644 Locs[i] = std::make_pair(MaskIdx, HiIdx);
4645 (*MaskPtr)[HiIdx] = Idx;
4650 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4651 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4652 SmallVector<int, 8> MaskOps;
4653 for (unsigned i = 0; i != 4; ++i) {
4654 if (Locs[i].first == -1) {
4655 MaskOps.push_back(-1);
4657 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4658 MaskOps.push_back(Idx);
4661 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4665 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
4666 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4667 SDValue V1 = Op.getOperand(0);
4668 SDValue V2 = Op.getOperand(1);
4669 EVT VT = Op.getValueType();
4670 DebugLoc dl = Op.getDebugLoc();
4671 unsigned NumElems = VT.getVectorNumElements();
4672 bool isMMX = VT.getSizeInBits() == 64;
4673 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4674 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4675 bool V1IsSplat = false;
4676 bool V2IsSplat = false;
4678 if (isZeroShuffle(SVOp))
4679 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4681 // Promote splats to v4f32.
4682 if (SVOp->isSplat()) {
4683 if (isMMX || NumElems < 4)
4685 return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4688 // If the shuffle can be profitably rewritten as a narrower shuffle, then
4690 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4691 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4692 if (NewOp.getNode())
4693 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4694 LowerVECTOR_SHUFFLE(NewOp, DAG));
4695 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4696 // FIXME: Figure out a cleaner way to do this.
4697 // Try to make use of movq to zero out the top part.
4698 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4699 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4700 if (NewOp.getNode()) {
4701 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4702 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4703 DAG, Subtarget, dl);
4705 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4706 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4707 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4708 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4709 DAG, Subtarget, dl);
4713 if (X86::isPSHUFDMask(SVOp))
4716 // Check if this can be converted into a logical shift.
4717 bool isLeft = false;
4720 bool isShift = getSubtarget()->hasSSE2() &&
4721 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4722 if (isShift && ShVal.hasOneUse()) {
4723 // If the shifted value has multiple uses, it may be cheaper to use
4724 // v_set0 + movlhps or movhlps, etc.
4725 EVT EltVT = VT.getVectorElementType();
4726 ShAmt *= EltVT.getSizeInBits();
4727 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4730 if (X86::isMOVLMask(SVOp)) {
4733 if (ISD::isBuildVectorAllZeros(V1.getNode()))
4734 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4739 // FIXME: fold these into legal mask.
4740 if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4741 X86::isMOVSLDUPMask(SVOp) ||
4742 X86::isMOVHLPSMask(SVOp) ||
4743 X86::isMOVLHPSMask(SVOp) ||
4744 X86::isMOVLPMask(SVOp)))
4747 if (ShouldXformToMOVHLPS(SVOp) ||
4748 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4749 return CommuteVectorShuffle(SVOp, DAG);
4752 // No better options. Use a vshl / vsrl.
4753 EVT EltVT = VT.getVectorElementType();
4754 ShAmt *= EltVT.getSizeInBits();
4755 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4758 bool Commuted = false;
4759 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4760 // 1,1,1,1 -> v8i16 though.
4761 V1IsSplat = isSplatVector(V1.getNode());
4762 V2IsSplat = isSplatVector(V2.getNode());
4764 // Canonicalize the splat or undef, if present, to be on the RHS.
4765 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4766 Op = CommuteVectorShuffle(SVOp, DAG);
4767 SVOp = cast<ShuffleVectorSDNode>(Op);
4768 V1 = SVOp->getOperand(0);
4769 V2 = SVOp->getOperand(1);
4770 std::swap(V1IsSplat, V2IsSplat);
4771 std::swap(V1IsUndef, V2IsUndef);
4775 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4776 // Shuffling low element of v1 into undef, just return v1.
4779 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4780 // the instruction selector will not match, so get a canonical MOVL with
4781 // swapped operands to undo the commute.
4782 return getMOVL(DAG, dl, VT, V2, V1);
4785 if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4786 X86::isUNPCKH_v_undef_Mask(SVOp) ||
4787 X86::isUNPCKLMask(SVOp) ||
4788 X86::isUNPCKHMask(SVOp))
4792 // Normalize mask so all entries that point to V2 points to its first
4793 // element then try to match unpck{h|l} again. If match, return a
4794 // new vector_shuffle with the corrected mask.
4795 SDValue NewMask = NormalizeMask(SVOp, DAG);
4796 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4797 if (NSVOp != SVOp) {
4798 if (X86::isUNPCKLMask(NSVOp, true)) {
4800 } else if (X86::isUNPCKHMask(NSVOp, true)) {
4807 // Commute is back and try unpck* again.
4808 // FIXME: this seems wrong.
4809 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4810 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4811 if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4812 X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4813 X86::isUNPCKLMask(NewSVOp) ||
4814 X86::isUNPCKHMask(NewSVOp))
4818 // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4820 // Normalize the node to match x86 shuffle ops if needed
4821 if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4822 return CommuteVectorShuffle(SVOp, DAG);
4824 // Check for legal shuffle and return?
4825 SmallVector<int, 16> PermMask;
4826 SVOp->getMask(PermMask);
4827 if (isShuffleMaskLegal(PermMask, VT))
4830 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4831 if (VT == MVT::v8i16) {
4832 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4833 if (NewOp.getNode())
4837 if (VT == MVT::v16i8) {
4838 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4839 if (NewOp.getNode())
4843 // Handle all 4 wide cases with a number of shuffles except for MMX.
4844 if (NumElems == 4 && !isMMX)
4845 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4851 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4852 SelectionDAG &DAG) const {
4853 EVT VT = Op.getValueType();
4854 DebugLoc dl = Op.getDebugLoc();
4855 if (VT.getSizeInBits() == 8) {
4856 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4857 Op.getOperand(0), Op.getOperand(1));
4858 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4859 DAG.getValueType(VT));
4860 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4861 } else if (VT.getSizeInBits() == 16) {
4862 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4863 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4865 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4866 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4867 DAG.getNode(ISD::BIT_CONVERT, dl,
4871 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4872 Op.getOperand(0), Op.getOperand(1));
4873 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4874 DAG.getValueType(VT));
4875 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4876 } else if (VT == MVT::f32) {
4877 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4878 // the result back to FR32 register. It's only worth matching if the
4879 // result has a single use which is a store or a bitcast to i32. And in
4880 // the case of a store, it's not worth it if the index is a constant 0,
4881 // because a MOVSSmr can be used instead, which is smaller and faster.
4882 if (!Op.hasOneUse())
4884 SDNode *User = *Op.getNode()->use_begin();
4885 if ((User->getOpcode() != ISD::STORE ||
4886 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4887 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4888 (User->getOpcode() != ISD::BIT_CONVERT ||
4889 User->getValueType(0) != MVT::i32))
4891 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4892 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4895 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4896 } else if (VT == MVT::i32) {
4897 // ExtractPS works with constant index.
4898 if (isa<ConstantSDNode>(Op.getOperand(1)))
4906 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
4907 SelectionDAG &DAG) const {
4908 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4911 if (Subtarget->hasSSE41()) {
4912 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4917 EVT VT = Op.getValueType();
4918 DebugLoc dl = Op.getDebugLoc();
4919 // TODO: handle v16i8.
4920 if (VT.getSizeInBits() == 16) {
4921 SDValue Vec = Op.getOperand(0);
4922 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4924 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4925 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4926 DAG.getNode(ISD::BIT_CONVERT, dl,
4929 // Transform it so it match pextrw which produces a 32-bit result.
4930 EVT EltVT = MVT::i32;
4931 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
4932 Op.getOperand(0), Op.getOperand(1));
4933 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
4934 DAG.getValueType(VT));
4935 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4936 } else if (VT.getSizeInBits() == 32) {
4937 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4941 // SHUFPS the element to the lowest double word, then movss.
4942 int Mask[4] = { Idx, -1, -1, -1 };
4943 EVT VVT = Op.getOperand(0).getValueType();
4944 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4945 DAG.getUNDEF(VVT), Mask);
4946 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4947 DAG.getIntPtrConstant(0));
4948 } else if (VT.getSizeInBits() == 64) {
4949 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4950 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4951 // to match extract_elt for f64.
4952 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4956 // UNPCKHPD the element to the lowest double word, then movsd.
4957 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4958 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4959 int Mask[2] = { 1, -1 };
4960 EVT VVT = Op.getOperand(0).getValueType();
4961 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4962 DAG.getUNDEF(VVT), Mask);
4963 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4964 DAG.getIntPtrConstant(0));
4971 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
4972 SelectionDAG &DAG) const {
4973 EVT VT = Op.getValueType();
4974 EVT EltVT = VT.getVectorElementType();
4975 DebugLoc dl = Op.getDebugLoc();
4977 SDValue N0 = Op.getOperand(0);
4978 SDValue N1 = Op.getOperand(1);
4979 SDValue N2 = Op.getOperand(2);
4981 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
4982 isa<ConstantSDNode>(N2)) {
4984 if (VT == MVT::v8i16)
4985 Opc = X86ISD::PINSRW;
4986 else if (VT == MVT::v4i16)
4987 Opc = X86ISD::MMX_PINSRW;
4988 else if (VT == MVT::v16i8)
4989 Opc = X86ISD::PINSRB;
4991 Opc = X86ISD::PINSRB;
4993 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
4995 if (N1.getValueType() != MVT::i32)
4996 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
4997 if (N2.getValueType() != MVT::i32)
4998 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
4999 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
5000 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
5001 // Bits [7:6] of the constant are the source select. This will always be
5002 // zero here. The DAG Combiner may combine an extract_elt index into these
5003 // bits. For example (insert (extract, 3), 2) could be matched by putting
5004 // the '3' into bits [7:6] of X86ISD::INSERTPS.
5005 // Bits [5:4] of the constant are the destination select. This is the
5006 // value of the incoming immediate.
5007 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
5008 // combine either bitwise AND or insert of float 0.0 to set these bits.
5009 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
5010 // Create this as a scalar to vector..
5011 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
5012 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
5013 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
5014 // PINSR* works with constant index.
5021 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
5022 EVT VT = Op.getValueType();
5023 EVT EltVT = VT.getVectorElementType();
5025 if (Subtarget->hasSSE41())
5026 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
5028 if (EltVT == MVT::i8)
5031 DebugLoc dl = Op.getDebugLoc();
5032 SDValue N0 = Op.getOperand(0);
5033 SDValue N1 = Op.getOperand(1);
5034 SDValue N2 = Op.getOperand(2);
5036 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
5037 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
5038 // as its second argument.
5039 if (N1.getValueType() != MVT::i32)
5040 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5041 if (N2.getValueType() != MVT::i32)
5042 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5043 return DAG.getNode(VT == MVT::v8i16 ? X86ISD::PINSRW : X86ISD::MMX_PINSRW,
5044 dl, VT, N0, N1, N2);
5050 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5051 DebugLoc dl = Op.getDebugLoc();
5052 if (Op.getValueType() == MVT::v2f32)
5053 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f32,
5054 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i32,
5055 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32,
5056 Op.getOperand(0))));
5058 if (Op.getValueType() == MVT::v1i64 && Op.getOperand(0).getValueType() == MVT::i64)
5059 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5061 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5062 EVT VT = MVT::v2i32;
5063 switch (Op.getValueType().getSimpleVT().SimpleTy) {
5070 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
5071 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
5074 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5075 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5076 // one of the above mentioned nodes. It has to be wrapped because otherwise
5077 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5078 // be used to form addressing mode. These wrapped nodes will be selected
5081 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
5082 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5084 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5086 unsigned char OpFlag = 0;
5087 unsigned WrapperKind = X86ISD::Wrapper;
5088 CodeModel::Model M = getTargetMachine().getCodeModel();
5090 if (Subtarget->isPICStyleRIPRel() &&
5091 (M == CodeModel::Small || M == CodeModel::Kernel))
5092 WrapperKind = X86ISD::WrapperRIP;
5093 else if (Subtarget->isPICStyleGOT())
5094 OpFlag = X86II::MO_GOTOFF;
5095 else if (Subtarget->isPICStyleStubPIC())
5096 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5098 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5100 CP->getOffset(), OpFlag);
5101 DebugLoc DL = CP->getDebugLoc();
5102 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5103 // With PIC, the address is actually $g + Offset.
5105 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5106 DAG.getNode(X86ISD::GlobalBaseReg,
5107 DebugLoc(), getPointerTy()),
5114 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
5115 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5117 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5119 unsigned char OpFlag = 0;
5120 unsigned WrapperKind = X86ISD::Wrapper;
5121 CodeModel::Model M = getTargetMachine().getCodeModel();
5123 if (Subtarget->isPICStyleRIPRel() &&
5124 (M == CodeModel::Small || M == CodeModel::Kernel))
5125 WrapperKind = X86ISD::WrapperRIP;
5126 else if (Subtarget->isPICStyleGOT())
5127 OpFlag = X86II::MO_GOTOFF;
5128 else if (Subtarget->isPICStyleStubPIC())
5129 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5131 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5133 DebugLoc DL = JT->getDebugLoc();
5134 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5136 // With PIC, the address is actually $g + Offset.
5138 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5139 DAG.getNode(X86ISD::GlobalBaseReg,
5140 DebugLoc(), getPointerTy()),
5148 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
5149 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5151 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5153 unsigned char OpFlag = 0;
5154 unsigned WrapperKind = X86ISD::Wrapper;
5155 CodeModel::Model M = getTargetMachine().getCodeModel();
5157 if (Subtarget->isPICStyleRIPRel() &&
5158 (M == CodeModel::Small || M == CodeModel::Kernel))
5159 WrapperKind = X86ISD::WrapperRIP;
5160 else if (Subtarget->isPICStyleGOT())
5161 OpFlag = X86II::MO_GOTOFF;
5162 else if (Subtarget->isPICStyleStubPIC())
5163 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5165 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5167 DebugLoc DL = Op.getDebugLoc();
5168 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5171 // With PIC, the address is actually $g + Offset.
5172 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
5173 !Subtarget->is64Bit()) {
5174 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5175 DAG.getNode(X86ISD::GlobalBaseReg,
5176 DebugLoc(), getPointerTy()),
5184 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
5185 // Create the TargetBlockAddressAddress node.
5186 unsigned char OpFlags =
5187 Subtarget->ClassifyBlockAddressReference();
5188 CodeModel::Model M = getTargetMachine().getCodeModel();
5189 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5190 DebugLoc dl = Op.getDebugLoc();
5191 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5192 /*isTarget=*/true, OpFlags);
5194 if (Subtarget->isPICStyleRIPRel() &&
5195 (M == CodeModel::Small || M == CodeModel::Kernel))
5196 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5198 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5200 // With PIC, the address is actually $g + Offset.
5201 if (isGlobalRelativeToPICBase(OpFlags)) {
5202 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5203 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5211 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
5213 SelectionDAG &DAG) const {
5214 // Create the TargetGlobalAddress node, folding in the constant
5215 // offset if it is legal.
5216 unsigned char OpFlags =
5217 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5218 CodeModel::Model M = getTargetMachine().getCodeModel();
5220 if (OpFlags == X86II::MO_NO_FLAG &&
5221 X86::isOffsetSuitableForCodeModel(Offset, M)) {
5222 // A direct static reference to a global.
5223 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
5226 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
5229 if (Subtarget->isPICStyleRIPRel() &&
5230 (M == CodeModel::Small || M == CodeModel::Kernel))
5231 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5233 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5235 // With PIC, the address is actually $g + Offset.
5236 if (isGlobalRelativeToPICBase(OpFlags)) {
5237 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5238 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5242 // For globals that require a load from a stub to get the address, emit the
5244 if (isGlobalStubReference(OpFlags))
5245 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
5246 PseudoSourceValue::getGOT(), 0, false, false, 0);
5248 // If there was a non-zero offset that we didn't fold, create an explicit
5251 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
5252 DAG.getConstant(Offset, getPointerTy()));
5258 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
5259 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
5260 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
5261 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
5265 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
5266 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
5267 unsigned char OperandFlags) {
5268 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5269 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5270 DebugLoc dl = GA->getDebugLoc();
5271 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
5272 GA->getValueType(0),
5276 SDValue Ops[] = { Chain, TGA, *InFlag };
5277 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
5279 SDValue Ops[] = { Chain, TGA };
5280 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
5283 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
5284 MFI->setAdjustsStack(true);
5286 SDValue Flag = Chain.getValue(1);
5287 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
5290 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
5292 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5295 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
5296 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
5297 DAG.getNode(X86ISD::GlobalBaseReg,
5298 DebugLoc(), PtrVT), InFlag);
5299 InFlag = Chain.getValue(1);
5301 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
5304 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
5306 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5308 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
5309 X86::RAX, X86II::MO_TLSGD);
5312 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
5313 // "local exec" model.
5314 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5315 const EVT PtrVT, TLSModel::Model model,
5317 DebugLoc dl = GA->getDebugLoc();
5318 // Get the Thread Pointer
5319 SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
5321 DAG.getRegister(is64Bit? X86::FS : X86::GS,
5324 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
5325 NULL, 0, false, false, 0);
5327 unsigned char OperandFlags = 0;
5328 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
5330 unsigned WrapperKind = X86ISD::Wrapper;
5331 if (model == TLSModel::LocalExec) {
5332 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
5333 } else if (is64Bit) {
5334 assert(model == TLSModel::InitialExec);
5335 OperandFlags = X86II::MO_GOTTPOFF;
5336 WrapperKind = X86ISD::WrapperRIP;
5338 assert(model == TLSModel::InitialExec);
5339 OperandFlags = X86II::MO_INDNTPOFF;
5342 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
5344 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
5345 GA->getOffset(), OperandFlags);
5346 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
5348 if (model == TLSModel::InitialExec)
5349 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
5350 PseudoSourceValue::getGOT(), 0, false, false, 0);
5352 // The address of the thread local variable is the add of the thread
5353 // pointer with the offset of the variable.
5354 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
5358 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
5359 // TODO: implement the "local dynamic" model
5360 // TODO: implement the "initial exec"model for pic executables
5361 assert(Subtarget->isTargetELF() &&
5362 "TLS not implemented for non-ELF targets");
5363 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5364 const GlobalValue *GV = GA->getGlobal();
5366 // If GV is an alias then use the aliasee for determining
5367 // thread-localness.
5368 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
5369 GV = GA->resolveAliasedGlobal(false);
5371 TLSModel::Model model = getTLSModel(GV,
5372 getTargetMachine().getRelocationModel());
5375 case TLSModel::GeneralDynamic:
5376 case TLSModel::LocalDynamic: // not implemented
5377 if (Subtarget->is64Bit())
5378 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
5379 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
5381 case TLSModel::InitialExec:
5382 case TLSModel::LocalExec:
5383 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
5384 Subtarget->is64Bit());
5387 llvm_unreachable("Unreachable");
5392 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
5393 /// take a 2 x i32 value to shift plus a shift amount.
5394 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
5395 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5396 EVT VT = Op.getValueType();
5397 unsigned VTBits = VT.getSizeInBits();
5398 DebugLoc dl = Op.getDebugLoc();
5399 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
5400 SDValue ShOpLo = Op.getOperand(0);
5401 SDValue ShOpHi = Op.getOperand(1);
5402 SDValue ShAmt = Op.getOperand(2);
5403 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
5404 DAG.getConstant(VTBits - 1, MVT::i8))
5405 : DAG.getConstant(0, VT);
5408 if (Op.getOpcode() == ISD::SHL_PARTS) {
5409 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
5410 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5412 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
5413 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
5416 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
5417 DAG.getConstant(VTBits, MVT::i8));
5418 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
5419 AndNode, DAG.getConstant(0, MVT::i8));
5422 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5423 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
5424 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
5426 if (Op.getOpcode() == ISD::SHL_PARTS) {
5427 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5428 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5430 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5431 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5434 SDValue Ops[2] = { Lo, Hi };
5435 return DAG.getMergeValues(Ops, 2, dl);
5438 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
5439 SelectionDAG &DAG) const {
5440 EVT SrcVT = Op.getOperand(0).getValueType();
5442 if (SrcVT.isVector()) {
5443 if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
5449 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
5450 "Unknown SINT_TO_FP to lower!");
5452 // These are really Legal; return the operand so the caller accepts it as
5454 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
5456 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
5457 Subtarget->is64Bit()) {
5461 DebugLoc dl = Op.getDebugLoc();
5462 unsigned Size = SrcVT.getSizeInBits()/8;
5463 MachineFunction &MF = DAG.getMachineFunction();
5464 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
5465 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5466 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5468 PseudoSourceValue::getFixedStack(SSFI), 0,
5470 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
5473 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
5475 SelectionDAG &DAG) const {
5477 DebugLoc dl = Op.getDebugLoc();
5479 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
5481 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
5483 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
5484 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
5485 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
5486 Tys, Ops, array_lengthof(Ops));
5489 Chain = Result.getValue(1);
5490 SDValue InFlag = Result.getValue(2);
5492 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5493 // shouldn't be necessary except that RFP cannot be live across
5494 // multiple blocks. When stackifier is fixed, they can be uncoupled.
5495 MachineFunction &MF = DAG.getMachineFunction();
5496 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5497 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5498 Tys = DAG.getVTList(MVT::Other);
5500 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
5502 Chain = DAG.getNode(X86ISD::FST, dl, Tys, Ops, array_lengthof(Ops));
5503 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5504 PseudoSourceValue::getFixedStack(SSFI), 0,
5511 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5512 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
5513 SelectionDAG &DAG) const {
5514 // This algorithm is not obvious. Here it is in C code, more or less:
5516 double uint64_to_double( uint32_t hi, uint32_t lo ) {
5517 static const __m128i exp = { 0x4330000045300000ULL, 0 };
5518 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5520 // Copy ints to xmm registers.
5521 __m128i xh = _mm_cvtsi32_si128( hi );
5522 __m128i xl = _mm_cvtsi32_si128( lo );
5524 // Combine into low half of a single xmm register.
5525 __m128i x = _mm_unpacklo_epi32( xh, xl );
5529 // Merge in appropriate exponents to give the integer bits the right
5531 x = _mm_unpacklo_epi32( x, exp );
5533 // Subtract away the biases to deal with the IEEE-754 double precision
5535 d = _mm_sub_pd( (__m128d) x, bias );
5537 // All conversions up to here are exact. The correctly rounded result is
5538 // calculated using the current rounding mode using the following
5540 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5541 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
5542 // store doesn't really need to be here (except
5543 // maybe to zero the other double)
5548 DebugLoc dl = Op.getDebugLoc();
5549 LLVMContext *Context = DAG.getContext();
5551 // Build some magic constants.
5552 std::vector<Constant*> CV0;
5553 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
5554 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
5555 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5556 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5557 Constant *C0 = ConstantVector::get(CV0);
5558 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5560 std::vector<Constant*> CV1;
5562 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
5564 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
5565 Constant *C1 = ConstantVector::get(CV1);
5566 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5568 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5569 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5571 DAG.getIntPtrConstant(1)));
5572 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5573 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5575 DAG.getIntPtrConstant(0)));
5576 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
5577 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5578 PseudoSourceValue::getConstantPool(), 0,
5580 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
5581 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5582 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5583 PseudoSourceValue::getConstantPool(), 0,
5585 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5587 // Add the halves; easiest way is to swap them into another reg first.
5588 int ShufMask[2] = { 1, -1 };
5589 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
5590 DAG.getUNDEF(MVT::v2f64), ShufMask);
5591 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5592 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5593 DAG.getIntPtrConstant(0));
5596 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5597 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
5598 SelectionDAG &DAG) const {
5599 DebugLoc dl = Op.getDebugLoc();
5600 // FP constant to bias correct the final result.
5601 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5604 // Load the 32-bit value into an XMM register.
5605 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5606 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5608 DAG.getIntPtrConstant(0)));
5610 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5611 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5612 DAG.getIntPtrConstant(0));
5614 // Or the load with the bias.
5615 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5616 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5617 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5619 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5620 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5621 MVT::v2f64, Bias)));
5622 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5623 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5624 DAG.getIntPtrConstant(0));
5626 // Subtract the bias.
5627 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5629 // Handle final rounding.
5630 EVT DestVT = Op.getValueType();
5632 if (DestVT.bitsLT(MVT::f64)) {
5633 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5634 DAG.getIntPtrConstant(0));
5635 } else if (DestVT.bitsGT(MVT::f64)) {
5636 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5639 // Handle final rounding.
5643 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
5644 SelectionDAG &DAG) const {
5645 SDValue N0 = Op.getOperand(0);
5646 DebugLoc dl = Op.getDebugLoc();
5648 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
5649 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5650 // the optimization here.
5651 if (DAG.SignBitIsZero(N0))
5652 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5654 EVT SrcVT = N0.getValueType();
5655 EVT DstVT = Op.getValueType();
5656 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
5657 return LowerUINT_TO_FP_i64(Op, DAG);
5658 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
5659 return LowerUINT_TO_FP_i32(Op, DAG);
5661 // Make a 64-bit buffer, and use it to build an FILD.
5662 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5663 if (SrcVT == MVT::i32) {
5664 SDValue WordOff = DAG.getConstant(4, getPointerTy());
5665 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5666 getPointerTy(), StackSlot, WordOff);
5667 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5668 StackSlot, NULL, 0, false, false, 0);
5669 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5670 OffsetSlot, NULL, 0, false, false, 0);
5671 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5675 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
5676 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5677 StackSlot, NULL, 0, false, false, 0);
5678 // For i64 source, we need to add the appropriate power of 2 if the input
5679 // was negative. This is the same as the optimization in
5680 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
5681 // we must be careful to do the computation in x87 extended precision, not
5682 // in SSE. (The generic code can't know it's OK to do this, or how to.)
5683 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
5684 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
5685 SDValue Fild = DAG.getNode(X86ISD::FILD, dl, Tys, Ops, 3);
5687 APInt FF(32, 0x5F800000ULL);
5689 // Check whether the sign bit is set.
5690 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
5691 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
5694 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
5695 SDValue FudgePtr = DAG.getConstantPool(
5696 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
5699 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
5700 SDValue Zero = DAG.getIntPtrConstant(0);
5701 SDValue Four = DAG.getIntPtrConstant(4);
5702 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
5704 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
5706 // Load the value out, extending it from f32 to f80.
5707 // FIXME: Avoid the extend by constructing the right constant pool?
5708 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
5709 FudgePtr, PseudoSourceValue::getConstantPool(),
5710 0, MVT::f32, false, false, 4);
5711 // Extend everything to 80 bits to force it to be done on x87.
5712 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
5713 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
5716 std::pair<SDValue,SDValue> X86TargetLowering::
5717 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
5718 DebugLoc dl = Op.getDebugLoc();
5720 EVT DstTy = Op.getValueType();
5723 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5727 assert(DstTy.getSimpleVT() <= MVT::i64 &&
5728 DstTy.getSimpleVT() >= MVT::i16 &&
5729 "Unknown FP_TO_SINT to lower!");
5731 // These are really Legal.
5732 if (DstTy == MVT::i32 &&
5733 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5734 return std::make_pair(SDValue(), SDValue());
5735 if (Subtarget->is64Bit() &&
5736 DstTy == MVT::i64 &&
5737 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5738 return std::make_pair(SDValue(), SDValue());
5740 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5742 MachineFunction &MF = DAG.getMachineFunction();
5743 unsigned MemSize = DstTy.getSizeInBits()/8;
5744 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5745 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5748 switch (DstTy.getSimpleVT().SimpleTy) {
5749 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5750 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5751 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5752 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5755 SDValue Chain = DAG.getEntryNode();
5756 SDValue Value = Op.getOperand(0);
5757 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5758 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5759 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5760 PseudoSourceValue::getFixedStack(SSFI), 0,
5762 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5764 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5766 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5767 Chain = Value.getValue(1);
5768 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5769 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5772 // Build the FP_TO_INT*_IN_MEM
5773 SDValue Ops[] = { Chain, Value, StackSlot };
5774 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5776 return std::make_pair(FIST, StackSlot);
5779 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
5780 SelectionDAG &DAG) const {
5781 if (Op.getValueType().isVector()) {
5782 if (Op.getValueType() == MVT::v2i32 &&
5783 Op.getOperand(0).getValueType() == MVT::v2f64) {
5789 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5790 SDValue FIST = Vals.first, StackSlot = Vals.second;
5791 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5792 if (FIST.getNode() == 0) return Op;
5795 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5796 FIST, StackSlot, NULL, 0, false, false, 0);
5799 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
5800 SelectionDAG &DAG) const {
5801 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5802 SDValue FIST = Vals.first, StackSlot = Vals.second;
5803 assert(FIST.getNode() && "Unexpected failure");
5806 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5807 FIST, StackSlot, NULL, 0, false, false, 0);
5810 SDValue X86TargetLowering::LowerFABS(SDValue Op,
5811 SelectionDAG &DAG) const {
5812 LLVMContext *Context = DAG.getContext();
5813 DebugLoc dl = Op.getDebugLoc();
5814 EVT VT = Op.getValueType();
5817 EltVT = VT.getVectorElementType();
5818 std::vector<Constant*> CV;
5819 if (EltVT == MVT::f64) {
5820 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5824 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5830 Constant *C = ConstantVector::get(CV);
5831 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5832 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5833 PseudoSourceValue::getConstantPool(), 0,
5835 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5838 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
5839 LLVMContext *Context = DAG.getContext();
5840 DebugLoc dl = Op.getDebugLoc();
5841 EVT VT = Op.getValueType();
5844 EltVT = VT.getVectorElementType();
5845 std::vector<Constant*> CV;
5846 if (EltVT == MVT::f64) {
5847 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5851 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5857 Constant *C = ConstantVector::get(CV);
5858 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5859 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5860 PseudoSourceValue::getConstantPool(), 0,
5862 if (VT.isVector()) {
5863 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5864 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5865 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5867 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5869 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5873 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5874 LLVMContext *Context = DAG.getContext();
5875 SDValue Op0 = Op.getOperand(0);
5876 SDValue Op1 = Op.getOperand(1);
5877 DebugLoc dl = Op.getDebugLoc();
5878 EVT VT = Op.getValueType();
5879 EVT SrcVT = Op1.getValueType();
5881 // If second operand is smaller, extend it first.
5882 if (SrcVT.bitsLT(VT)) {
5883 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5886 // And if it is bigger, shrink it first.
5887 if (SrcVT.bitsGT(VT)) {
5888 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5892 // At this point the operands and the result should have the same
5893 // type, and that won't be f80 since that is not custom lowered.
5895 // First get the sign bit of second operand.
5896 std::vector<Constant*> CV;
5897 if (SrcVT == MVT::f64) {
5898 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
5899 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5901 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
5902 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5903 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5904 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5906 Constant *C = ConstantVector::get(CV);
5907 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5908 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5909 PseudoSourceValue::getConstantPool(), 0,
5911 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5913 // Shift sign bit right or left if the two operands have different types.
5914 if (SrcVT.bitsGT(VT)) {
5915 // Op0 is MVT::f32, Op1 is MVT::f64.
5916 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5917 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5918 DAG.getConstant(32, MVT::i32));
5919 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5920 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5921 DAG.getIntPtrConstant(0));
5924 // Clear first operand sign bit.
5926 if (VT == MVT::f64) {
5927 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
5928 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5930 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
5931 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5932 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5933 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5935 C = ConstantVector::get(CV);
5936 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5937 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5938 PseudoSourceValue::getConstantPool(), 0,
5940 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5942 // Or the value with the sign bit.
5943 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
5946 /// Emit nodes that will be selected as "test Op0,Op0", or something
5948 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
5949 SelectionDAG &DAG) const {
5950 DebugLoc dl = Op.getDebugLoc();
5952 // CF and OF aren't always set the way we want. Determine which
5953 // of these we need.
5954 bool NeedCF = false;
5955 bool NeedOF = false;
5957 case X86::COND_A: case X86::COND_AE:
5958 case X86::COND_B: case X86::COND_BE:
5961 case X86::COND_G: case X86::COND_GE:
5962 case X86::COND_L: case X86::COND_LE:
5963 case X86::COND_O: case X86::COND_NO:
5969 // See if we can use the EFLAGS value from the operand instead of
5970 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
5971 // we prove that the arithmetic won't overflow, we can't use OF or CF.
5972 if (Op.getResNo() == 0 && !NeedOF && !NeedCF) {
5973 unsigned Opcode = 0;
5974 unsigned NumOperands = 0;
5975 switch (Op.getNode()->getOpcode()) {
5977 // Due to an isel shortcoming, be conservative if this add is
5978 // likely to be selected as part of a load-modify-store
5979 // instruction. When the root node in a match is a store, isel
5980 // doesn't know how to remap non-chain non-flag uses of other
5981 // nodes in the match, such as the ADD in this case. This leads
5982 // to the ADD being left around and reselected, with the result
5983 // being two adds in the output. Alas, even if none our users
5984 // are stores, that doesn't prove we're O.K. Ergo, if we have
5985 // any parents that aren't CopyToReg or SETCC, eschew INC/DEC.
5986 // A better fix seems to require climbing the DAG back to the
5987 // root, and it doesn't seem to be worth the effort.
5988 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
5989 UE = Op.getNode()->use_end(); UI != UE; ++UI)
5990 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
5992 if (ConstantSDNode *C =
5993 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
5994 // An add of one will be selected as an INC.
5995 if (C->getAPIntValue() == 1) {
5996 Opcode = X86ISD::INC;
6000 // An add of negative one (subtract of one) will be selected as a DEC.
6001 if (C->getAPIntValue().isAllOnesValue()) {
6002 Opcode = X86ISD::DEC;
6007 // Otherwise use a regular EFLAGS-setting add.
6008 Opcode = X86ISD::ADD;
6012 // If the primary and result isn't used, don't bother using X86ISD::AND,
6013 // because a TEST instruction will be better.
6014 bool NonFlagUse = false;
6015 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6016 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
6018 unsigned UOpNo = UI.getOperandNo();
6019 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
6020 // Look pass truncate.
6021 UOpNo = User->use_begin().getOperandNo();
6022 User = *User->use_begin();
6024 if (User->getOpcode() != ISD::BRCOND &&
6025 User->getOpcode() != ISD::SETCC &&
6026 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
6038 // Due to the ISEL shortcoming noted above, be conservative if this op is
6039 // likely to be selected as part of a load-modify-store instruction.
6040 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6041 UE = Op.getNode()->use_end(); UI != UE; ++UI)
6042 if (UI->getOpcode() == ISD::STORE)
6044 // Otherwise use a regular EFLAGS-setting instruction.
6045 switch (Op.getNode()->getOpcode()) {
6046 case ISD::SUB: Opcode = X86ISD::SUB; break;
6047 case ISD::OR: Opcode = X86ISD::OR; break;
6048 case ISD::XOR: Opcode = X86ISD::XOR; break;
6049 case ISD::AND: Opcode = X86ISD::AND; break;
6050 default: llvm_unreachable("unexpected operator!");
6061 return SDValue(Op.getNode(), 1);
6067 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
6068 SmallVector<SDValue, 4> Ops;
6069 for (unsigned i = 0; i != NumOperands; ++i)
6070 Ops.push_back(Op.getOperand(i));
6071 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
6072 DAG.ReplaceAllUsesWith(Op, New);
6073 return SDValue(New.getNode(), 1);
6077 // Otherwise just emit a CMP with 0, which is the TEST pattern.
6078 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6079 DAG.getConstant(0, Op.getValueType()));
6082 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
6084 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
6085 SelectionDAG &DAG) const {
6086 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
6087 if (C->getAPIntValue() == 0)
6088 return EmitTest(Op0, X86CC, DAG);
6090 DebugLoc dl = Op0.getDebugLoc();
6091 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
6094 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
6095 /// if it's possible.
6096 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
6097 DebugLoc dl, SelectionDAG &DAG) const {
6098 SDValue Op0 = And.getOperand(0);
6099 SDValue Op1 = And.getOperand(1);
6100 if (Op0.getOpcode() == ISD::TRUNCATE)
6101 Op0 = Op0.getOperand(0);
6102 if (Op1.getOpcode() == ISD::TRUNCATE)
6103 Op1 = Op1.getOperand(0);
6106 if (Op1.getOpcode() == ISD::SHL) {
6107 if (ConstantSDNode *And10C = dyn_cast<ConstantSDNode>(Op1.getOperand(0)))
6108 if (And10C->getZExtValue() == 1) {
6110 RHS = Op1.getOperand(1);
6112 } else if (Op0.getOpcode() == ISD::SHL) {
6113 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
6114 if (And00C->getZExtValue() == 1) {
6116 RHS = Op0.getOperand(1);
6118 } else if (Op1.getOpcode() == ISD::Constant) {
6119 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
6120 SDValue AndLHS = Op0;
6121 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
6122 LHS = AndLHS.getOperand(0);
6123 RHS = AndLHS.getOperand(1);
6127 if (LHS.getNode()) {
6128 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
6129 // instruction. Since the shift amount is in-range-or-undefined, we know
6130 // that doing a bittest on the i32 value is ok. We extend to i32 because
6131 // the encoding for the i16 version is larger than the i32 version.
6132 // Also promote i16 to i32 for performance / code size reason.
6133 if (LHS.getValueType() == MVT::i8 ||
6134 LHS.getValueType() == MVT::i16)
6135 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
6137 // If the operand types disagree, extend the shift amount to match. Since
6138 // BT ignores high bits (like shifts) we can use anyextend.
6139 if (LHS.getValueType() != RHS.getValueType())
6140 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
6142 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
6143 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
6144 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6145 DAG.getConstant(Cond, MVT::i8), BT);
6151 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
6152 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
6153 SDValue Op0 = Op.getOperand(0);
6154 SDValue Op1 = Op.getOperand(1);
6155 DebugLoc dl = Op.getDebugLoc();
6156 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6158 // Optimize to BT if possible.
6159 // Lower (X & (1 << N)) == 0 to BT(X, N).
6160 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
6161 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
6162 if (Op0.getOpcode() == ISD::AND &&
6164 Op1.getOpcode() == ISD::Constant &&
6165 cast<ConstantSDNode>(Op1)->getZExtValue() == 0 &&
6166 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6167 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
6168 if (NewSetCC.getNode())
6172 // Look for "(setcc) == / != 1" to avoid unncessary setcc.
6173 if (Op0.getOpcode() == X86ISD::SETCC &&
6174 Op1.getOpcode() == ISD::Constant &&
6175 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
6176 cast<ConstantSDNode>(Op1)->isNullValue()) &&
6177 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6178 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
6179 bool Invert = (CC == ISD::SETNE) ^
6180 cast<ConstantSDNode>(Op1)->isNullValue();
6182 CCode = X86::GetOppositeBranchCondition(CCode);
6183 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6184 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
6187 bool isFP = Op1.getValueType().isFloatingPoint();
6188 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
6189 if (X86CC == X86::COND_INVALID)
6192 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
6194 // Use sbb x, x to materialize carry bit into a GPR.
6195 if (X86CC == X86::COND_B)
6196 return DAG.getNode(ISD::AND, dl, MVT::i8,
6197 DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
6198 DAG.getConstant(X86CC, MVT::i8), Cond),
6199 DAG.getConstant(1, MVT::i8));
6201 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6202 DAG.getConstant(X86CC, MVT::i8), Cond);
6205 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
6207 SDValue Op0 = Op.getOperand(0);
6208 SDValue Op1 = Op.getOperand(1);
6209 SDValue CC = Op.getOperand(2);
6210 EVT VT = Op.getValueType();
6211 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6212 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
6213 DebugLoc dl = Op.getDebugLoc();
6217 EVT VT0 = Op0.getValueType();
6218 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
6219 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
6222 switch (SetCCOpcode) {
6225 case ISD::SETEQ: SSECC = 0; break;
6227 case ISD::SETGT: Swap = true; // Fallthrough
6229 case ISD::SETOLT: SSECC = 1; break;
6231 case ISD::SETGE: Swap = true; // Fallthrough
6233 case ISD::SETOLE: SSECC = 2; break;
6234 case ISD::SETUO: SSECC = 3; break;
6236 case ISD::SETNE: SSECC = 4; break;
6237 case ISD::SETULE: Swap = true;
6238 case ISD::SETUGE: SSECC = 5; break;
6239 case ISD::SETULT: Swap = true;
6240 case ISD::SETUGT: SSECC = 6; break;
6241 case ISD::SETO: SSECC = 7; break;
6244 std::swap(Op0, Op1);
6246 // In the two special cases we can't handle, emit two comparisons.
6248 if (SetCCOpcode == ISD::SETUEQ) {
6250 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
6251 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
6252 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
6254 else if (SetCCOpcode == ISD::SETONE) {
6256 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
6257 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
6258 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
6260 llvm_unreachable("Illegal FP comparison");
6262 // Handle all other FP comparisons here.
6263 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
6266 // We are handling one of the integer comparisons here. Since SSE only has
6267 // GT and EQ comparisons for integer, swapping operands and multiple
6268 // operations may be required for some comparisons.
6269 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
6270 bool Swap = false, Invert = false, FlipSigns = false;
6272 switch (VT.getSimpleVT().SimpleTy) {
6275 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
6277 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
6279 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
6280 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
6283 switch (SetCCOpcode) {
6285 case ISD::SETNE: Invert = true;
6286 case ISD::SETEQ: Opc = EQOpc; break;
6287 case ISD::SETLT: Swap = true;
6288 case ISD::SETGT: Opc = GTOpc; break;
6289 case ISD::SETGE: Swap = true;
6290 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
6291 case ISD::SETULT: Swap = true;
6292 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
6293 case ISD::SETUGE: Swap = true;
6294 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
6297 std::swap(Op0, Op1);
6299 // Since SSE has no unsigned integer comparisons, we need to flip the sign
6300 // bits of the inputs before performing those operations.
6302 EVT EltVT = VT.getVectorElementType();
6303 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
6305 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
6306 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
6308 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
6309 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
6312 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
6314 // If the logical-not of the result is required, perform that now.
6316 Result = DAG.getNOT(dl, Result, VT);
6321 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
6322 static bool isX86LogicalCmp(SDValue Op) {
6323 unsigned Opc = Op.getNode()->getOpcode();
6324 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
6326 if (Op.getResNo() == 1 &&
6327 (Opc == X86ISD::ADD ||
6328 Opc == X86ISD::SUB ||
6329 Opc == X86ISD::SMUL ||
6330 Opc == X86ISD::UMUL ||
6331 Opc == X86ISD::INC ||
6332 Opc == X86ISD::DEC ||
6333 Opc == X86ISD::OR ||
6334 Opc == X86ISD::XOR ||
6335 Opc == X86ISD::AND))
6341 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
6342 bool addTest = true;
6343 SDValue Cond = Op.getOperand(0);
6344 DebugLoc dl = Op.getDebugLoc();
6347 if (Cond.getOpcode() == ISD::SETCC) {
6348 SDValue NewCond = LowerSETCC(Cond, DAG);
6349 if (NewCond.getNode())
6353 // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
6354 SDValue Op1 = Op.getOperand(1);
6355 SDValue Op2 = Op.getOperand(2);
6356 if (Cond.getOpcode() == X86ISD::SETCC &&
6357 cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
6358 SDValue Cmp = Cond.getOperand(1);
6359 if (Cmp.getOpcode() == X86ISD::CMP) {
6360 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
6361 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
6362 ConstantSDNode *RHSC =
6363 dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
6364 if (N1C && N1C->isAllOnesValue() &&
6365 N2C && N2C->isNullValue() &&
6366 RHSC && RHSC->isNullValue()) {
6367 SDValue CmpOp0 = Cmp.getOperand(0);
6368 Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6369 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
6370 return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
6371 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
6376 // Look pass (and (setcc_carry (cmp ...)), 1).
6377 if (Cond.getOpcode() == ISD::AND &&
6378 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6379 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6380 if (C && C->getAPIntValue() == 1)
6381 Cond = Cond.getOperand(0);
6384 // If condition flag is set by a X86ISD::CMP, then use it as the condition
6385 // setting operand in place of the X86ISD::SETCC.
6386 if (Cond.getOpcode() == X86ISD::SETCC ||
6387 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6388 CC = Cond.getOperand(0);
6390 SDValue Cmp = Cond.getOperand(1);
6391 unsigned Opc = Cmp.getOpcode();
6392 EVT VT = Op.getValueType();
6394 bool IllegalFPCMov = false;
6395 if (VT.isFloatingPoint() && !VT.isVector() &&
6396 !isScalarFPTypeInSSEReg(VT)) // FPStack?
6397 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
6399 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
6400 Opc == X86ISD::BT) { // FIXME
6407 // Look pass the truncate.
6408 if (Cond.getOpcode() == ISD::TRUNCATE)
6409 Cond = Cond.getOperand(0);
6411 // We know the result of AND is compared against zero. Try to match
6413 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
6414 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6415 if (NewSetCC.getNode()) {
6416 CC = NewSetCC.getOperand(0);
6417 Cond = NewSetCC.getOperand(1);
6424 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6425 Cond = EmitTest(Cond, X86::COND_NE, DAG);
6428 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
6429 // condition is true.
6430 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
6431 SDValue Ops[] = { Op2, Op1, CC, Cond };
6432 return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
6435 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
6436 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
6437 // from the AND / OR.
6438 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
6439 Opc = Op.getOpcode();
6440 if (Opc != ISD::OR && Opc != ISD::AND)
6442 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6443 Op.getOperand(0).hasOneUse() &&
6444 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
6445 Op.getOperand(1).hasOneUse());
6448 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
6449 // 1 and that the SETCC node has a single use.
6450 static bool isXor1OfSetCC(SDValue Op) {
6451 if (Op.getOpcode() != ISD::XOR)
6453 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6454 if (N1C && N1C->getAPIntValue() == 1) {
6455 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6456 Op.getOperand(0).hasOneUse();
6461 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
6462 bool addTest = true;
6463 SDValue Chain = Op.getOperand(0);
6464 SDValue Cond = Op.getOperand(1);
6465 SDValue Dest = Op.getOperand(2);
6466 DebugLoc dl = Op.getDebugLoc();
6469 if (Cond.getOpcode() == ISD::SETCC) {
6470 SDValue NewCond = LowerSETCC(Cond, DAG);
6471 if (NewCond.getNode())
6475 // FIXME: LowerXALUO doesn't handle these!!
6476 else if (Cond.getOpcode() == X86ISD::ADD ||
6477 Cond.getOpcode() == X86ISD::SUB ||
6478 Cond.getOpcode() == X86ISD::SMUL ||
6479 Cond.getOpcode() == X86ISD::UMUL)
6480 Cond = LowerXALUO(Cond, DAG);
6483 // Look pass (and (setcc_carry (cmp ...)), 1).
6484 if (Cond.getOpcode() == ISD::AND &&
6485 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6486 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6487 if (C && C->getAPIntValue() == 1)
6488 Cond = Cond.getOperand(0);
6491 // If condition flag is set by a X86ISD::CMP, then use it as the condition
6492 // setting operand in place of the X86ISD::SETCC.
6493 if (Cond.getOpcode() == X86ISD::SETCC ||
6494 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6495 CC = Cond.getOperand(0);
6497 SDValue Cmp = Cond.getOperand(1);
6498 unsigned Opc = Cmp.getOpcode();
6499 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
6500 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
6504 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
6508 // These can only come from an arithmetic instruction with overflow,
6509 // e.g. SADDO, UADDO.
6510 Cond = Cond.getNode()->getOperand(1);
6517 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
6518 SDValue Cmp = Cond.getOperand(0).getOperand(1);
6519 if (CondOpc == ISD::OR) {
6520 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
6521 // two branches instead of an explicit OR instruction with a
6523 if (Cmp == Cond.getOperand(1).getOperand(1) &&
6524 isX86LogicalCmp(Cmp)) {
6525 CC = Cond.getOperand(0).getOperand(0);
6526 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6527 Chain, Dest, CC, Cmp);
6528 CC = Cond.getOperand(1).getOperand(0);
6532 } else { // ISD::AND
6533 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
6534 // two branches instead of an explicit AND instruction with a
6535 // separate test. However, we only do this if this block doesn't
6536 // have a fall-through edge, because this requires an explicit
6537 // jmp when the condition is false.
6538 if (Cmp == Cond.getOperand(1).getOperand(1) &&
6539 isX86LogicalCmp(Cmp) &&
6540 Op.getNode()->hasOneUse()) {
6541 X86::CondCode CCode =
6542 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6543 CCode = X86::GetOppositeBranchCondition(CCode);
6544 CC = DAG.getConstant(CCode, MVT::i8);
6545 SDValue User = SDValue(*Op.getNode()->use_begin(), 0);
6546 // Look for an unconditional branch following this conditional branch.
6547 // We need this because we need to reverse the successors in order
6548 // to implement FCMP_OEQ.
6549 if (User.getOpcode() == ISD::BR) {
6550 SDValue FalseBB = User.getOperand(1);
6552 DAG.UpdateNodeOperands(User, User.getOperand(0), Dest);
6553 assert(NewBR == User);
6556 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6557 Chain, Dest, CC, Cmp);
6558 X86::CondCode CCode =
6559 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
6560 CCode = X86::GetOppositeBranchCondition(CCode);
6561 CC = DAG.getConstant(CCode, MVT::i8);
6567 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
6568 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
6569 // It should be transformed during dag combiner except when the condition
6570 // is set by a arithmetics with overflow node.
6571 X86::CondCode CCode =
6572 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6573 CCode = X86::GetOppositeBranchCondition(CCode);
6574 CC = DAG.getConstant(CCode, MVT::i8);
6575 Cond = Cond.getOperand(0).getOperand(1);
6581 // Look pass the truncate.
6582 if (Cond.getOpcode() == ISD::TRUNCATE)
6583 Cond = Cond.getOperand(0);
6585 // We know the result of AND is compared against zero. Try to match
6587 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
6588 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6589 if (NewSetCC.getNode()) {
6590 CC = NewSetCC.getOperand(0);
6591 Cond = NewSetCC.getOperand(1);
6598 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6599 Cond = EmitTest(Cond, X86::COND_NE, DAG);
6601 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6602 Chain, Dest, CC, Cond);
6606 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
6607 // Calls to _alloca is needed to probe the stack when allocating more than 4k
6608 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
6609 // that the guard pages used by the OS virtual memory manager are allocated in
6610 // correct sequence.
6612 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6613 SelectionDAG &DAG) const {
6614 assert(Subtarget->isTargetCygMing() &&
6615 "This should be used only on Cygwin/Mingw targets");
6616 DebugLoc dl = Op.getDebugLoc();
6619 SDValue Chain = Op.getOperand(0);
6620 SDValue Size = Op.getOperand(1);
6621 // FIXME: Ensure alignment here
6625 EVT IntPtr = getPointerTy();
6626 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
6628 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
6629 Flag = Chain.getValue(1);
6631 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6633 Chain = DAG.getNode(X86ISD::MINGW_ALLOCA, dl, NodeTys, Chain, Flag);
6634 Flag = Chain.getValue(1);
6636 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
6638 SDValue Ops1[2] = { Chain.getValue(0), Chain };
6639 return DAG.getMergeValues(Ops1, 2, dl);
6642 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
6643 MachineFunction &MF = DAG.getMachineFunction();
6644 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
6646 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6647 DebugLoc dl = Op.getDebugLoc();
6649 if (!Subtarget->is64Bit()) {
6650 // vastart just stores the address of the VarArgsFrameIndex slot into the
6651 // memory location argument.
6652 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
6654 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0,
6659 // gp_offset (0 - 6 * 8)
6660 // fp_offset (48 - 48 + 8 * 16)
6661 // overflow_arg_area (point to parameters coming in memory).
6663 SmallVector<SDValue, 8> MemOps;
6664 SDValue FIN = Op.getOperand(1);
6666 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6667 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
6669 FIN, SV, 0, false, false, 0);
6670 MemOps.push_back(Store);
6673 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6674 FIN, DAG.getIntPtrConstant(4));
6675 Store = DAG.getStore(Op.getOperand(0), dl,
6676 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
6678 FIN, SV, 0, false, false, 0);
6679 MemOps.push_back(Store);
6681 // Store ptr to overflow_arg_area
6682 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6683 FIN, DAG.getIntPtrConstant(4));
6684 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
6686 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0,
6688 MemOps.push_back(Store);
6690 // Store ptr to reg_save_area.
6691 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6692 FIN, DAG.getIntPtrConstant(8));
6693 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
6695 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0,
6697 MemOps.push_back(Store);
6698 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6699 &MemOps[0], MemOps.size());
6702 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
6703 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6704 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6705 SDValue Chain = Op.getOperand(0);
6706 SDValue SrcPtr = Op.getOperand(1);
6707 SDValue SrcSV = Op.getOperand(2);
6709 report_fatal_error("VAArgInst is not yet implemented for x86-64!");
6713 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
6714 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6715 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6716 SDValue Chain = Op.getOperand(0);
6717 SDValue DstPtr = Op.getOperand(1);
6718 SDValue SrcPtr = Op.getOperand(2);
6719 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6720 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6721 DebugLoc dl = Op.getDebugLoc();
6723 return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6724 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
6725 false, DstSV, 0, SrcSV, 0);
6729 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
6730 DebugLoc dl = Op.getDebugLoc();
6731 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6733 default: return SDValue(); // Don't custom lower most intrinsics.
6734 // Comparison intrinsics.
6735 case Intrinsic::x86_sse_comieq_ss:
6736 case Intrinsic::x86_sse_comilt_ss:
6737 case Intrinsic::x86_sse_comile_ss:
6738 case Intrinsic::x86_sse_comigt_ss:
6739 case Intrinsic::x86_sse_comige_ss:
6740 case Intrinsic::x86_sse_comineq_ss:
6741 case Intrinsic::x86_sse_ucomieq_ss:
6742 case Intrinsic::x86_sse_ucomilt_ss:
6743 case Intrinsic::x86_sse_ucomile_ss:
6744 case Intrinsic::x86_sse_ucomigt_ss:
6745 case Intrinsic::x86_sse_ucomige_ss:
6746 case Intrinsic::x86_sse_ucomineq_ss:
6747 case Intrinsic::x86_sse2_comieq_sd:
6748 case Intrinsic::x86_sse2_comilt_sd:
6749 case Intrinsic::x86_sse2_comile_sd:
6750 case Intrinsic::x86_sse2_comigt_sd:
6751 case Intrinsic::x86_sse2_comige_sd:
6752 case Intrinsic::x86_sse2_comineq_sd:
6753 case Intrinsic::x86_sse2_ucomieq_sd:
6754 case Intrinsic::x86_sse2_ucomilt_sd:
6755 case Intrinsic::x86_sse2_ucomile_sd:
6756 case Intrinsic::x86_sse2_ucomigt_sd:
6757 case Intrinsic::x86_sse2_ucomige_sd:
6758 case Intrinsic::x86_sse2_ucomineq_sd: {
6760 ISD::CondCode CC = ISD::SETCC_INVALID;
6763 case Intrinsic::x86_sse_comieq_ss:
6764 case Intrinsic::x86_sse2_comieq_sd:
6768 case Intrinsic::x86_sse_comilt_ss:
6769 case Intrinsic::x86_sse2_comilt_sd:
6773 case Intrinsic::x86_sse_comile_ss:
6774 case Intrinsic::x86_sse2_comile_sd:
6778 case Intrinsic::x86_sse_comigt_ss:
6779 case Intrinsic::x86_sse2_comigt_sd:
6783 case Intrinsic::x86_sse_comige_ss:
6784 case Intrinsic::x86_sse2_comige_sd:
6788 case Intrinsic::x86_sse_comineq_ss:
6789 case Intrinsic::x86_sse2_comineq_sd:
6793 case Intrinsic::x86_sse_ucomieq_ss:
6794 case Intrinsic::x86_sse2_ucomieq_sd:
6795 Opc = X86ISD::UCOMI;
6798 case Intrinsic::x86_sse_ucomilt_ss:
6799 case Intrinsic::x86_sse2_ucomilt_sd:
6800 Opc = X86ISD::UCOMI;
6803 case Intrinsic::x86_sse_ucomile_ss:
6804 case Intrinsic::x86_sse2_ucomile_sd:
6805 Opc = X86ISD::UCOMI;
6808 case Intrinsic::x86_sse_ucomigt_ss:
6809 case Intrinsic::x86_sse2_ucomigt_sd:
6810 Opc = X86ISD::UCOMI;
6813 case Intrinsic::x86_sse_ucomige_ss:
6814 case Intrinsic::x86_sse2_ucomige_sd:
6815 Opc = X86ISD::UCOMI;
6818 case Intrinsic::x86_sse_ucomineq_ss:
6819 case Intrinsic::x86_sse2_ucomineq_sd:
6820 Opc = X86ISD::UCOMI;
6825 SDValue LHS = Op.getOperand(1);
6826 SDValue RHS = Op.getOperand(2);
6827 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6828 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
6829 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6830 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6831 DAG.getConstant(X86CC, MVT::i8), Cond);
6832 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6834 // ptest intrinsics. The intrinsic these come from are designed to return
6835 // an integer value, not just an instruction so lower it to the ptest
6836 // pattern and a setcc for the result.
6837 case Intrinsic::x86_sse41_ptestz:
6838 case Intrinsic::x86_sse41_ptestc:
6839 case Intrinsic::x86_sse41_ptestnzc:{
6842 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
6843 case Intrinsic::x86_sse41_ptestz:
6845 X86CC = X86::COND_E;
6847 case Intrinsic::x86_sse41_ptestc:
6849 X86CC = X86::COND_B;
6851 case Intrinsic::x86_sse41_ptestnzc:
6853 X86CC = X86::COND_A;
6857 SDValue LHS = Op.getOperand(1);
6858 SDValue RHS = Op.getOperand(2);
6859 SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
6860 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
6861 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
6862 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6865 // Fix vector shift instructions where the last operand is a non-immediate
6867 case Intrinsic::x86_sse2_pslli_w:
6868 case Intrinsic::x86_sse2_pslli_d:
6869 case Intrinsic::x86_sse2_pslli_q:
6870 case Intrinsic::x86_sse2_psrli_w:
6871 case Intrinsic::x86_sse2_psrli_d:
6872 case Intrinsic::x86_sse2_psrli_q:
6873 case Intrinsic::x86_sse2_psrai_w:
6874 case Intrinsic::x86_sse2_psrai_d:
6875 case Intrinsic::x86_mmx_pslli_w:
6876 case Intrinsic::x86_mmx_pslli_d:
6877 case Intrinsic::x86_mmx_pslli_q:
6878 case Intrinsic::x86_mmx_psrli_w:
6879 case Intrinsic::x86_mmx_psrli_d:
6880 case Intrinsic::x86_mmx_psrli_q:
6881 case Intrinsic::x86_mmx_psrai_w:
6882 case Intrinsic::x86_mmx_psrai_d: {
6883 SDValue ShAmt = Op.getOperand(2);
6884 if (isa<ConstantSDNode>(ShAmt))
6887 unsigned NewIntNo = 0;
6888 EVT ShAmtVT = MVT::v4i32;
6890 case Intrinsic::x86_sse2_pslli_w:
6891 NewIntNo = Intrinsic::x86_sse2_psll_w;
6893 case Intrinsic::x86_sse2_pslli_d:
6894 NewIntNo = Intrinsic::x86_sse2_psll_d;
6896 case Intrinsic::x86_sse2_pslli_q:
6897 NewIntNo = Intrinsic::x86_sse2_psll_q;
6899 case Intrinsic::x86_sse2_psrli_w:
6900 NewIntNo = Intrinsic::x86_sse2_psrl_w;
6902 case Intrinsic::x86_sse2_psrli_d:
6903 NewIntNo = Intrinsic::x86_sse2_psrl_d;
6905 case Intrinsic::x86_sse2_psrli_q:
6906 NewIntNo = Intrinsic::x86_sse2_psrl_q;
6908 case Intrinsic::x86_sse2_psrai_w:
6909 NewIntNo = Intrinsic::x86_sse2_psra_w;
6911 case Intrinsic::x86_sse2_psrai_d:
6912 NewIntNo = Intrinsic::x86_sse2_psra_d;
6915 ShAmtVT = MVT::v2i32;
6917 case Intrinsic::x86_mmx_pslli_w:
6918 NewIntNo = Intrinsic::x86_mmx_psll_w;
6920 case Intrinsic::x86_mmx_pslli_d:
6921 NewIntNo = Intrinsic::x86_mmx_psll_d;
6923 case Intrinsic::x86_mmx_pslli_q:
6924 NewIntNo = Intrinsic::x86_mmx_psll_q;
6926 case Intrinsic::x86_mmx_psrli_w:
6927 NewIntNo = Intrinsic::x86_mmx_psrl_w;
6929 case Intrinsic::x86_mmx_psrli_d:
6930 NewIntNo = Intrinsic::x86_mmx_psrl_d;
6932 case Intrinsic::x86_mmx_psrli_q:
6933 NewIntNo = Intrinsic::x86_mmx_psrl_q;
6935 case Intrinsic::x86_mmx_psrai_w:
6936 NewIntNo = Intrinsic::x86_mmx_psra_w;
6938 case Intrinsic::x86_mmx_psrai_d:
6939 NewIntNo = Intrinsic::x86_mmx_psra_d;
6941 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
6947 // The vector shift intrinsics with scalars uses 32b shift amounts but
6948 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
6952 ShOps[1] = DAG.getConstant(0, MVT::i32);
6953 if (ShAmtVT == MVT::v4i32) {
6954 ShOps[2] = DAG.getUNDEF(MVT::i32);
6955 ShOps[3] = DAG.getUNDEF(MVT::i32);
6956 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
6958 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
6961 EVT VT = Op.getValueType();
6962 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
6963 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
6964 DAG.getConstant(NewIntNo, MVT::i32),
6965 Op.getOperand(1), ShAmt);
6970 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
6971 SelectionDAG &DAG) const {
6972 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6973 DebugLoc dl = Op.getDebugLoc();
6976 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
6978 DAG.getConstant(TD->getPointerSize(),
6979 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
6980 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6981 DAG.getNode(ISD::ADD, dl, getPointerTy(),
6983 NULL, 0, false, false, 0);
6986 // Just load the return address.
6987 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
6988 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
6989 RetAddrFI, NULL, 0, false, false, 0);
6992 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
6993 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
6994 MFI->setFrameAddressIsTaken(true);
6995 EVT VT = Op.getValueType();
6996 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
6997 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6998 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
6999 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
7001 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0,
7006 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
7007 SelectionDAG &DAG) const {
7008 return DAG.getIntPtrConstant(2*TD->getPointerSize());
7011 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
7012 MachineFunction &MF = DAG.getMachineFunction();
7013 SDValue Chain = Op.getOperand(0);
7014 SDValue Offset = Op.getOperand(1);
7015 SDValue Handler = Op.getOperand(2);
7016 DebugLoc dl = Op.getDebugLoc();
7018 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
7020 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
7022 SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
7023 DAG.getIntPtrConstant(-TD->getPointerSize()));
7024 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
7025 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0, false, false, 0);
7026 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
7027 MF.getRegInfo().addLiveOut(StoreAddrReg);
7029 return DAG.getNode(X86ISD::EH_RETURN, dl,
7031 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
7034 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
7035 SelectionDAG &DAG) const {
7036 SDValue Root = Op.getOperand(0);
7037 SDValue Trmp = Op.getOperand(1); // trampoline
7038 SDValue FPtr = Op.getOperand(2); // nested function
7039 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
7040 DebugLoc dl = Op.getDebugLoc();
7042 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7044 if (Subtarget->is64Bit()) {
7045 SDValue OutChains[6];
7047 // Large code-model.
7048 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
7049 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
7051 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
7052 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
7054 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
7056 // Load the pointer to the nested function into R11.
7057 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
7058 SDValue Addr = Trmp;
7059 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7060 Addr, TrmpAddr, 0, false, false, 0);
7062 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7063 DAG.getConstant(2, MVT::i64));
7064 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2,
7067 // Load the 'nest' parameter value into R10.
7068 // R10 is specified in X86CallingConv.td
7069 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
7070 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7071 DAG.getConstant(10, MVT::i64));
7072 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7073 Addr, TrmpAddr, 10, false, false, 0);
7075 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7076 DAG.getConstant(12, MVT::i64));
7077 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12,
7080 // Jump to the nested function.
7081 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
7082 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7083 DAG.getConstant(20, MVT::i64));
7084 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7085 Addr, TrmpAddr, 20, false, false, 0);
7087 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
7088 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7089 DAG.getConstant(22, MVT::i64));
7090 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
7091 TrmpAddr, 22, false, false, 0);
7094 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
7095 return DAG.getMergeValues(Ops, 2, dl);
7097 const Function *Func =
7098 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
7099 CallingConv::ID CC = Func->getCallingConv();
7104 llvm_unreachable("Unsupported calling convention");
7105 case CallingConv::C:
7106 case CallingConv::X86_StdCall: {
7107 // Pass 'nest' parameter in ECX.
7108 // Must be kept in sync with X86CallingConv.td
7111 // Check that ECX wasn't needed by an 'inreg' parameter.
7112 const FunctionType *FTy = Func->getFunctionType();
7113 const AttrListPtr &Attrs = Func->getAttributes();
7115 if (!Attrs.isEmpty() && !Func->isVarArg()) {
7116 unsigned InRegCount = 0;
7119 for (FunctionType::param_iterator I = FTy->param_begin(),
7120 E = FTy->param_end(); I != E; ++I, ++Idx)
7121 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
7122 // FIXME: should only count parameters that are lowered to integers.
7123 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
7125 if (InRegCount > 2) {
7126 report_fatal_error("Nest register in use - reduce number of inreg parameters!");
7131 case CallingConv::X86_FastCall:
7132 case CallingConv::X86_ThisCall:
7133 case CallingConv::Fast:
7134 // Pass 'nest' parameter in EAX.
7135 // Must be kept in sync with X86CallingConv.td
7140 SDValue OutChains[4];
7143 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7144 DAG.getConstant(10, MVT::i32));
7145 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
7147 // This is storing the opcode for MOV32ri.
7148 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
7149 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
7150 OutChains[0] = DAG.getStore(Root, dl,
7151 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
7152 Trmp, TrmpAddr, 0, false, false, 0);
7154 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7155 DAG.getConstant(1, MVT::i32));
7156 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1,
7159 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
7160 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7161 DAG.getConstant(5, MVT::i32));
7162 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
7163 TrmpAddr, 5, false, false, 1);
7165 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7166 DAG.getConstant(6, MVT::i32));
7167 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6,
7171 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
7172 return DAG.getMergeValues(Ops, 2, dl);
7176 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
7177 SelectionDAG &DAG) const {
7179 The rounding mode is in bits 11:10 of FPSR, and has the following
7186 FLT_ROUNDS, on the other hand, expects the following:
7193 To perform the conversion, we do:
7194 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
7197 MachineFunction &MF = DAG.getMachineFunction();
7198 const TargetMachine &TM = MF.getTarget();
7199 const TargetFrameInfo &TFI = *TM.getFrameInfo();
7200 unsigned StackAlignment = TFI.getStackAlignment();
7201 EVT VT = Op.getValueType();
7202 DebugLoc dl = Op.getDebugLoc();
7204 // Save FP Control Word to stack slot
7205 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
7206 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7208 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
7209 DAG.getEntryNode(), StackSlot);
7211 // Load FP Control Word from stack slot
7212 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0,
7215 // Transform as necessary
7217 DAG.getNode(ISD::SRL, dl, MVT::i16,
7218 DAG.getNode(ISD::AND, dl, MVT::i16,
7219 CWD, DAG.getConstant(0x800, MVT::i16)),
7220 DAG.getConstant(11, MVT::i8));
7222 DAG.getNode(ISD::SRL, dl, MVT::i16,
7223 DAG.getNode(ISD::AND, dl, MVT::i16,
7224 CWD, DAG.getConstant(0x400, MVT::i16)),
7225 DAG.getConstant(9, MVT::i8));
7228 DAG.getNode(ISD::AND, dl, MVT::i16,
7229 DAG.getNode(ISD::ADD, dl, MVT::i16,
7230 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
7231 DAG.getConstant(1, MVT::i16)),
7232 DAG.getConstant(3, MVT::i16));
7235 return DAG.getNode((VT.getSizeInBits() < 16 ?
7236 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7239 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
7240 EVT VT = Op.getValueType();
7242 unsigned NumBits = VT.getSizeInBits();
7243 DebugLoc dl = Op.getDebugLoc();
7245 Op = Op.getOperand(0);
7246 if (VT == MVT::i8) {
7247 // Zero extend to i32 since there is not an i8 bsr.
7249 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7252 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
7253 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7254 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
7256 // If src is zero (i.e. bsr sets ZF), returns NumBits.
7259 DAG.getConstant(NumBits+NumBits-1, OpVT),
7260 DAG.getConstant(X86::COND_E, MVT::i8),
7263 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7265 // Finally xor with NumBits-1.
7266 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
7269 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7273 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
7274 EVT VT = Op.getValueType();
7276 unsigned NumBits = VT.getSizeInBits();
7277 DebugLoc dl = Op.getDebugLoc();
7279 Op = Op.getOperand(0);
7280 if (VT == MVT::i8) {
7282 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7285 // Issue a bsf (scan bits forward) which also sets EFLAGS.
7286 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7287 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
7289 // If src is zero (i.e. bsf sets ZF), returns NumBits.
7292 DAG.getConstant(NumBits, OpVT),
7293 DAG.getConstant(X86::COND_E, MVT::i8),
7296 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7299 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7303 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
7304 EVT VT = Op.getValueType();
7305 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
7306 DebugLoc dl = Op.getDebugLoc();
7308 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
7309 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
7310 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
7311 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
7312 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
7314 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
7315 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
7316 // return AloBlo + AloBhi + AhiBlo;
7318 SDValue A = Op.getOperand(0);
7319 SDValue B = Op.getOperand(1);
7321 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7322 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7323 A, DAG.getConstant(32, MVT::i32));
7324 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7325 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7326 B, DAG.getConstant(32, MVT::i32));
7327 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7328 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7330 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7331 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7333 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7334 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7336 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7337 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7338 AloBhi, DAG.getConstant(32, MVT::i32));
7339 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7340 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7341 AhiBlo, DAG.getConstant(32, MVT::i32));
7342 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
7343 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
7348 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
7349 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
7350 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
7351 // looks for this combo and may remove the "setcc" instruction if the "setcc"
7352 // has only one use.
7353 SDNode *N = Op.getNode();
7354 SDValue LHS = N->getOperand(0);
7355 SDValue RHS = N->getOperand(1);
7356 unsigned BaseOp = 0;
7358 DebugLoc dl = Op.getDebugLoc();
7360 switch (Op.getOpcode()) {
7361 default: llvm_unreachable("Unknown ovf instruction!");
7363 // A subtract of one will be selected as a INC. Note that INC doesn't
7364 // set CF, so we can't do this for UADDO.
7365 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7366 if (C->getAPIntValue() == 1) {
7367 BaseOp = X86ISD::INC;
7371 BaseOp = X86ISD::ADD;
7375 BaseOp = X86ISD::ADD;
7379 // A subtract of one will be selected as a DEC. Note that DEC doesn't
7380 // set CF, so we can't do this for USUBO.
7381 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7382 if (C->getAPIntValue() == 1) {
7383 BaseOp = X86ISD::DEC;
7387 BaseOp = X86ISD::SUB;
7391 BaseOp = X86ISD::SUB;
7395 BaseOp = X86ISD::SMUL;
7399 BaseOp = X86ISD::UMUL;
7404 // Also sets EFLAGS.
7405 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
7406 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
7409 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
7410 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
7412 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
7416 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
7417 EVT T = Op.getValueType();
7418 DebugLoc dl = Op.getDebugLoc();
7421 switch(T.getSimpleVT().SimpleTy) {
7423 assert(false && "Invalid value type!");
7424 case MVT::i8: Reg = X86::AL; size = 1; break;
7425 case MVT::i16: Reg = X86::AX; size = 2; break;
7426 case MVT::i32: Reg = X86::EAX; size = 4; break;
7428 assert(Subtarget->is64Bit() && "Node not type legal!");
7429 Reg = X86::RAX; size = 8;
7432 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
7433 Op.getOperand(2), SDValue());
7434 SDValue Ops[] = { cpIn.getValue(0),
7437 DAG.getTargetConstant(size, MVT::i8),
7439 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7440 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
7442 DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
7446 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
7447 SelectionDAG &DAG) const {
7448 assert(Subtarget->is64Bit() && "Result not type legalized?");
7449 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7450 SDValue TheChain = Op.getOperand(0);
7451 DebugLoc dl = Op.getDebugLoc();
7452 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7453 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
7454 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
7456 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
7457 DAG.getConstant(32, MVT::i8));
7459 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
7462 return DAG.getMergeValues(Ops, 2, dl);
7465 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
7466 SDNode *Node = Op.getNode();
7467 DebugLoc dl = Node->getDebugLoc();
7468 EVT T = Node->getValueType(0);
7469 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
7470 DAG.getConstant(0, T), Node->getOperand(2));
7471 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
7472 cast<AtomicSDNode>(Node)->getMemoryVT(),
7473 Node->getOperand(0),
7474 Node->getOperand(1), negOp,
7475 cast<AtomicSDNode>(Node)->getSrcValue(),
7476 cast<AtomicSDNode>(Node)->getAlignment());
7479 /// LowerOperation - Provide custom lowering hooks for some operations.
7481 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7482 switch (Op.getOpcode()) {
7483 default: llvm_unreachable("Should not custom lower this!");
7484 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
7485 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
7486 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
7487 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
7488 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7489 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7490 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7491 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
7492 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
7493 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
7494 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7495 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
7496 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
7497 case ISD::SHL_PARTS:
7498 case ISD::SRA_PARTS:
7499 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
7500 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
7501 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
7502 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
7503 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
7504 case ISD::FABS: return LowerFABS(Op, DAG);
7505 case ISD::FNEG: return LowerFNEG(Op, DAG);
7506 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
7507 case ISD::SETCC: return LowerSETCC(Op, DAG);
7508 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
7509 case ISD::SELECT: return LowerSELECT(Op, DAG);
7510 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
7511 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
7512 case ISD::VASTART: return LowerVASTART(Op, DAG);
7513 case ISD::VAARG: return LowerVAARG(Op, DAG);
7514 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
7515 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7516 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
7517 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
7518 case ISD::FRAME_TO_ARGS_OFFSET:
7519 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
7520 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
7521 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
7522 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
7523 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
7524 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
7525 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
7526 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
7532 case ISD::UMULO: return LowerXALUO(Op, DAG);
7533 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
7537 void X86TargetLowering::
7538 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
7539 SelectionDAG &DAG, unsigned NewOp) const {
7540 EVT T = Node->getValueType(0);
7541 DebugLoc dl = Node->getDebugLoc();
7542 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
7544 SDValue Chain = Node->getOperand(0);
7545 SDValue In1 = Node->getOperand(1);
7546 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7547 Node->getOperand(2), DAG.getIntPtrConstant(0));
7548 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7549 Node->getOperand(2), DAG.getIntPtrConstant(1));
7550 SDValue Ops[] = { Chain, In1, In2L, In2H };
7551 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7553 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
7554 cast<MemSDNode>(Node)->getMemOperand());
7555 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7556 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7557 Results.push_back(Result.getValue(2));
7560 /// ReplaceNodeResults - Replace a node with an illegal result type
7561 /// with a new node built out of custom code.
7562 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7563 SmallVectorImpl<SDValue>&Results,
7564 SelectionDAG &DAG) const {
7565 DebugLoc dl = N->getDebugLoc();
7566 switch (N->getOpcode()) {
7568 assert(false && "Do not know how to custom type legalize this operation!");
7570 case ISD::FP_TO_SINT: {
7571 std::pair<SDValue,SDValue> Vals =
7572 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
7573 SDValue FIST = Vals.first, StackSlot = Vals.second;
7574 if (FIST.getNode() != 0) {
7575 EVT VT = N->getValueType(0);
7576 // Return a load from the stack slot.
7577 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0,
7582 case ISD::READCYCLECOUNTER: {
7583 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7584 SDValue TheChain = N->getOperand(0);
7585 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7586 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7588 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7590 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7591 SDValue Ops[] = { eax, edx };
7592 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7593 Results.push_back(edx.getValue(1));
7596 case ISD::ATOMIC_CMP_SWAP: {
7597 EVT T = N->getValueType(0);
7598 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7599 SDValue cpInL, cpInH;
7600 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7601 DAG.getConstant(0, MVT::i32));
7602 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7603 DAG.getConstant(1, MVT::i32));
7604 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7605 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7607 SDValue swapInL, swapInH;
7608 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7609 DAG.getConstant(0, MVT::i32));
7610 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7611 DAG.getConstant(1, MVT::i32));
7612 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7614 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7615 swapInL.getValue(1));
7616 SDValue Ops[] = { swapInH.getValue(0),
7618 swapInH.getValue(1) };
7619 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7620 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7621 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7622 MVT::i32, Result.getValue(1));
7623 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7624 MVT::i32, cpOutL.getValue(2));
7625 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7626 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7627 Results.push_back(cpOutH.getValue(1));
7630 case ISD::ATOMIC_LOAD_ADD:
7631 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7633 case ISD::ATOMIC_LOAD_AND:
7634 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7636 case ISD::ATOMIC_LOAD_NAND:
7637 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7639 case ISD::ATOMIC_LOAD_OR:
7640 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7642 case ISD::ATOMIC_LOAD_SUB:
7643 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7645 case ISD::ATOMIC_LOAD_XOR:
7646 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7648 case ISD::ATOMIC_SWAP:
7649 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7654 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7656 default: return NULL;
7657 case X86ISD::BSF: return "X86ISD::BSF";
7658 case X86ISD::BSR: return "X86ISD::BSR";
7659 case X86ISD::SHLD: return "X86ISD::SHLD";
7660 case X86ISD::SHRD: return "X86ISD::SHRD";
7661 case X86ISD::FAND: return "X86ISD::FAND";
7662 case X86ISD::FOR: return "X86ISD::FOR";
7663 case X86ISD::FXOR: return "X86ISD::FXOR";
7664 case X86ISD::FSRL: return "X86ISD::FSRL";
7665 case X86ISD::FILD: return "X86ISD::FILD";
7666 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
7667 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7668 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7669 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7670 case X86ISD::FLD: return "X86ISD::FLD";
7671 case X86ISD::FST: return "X86ISD::FST";
7672 case X86ISD::CALL: return "X86ISD::CALL";
7673 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
7674 case X86ISD::BT: return "X86ISD::BT";
7675 case X86ISD::CMP: return "X86ISD::CMP";
7676 case X86ISD::COMI: return "X86ISD::COMI";
7677 case X86ISD::UCOMI: return "X86ISD::UCOMI";
7678 case X86ISD::SETCC: return "X86ISD::SETCC";
7679 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
7680 case X86ISD::CMOV: return "X86ISD::CMOV";
7681 case X86ISD::BRCOND: return "X86ISD::BRCOND";
7682 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
7683 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
7684 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
7685 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
7686 case X86ISD::Wrapper: return "X86ISD::Wrapper";
7687 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
7688 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
7689 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
7690 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
7691 case X86ISD::PINSRB: return "X86ISD::PINSRB";
7692 case X86ISD::PINSRW: return "X86ISD::PINSRW";
7693 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
7694 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
7695 case X86ISD::FMAX: return "X86ISD::FMAX";
7696 case X86ISD::FMIN: return "X86ISD::FMIN";
7697 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
7698 case X86ISD::FRCP: return "X86ISD::FRCP";
7699 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
7700 case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7701 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
7702 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
7703 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
7704 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
7705 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
7706 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
7707 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
7708 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
7709 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
7710 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
7711 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
7712 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
7713 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
7714 case X86ISD::VSHL: return "X86ISD::VSHL";
7715 case X86ISD::VSRL: return "X86ISD::VSRL";
7716 case X86ISD::CMPPD: return "X86ISD::CMPPD";
7717 case X86ISD::CMPPS: return "X86ISD::CMPPS";
7718 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
7719 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
7720 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
7721 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
7722 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
7723 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
7724 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
7725 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
7726 case X86ISD::ADD: return "X86ISD::ADD";
7727 case X86ISD::SUB: return "X86ISD::SUB";
7728 case X86ISD::SMUL: return "X86ISD::SMUL";
7729 case X86ISD::UMUL: return "X86ISD::UMUL";
7730 case X86ISD::INC: return "X86ISD::INC";
7731 case X86ISD::DEC: return "X86ISD::DEC";
7732 case X86ISD::OR: return "X86ISD::OR";
7733 case X86ISD::XOR: return "X86ISD::XOR";
7734 case X86ISD::AND: return "X86ISD::AND";
7735 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
7736 case X86ISD::PTEST: return "X86ISD::PTEST";
7737 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
7738 case X86ISD::MINGW_ALLOCA: return "X86ISD::MINGW_ALLOCA";
7742 // isLegalAddressingMode - Return true if the addressing mode represented
7743 // by AM is legal for this target, for a load/store of the specified type.
7744 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7745 const Type *Ty) const {
7746 // X86 supports extremely general addressing modes.
7747 CodeModel::Model M = getTargetMachine().getCodeModel();
7749 // X86 allows a sign-extended 32-bit immediate field as a displacement.
7750 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
7755 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7757 // If a reference to this global requires an extra load, we can't fold it.
7758 if (isGlobalStubReference(GVFlags))
7761 // If BaseGV requires a register for the PIC base, we cannot also have a
7762 // BaseReg specified.
7763 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
7766 // If lower 4G is not available, then we must use rip-relative addressing.
7767 if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
7777 // These scales always work.
7782 // These scales are formed with basereg+scalereg. Only accept if there is
7787 default: // Other stuff never works.
7795 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7796 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7798 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7799 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7800 if (NumBits1 <= NumBits2)
7805 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7806 if (!VT1.isInteger() || !VT2.isInteger())
7808 unsigned NumBits1 = VT1.getSizeInBits();
7809 unsigned NumBits2 = VT2.getSizeInBits();
7810 if (NumBits1 <= NumBits2)
7815 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7816 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7817 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
7820 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7821 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7822 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7825 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
7826 // i16 instructions are longer (0x66 prefix) and potentially slower.
7827 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7830 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7831 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7832 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7833 /// are assumed to be legal.
7835 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
7837 // Very little shuffling can be done for 64-bit vectors right now.
7838 if (VT.getSizeInBits() == 64)
7839 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
7841 // FIXME: pshufb, blends, shifts.
7842 return (VT.getVectorNumElements() == 2 ||
7843 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7844 isMOVLMask(M, VT) ||
7845 isSHUFPMask(M, VT) ||
7846 isPSHUFDMask(M, VT) ||
7847 isPSHUFHWMask(M, VT) ||
7848 isPSHUFLWMask(M, VT) ||
7849 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
7850 isUNPCKLMask(M, VT) ||
7851 isUNPCKHMask(M, VT) ||
7852 isUNPCKL_v_undef_Mask(M, VT) ||
7853 isUNPCKH_v_undef_Mask(M, VT));
7857 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
7859 unsigned NumElts = VT.getVectorNumElements();
7860 // FIXME: This collection of masks seems suspect.
7863 if (NumElts == 4 && VT.getSizeInBits() == 128) {
7864 return (isMOVLMask(Mask, VT) ||
7865 isCommutedMOVLMask(Mask, VT, true) ||
7866 isSHUFPMask(Mask, VT) ||
7867 isCommutedSHUFPMask(Mask, VT));
7872 //===----------------------------------------------------------------------===//
7873 // X86 Scheduler Hooks
7874 //===----------------------------------------------------------------------===//
7876 // private utility function
7878 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7879 MachineBasicBlock *MBB,
7887 TargetRegisterClass *RC,
7888 bool invSrc) const {
7889 // For the atomic bitwise operator, we generate
7892 // ld t1 = [bitinstr.addr]
7893 // op t2 = t1, [bitinstr.val]
7895 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7897 // fallthrough -->nextMBB
7898 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7899 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7900 MachineFunction::iterator MBBIter = MBB;
7903 /// First build the CFG
7904 MachineFunction *F = MBB->getParent();
7905 MachineBasicBlock *thisMBB = MBB;
7906 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
7907 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
7908 F->insert(MBBIter, newMBB);
7909 F->insert(MBBIter, nextMBB);
7911 // Move all successors to thisMBB to nextMBB
7912 nextMBB->transferSuccessors(thisMBB);
7914 // Update thisMBB to fall through to newMBB
7915 thisMBB->addSuccessor(newMBB);
7917 // newMBB jumps to itself and fall through to nextMBB
7918 newMBB->addSuccessor(nextMBB);
7919 newMBB->addSuccessor(newMBB);
7921 // Insert instructions into newMBB based on incoming instruction
7922 assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
7923 "unexpected number of operands");
7924 DebugLoc dl = bInstr->getDebugLoc();
7925 MachineOperand& destOper = bInstr->getOperand(0);
7926 MachineOperand* argOpers[2 + X86AddrNumOperands];
7927 int numArgs = bInstr->getNumOperands() - 1;
7928 for (int i=0; i < numArgs; ++i)
7929 argOpers[i] = &bInstr->getOperand(i+1);
7931 // x86 address has 4 operands: base, index, scale, and displacement
7932 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
7933 int valArgIndx = lastAddrIndx + 1;
7935 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
7936 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
7937 for (int i=0; i <= lastAddrIndx; ++i)
7938 (*MIB).addOperand(*argOpers[i]);
7940 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
7942 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
7947 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
7948 assert((argOpers[valArgIndx]->isReg() ||
7949 argOpers[valArgIndx]->isImm()) &&
7951 if (argOpers[valArgIndx]->isReg())
7952 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
7954 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
7956 (*MIB).addOperand(*argOpers[valArgIndx]);
7958 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
7961 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
7962 for (int i=0; i <= lastAddrIndx; ++i)
7963 (*MIB).addOperand(*argOpers[i]);
7965 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
7966 (*MIB).setMemRefs(bInstr->memoperands_begin(),
7967 bInstr->memoperands_end());
7969 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
7973 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
7975 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
7979 // private utility function: 64 bit atomics on 32 bit host.
7981 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
7982 MachineBasicBlock *MBB,
7987 bool invSrc) const {
7988 // For the atomic bitwise operator, we generate
7989 // thisMBB (instructions are in pairs, except cmpxchg8b)
7990 // ld t1,t2 = [bitinstr.addr]
7992 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
7993 // op t5, t6 <- out1, out2, [bitinstr.val]
7994 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
7995 // mov ECX, EBX <- t5, t6
7996 // mov EAX, EDX <- t1, t2
7997 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
7998 // mov t3, t4 <- EAX, EDX
8000 // result in out1, out2
8001 // fallthrough -->nextMBB
8003 const TargetRegisterClass *RC = X86::GR32RegisterClass;
8004 const unsigned LoadOpc = X86::MOV32rm;
8005 const unsigned copyOpc = X86::MOV32rr;
8006 const unsigned NotOpc = X86::NOT32r;
8007 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8008 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8009 MachineFunction::iterator MBBIter = MBB;
8012 /// First build the CFG
8013 MachineFunction *F = MBB->getParent();
8014 MachineBasicBlock *thisMBB = MBB;
8015 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8016 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8017 F->insert(MBBIter, newMBB);
8018 F->insert(MBBIter, nextMBB);
8020 // Move all successors to thisMBB to nextMBB
8021 nextMBB->transferSuccessors(thisMBB);
8023 // Update thisMBB to fall through to newMBB
8024 thisMBB->addSuccessor(newMBB);
8026 // newMBB jumps to itself and fall through to nextMBB
8027 newMBB->addSuccessor(nextMBB);
8028 newMBB->addSuccessor(newMBB);
8030 DebugLoc dl = bInstr->getDebugLoc();
8031 // Insert instructions into newMBB based on incoming instruction
8032 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
8033 assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
8034 "unexpected number of operands");
8035 MachineOperand& dest1Oper = bInstr->getOperand(0);
8036 MachineOperand& dest2Oper = bInstr->getOperand(1);
8037 MachineOperand* argOpers[2 + X86AddrNumOperands];
8038 for (int i=0; i < 2 + X86AddrNumOperands; ++i) {
8039 argOpers[i] = &bInstr->getOperand(i+2);
8041 // We use some of the operands multiple times, so conservatively just
8042 // clear any kill flags that might be present.
8043 if (argOpers[i]->isReg() && argOpers[i]->isUse())
8044 argOpers[i]->setIsKill(false);
8047 // x86 address has 5 operands: base, index, scale, displacement, and segment.
8048 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8050 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
8051 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
8052 for (int i=0; i <= lastAddrIndx; ++i)
8053 (*MIB).addOperand(*argOpers[i]);
8054 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8055 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
8056 // add 4 to displacement.
8057 for (int i=0; i <= lastAddrIndx-2; ++i)
8058 (*MIB).addOperand(*argOpers[i]);
8059 MachineOperand newOp3 = *(argOpers[3]);
8061 newOp3.setImm(newOp3.getImm()+4);
8063 newOp3.setOffset(newOp3.getOffset()+4);
8064 (*MIB).addOperand(newOp3);
8065 (*MIB).addOperand(*argOpers[lastAddrIndx]);
8067 // t3/4 are defined later, at the bottom of the loop
8068 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
8069 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
8070 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
8071 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
8072 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
8073 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
8075 // The subsequent operations should be using the destination registers of
8076 //the PHI instructions.
8078 t1 = F->getRegInfo().createVirtualRegister(RC);
8079 t2 = F->getRegInfo().createVirtualRegister(RC);
8080 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
8081 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
8083 t1 = dest1Oper.getReg();
8084 t2 = dest2Oper.getReg();
8087 int valArgIndx = lastAddrIndx + 1;
8088 assert((argOpers[valArgIndx]->isReg() ||
8089 argOpers[valArgIndx]->isImm()) &&
8091 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
8092 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
8093 if (argOpers[valArgIndx]->isReg())
8094 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
8096 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
8097 if (regOpcL != X86::MOV32rr)
8099 (*MIB).addOperand(*argOpers[valArgIndx]);
8100 assert(argOpers[valArgIndx + 1]->isReg() ==
8101 argOpers[valArgIndx]->isReg());
8102 assert(argOpers[valArgIndx + 1]->isImm() ==
8103 argOpers[valArgIndx]->isImm());
8104 if (argOpers[valArgIndx + 1]->isReg())
8105 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
8107 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
8108 if (regOpcH != X86::MOV32rr)
8110 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
8112 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
8114 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
8117 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
8119 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
8122 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
8123 for (int i=0; i <= lastAddrIndx; ++i)
8124 (*MIB).addOperand(*argOpers[i]);
8126 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8127 (*MIB).setMemRefs(bInstr->memoperands_begin(),
8128 bInstr->memoperands_end());
8130 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
8131 MIB.addReg(X86::EAX);
8132 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
8133 MIB.addReg(X86::EDX);
8136 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8138 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
8142 // private utility function
8144 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
8145 MachineBasicBlock *MBB,
8146 unsigned cmovOpc) const {
8147 // For the atomic min/max operator, we generate
8150 // ld t1 = [min/max.addr]
8151 // mov t2 = [min/max.val]
8153 // cmov[cond] t2 = t1
8155 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
8157 // fallthrough -->nextMBB
8159 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8160 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8161 MachineFunction::iterator MBBIter = MBB;
8164 /// First build the CFG
8165 MachineFunction *F = MBB->getParent();
8166 MachineBasicBlock *thisMBB = MBB;
8167 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8168 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8169 F->insert(MBBIter, newMBB);
8170 F->insert(MBBIter, nextMBB);
8172 // Move all successors of thisMBB to nextMBB
8173 nextMBB->transferSuccessors(thisMBB);
8175 // Update thisMBB to fall through to newMBB
8176 thisMBB->addSuccessor(newMBB);
8178 // newMBB jumps to newMBB and fall through to nextMBB
8179 newMBB->addSuccessor(nextMBB);
8180 newMBB->addSuccessor(newMBB);
8182 DebugLoc dl = mInstr->getDebugLoc();
8183 // Insert instructions into newMBB based on incoming instruction
8184 assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
8185 "unexpected number of operands");
8186 MachineOperand& destOper = mInstr->getOperand(0);
8187 MachineOperand* argOpers[2 + X86AddrNumOperands];
8188 int numArgs = mInstr->getNumOperands() - 1;
8189 for (int i=0; i < numArgs; ++i)
8190 argOpers[i] = &mInstr->getOperand(i+1);
8192 // x86 address has 4 operands: base, index, scale, and displacement
8193 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8194 int valArgIndx = lastAddrIndx + 1;
8196 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8197 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
8198 for (int i=0; i <= lastAddrIndx; ++i)
8199 (*MIB).addOperand(*argOpers[i]);
8201 // We only support register and immediate values
8202 assert((argOpers[valArgIndx]->isReg() ||
8203 argOpers[valArgIndx]->isImm()) &&
8206 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8207 if (argOpers[valArgIndx]->isReg())
8208 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8210 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8211 (*MIB).addOperand(*argOpers[valArgIndx]);
8213 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
8216 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
8221 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8222 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
8226 // Cmp and exchange if none has modified the memory location
8227 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
8228 for (int i=0; i <= lastAddrIndx; ++i)
8229 (*MIB).addOperand(*argOpers[i]);
8231 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8232 (*MIB).setMemRefs(mInstr->memoperands_begin(),
8233 mInstr->memoperands_end());
8235 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
8236 MIB.addReg(X86::EAX);
8239 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8241 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
8245 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
8246 // all of this code can be replaced with that in the .td file.
8248 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
8249 unsigned numArgs, bool memArg) const {
8251 MachineFunction *F = BB->getParent();
8252 DebugLoc dl = MI->getDebugLoc();
8253 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8257 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
8259 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
8261 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
8263 for (unsigned i = 0; i < numArgs; ++i) {
8264 MachineOperand &Op = MI->getOperand(i+1);
8266 if (!(Op.isReg() && Op.isImplicit()))
8270 BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
8273 F->DeleteMachineInstr(MI);
8279 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
8281 MachineBasicBlock *MBB) const {
8282 // Emit code to save XMM registers to the stack. The ABI says that the
8283 // number of registers to save is given in %al, so it's theoretically
8284 // possible to do an indirect jump trick to avoid saving all of them,
8285 // however this code takes a simpler approach and just executes all
8286 // of the stores if %al is non-zero. It's less code, and it's probably
8287 // easier on the hardware branch predictor, and stores aren't all that
8288 // expensive anyway.
8290 // Create the new basic blocks. One block contains all the XMM stores,
8291 // and one block is the final destination regardless of whether any
8292 // stores were performed.
8293 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8294 MachineFunction *F = MBB->getParent();
8295 MachineFunction::iterator MBBIter = MBB;
8297 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
8298 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
8299 F->insert(MBBIter, XMMSaveMBB);
8300 F->insert(MBBIter, EndMBB);
8303 // Move any original successors of MBB to the end block.
8304 EndMBB->transferSuccessors(MBB);
8305 // The original block will now fall through to the XMM save block.
8306 MBB->addSuccessor(XMMSaveMBB);
8307 // The XMMSaveMBB will fall through to the end block.
8308 XMMSaveMBB->addSuccessor(EndMBB);
8310 // Now add the instructions.
8311 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8312 DebugLoc DL = MI->getDebugLoc();
8314 unsigned CountReg = MI->getOperand(0).getReg();
8315 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
8316 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
8318 if (!Subtarget->isTargetWin64()) {
8319 // If %al is 0, branch around the XMM save block.
8320 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
8321 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
8322 MBB->addSuccessor(EndMBB);
8325 // In the XMM save block, save all the XMM argument registers.
8326 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
8327 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
8328 MachineMemOperand *MMO =
8329 F->getMachineMemOperand(
8330 PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
8331 MachineMemOperand::MOStore, Offset,
8332 /*Size=*/16, /*Align=*/16);
8333 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
8334 .addFrameIndex(RegSaveFrameIndex)
8335 .addImm(/*Scale=*/1)
8336 .addReg(/*IndexReg=*/0)
8337 .addImm(/*Disp=*/Offset)
8338 .addReg(/*Segment=*/0)
8339 .addReg(MI->getOperand(i).getReg())
8340 .addMemOperand(MMO);
8343 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8349 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
8350 MachineBasicBlock *BB) const {
8351 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8352 DebugLoc DL = MI->getDebugLoc();
8354 // To "insert" a SELECT_CC instruction, we actually have to insert the
8355 // diamond control-flow pattern. The incoming instruction knows the
8356 // destination vreg to set, the condition code register to branch on, the
8357 // true/false values to select between, and a branch opcode to use.
8358 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8359 MachineFunction::iterator It = BB;
8365 // cmpTY ccX, r1, r2
8367 // fallthrough --> copy0MBB
8368 MachineBasicBlock *thisMBB = BB;
8369 MachineFunction *F = BB->getParent();
8370 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8371 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8373 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
8374 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
8375 F->insert(It, copy0MBB);
8376 F->insert(It, sinkMBB);
8377 // Update machine-CFG edges by first adding all successors of the current
8378 // block to the new block which will contain the Phi node for the select.
8379 for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
8380 E = BB->succ_end(); I != E; ++I)
8381 sinkMBB->addSuccessor(*I);
8382 // Next, remove all successors of the current block, and add the true
8383 // and fallthrough blocks as its successors.
8384 while (!BB->succ_empty())
8385 BB->removeSuccessor(BB->succ_begin());
8386 // Add the true and fallthrough blocks as its successors.
8387 BB->addSuccessor(copy0MBB);
8388 BB->addSuccessor(sinkMBB);
8391 // %FalseValue = ...
8392 // # fallthrough to sinkMBB
8393 copy0MBB->addSuccessor(sinkMBB);
8396 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8398 BuildMI(sinkMBB, DL, TII->get(X86::PHI), MI->getOperand(0).getReg())
8399 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8400 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8402 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8407 X86TargetLowering::EmitLoweredMingwAlloca(MachineInstr *MI,
8408 MachineBasicBlock *BB) const {
8409 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8410 DebugLoc DL = MI->getDebugLoc();
8411 MachineFunction *F = BB->getParent();
8413 // The lowering is pretty easy: we're just emitting the call to _alloca. The
8414 // non-trivial part is impdef of ESP.
8415 // FIXME: The code should be tweaked as soon as we'll try to do codegen for
8418 BuildMI(BB, DL, TII->get(X86::CALLpcrel32))
8419 .addExternalSymbol("_alloca")
8420 .addReg(X86::EAX, RegState::Implicit)
8421 .addReg(X86::ESP, RegState::Implicit)
8422 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
8423 .addReg(X86::ESP, RegState::Define | RegState::Implicit);
8425 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8430 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8431 MachineBasicBlock *BB) const {
8432 switch (MI->getOpcode()) {
8433 default: assert(false && "Unexpected instr type to insert");
8434 case X86::MINGW_ALLOCA:
8435 return EmitLoweredMingwAlloca(MI, BB);
8437 case X86::CMOV_V1I64:
8438 case X86::CMOV_FR32:
8439 case X86::CMOV_FR64:
8440 case X86::CMOV_V4F32:
8441 case X86::CMOV_V2F64:
8442 case X86::CMOV_V2I64:
8443 case X86::CMOV_GR16:
8444 case X86::CMOV_GR32:
8445 case X86::CMOV_RFP32:
8446 case X86::CMOV_RFP64:
8447 case X86::CMOV_RFP80:
8448 return EmitLoweredSelect(MI, BB);
8450 case X86::FP32_TO_INT16_IN_MEM:
8451 case X86::FP32_TO_INT32_IN_MEM:
8452 case X86::FP32_TO_INT64_IN_MEM:
8453 case X86::FP64_TO_INT16_IN_MEM:
8454 case X86::FP64_TO_INT32_IN_MEM:
8455 case X86::FP64_TO_INT64_IN_MEM:
8456 case X86::FP80_TO_INT16_IN_MEM:
8457 case X86::FP80_TO_INT32_IN_MEM:
8458 case X86::FP80_TO_INT64_IN_MEM: {
8459 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8460 DebugLoc DL = MI->getDebugLoc();
8462 // Change the floating point control register to use "round towards zero"
8463 // mode when truncating to an integer value.
8464 MachineFunction *F = BB->getParent();
8465 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
8466 addFrameReference(BuildMI(BB, DL, TII->get(X86::FNSTCW16m)), CWFrameIdx);
8468 // Load the old value of the high byte of the control word...
8470 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
8471 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16rm), OldCW),
8474 // Set the high part to be round to zero...
8475 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
8478 // Reload the modified control word now...
8479 addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8481 // Restore the memory image of control word to original value
8482 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
8485 // Get the X86 opcode to use.
8487 switch (MI->getOpcode()) {
8488 default: llvm_unreachable("illegal opcode!");
8489 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
8490 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
8491 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
8492 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
8493 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
8494 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
8495 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
8496 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
8497 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
8501 MachineOperand &Op = MI->getOperand(0);
8503 AM.BaseType = X86AddressMode::RegBase;
8504 AM.Base.Reg = Op.getReg();
8506 AM.BaseType = X86AddressMode::FrameIndexBase;
8507 AM.Base.FrameIndex = Op.getIndex();
8509 Op = MI->getOperand(1);
8511 AM.Scale = Op.getImm();
8512 Op = MI->getOperand(2);
8514 AM.IndexReg = Op.getImm();
8515 Op = MI->getOperand(3);
8516 if (Op.isGlobal()) {
8517 AM.GV = Op.getGlobal();
8519 AM.Disp = Op.getImm();
8521 addFullAddress(BuildMI(BB, DL, TII->get(Opc)), AM)
8522 .addReg(MI->getOperand(X86AddrNumOperands).getReg());
8524 // Reload the original control word now.
8525 addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8527 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8530 // String/text processing lowering.
8531 case X86::PCMPISTRM128REG:
8532 return EmitPCMP(MI, BB, 3, false /* in-mem */);
8533 case X86::PCMPISTRM128MEM:
8534 return EmitPCMP(MI, BB, 3, true /* in-mem */);
8535 case X86::PCMPESTRM128REG:
8536 return EmitPCMP(MI, BB, 5, false /* in mem */);
8537 case X86::PCMPESTRM128MEM:
8538 return EmitPCMP(MI, BB, 5, true /* in mem */);
8541 case X86::ATOMAND32:
8542 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8543 X86::AND32ri, X86::MOV32rm,
8544 X86::LCMPXCHG32, X86::MOV32rr,
8545 X86::NOT32r, X86::EAX,
8546 X86::GR32RegisterClass);
8548 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
8549 X86::OR32ri, X86::MOV32rm,
8550 X86::LCMPXCHG32, X86::MOV32rr,
8551 X86::NOT32r, X86::EAX,
8552 X86::GR32RegisterClass);
8553 case X86::ATOMXOR32:
8554 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
8555 X86::XOR32ri, X86::MOV32rm,
8556 X86::LCMPXCHG32, X86::MOV32rr,
8557 X86::NOT32r, X86::EAX,
8558 X86::GR32RegisterClass);
8559 case X86::ATOMNAND32:
8560 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8561 X86::AND32ri, X86::MOV32rm,
8562 X86::LCMPXCHG32, X86::MOV32rr,
8563 X86::NOT32r, X86::EAX,
8564 X86::GR32RegisterClass, true);
8565 case X86::ATOMMIN32:
8566 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
8567 case X86::ATOMMAX32:
8568 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
8569 case X86::ATOMUMIN32:
8570 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
8571 case X86::ATOMUMAX32:
8572 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
8574 case X86::ATOMAND16:
8575 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8576 X86::AND16ri, X86::MOV16rm,
8577 X86::LCMPXCHG16, X86::MOV16rr,
8578 X86::NOT16r, X86::AX,
8579 X86::GR16RegisterClass);
8581 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
8582 X86::OR16ri, X86::MOV16rm,
8583 X86::LCMPXCHG16, X86::MOV16rr,
8584 X86::NOT16r, X86::AX,
8585 X86::GR16RegisterClass);
8586 case X86::ATOMXOR16:
8587 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
8588 X86::XOR16ri, X86::MOV16rm,
8589 X86::LCMPXCHG16, X86::MOV16rr,
8590 X86::NOT16r, X86::AX,
8591 X86::GR16RegisterClass);
8592 case X86::ATOMNAND16:
8593 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8594 X86::AND16ri, X86::MOV16rm,
8595 X86::LCMPXCHG16, X86::MOV16rr,
8596 X86::NOT16r, X86::AX,
8597 X86::GR16RegisterClass, true);
8598 case X86::ATOMMIN16:
8599 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
8600 case X86::ATOMMAX16:
8601 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
8602 case X86::ATOMUMIN16:
8603 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
8604 case X86::ATOMUMAX16:
8605 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
8608 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8609 X86::AND8ri, X86::MOV8rm,
8610 X86::LCMPXCHG8, X86::MOV8rr,
8611 X86::NOT8r, X86::AL,
8612 X86::GR8RegisterClass);
8614 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
8615 X86::OR8ri, X86::MOV8rm,
8616 X86::LCMPXCHG8, X86::MOV8rr,
8617 X86::NOT8r, X86::AL,
8618 X86::GR8RegisterClass);
8620 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
8621 X86::XOR8ri, X86::MOV8rm,
8622 X86::LCMPXCHG8, X86::MOV8rr,
8623 X86::NOT8r, X86::AL,
8624 X86::GR8RegisterClass);
8625 case X86::ATOMNAND8:
8626 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8627 X86::AND8ri, X86::MOV8rm,
8628 X86::LCMPXCHG8, X86::MOV8rr,
8629 X86::NOT8r, X86::AL,
8630 X86::GR8RegisterClass, true);
8631 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
8632 // This group is for 64-bit host.
8633 case X86::ATOMAND64:
8634 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8635 X86::AND64ri32, X86::MOV64rm,
8636 X86::LCMPXCHG64, X86::MOV64rr,
8637 X86::NOT64r, X86::RAX,
8638 X86::GR64RegisterClass);
8640 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
8641 X86::OR64ri32, X86::MOV64rm,
8642 X86::LCMPXCHG64, X86::MOV64rr,
8643 X86::NOT64r, X86::RAX,
8644 X86::GR64RegisterClass);
8645 case X86::ATOMXOR64:
8646 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
8647 X86::XOR64ri32, X86::MOV64rm,
8648 X86::LCMPXCHG64, X86::MOV64rr,
8649 X86::NOT64r, X86::RAX,
8650 X86::GR64RegisterClass);
8651 case X86::ATOMNAND64:
8652 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8653 X86::AND64ri32, X86::MOV64rm,
8654 X86::LCMPXCHG64, X86::MOV64rr,
8655 X86::NOT64r, X86::RAX,
8656 X86::GR64RegisterClass, true);
8657 case X86::ATOMMIN64:
8658 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
8659 case X86::ATOMMAX64:
8660 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
8661 case X86::ATOMUMIN64:
8662 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
8663 case X86::ATOMUMAX64:
8664 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
8666 // This group does 64-bit operations on a 32-bit host.
8667 case X86::ATOMAND6432:
8668 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8669 X86::AND32rr, X86::AND32rr,
8670 X86::AND32ri, X86::AND32ri,
8672 case X86::ATOMOR6432:
8673 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8674 X86::OR32rr, X86::OR32rr,
8675 X86::OR32ri, X86::OR32ri,
8677 case X86::ATOMXOR6432:
8678 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8679 X86::XOR32rr, X86::XOR32rr,
8680 X86::XOR32ri, X86::XOR32ri,
8682 case X86::ATOMNAND6432:
8683 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8684 X86::AND32rr, X86::AND32rr,
8685 X86::AND32ri, X86::AND32ri,
8687 case X86::ATOMADD6432:
8688 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8689 X86::ADD32rr, X86::ADC32rr,
8690 X86::ADD32ri, X86::ADC32ri,
8692 case X86::ATOMSUB6432:
8693 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8694 X86::SUB32rr, X86::SBB32rr,
8695 X86::SUB32ri, X86::SBB32ri,
8697 case X86::ATOMSWAP6432:
8698 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8699 X86::MOV32rr, X86::MOV32rr,
8700 X86::MOV32ri, X86::MOV32ri,
8702 case X86::VASTART_SAVE_XMM_REGS:
8703 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
8707 //===----------------------------------------------------------------------===//
8708 // X86 Optimization Hooks
8709 //===----------------------------------------------------------------------===//
8711 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8715 const SelectionDAG &DAG,
8716 unsigned Depth) const {
8717 unsigned Opc = Op.getOpcode();
8718 assert((Opc >= ISD::BUILTIN_OP_END ||
8719 Opc == ISD::INTRINSIC_WO_CHAIN ||
8720 Opc == ISD::INTRINSIC_W_CHAIN ||
8721 Opc == ISD::INTRINSIC_VOID) &&
8722 "Should use MaskedValueIsZero if you don't know whether Op"
8723 " is a target node!");
8725 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
8737 // These nodes' second result is a boolean.
8738 if (Op.getResNo() == 0)
8742 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
8743 Mask.getBitWidth() - 1);
8748 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
8749 /// node is a GlobalAddress + offset.
8750 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
8751 const GlobalValue* &GA,
8752 int64_t &Offset) const {
8753 if (N->getOpcode() == X86ISD::Wrapper) {
8754 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
8755 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
8756 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
8760 return TargetLowering::isGAPlusOffset(N, GA, Offset);
8763 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8764 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8765 /// if the load addresses are consecutive, non-overlapping, and in the right
8767 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8768 const TargetLowering &TLI) {
8769 DebugLoc dl = N->getDebugLoc();
8770 EVT VT = N->getValueType(0);
8771 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8773 if (VT.getSizeInBits() != 128)
8776 SmallVector<SDValue, 16> Elts;
8777 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
8778 Elts.push_back(DAG.getShuffleScalarElt(SVN, i));
8780 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
8783 /// PerformShuffleCombine - Detect vector gather/scatter index generation
8784 /// and convert it from being a bunch of shuffles and extracts to a simple
8785 /// store and scalar loads to extract the elements.
8786 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
8787 const TargetLowering &TLI) {
8788 SDValue InputVector = N->getOperand(0);
8790 // Only operate on vectors of 4 elements, where the alternative shuffling
8791 // gets to be more expensive.
8792 if (InputVector.getValueType() != MVT::v4i32)
8795 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
8796 // single use which is a sign-extend or zero-extend, and all elements are
8798 SmallVector<SDNode *, 4> Uses;
8799 unsigned ExtractedElements = 0;
8800 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
8801 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
8802 if (UI.getUse().getResNo() != InputVector.getResNo())
8805 SDNode *Extract = *UI;
8806 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8809 if (Extract->getValueType(0) != MVT::i32)
8811 if (!Extract->hasOneUse())
8813 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
8814 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
8816 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
8819 // Record which element was extracted.
8820 ExtractedElements |=
8821 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
8823 Uses.push_back(Extract);
8826 // If not all the elements were used, this may not be worthwhile.
8827 if (ExtractedElements != 15)
8830 // Ok, we've now decided to do the transformation.
8831 DebugLoc dl = InputVector.getDebugLoc();
8833 // Store the value to a temporary stack slot.
8834 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
8835 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr, NULL, 0,
8838 // Replace each use (extract) with a load of the appropriate element.
8839 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
8840 UE = Uses.end(); UI != UE; ++UI) {
8841 SDNode *Extract = *UI;
8843 // Compute the element's address.
8844 SDValue Idx = Extract->getOperand(1);
8846 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
8847 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
8848 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
8850 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), OffsetVal, StackPtr);
8853 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch, ScalarAddr,
8854 NULL, 0, false, false, 0);
8856 // Replace the exact with the load.
8857 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
8860 // The replacement was made in place; don't return anything.
8864 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
8865 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
8866 const X86Subtarget *Subtarget) {
8867 DebugLoc DL = N->getDebugLoc();
8868 SDValue Cond = N->getOperand(0);
8869 // Get the LHS/RHS of the select.
8870 SDValue LHS = N->getOperand(1);
8871 SDValue RHS = N->getOperand(2);
8873 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
8874 // instructions match the semantics of the common C idiom x<y?x:y but not
8875 // x<=y?x:y, because of how they handle negative zero (which can be
8876 // ignored in unsafe-math mode).
8877 if (Subtarget->hasSSE2() &&
8878 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
8879 Cond.getOpcode() == ISD::SETCC) {
8880 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
8882 unsigned Opcode = 0;
8883 // Check for x CC y ? x : y.
8884 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
8885 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
8889 // Converting this to a min would handle NaNs incorrectly, and swapping
8890 // the operands would cause it to handle comparisons between positive
8891 // and negative zero incorrectly.
8892 if (!FiniteOnlyFPMath() &&
8893 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
8894 if (!UnsafeFPMath &&
8895 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8897 std::swap(LHS, RHS);
8899 Opcode = X86ISD::FMIN;
8902 // Converting this to a min would handle comparisons between positive
8903 // and negative zero incorrectly.
8904 if (!UnsafeFPMath &&
8905 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
8907 Opcode = X86ISD::FMIN;
8910 // Converting this to a min would handle both negative zeros and NaNs
8911 // incorrectly, but we can swap the operands to fix both.
8912 std::swap(LHS, RHS);
8916 Opcode = X86ISD::FMIN;
8920 // Converting this to a max would handle comparisons between positive
8921 // and negative zero incorrectly.
8922 if (!UnsafeFPMath &&
8923 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
8925 Opcode = X86ISD::FMAX;
8928 // Converting this to a max would handle NaNs incorrectly, and swapping
8929 // the operands would cause it to handle comparisons between positive
8930 // and negative zero incorrectly.
8931 if (!FiniteOnlyFPMath() &&
8932 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
8933 if (!UnsafeFPMath &&
8934 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
8936 std::swap(LHS, RHS);
8938 Opcode = X86ISD::FMAX;
8941 // Converting this to a max would handle both negative zeros and NaNs
8942 // incorrectly, but we can swap the operands to fix both.
8943 std::swap(LHS, RHS);
8947 Opcode = X86ISD::FMAX;
8950 // Check for x CC y ? y : x -- a min/max with reversed arms.
8951 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
8952 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
8956 // Converting this to a min would handle comparisons between positive
8957 // and negative zero incorrectly, and swapping the operands would
8958 // cause it to handle NaNs incorrectly.
8959 if (!UnsafeFPMath &&
8960 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
8961 if (!FiniteOnlyFPMath() &&
8962 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
8964 std::swap(LHS, RHS);
8966 Opcode = X86ISD::FMIN;
8969 // Converting this to a min would handle NaNs incorrectly.
8970 if (!UnsafeFPMath &&
8971 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
8973 Opcode = X86ISD::FMIN;
8976 // Converting this to a min would handle both negative zeros and NaNs
8977 // incorrectly, but we can swap the operands to fix both.
8978 std::swap(LHS, RHS);
8982 Opcode = X86ISD::FMIN;
8986 // Converting this to a max would handle NaNs incorrectly.
8987 if (!FiniteOnlyFPMath() &&
8988 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
8990 Opcode = X86ISD::FMAX;
8993 // Converting this to a max would handle comparisons between positive
8994 // and negative zero incorrectly, and swapping the operands would
8995 // cause it to handle NaNs incorrectly.
8996 if (!UnsafeFPMath &&
8997 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
8998 if (!FiniteOnlyFPMath() &&
8999 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9001 std::swap(LHS, RHS);
9003 Opcode = X86ISD::FMAX;
9006 // Converting this to a max would handle both negative zeros and NaNs
9007 // incorrectly, but we can swap the operands to fix both.
9008 std::swap(LHS, RHS);
9012 Opcode = X86ISD::FMAX;
9018 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
9021 // If this is a select between two integer constants, try to do some
9023 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
9024 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
9025 // Don't do this for crazy integer types.
9026 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
9027 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
9028 // so that TrueC (the true value) is larger than FalseC.
9029 bool NeedsCondInvert = false;
9031 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
9032 // Efficiently invertible.
9033 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
9034 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
9035 isa<ConstantSDNode>(Cond.getOperand(1))))) {
9036 NeedsCondInvert = true;
9037 std::swap(TrueC, FalseC);
9040 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
9041 if (FalseC->getAPIntValue() == 0 &&
9042 TrueC->getAPIntValue().isPowerOf2()) {
9043 if (NeedsCondInvert) // Invert the condition if needed.
9044 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9045 DAG.getConstant(1, Cond.getValueType()));
9047 // Zero extend the condition if needed.
9048 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
9050 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9051 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
9052 DAG.getConstant(ShAmt, MVT::i8));
9055 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
9056 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9057 if (NeedsCondInvert) // Invert the condition if needed.
9058 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9059 DAG.getConstant(1, Cond.getValueType()));
9061 // Zero extend the condition if needed.
9062 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9063 FalseC->getValueType(0), Cond);
9064 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9065 SDValue(FalseC, 0));
9068 // Optimize cases that will turn into an LEA instruction. This requires
9069 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9070 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9071 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9072 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9074 bool isFastMultiplier = false;
9076 switch ((unsigned char)Diff) {
9078 case 1: // result = add base, cond
9079 case 2: // result = lea base( , cond*2)
9080 case 3: // result = lea base(cond, cond*2)
9081 case 4: // result = lea base( , cond*4)
9082 case 5: // result = lea base(cond, cond*4)
9083 case 8: // result = lea base( , cond*8)
9084 case 9: // result = lea base(cond, cond*8)
9085 isFastMultiplier = true;
9090 if (isFastMultiplier) {
9091 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9092 if (NeedsCondInvert) // Invert the condition if needed.
9093 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9094 DAG.getConstant(1, Cond.getValueType()));
9096 // Zero extend the condition if needed.
9097 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9099 // Scale the condition by the difference.
9101 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9102 DAG.getConstant(Diff, Cond.getValueType()));
9104 // Add the base if non-zero.
9105 if (FalseC->getAPIntValue() != 0)
9106 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9107 SDValue(FalseC, 0));
9117 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
9118 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
9119 TargetLowering::DAGCombinerInfo &DCI) {
9120 DebugLoc DL = N->getDebugLoc();
9122 // If the flag operand isn't dead, don't touch this CMOV.
9123 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
9126 // If this is a select between two integer constants, try to do some
9127 // optimizations. Note that the operands are ordered the opposite of SELECT
9129 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
9130 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9131 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
9132 // larger than FalseC (the false value).
9133 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
9135 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
9136 CC = X86::GetOppositeBranchCondition(CC);
9137 std::swap(TrueC, FalseC);
9140 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
9141 // This is efficient for any integer data type (including i8/i16) and
9143 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
9144 SDValue Cond = N->getOperand(3);
9145 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9146 DAG.getConstant(CC, MVT::i8), Cond);
9148 // Zero extend the condition if needed.
9149 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
9151 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9152 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
9153 DAG.getConstant(ShAmt, MVT::i8));
9154 if (N->getNumValues() == 2) // Dead flag value?
9155 return DCI.CombineTo(N, Cond, SDValue());
9159 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
9160 // for any integer data type, including i8/i16.
9161 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9162 SDValue Cond = N->getOperand(3);
9163 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9164 DAG.getConstant(CC, MVT::i8), Cond);
9166 // Zero extend the condition if needed.
9167 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9168 FalseC->getValueType(0), Cond);
9169 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9170 SDValue(FalseC, 0));
9172 if (N->getNumValues() == 2) // Dead flag value?
9173 return DCI.CombineTo(N, Cond, SDValue());
9177 // Optimize cases that will turn into an LEA instruction. This requires
9178 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9179 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9180 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9181 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9183 bool isFastMultiplier = false;
9185 switch ((unsigned char)Diff) {
9187 case 1: // result = add base, cond
9188 case 2: // result = lea base( , cond*2)
9189 case 3: // result = lea base(cond, cond*2)
9190 case 4: // result = lea base( , cond*4)
9191 case 5: // result = lea base(cond, cond*4)
9192 case 8: // result = lea base( , cond*8)
9193 case 9: // result = lea base(cond, cond*8)
9194 isFastMultiplier = true;
9199 if (isFastMultiplier) {
9200 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9201 SDValue Cond = N->getOperand(3);
9202 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9203 DAG.getConstant(CC, MVT::i8), Cond);
9204 // Zero extend the condition if needed.
9205 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9207 // Scale the condition by the difference.
9209 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9210 DAG.getConstant(Diff, Cond.getValueType()));
9212 // Add the base if non-zero.
9213 if (FalseC->getAPIntValue() != 0)
9214 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9215 SDValue(FalseC, 0));
9216 if (N->getNumValues() == 2) // Dead flag value?
9217 return DCI.CombineTo(N, Cond, SDValue());
9227 /// PerformMulCombine - Optimize a single multiply with constant into two
9228 /// in order to implement it with two cheaper instructions, e.g.
9229 /// LEA + SHL, LEA + LEA.
9230 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
9231 TargetLowering::DAGCombinerInfo &DCI) {
9232 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9235 EVT VT = N->getValueType(0);
9239 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9242 uint64_t MulAmt = C->getZExtValue();
9243 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
9246 uint64_t MulAmt1 = 0;
9247 uint64_t MulAmt2 = 0;
9248 if ((MulAmt % 9) == 0) {
9250 MulAmt2 = MulAmt / 9;
9251 } else if ((MulAmt % 5) == 0) {
9253 MulAmt2 = MulAmt / 5;
9254 } else if ((MulAmt % 3) == 0) {
9256 MulAmt2 = MulAmt / 3;
9259 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
9260 DebugLoc DL = N->getDebugLoc();
9262 if (isPowerOf2_64(MulAmt2) &&
9263 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
9264 // If second multiplifer is pow2, issue it first. We want the multiply by
9265 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
9267 std::swap(MulAmt1, MulAmt2);
9270 if (isPowerOf2_64(MulAmt1))
9271 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
9272 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
9274 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
9275 DAG.getConstant(MulAmt1, VT));
9277 if (isPowerOf2_64(MulAmt2))
9278 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
9279 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
9281 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
9282 DAG.getConstant(MulAmt2, VT));
9284 // Do not add new nodes to DAG combiner worklist.
9285 DCI.CombineTo(N, NewMul, false);
9290 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
9291 SDValue N0 = N->getOperand(0);
9292 SDValue N1 = N->getOperand(1);
9293 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9294 EVT VT = N0.getValueType();
9296 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
9297 // since the result of setcc_c is all zero's or all ones.
9298 if (N1C && N0.getOpcode() == ISD::AND &&
9299 N0.getOperand(1).getOpcode() == ISD::Constant) {
9300 SDValue N00 = N0.getOperand(0);
9301 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
9302 ((N00.getOpcode() == ISD::ANY_EXTEND ||
9303 N00.getOpcode() == ISD::ZERO_EXTEND) &&
9304 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
9305 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
9306 APInt ShAmt = N1C->getAPIntValue();
9307 Mask = Mask.shl(ShAmt);
9309 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
9310 N00, DAG.getConstant(Mask, VT));
9317 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
9319 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
9320 const X86Subtarget *Subtarget) {
9321 EVT VT = N->getValueType(0);
9322 if (!VT.isVector() && VT.isInteger() &&
9323 N->getOpcode() == ISD::SHL)
9324 return PerformSHLCombine(N, DAG);
9326 // On X86 with SSE2 support, we can transform this to a vector shift if
9327 // all elements are shifted by the same amount. We can't do this in legalize
9328 // because the a constant vector is typically transformed to a constant pool
9329 // so we have no knowledge of the shift amount.
9330 if (!Subtarget->hasSSE2())
9333 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
9336 SDValue ShAmtOp = N->getOperand(1);
9337 EVT EltVT = VT.getVectorElementType();
9338 DebugLoc DL = N->getDebugLoc();
9339 SDValue BaseShAmt = SDValue();
9340 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
9341 unsigned NumElts = VT.getVectorNumElements();
9343 for (; i != NumElts; ++i) {
9344 SDValue Arg = ShAmtOp.getOperand(i);
9345 if (Arg.getOpcode() == ISD::UNDEF) continue;
9349 for (; i != NumElts; ++i) {
9350 SDValue Arg = ShAmtOp.getOperand(i);
9351 if (Arg.getOpcode() == ISD::UNDEF) continue;
9352 if (Arg != BaseShAmt) {
9356 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
9357 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
9358 SDValue InVec = ShAmtOp.getOperand(0);
9359 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
9360 unsigned NumElts = InVec.getValueType().getVectorNumElements();
9362 for (; i != NumElts; ++i) {
9363 SDValue Arg = InVec.getOperand(i);
9364 if (Arg.getOpcode() == ISD::UNDEF) continue;
9368 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
9369 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
9370 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
9371 if (C->getZExtValue() == SplatIdx)
9372 BaseShAmt = InVec.getOperand(1);
9375 if (BaseShAmt.getNode() == 0)
9376 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
9377 DAG.getIntPtrConstant(0));
9381 // The shift amount is an i32.
9382 if (EltVT.bitsGT(MVT::i32))
9383 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
9384 else if (EltVT.bitsLT(MVT::i32))
9385 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
9387 // The shift amount is identical so we can do a vector shift.
9388 SDValue ValOp = N->getOperand(0);
9389 switch (N->getOpcode()) {
9391 llvm_unreachable("Unknown shift opcode!");
9394 if (VT == MVT::v2i64)
9395 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9396 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9398 if (VT == MVT::v4i32)
9399 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9400 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9402 if (VT == MVT::v8i16)
9403 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9404 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9408 if (VT == MVT::v4i32)
9409 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9410 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9412 if (VT == MVT::v8i16)
9413 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9414 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9418 if (VT == MVT::v2i64)
9419 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9420 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9422 if (VT == MVT::v4i32)
9423 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9424 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9426 if (VT == MVT::v8i16)
9427 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9428 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9435 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
9436 TargetLowering::DAGCombinerInfo &DCI,
9437 const X86Subtarget *Subtarget) {
9438 if (DCI.isBeforeLegalizeOps())
9441 EVT VT = N->getValueType(0);
9442 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
9445 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
9446 SDValue N0 = N->getOperand(0);
9447 SDValue N1 = N->getOperand(1);
9448 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
9450 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
9452 if (!N0.hasOneUse() || !N1.hasOneUse())
9455 SDValue ShAmt0 = N0.getOperand(1);
9456 if (ShAmt0.getValueType() != MVT::i8)
9458 SDValue ShAmt1 = N1.getOperand(1);
9459 if (ShAmt1.getValueType() != MVT::i8)
9461 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
9462 ShAmt0 = ShAmt0.getOperand(0);
9463 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
9464 ShAmt1 = ShAmt1.getOperand(0);
9466 DebugLoc DL = N->getDebugLoc();
9467 unsigned Opc = X86ISD::SHLD;
9468 SDValue Op0 = N0.getOperand(0);
9469 SDValue Op1 = N1.getOperand(0);
9470 if (ShAmt0.getOpcode() == ISD::SUB) {
9472 std::swap(Op0, Op1);
9473 std::swap(ShAmt0, ShAmt1);
9476 unsigned Bits = VT.getSizeInBits();
9477 if (ShAmt1.getOpcode() == ISD::SUB) {
9478 SDValue Sum = ShAmt1.getOperand(0);
9479 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
9480 if (SumC->getSExtValue() == Bits &&
9481 ShAmt1.getOperand(1) == ShAmt0)
9482 return DAG.getNode(Opc, DL, VT,
9484 DAG.getNode(ISD::TRUNCATE, DL,
9487 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
9488 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
9490 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
9491 return DAG.getNode(Opc, DL, VT,
9492 N0.getOperand(0), N1.getOperand(0),
9493 DAG.getNode(ISD::TRUNCATE, DL,
9500 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
9501 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
9502 const X86Subtarget *Subtarget) {
9503 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
9504 // the FP state in cases where an emms may be missing.
9505 // A preferable solution to the general problem is to figure out the right
9506 // places to insert EMMS. This qualifies as a quick hack.
9508 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
9509 StoreSDNode *St = cast<StoreSDNode>(N);
9510 EVT VT = St->getValue().getValueType();
9511 if (VT.getSizeInBits() != 64)
9514 const Function *F = DAG.getMachineFunction().getFunction();
9515 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
9516 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
9517 && Subtarget->hasSSE2();
9518 if ((VT.isVector() ||
9519 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
9520 isa<LoadSDNode>(St->getValue()) &&
9521 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
9522 St->getChain().hasOneUse() && !St->isVolatile()) {
9523 SDNode* LdVal = St->getValue().getNode();
9525 int TokenFactorIndex = -1;
9526 SmallVector<SDValue, 8> Ops;
9527 SDNode* ChainVal = St->getChain().getNode();
9528 // Must be a store of a load. We currently handle two cases: the load
9529 // is a direct child, and it's under an intervening TokenFactor. It is
9530 // possible to dig deeper under nested TokenFactors.
9531 if (ChainVal == LdVal)
9532 Ld = cast<LoadSDNode>(St->getChain());
9533 else if (St->getValue().hasOneUse() &&
9534 ChainVal->getOpcode() == ISD::TokenFactor) {
9535 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
9536 if (ChainVal->getOperand(i).getNode() == LdVal) {
9537 TokenFactorIndex = i;
9538 Ld = cast<LoadSDNode>(St->getValue());
9540 Ops.push_back(ChainVal->getOperand(i));
9544 if (!Ld || !ISD::isNormalLoad(Ld))
9547 // If this is not the MMX case, i.e. we are just turning i64 load/store
9548 // into f64 load/store, avoid the transformation if there are multiple
9549 // uses of the loaded value.
9550 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
9553 DebugLoc LdDL = Ld->getDebugLoc();
9554 DebugLoc StDL = N->getDebugLoc();
9555 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
9556 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
9558 if (Subtarget->is64Bit() || F64IsLegal) {
9559 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
9560 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
9561 Ld->getBasePtr(), Ld->getSrcValue(),
9562 Ld->getSrcValueOffset(), Ld->isVolatile(),
9563 Ld->isNonTemporal(), Ld->getAlignment());
9564 SDValue NewChain = NewLd.getValue(1);
9565 if (TokenFactorIndex != -1) {
9566 Ops.push_back(NewChain);
9567 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9570 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
9571 St->getSrcValue(), St->getSrcValueOffset(),
9572 St->isVolatile(), St->isNonTemporal(),
9573 St->getAlignment());
9576 // Otherwise, lower to two pairs of 32-bit loads / stores.
9577 SDValue LoAddr = Ld->getBasePtr();
9578 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
9579 DAG.getConstant(4, MVT::i32));
9581 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
9582 Ld->getSrcValue(), Ld->getSrcValueOffset(),
9583 Ld->isVolatile(), Ld->isNonTemporal(),
9584 Ld->getAlignment());
9585 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
9586 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
9587 Ld->isVolatile(), Ld->isNonTemporal(),
9588 MinAlign(Ld->getAlignment(), 4));
9590 SDValue NewChain = LoLd.getValue(1);
9591 if (TokenFactorIndex != -1) {
9592 Ops.push_back(LoLd);
9593 Ops.push_back(HiLd);
9594 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9598 LoAddr = St->getBasePtr();
9599 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
9600 DAG.getConstant(4, MVT::i32));
9602 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
9603 St->getSrcValue(), St->getSrcValueOffset(),
9604 St->isVolatile(), St->isNonTemporal(),
9605 St->getAlignment());
9606 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
9608 St->getSrcValueOffset() + 4,
9610 St->isNonTemporal(),
9611 MinAlign(St->getAlignment(), 4));
9612 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
9617 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
9618 /// X86ISD::FXOR nodes.
9619 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
9620 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
9621 // F[X]OR(0.0, x) -> x
9622 // F[X]OR(x, 0.0) -> x
9623 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9624 if (C->getValueAPF().isPosZero())
9625 return N->getOperand(1);
9626 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9627 if (C->getValueAPF().isPosZero())
9628 return N->getOperand(0);
9632 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
9633 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
9634 // FAND(0.0, x) -> 0.0
9635 // FAND(x, 0.0) -> 0.0
9636 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9637 if (C->getValueAPF().isPosZero())
9638 return N->getOperand(0);
9639 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9640 if (C->getValueAPF().isPosZero())
9641 return N->getOperand(1);
9645 static SDValue PerformBTCombine(SDNode *N,
9647 TargetLowering::DAGCombinerInfo &DCI) {
9648 // BT ignores high bits in the bit index operand.
9649 SDValue Op1 = N->getOperand(1);
9650 if (Op1.hasOneUse()) {
9651 unsigned BitWidth = Op1.getValueSizeInBits();
9652 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
9653 APInt KnownZero, KnownOne;
9654 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
9655 !DCI.isBeforeLegalizeOps());
9656 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9657 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
9658 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
9659 DCI.CommitTargetLoweringOpt(TLO);
9664 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
9665 SDValue Op = N->getOperand(0);
9666 if (Op.getOpcode() == ISD::BIT_CONVERT)
9667 Op = Op.getOperand(0);
9668 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
9669 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
9670 VT.getVectorElementType().getSizeInBits() ==
9671 OpVT.getVectorElementType().getSizeInBits()) {
9672 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
9677 // On X86 and X86-64, atomic operations are lowered to locked instructions.
9678 // Locked instructions, in turn, have implicit fence semantics (all memory
9679 // operations are flushed before issuing the locked instruction, and the
9680 // are not buffered), so we can fold away the common pattern of
9681 // fence-atomic-fence.
9682 static SDValue PerformMEMBARRIERCombine(SDNode* N, SelectionDAG &DAG) {
9683 SDValue atomic = N->getOperand(0);
9684 switch (atomic.getOpcode()) {
9685 case ISD::ATOMIC_CMP_SWAP:
9686 case ISD::ATOMIC_SWAP:
9687 case ISD::ATOMIC_LOAD_ADD:
9688 case ISD::ATOMIC_LOAD_SUB:
9689 case ISD::ATOMIC_LOAD_AND:
9690 case ISD::ATOMIC_LOAD_OR:
9691 case ISD::ATOMIC_LOAD_XOR:
9692 case ISD::ATOMIC_LOAD_NAND:
9693 case ISD::ATOMIC_LOAD_MIN:
9694 case ISD::ATOMIC_LOAD_MAX:
9695 case ISD::ATOMIC_LOAD_UMIN:
9696 case ISD::ATOMIC_LOAD_UMAX:
9702 SDValue fence = atomic.getOperand(0);
9703 if (fence.getOpcode() != ISD::MEMBARRIER)
9706 switch (atomic.getOpcode()) {
9707 case ISD::ATOMIC_CMP_SWAP:
9708 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9709 atomic.getOperand(1), atomic.getOperand(2),
9710 atomic.getOperand(3));
9711 case ISD::ATOMIC_SWAP:
9712 case ISD::ATOMIC_LOAD_ADD:
9713 case ISD::ATOMIC_LOAD_SUB:
9714 case ISD::ATOMIC_LOAD_AND:
9715 case ISD::ATOMIC_LOAD_OR:
9716 case ISD::ATOMIC_LOAD_XOR:
9717 case ISD::ATOMIC_LOAD_NAND:
9718 case ISD::ATOMIC_LOAD_MIN:
9719 case ISD::ATOMIC_LOAD_MAX:
9720 case ISD::ATOMIC_LOAD_UMIN:
9721 case ISD::ATOMIC_LOAD_UMAX:
9722 return DAG.UpdateNodeOperands(atomic, fence.getOperand(0),
9723 atomic.getOperand(1), atomic.getOperand(2));
9729 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
9730 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
9731 // (and (i32 x86isd::setcc_carry), 1)
9732 // This eliminates the zext. This transformation is necessary because
9733 // ISD::SETCC is always legalized to i8.
9734 DebugLoc dl = N->getDebugLoc();
9735 SDValue N0 = N->getOperand(0);
9736 EVT VT = N->getValueType(0);
9737 if (N0.getOpcode() == ISD::AND &&
9739 N0.getOperand(0).hasOneUse()) {
9740 SDValue N00 = N0.getOperand(0);
9741 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
9743 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9744 if (!C || C->getZExtValue() != 1)
9746 return DAG.getNode(ISD::AND, dl, VT,
9747 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
9748 N00.getOperand(0), N00.getOperand(1)),
9749 DAG.getConstant(1, VT));
9755 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
9756 DAGCombinerInfo &DCI) const {
9757 SelectionDAG &DAG = DCI.DAG;
9758 switch (N->getOpcode()) {
9760 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
9761 case ISD::EXTRACT_VECTOR_ELT:
9762 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
9763 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
9764 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
9765 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
9768 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
9769 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
9770 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
9772 case X86ISD::FOR: return PerformFORCombine(N, DAG);
9773 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
9774 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
9775 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
9776 case ISD::MEMBARRIER: return PerformMEMBARRIERCombine(N, DAG);
9777 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
9783 /// isTypeDesirableForOp - Return true if the target has native support for
9784 /// the specified value type and it is 'desirable' to use the type for the
9785 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
9786 /// instruction encodings are longer and some i16 instructions are slow.
9787 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
9788 if (!isTypeLegal(VT))
9797 case ISD::SIGN_EXTEND:
9798 case ISD::ZERO_EXTEND:
9799 case ISD::ANY_EXTEND:
9812 static bool MayFoldLoad(SDValue Op) {
9813 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
9816 static bool MayFoldIntoStore(SDValue Op) {
9817 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
9820 /// IsDesirableToPromoteOp - This method query the target whether it is
9821 /// beneficial for dag combiner to promote the specified node. If true, it
9822 /// should return the desired promotion type by reference.
9823 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
9824 EVT VT = Op.getValueType();
9828 bool Promote = false;
9829 bool Commute = false;
9830 switch (Op.getOpcode()) {
9833 LoadSDNode *LD = cast<LoadSDNode>(Op);
9834 // If the non-extending load has a single use and it's not live out, then it
9836 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
9838 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9839 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9840 // The only case where we'd want to promote LOAD (rather then it being
9841 // promoted as an operand is when it's only use is liveout.
9842 if (UI->getOpcode() != ISD::CopyToReg)
9849 case ISD::SIGN_EXTEND:
9850 case ISD::ZERO_EXTEND:
9851 case ISD::ANY_EXTEND:
9856 SDValue N0 = Op.getOperand(0);
9857 // Look out for (store (shl (load), x)).
9858 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
9871 SDValue N0 = Op.getOperand(0);
9872 SDValue N1 = Op.getOperand(1);
9873 if (!Commute && MayFoldLoad(N1))
9875 // Avoid disabling potential load folding opportunities.
9876 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
9878 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
9888 //===----------------------------------------------------------------------===//
9889 // X86 Inline Assembly Support
9890 //===----------------------------------------------------------------------===//
9892 static bool LowerToBSwap(CallInst *CI) {
9893 // FIXME: this should verify that we are targetting a 486 or better. If not,
9894 // we will turn this bswap into something that will be lowered to logical ops
9895 // instead of emitting the bswap asm. For now, we don't support 486 or lower
9896 // so don't worry about this.
9898 // Verify this is a simple bswap.
9899 if (CI->getNumOperands() != 2 ||
9900 CI->getType() != CI->getOperand(1)->getType() ||
9901 !CI->getType()->isIntegerTy())
9904 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
9905 if (!Ty || Ty->getBitWidth() % 16 != 0)
9908 // Okay, we can do this xform, do so now.
9909 const Type *Tys[] = { Ty };
9910 Module *M = CI->getParent()->getParent()->getParent();
9911 Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
9913 Value *Op = CI->getOperand(1);
9914 Op = CallInst::Create(Int, Op, CI->getName(), CI);
9916 CI->replaceAllUsesWith(Op);
9917 CI->eraseFromParent();
9921 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
9922 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
9923 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
9925 std::string AsmStr = IA->getAsmString();
9927 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
9928 SmallVector<StringRef, 4> AsmPieces;
9929 SplitString(AsmStr, AsmPieces, "\n"); // ; as separator?
9931 switch (AsmPieces.size()) {
9932 default: return false;
9934 AsmStr = AsmPieces[0];
9936 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
9939 if (AsmPieces.size() == 2 &&
9940 (AsmPieces[0] == "bswap" ||
9941 AsmPieces[0] == "bswapq" ||
9942 AsmPieces[0] == "bswapl") &&
9943 (AsmPieces[1] == "$0" ||
9944 AsmPieces[1] == "${0:q}")) {
9945 // No need to check constraints, nothing other than the equivalent of
9946 // "=r,0" would be valid here.
9947 return LowerToBSwap(CI);
9949 // rorw $$8, ${0:w} --> llvm.bswap.i16
9950 if (CI->getType()->isIntegerTy(16) &&
9951 AsmPieces.size() == 3 &&
9952 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
9953 AsmPieces[1] == "$$8," &&
9954 AsmPieces[2] == "${0:w}" &&
9955 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
9957 const std::string &Constraints = IA->getConstraintString();
9958 SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
9959 std::sort(AsmPieces.begin(), AsmPieces.end());
9960 if (AsmPieces.size() == 4 &&
9961 AsmPieces[0] == "~{cc}" &&
9962 AsmPieces[1] == "~{dirflag}" &&
9963 AsmPieces[2] == "~{flags}" &&
9964 AsmPieces[3] == "~{fpsr}") {
9965 return LowerToBSwap(CI);
9970 if (CI->getType()->isIntegerTy(64) &&
9971 Constraints.size() >= 2 &&
9972 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
9973 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
9974 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
9975 SmallVector<StringRef, 4> Words;
9976 SplitString(AsmPieces[0], Words, " \t");
9977 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
9979 SplitString(AsmPieces[1], Words, " \t");
9980 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
9982 SplitString(AsmPieces[2], Words, " \t,");
9983 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
9984 Words[2] == "%edx") {
9985 return LowerToBSwap(CI);
9997 /// getConstraintType - Given a constraint letter, return the type of
9998 /// constraint it is for this target.
9999 X86TargetLowering::ConstraintType
10000 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
10001 if (Constraint.size() == 1) {
10002 switch (Constraint[0]) {
10014 return C_RegisterClass;
10022 return TargetLowering::getConstraintType(Constraint);
10025 /// LowerXConstraint - try to replace an X constraint, which matches anything,
10026 /// with another that has more specific requirements based on the type of the
10027 /// corresponding operand.
10028 const char *X86TargetLowering::
10029 LowerXConstraint(EVT ConstraintVT) const {
10030 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
10031 // 'f' like normal targets.
10032 if (ConstraintVT.isFloatingPoint()) {
10033 if (Subtarget->hasSSE2())
10035 if (Subtarget->hasSSE1())
10039 return TargetLowering::LowerXConstraint(ConstraintVT);
10042 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10043 /// vector. If it is invalid, don't add anything to Ops.
10044 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10047 std::vector<SDValue>&Ops,
10048 SelectionDAG &DAG) const {
10049 SDValue Result(0, 0);
10051 switch (Constraint) {
10054 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10055 if (C->getZExtValue() <= 31) {
10056 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10062 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10063 if (C->getZExtValue() <= 63) {
10064 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10070 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10071 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
10072 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10078 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10079 if (C->getZExtValue() <= 255) {
10080 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10086 // 32-bit signed value
10087 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10088 const ConstantInt *CI = C->getConstantIntValue();
10089 if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10090 C->getSExtValue())) {
10091 // Widen to 64 bits here to get it sign extended.
10092 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
10095 // FIXME gcc accepts some relocatable values here too, but only in certain
10096 // memory models; it's complicated.
10101 // 32-bit unsigned value
10102 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10103 const ConstantInt *CI = C->getConstantIntValue();
10104 if (CI->isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10105 C->getZExtValue())) {
10106 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10110 // FIXME gcc accepts some relocatable values here too, but only in certain
10111 // memory models; it's complicated.
10115 // Literal immediates are always ok.
10116 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
10117 // Widen to 64 bits here to get it sign extended.
10118 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
10122 // If we are in non-pic codegen mode, we allow the address of a global (with
10123 // an optional displacement) to be used with 'i'.
10124 GlobalAddressSDNode *GA = 0;
10125 int64_t Offset = 0;
10127 // Match either (GA), (GA+C), (GA+C1+C2), etc.
10129 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
10130 Offset += GA->getOffset();
10132 } else if (Op.getOpcode() == ISD::ADD) {
10133 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10134 Offset += C->getZExtValue();
10135 Op = Op.getOperand(0);
10138 } else if (Op.getOpcode() == ISD::SUB) {
10139 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10140 Offset += -C->getZExtValue();
10141 Op = Op.getOperand(0);
10146 // Otherwise, this isn't something we can handle, reject it.
10150 const GlobalValue *GV = GA->getGlobal();
10151 // If we require an extra load to get this address, as in PIC mode, we
10152 // can't accept it.
10153 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
10154 getTargetMachine())))
10158 Op = LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
10160 Op = DAG.getTargetGlobalAddress(GV, GA->getValueType(0), Offset);
10166 if (Result.getNode()) {
10167 Ops.push_back(Result);
10170 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, hasMemory,
10174 std::vector<unsigned> X86TargetLowering::
10175 getRegClassForInlineAsmConstraint(const std::string &Constraint,
10177 if (Constraint.size() == 1) {
10178 // FIXME: not handling fp-stack yet!
10179 switch (Constraint[0]) { // GCC X86 Constraint Letters
10180 default: break; // Unknown constraint letter
10181 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
10182 if (Subtarget->is64Bit()) {
10183 if (VT == MVT::i32)
10184 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
10185 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
10186 X86::R10D,X86::R11D,X86::R12D,
10187 X86::R13D,X86::R14D,X86::R15D,
10188 X86::EBP, X86::ESP, 0);
10189 else if (VT == MVT::i16)
10190 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
10191 X86::SI, X86::DI, X86::R8W,X86::R9W,
10192 X86::R10W,X86::R11W,X86::R12W,
10193 X86::R13W,X86::R14W,X86::R15W,
10194 X86::BP, X86::SP, 0);
10195 else if (VT == MVT::i8)
10196 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
10197 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
10198 X86::R10B,X86::R11B,X86::R12B,
10199 X86::R13B,X86::R14B,X86::R15B,
10200 X86::BPL, X86::SPL, 0);
10202 else if (VT == MVT::i64)
10203 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
10204 X86::RSI, X86::RDI, X86::R8, X86::R9,
10205 X86::R10, X86::R11, X86::R12,
10206 X86::R13, X86::R14, X86::R15,
10207 X86::RBP, X86::RSP, 0);
10211 // 32-bit fallthrough
10212 case 'Q': // Q_REGS
10213 if (VT == MVT::i32)
10214 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
10215 else if (VT == MVT::i16)
10216 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
10217 else if (VT == MVT::i8)
10218 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
10219 else if (VT == MVT::i64)
10220 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
10225 return std::vector<unsigned>();
10228 std::pair<unsigned, const TargetRegisterClass*>
10229 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10231 // First, see if this is a constraint that directly corresponds to an LLVM
10233 if (Constraint.size() == 1) {
10234 // GCC Constraint Letters
10235 switch (Constraint[0]) {
10237 case 'r': // GENERAL_REGS
10238 case 'l': // INDEX_REGS
10240 return std::make_pair(0U, X86::GR8RegisterClass);
10241 if (VT == MVT::i16)
10242 return std::make_pair(0U, X86::GR16RegisterClass);
10243 if (VT == MVT::i32 || !Subtarget->is64Bit())
10244 return std::make_pair(0U, X86::GR32RegisterClass);
10245 return std::make_pair(0U, X86::GR64RegisterClass);
10246 case 'R': // LEGACY_REGS
10248 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
10249 if (VT == MVT::i16)
10250 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
10251 if (VT == MVT::i32 || !Subtarget->is64Bit())
10252 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
10253 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
10254 case 'f': // FP Stack registers.
10255 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
10256 // value to the correct fpstack register class.
10257 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
10258 return std::make_pair(0U, X86::RFP32RegisterClass);
10259 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
10260 return std::make_pair(0U, X86::RFP64RegisterClass);
10261 return std::make_pair(0U, X86::RFP80RegisterClass);
10262 case 'y': // MMX_REGS if MMX allowed.
10263 if (!Subtarget->hasMMX()) break;
10264 return std::make_pair(0U, X86::VR64RegisterClass);
10265 case 'Y': // SSE_REGS if SSE2 allowed
10266 if (!Subtarget->hasSSE2()) break;
10268 case 'x': // SSE_REGS if SSE1 allowed
10269 if (!Subtarget->hasSSE1()) break;
10271 switch (VT.getSimpleVT().SimpleTy) {
10273 // Scalar SSE types.
10276 return std::make_pair(0U, X86::FR32RegisterClass);
10279 return std::make_pair(0U, X86::FR64RegisterClass);
10287 return std::make_pair(0U, X86::VR128RegisterClass);
10293 // Use the default implementation in TargetLowering to convert the register
10294 // constraint into a member of a register class.
10295 std::pair<unsigned, const TargetRegisterClass*> Res;
10296 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10298 // Not found as a standard register?
10299 if (Res.second == 0) {
10300 // Map st(0) -> st(7) -> ST0
10301 if (Constraint.size() == 7 && Constraint[0] == '{' &&
10302 tolower(Constraint[1]) == 's' &&
10303 tolower(Constraint[2]) == 't' &&
10304 Constraint[3] == '(' &&
10305 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
10306 Constraint[5] == ')' &&
10307 Constraint[6] == '}') {
10309 Res.first = X86::ST0+Constraint[4]-'0';
10310 Res.second = X86::RFP80RegisterClass;
10314 // GCC allows "st(0)" to be called just plain "st".
10315 if (StringRef("{st}").equals_lower(Constraint)) {
10316 Res.first = X86::ST0;
10317 Res.second = X86::RFP80RegisterClass;
10322 if (StringRef("{flags}").equals_lower(Constraint)) {
10323 Res.first = X86::EFLAGS;
10324 Res.second = X86::CCRRegisterClass;
10328 // 'A' means EAX + EDX.
10329 if (Constraint == "A") {
10330 Res.first = X86::EAX;
10331 Res.second = X86::GR32_ADRegisterClass;
10337 // Otherwise, check to see if this is a register class of the wrong value
10338 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
10339 // turn into {ax},{dx}.
10340 if (Res.second->hasType(VT))
10341 return Res; // Correct type already, nothing to do.
10343 // All of the single-register GCC register classes map their values onto
10344 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
10345 // really want an 8-bit or 32-bit register, map to the appropriate register
10346 // class and return the appropriate register.
10347 if (Res.second == X86::GR16RegisterClass) {
10348 if (VT == MVT::i8) {
10349 unsigned DestReg = 0;
10350 switch (Res.first) {
10352 case X86::AX: DestReg = X86::AL; break;
10353 case X86::DX: DestReg = X86::DL; break;
10354 case X86::CX: DestReg = X86::CL; break;
10355 case X86::BX: DestReg = X86::BL; break;
10358 Res.first = DestReg;
10359 Res.second = X86::GR8RegisterClass;
10361 } else if (VT == MVT::i32) {
10362 unsigned DestReg = 0;
10363 switch (Res.first) {
10365 case X86::AX: DestReg = X86::EAX; break;
10366 case X86::DX: DestReg = X86::EDX; break;
10367 case X86::CX: DestReg = X86::ECX; break;
10368 case X86::BX: DestReg = X86::EBX; break;
10369 case X86::SI: DestReg = X86::ESI; break;
10370 case X86::DI: DestReg = X86::EDI; break;
10371 case X86::BP: DestReg = X86::EBP; break;
10372 case X86::SP: DestReg = X86::ESP; break;
10375 Res.first = DestReg;
10376 Res.second = X86::GR32RegisterClass;
10378 } else if (VT == MVT::i64) {
10379 unsigned DestReg = 0;
10380 switch (Res.first) {
10382 case X86::AX: DestReg = X86::RAX; break;
10383 case X86::DX: DestReg = X86::RDX; break;
10384 case X86::CX: DestReg = X86::RCX; break;
10385 case X86::BX: DestReg = X86::RBX; break;
10386 case X86::SI: DestReg = X86::RSI; break;
10387 case X86::DI: DestReg = X86::RDI; break;
10388 case X86::BP: DestReg = X86::RBP; break;
10389 case X86::SP: DestReg = X86::RSP; break;
10392 Res.first = DestReg;
10393 Res.second = X86::GR64RegisterClass;
10396 } else if (Res.second == X86::FR32RegisterClass ||
10397 Res.second == X86::FR64RegisterClass ||
10398 Res.second == X86::VR128RegisterClass) {
10399 // Handle references to XMM physical registers that got mapped into the
10400 // wrong class. This can happen with constraints like {xmm0} where the
10401 // target independent register mapper will just pick the first match it can
10402 // find, ignoring the required type.
10403 if (VT == MVT::f32)
10404 Res.second = X86::FR32RegisterClass;
10405 else if (VT == MVT::f64)
10406 Res.second = X86::FR64RegisterClass;
10407 else if (X86::VR128RegisterClass->hasType(VT))
10408 Res.second = X86::VR128RegisterClass;