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(Sched::RegPressure);
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 // Without SSE, i64->f64 goes through memory; i64->MMX is Legal.
223 if (Subtarget->hasMMX() && !DisableMMX)
224 setOperationAction(ISD::BIT_CONVERT , MVT::i64 , Custom);
226 setOperationAction(ISD::BIT_CONVERT , MVT::i64 , Expand);
230 // Scalar integer divide and remainder are lowered to use operations that
231 // produce two results, to match the available instructions. This exposes
232 // the two-result form to trivial CSE, which is able to combine x/y and x%y
233 // into a single instruction.
235 // Scalar integer multiply-high is also lowered to use two-result
236 // operations, to match the available instructions. However, plain multiply
237 // (low) operations are left as Legal, as there are single-result
238 // instructions for this in x86. Using the two-result multiply instructions
239 // when both high and low results are needed must be arranged by dagcombine.
240 setOperationAction(ISD::MULHS , MVT::i8 , Expand);
241 setOperationAction(ISD::MULHU , MVT::i8 , Expand);
242 setOperationAction(ISD::SDIV , MVT::i8 , Expand);
243 setOperationAction(ISD::UDIV , MVT::i8 , Expand);
244 setOperationAction(ISD::SREM , MVT::i8 , Expand);
245 setOperationAction(ISD::UREM , MVT::i8 , Expand);
246 setOperationAction(ISD::MULHS , MVT::i16 , Expand);
247 setOperationAction(ISD::MULHU , MVT::i16 , Expand);
248 setOperationAction(ISD::SDIV , MVT::i16 , Expand);
249 setOperationAction(ISD::UDIV , MVT::i16 , Expand);
250 setOperationAction(ISD::SREM , MVT::i16 , Expand);
251 setOperationAction(ISD::UREM , MVT::i16 , Expand);
252 setOperationAction(ISD::MULHS , MVT::i32 , Expand);
253 setOperationAction(ISD::MULHU , MVT::i32 , Expand);
254 setOperationAction(ISD::SDIV , MVT::i32 , Expand);
255 setOperationAction(ISD::UDIV , MVT::i32 , Expand);
256 setOperationAction(ISD::SREM , MVT::i32 , Expand);
257 setOperationAction(ISD::UREM , MVT::i32 , Expand);
258 setOperationAction(ISD::MULHS , MVT::i64 , Expand);
259 setOperationAction(ISD::MULHU , MVT::i64 , Expand);
260 setOperationAction(ISD::SDIV , MVT::i64 , Expand);
261 setOperationAction(ISD::UDIV , MVT::i64 , Expand);
262 setOperationAction(ISD::SREM , MVT::i64 , Expand);
263 setOperationAction(ISD::UREM , MVT::i64 , Expand);
265 setOperationAction(ISD::BR_JT , MVT::Other, Expand);
266 setOperationAction(ISD::BRCOND , MVT::Other, Custom);
267 setOperationAction(ISD::BR_CC , MVT::Other, Expand);
268 setOperationAction(ISD::SELECT_CC , MVT::Other, Expand);
269 if (Subtarget->is64Bit())
270 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
271 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Legal);
272 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Legal);
273 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
274 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
275 setOperationAction(ISD::FREM , MVT::f32 , Expand);
276 setOperationAction(ISD::FREM , MVT::f64 , Expand);
277 setOperationAction(ISD::FREM , MVT::f80 , Expand);
278 setOperationAction(ISD::FLT_ROUNDS_ , MVT::i32 , Custom);
280 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
281 setOperationAction(ISD::CTTZ , MVT::i8 , Custom);
282 setOperationAction(ISD::CTLZ , MVT::i8 , Custom);
283 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
284 setOperationAction(ISD::CTTZ , MVT::i16 , Custom);
285 setOperationAction(ISD::CTLZ , MVT::i16 , Custom);
286 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
287 setOperationAction(ISD::CTTZ , MVT::i32 , Custom);
288 setOperationAction(ISD::CTLZ , MVT::i32 , Custom);
289 if (Subtarget->is64Bit()) {
290 setOperationAction(ISD::CTPOP , MVT::i64 , Expand);
291 setOperationAction(ISD::CTTZ , MVT::i64 , Custom);
292 setOperationAction(ISD::CTLZ , MVT::i64 , Custom);
295 setOperationAction(ISD::READCYCLECOUNTER , MVT::i64 , Custom);
296 setOperationAction(ISD::BSWAP , MVT::i16 , Expand);
298 // These should be promoted to a larger select which is supported.
299 setOperationAction(ISD::SELECT , MVT::i1 , Promote);
300 // X86 wants to expand cmov itself.
301 setOperationAction(ISD::SELECT , MVT::i8 , Custom);
302 setOperationAction(ISD::SELECT , MVT::i16 , Custom);
303 setOperationAction(ISD::SELECT , MVT::i32 , Custom);
304 setOperationAction(ISD::SELECT , MVT::f32 , Custom);
305 setOperationAction(ISD::SELECT , MVT::f64 , Custom);
306 setOperationAction(ISD::SELECT , MVT::f80 , Custom);
307 setOperationAction(ISD::SETCC , MVT::i8 , Custom);
308 setOperationAction(ISD::SETCC , MVT::i16 , Custom);
309 setOperationAction(ISD::SETCC , MVT::i32 , Custom);
310 setOperationAction(ISD::SETCC , MVT::f32 , Custom);
311 setOperationAction(ISD::SETCC , MVT::f64 , Custom);
312 setOperationAction(ISD::SETCC , MVT::f80 , Custom);
313 if (Subtarget->is64Bit()) {
314 setOperationAction(ISD::SELECT , MVT::i64 , Custom);
315 setOperationAction(ISD::SETCC , MVT::i64 , Custom);
317 setOperationAction(ISD::EH_RETURN , MVT::Other, Custom);
320 setOperationAction(ISD::ConstantPool , MVT::i32 , Custom);
321 setOperationAction(ISD::JumpTable , MVT::i32 , Custom);
322 setOperationAction(ISD::GlobalAddress , MVT::i32 , Custom);
323 setOperationAction(ISD::GlobalTLSAddress, MVT::i32 , Custom);
324 if (Subtarget->is64Bit())
325 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
326 setOperationAction(ISD::ExternalSymbol , MVT::i32 , Custom);
327 setOperationAction(ISD::BlockAddress , MVT::i32 , Custom);
328 if (Subtarget->is64Bit()) {
329 setOperationAction(ISD::ConstantPool , MVT::i64 , Custom);
330 setOperationAction(ISD::JumpTable , MVT::i64 , Custom);
331 setOperationAction(ISD::GlobalAddress , MVT::i64 , Custom);
332 setOperationAction(ISD::ExternalSymbol, MVT::i64 , Custom);
333 setOperationAction(ISD::BlockAddress , MVT::i64 , Custom);
335 // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
336 setOperationAction(ISD::SHL_PARTS , MVT::i32 , Custom);
337 setOperationAction(ISD::SRA_PARTS , MVT::i32 , Custom);
338 setOperationAction(ISD::SRL_PARTS , MVT::i32 , Custom);
339 if (Subtarget->is64Bit()) {
340 setOperationAction(ISD::SHL_PARTS , MVT::i64 , Custom);
341 setOperationAction(ISD::SRA_PARTS , MVT::i64 , Custom);
342 setOperationAction(ISD::SRL_PARTS , MVT::i64 , Custom);
345 if (Subtarget->hasSSE1())
346 setOperationAction(ISD::PREFETCH , MVT::Other, Legal);
348 if (!Subtarget->hasSSE2())
349 setOperationAction(ISD::MEMBARRIER , MVT::Other, Expand);
350 // On X86 and X86-64, atomic operations are lowered to locked instructions.
351 // Locked instructions, in turn, have implicit fence semantics (all memory
352 // operations are flushed before issuing the locked instruction, and they
353 // are not buffered), so we can fold away the common pattern of
354 // fence-atomic-fence.
355 setShouldFoldAtomicFences(true);
357 // Expand certain atomics
358 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, Custom);
359 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, Custom);
360 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
361 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
363 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i8, Custom);
364 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i16, Custom);
365 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
366 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
368 if (!Subtarget->is64Bit()) {
369 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
370 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
371 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
372 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
373 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
374 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
375 setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
378 // FIXME - use subtarget debug flags
379 if (!Subtarget->isTargetDarwin() &&
380 !Subtarget->isTargetELF() &&
381 !Subtarget->isTargetCygMing()) {
382 setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
385 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
386 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
387 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
388 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
389 if (Subtarget->is64Bit()) {
390 setExceptionPointerRegister(X86::RAX);
391 setExceptionSelectorRegister(X86::RDX);
393 setExceptionPointerRegister(X86::EAX);
394 setExceptionSelectorRegister(X86::EDX);
396 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
397 setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
399 setOperationAction(ISD::TRAMPOLINE, MVT::Other, Custom);
401 setOperationAction(ISD::TRAP, MVT::Other, Legal);
403 // VASTART needs to be custom lowered to use the VarArgsFrameIndex
404 setOperationAction(ISD::VASTART , MVT::Other, Custom);
405 setOperationAction(ISD::VAEND , MVT::Other, Expand);
406 if (Subtarget->is64Bit()) {
407 setOperationAction(ISD::VAARG , MVT::Other, Custom);
408 setOperationAction(ISD::VACOPY , MVT::Other, Custom);
410 setOperationAction(ISD::VAARG , MVT::Other, Expand);
411 setOperationAction(ISD::VACOPY , MVT::Other, Expand);
414 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
415 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
416 if (Subtarget->is64Bit())
417 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
418 if (Subtarget->isTargetCygMing())
419 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
421 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
423 if (!UseSoftFloat && X86ScalarSSEf64) {
424 // f32 and f64 use SSE.
425 // Set up the FP register classes.
426 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
427 addRegisterClass(MVT::f64, X86::FR64RegisterClass);
429 // Use ANDPD to simulate FABS.
430 setOperationAction(ISD::FABS , MVT::f64, Custom);
431 setOperationAction(ISD::FABS , MVT::f32, Custom);
433 // Use XORP to simulate FNEG.
434 setOperationAction(ISD::FNEG , MVT::f64, Custom);
435 setOperationAction(ISD::FNEG , MVT::f32, Custom);
437 // Use ANDPD and ORPD to simulate FCOPYSIGN.
438 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
439 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
441 // We don't support sin/cos/fmod
442 setOperationAction(ISD::FSIN , MVT::f64, Expand);
443 setOperationAction(ISD::FCOS , MVT::f64, Expand);
444 setOperationAction(ISD::FSIN , MVT::f32, Expand);
445 setOperationAction(ISD::FCOS , MVT::f32, Expand);
447 // Expand FP immediates into loads from the stack, except for the special
449 addLegalFPImmediate(APFloat(+0.0)); // xorpd
450 addLegalFPImmediate(APFloat(+0.0f)); // xorps
451 } else if (!UseSoftFloat && X86ScalarSSEf32) {
452 // Use SSE for f32, x87 for f64.
453 // Set up the FP register classes.
454 addRegisterClass(MVT::f32, X86::FR32RegisterClass);
455 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
457 // Use ANDPS to simulate FABS.
458 setOperationAction(ISD::FABS , MVT::f32, Custom);
460 // Use XORP to simulate FNEG.
461 setOperationAction(ISD::FNEG , MVT::f32, Custom);
463 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
465 // Use ANDPS and ORPS to simulate FCOPYSIGN.
466 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
467 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
469 // We don't support sin/cos/fmod
470 setOperationAction(ISD::FSIN , MVT::f32, Expand);
471 setOperationAction(ISD::FCOS , MVT::f32, Expand);
473 // Special cases we handle for FP constants.
474 addLegalFPImmediate(APFloat(+0.0f)); // xorps
475 addLegalFPImmediate(APFloat(+0.0)); // FLD0
476 addLegalFPImmediate(APFloat(+1.0)); // FLD1
477 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
478 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
481 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
482 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
484 } else if (!UseSoftFloat) {
485 // f32 and f64 in x87.
486 // Set up the FP register classes.
487 addRegisterClass(MVT::f64, X86::RFP64RegisterClass);
488 addRegisterClass(MVT::f32, X86::RFP32RegisterClass);
490 setOperationAction(ISD::UNDEF, MVT::f64, Expand);
491 setOperationAction(ISD::UNDEF, MVT::f32, Expand);
492 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
493 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
496 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
497 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
499 addLegalFPImmediate(APFloat(+0.0)); // FLD0
500 addLegalFPImmediate(APFloat(+1.0)); // FLD1
501 addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
502 addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
503 addLegalFPImmediate(APFloat(+0.0f)); // FLD0
504 addLegalFPImmediate(APFloat(+1.0f)); // FLD1
505 addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
506 addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
509 // Long double always uses X87.
511 addRegisterClass(MVT::f80, X86::RFP80RegisterClass);
512 setOperationAction(ISD::UNDEF, MVT::f80, Expand);
513 setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
516 APFloat TmpFlt(+0.0);
517 TmpFlt.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
519 addLegalFPImmediate(TmpFlt); // FLD0
521 addLegalFPImmediate(TmpFlt); // FLD0/FCHS
522 APFloat TmpFlt2(+1.0);
523 TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
525 addLegalFPImmediate(TmpFlt2); // FLD1
526 TmpFlt2.changeSign();
527 addLegalFPImmediate(TmpFlt2); // FLD1/FCHS
531 setOperationAction(ISD::FSIN , MVT::f80 , Expand);
532 setOperationAction(ISD::FCOS , MVT::f80 , Expand);
536 // Always use a library call for pow.
537 setOperationAction(ISD::FPOW , MVT::f32 , Expand);
538 setOperationAction(ISD::FPOW , MVT::f64 , Expand);
539 setOperationAction(ISD::FPOW , MVT::f80 , Expand);
541 setOperationAction(ISD::FLOG, MVT::f80, Expand);
542 setOperationAction(ISD::FLOG2, MVT::f80, Expand);
543 setOperationAction(ISD::FLOG10, MVT::f80, Expand);
544 setOperationAction(ISD::FEXP, MVT::f80, Expand);
545 setOperationAction(ISD::FEXP2, MVT::f80, Expand);
547 // First set operation action for all vector types to either promote
548 // (for widening) or expand (for scalarization). Then we will selectively
549 // turn on ones that can be effectively codegen'd.
550 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
551 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
552 setOperationAction(ISD::ADD , (MVT::SimpleValueType)VT, Expand);
553 setOperationAction(ISD::SUB , (MVT::SimpleValueType)VT, Expand);
554 setOperationAction(ISD::FADD, (MVT::SimpleValueType)VT, Expand);
555 setOperationAction(ISD::FNEG, (MVT::SimpleValueType)VT, Expand);
556 setOperationAction(ISD::FSUB, (MVT::SimpleValueType)VT, Expand);
557 setOperationAction(ISD::MUL , (MVT::SimpleValueType)VT, Expand);
558 setOperationAction(ISD::FMUL, (MVT::SimpleValueType)VT, Expand);
559 setOperationAction(ISD::SDIV, (MVT::SimpleValueType)VT, Expand);
560 setOperationAction(ISD::UDIV, (MVT::SimpleValueType)VT, Expand);
561 setOperationAction(ISD::FDIV, (MVT::SimpleValueType)VT, Expand);
562 setOperationAction(ISD::SREM, (MVT::SimpleValueType)VT, Expand);
563 setOperationAction(ISD::UREM, (MVT::SimpleValueType)VT, Expand);
564 setOperationAction(ISD::LOAD, (MVT::SimpleValueType)VT, Expand);
565 setOperationAction(ISD::VECTOR_SHUFFLE, (MVT::SimpleValueType)VT, Expand);
566 setOperationAction(ISD::EXTRACT_VECTOR_ELT,(MVT::SimpleValueType)VT,Expand);
567 setOperationAction(ISD::EXTRACT_SUBVECTOR,(MVT::SimpleValueType)VT,Expand);
568 setOperationAction(ISD::INSERT_VECTOR_ELT,(MVT::SimpleValueType)VT, Expand);
569 setOperationAction(ISD::FABS, (MVT::SimpleValueType)VT, Expand);
570 setOperationAction(ISD::FSIN, (MVT::SimpleValueType)VT, Expand);
571 setOperationAction(ISD::FCOS, (MVT::SimpleValueType)VT, Expand);
572 setOperationAction(ISD::FREM, (MVT::SimpleValueType)VT, Expand);
573 setOperationAction(ISD::FPOWI, (MVT::SimpleValueType)VT, Expand);
574 setOperationAction(ISD::FSQRT, (MVT::SimpleValueType)VT, Expand);
575 setOperationAction(ISD::FCOPYSIGN, (MVT::SimpleValueType)VT, Expand);
576 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
577 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
578 setOperationAction(ISD::SDIVREM, (MVT::SimpleValueType)VT, Expand);
579 setOperationAction(ISD::UDIVREM, (MVT::SimpleValueType)VT, Expand);
580 setOperationAction(ISD::FPOW, (MVT::SimpleValueType)VT, Expand);
581 setOperationAction(ISD::CTPOP, (MVT::SimpleValueType)VT, Expand);
582 setOperationAction(ISD::CTTZ, (MVT::SimpleValueType)VT, Expand);
583 setOperationAction(ISD::CTLZ, (MVT::SimpleValueType)VT, Expand);
584 setOperationAction(ISD::SHL, (MVT::SimpleValueType)VT, Expand);
585 setOperationAction(ISD::SRA, (MVT::SimpleValueType)VT, Expand);
586 setOperationAction(ISD::SRL, (MVT::SimpleValueType)VT, Expand);
587 setOperationAction(ISD::ROTL, (MVT::SimpleValueType)VT, Expand);
588 setOperationAction(ISD::ROTR, (MVT::SimpleValueType)VT, Expand);
589 setOperationAction(ISD::BSWAP, (MVT::SimpleValueType)VT, Expand);
590 setOperationAction(ISD::VSETCC, (MVT::SimpleValueType)VT, Expand);
591 setOperationAction(ISD::FLOG, (MVT::SimpleValueType)VT, Expand);
592 setOperationAction(ISD::FLOG2, (MVT::SimpleValueType)VT, Expand);
593 setOperationAction(ISD::FLOG10, (MVT::SimpleValueType)VT, Expand);
594 setOperationAction(ISD::FEXP, (MVT::SimpleValueType)VT, Expand);
595 setOperationAction(ISD::FEXP2, (MVT::SimpleValueType)VT, Expand);
596 setOperationAction(ISD::FP_TO_UINT, (MVT::SimpleValueType)VT, Expand);
597 setOperationAction(ISD::FP_TO_SINT, (MVT::SimpleValueType)VT, Expand);
598 setOperationAction(ISD::UINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
599 setOperationAction(ISD::SINT_TO_FP, (MVT::SimpleValueType)VT, Expand);
600 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,Expand);
601 setOperationAction(ISD::TRUNCATE, (MVT::SimpleValueType)VT, Expand);
602 setOperationAction(ISD::SIGN_EXTEND, (MVT::SimpleValueType)VT, Expand);
603 setOperationAction(ISD::ZERO_EXTEND, (MVT::SimpleValueType)VT, Expand);
604 setOperationAction(ISD::ANY_EXTEND, (MVT::SimpleValueType)VT, Expand);
605 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
606 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
607 setTruncStoreAction((MVT::SimpleValueType)VT,
608 (MVT::SimpleValueType)InnerVT, Expand);
609 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
610 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
611 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
614 // FIXME: In order to prevent SSE instructions being expanded to MMX ones
615 // with -msoft-float, disable use of MMX as well.
616 if (!UseSoftFloat && !DisableMMX && Subtarget->hasMMX()) {
617 addRegisterClass(MVT::v8i8, X86::VR64RegisterClass, false);
618 addRegisterClass(MVT::v4i16, X86::VR64RegisterClass, false);
619 addRegisterClass(MVT::v2i32, X86::VR64RegisterClass, false);
621 addRegisterClass(MVT::v1i64, X86::VR64RegisterClass, false);
623 setOperationAction(ISD::ADD, MVT::v8i8, Legal);
624 setOperationAction(ISD::ADD, MVT::v4i16, Legal);
625 setOperationAction(ISD::ADD, MVT::v2i32, Legal);
626 setOperationAction(ISD::ADD, MVT::v1i64, Legal);
628 setOperationAction(ISD::SUB, MVT::v8i8, Legal);
629 setOperationAction(ISD::SUB, MVT::v4i16, Legal);
630 setOperationAction(ISD::SUB, MVT::v2i32, Legal);
631 setOperationAction(ISD::SUB, MVT::v1i64, Legal);
633 setOperationAction(ISD::MULHS, MVT::v4i16, Legal);
634 setOperationAction(ISD::MUL, MVT::v4i16, Legal);
636 setOperationAction(ISD::AND, MVT::v8i8, Promote);
637 AddPromotedToType (ISD::AND, MVT::v8i8, MVT::v1i64);
638 setOperationAction(ISD::AND, MVT::v4i16, Promote);
639 AddPromotedToType (ISD::AND, MVT::v4i16, MVT::v1i64);
640 setOperationAction(ISD::AND, MVT::v2i32, Promote);
641 AddPromotedToType (ISD::AND, MVT::v2i32, MVT::v1i64);
642 setOperationAction(ISD::AND, MVT::v1i64, Legal);
644 setOperationAction(ISD::OR, MVT::v8i8, Promote);
645 AddPromotedToType (ISD::OR, MVT::v8i8, MVT::v1i64);
646 setOperationAction(ISD::OR, MVT::v4i16, Promote);
647 AddPromotedToType (ISD::OR, MVT::v4i16, MVT::v1i64);
648 setOperationAction(ISD::OR, MVT::v2i32, Promote);
649 AddPromotedToType (ISD::OR, MVT::v2i32, MVT::v1i64);
650 setOperationAction(ISD::OR, MVT::v1i64, Legal);
652 setOperationAction(ISD::XOR, MVT::v8i8, Promote);
653 AddPromotedToType (ISD::XOR, MVT::v8i8, MVT::v1i64);
654 setOperationAction(ISD::XOR, MVT::v4i16, Promote);
655 AddPromotedToType (ISD::XOR, MVT::v4i16, MVT::v1i64);
656 setOperationAction(ISD::XOR, MVT::v2i32, Promote);
657 AddPromotedToType (ISD::XOR, MVT::v2i32, MVT::v1i64);
658 setOperationAction(ISD::XOR, MVT::v1i64, Legal);
660 setOperationAction(ISD::LOAD, MVT::v8i8, Promote);
661 AddPromotedToType (ISD::LOAD, MVT::v8i8, MVT::v1i64);
662 setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
663 AddPromotedToType (ISD::LOAD, MVT::v4i16, MVT::v1i64);
664 setOperationAction(ISD::LOAD, MVT::v2i32, Promote);
665 AddPromotedToType (ISD::LOAD, MVT::v2i32, MVT::v1i64);
666 setOperationAction(ISD::LOAD, MVT::v1i64, Legal);
668 setOperationAction(ISD::BUILD_VECTOR, MVT::v8i8, Custom);
669 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
670 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i32, Custom);
671 setOperationAction(ISD::BUILD_VECTOR, MVT::v1i64, Custom);
673 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i8, Custom);
674 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
675 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i32, Custom);
676 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v1i64, Custom);
678 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i8, Custom);
679 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v4i16, Custom);
680 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v1i64, Custom);
682 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
684 setOperationAction(ISD::SELECT, MVT::v8i8, Promote);
685 setOperationAction(ISD::SELECT, MVT::v4i16, Promote);
686 setOperationAction(ISD::SELECT, MVT::v2i32, Promote);
687 setOperationAction(ISD::SELECT, MVT::v1i64, Custom);
688 setOperationAction(ISD::VSETCC, MVT::v8i8, Custom);
689 setOperationAction(ISD::VSETCC, MVT::v4i16, Custom);
690 setOperationAction(ISD::VSETCC, MVT::v2i32, Custom);
692 if (!X86ScalarSSEf64 && Subtarget->is64Bit()) {
693 setOperationAction(ISD::BIT_CONVERT, MVT::v8i8, Custom);
694 setOperationAction(ISD::BIT_CONVERT, MVT::v4i16, Custom);
695 setOperationAction(ISD::BIT_CONVERT, MVT::v2i32, Custom);
696 setOperationAction(ISD::BIT_CONVERT, MVT::v1i64, Custom);
700 if (!UseSoftFloat && Subtarget->hasSSE1()) {
701 addRegisterClass(MVT::v4f32, X86::VR128RegisterClass);
703 setOperationAction(ISD::FADD, MVT::v4f32, Legal);
704 setOperationAction(ISD::FSUB, MVT::v4f32, Legal);
705 setOperationAction(ISD::FMUL, MVT::v4f32, Legal);
706 setOperationAction(ISD::FDIV, MVT::v4f32, Legal);
707 setOperationAction(ISD::FSQRT, MVT::v4f32, Legal);
708 setOperationAction(ISD::FNEG, MVT::v4f32, Custom);
709 setOperationAction(ISD::LOAD, MVT::v4f32, Legal);
710 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f32, Custom);
711 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f32, Custom);
712 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
713 setOperationAction(ISD::SELECT, MVT::v4f32, Custom);
714 setOperationAction(ISD::VSETCC, MVT::v4f32, Custom);
717 if (!UseSoftFloat && Subtarget->hasSSE2()) {
718 addRegisterClass(MVT::v2f64, X86::VR128RegisterClass);
720 // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
721 // registers cannot be used even for integer operations.
722 addRegisterClass(MVT::v16i8, X86::VR128RegisterClass);
723 addRegisterClass(MVT::v8i16, X86::VR128RegisterClass);
724 addRegisterClass(MVT::v4i32, X86::VR128RegisterClass);
725 addRegisterClass(MVT::v2i64, X86::VR128RegisterClass);
727 setOperationAction(ISD::ADD, MVT::v16i8, Legal);
728 setOperationAction(ISD::ADD, MVT::v8i16, Legal);
729 setOperationAction(ISD::ADD, MVT::v4i32, Legal);
730 setOperationAction(ISD::ADD, MVT::v2i64, Legal);
731 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
732 setOperationAction(ISD::SUB, MVT::v16i8, Legal);
733 setOperationAction(ISD::SUB, MVT::v8i16, Legal);
734 setOperationAction(ISD::SUB, MVT::v4i32, Legal);
735 setOperationAction(ISD::SUB, MVT::v2i64, Legal);
736 setOperationAction(ISD::MUL, MVT::v8i16, Legal);
737 setOperationAction(ISD::FADD, MVT::v2f64, Legal);
738 setOperationAction(ISD::FSUB, MVT::v2f64, Legal);
739 setOperationAction(ISD::FMUL, MVT::v2f64, Legal);
740 setOperationAction(ISD::FDIV, MVT::v2f64, Legal);
741 setOperationAction(ISD::FSQRT, MVT::v2f64, Legal);
742 setOperationAction(ISD::FNEG, MVT::v2f64, Custom);
744 setOperationAction(ISD::VSETCC, MVT::v2f64, Custom);
745 setOperationAction(ISD::VSETCC, MVT::v16i8, Custom);
746 setOperationAction(ISD::VSETCC, MVT::v8i16, Custom);
747 setOperationAction(ISD::VSETCC, MVT::v4i32, Custom);
749 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i8, Custom);
750 setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v8i16, Custom);
751 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
752 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
753 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
755 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2f64, Custom);
756 setOperationAction(ISD::CONCAT_VECTORS, MVT::v2i64, Custom);
757 setOperationAction(ISD::CONCAT_VECTORS, MVT::v16i8, Custom);
758 setOperationAction(ISD::CONCAT_VECTORS, MVT::v8i16, Custom);
759 setOperationAction(ISD::CONCAT_VECTORS, MVT::v4i32, Custom);
761 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
762 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; ++i) {
763 EVT VT = (MVT::SimpleValueType)i;
764 // Do not attempt to custom lower non-power-of-2 vectors
765 if (!isPowerOf2_32(VT.getVectorNumElements()))
767 // Do not attempt to custom lower non-128-bit vectors
768 if (!VT.is128BitVector())
770 setOperationAction(ISD::BUILD_VECTOR,
771 VT.getSimpleVT().SimpleTy, Custom);
772 setOperationAction(ISD::VECTOR_SHUFFLE,
773 VT.getSimpleVT().SimpleTy, Custom);
774 setOperationAction(ISD::EXTRACT_VECTOR_ELT,
775 VT.getSimpleVT().SimpleTy, Custom);
778 setOperationAction(ISD::BUILD_VECTOR, MVT::v2f64, Custom);
779 setOperationAction(ISD::BUILD_VECTOR, MVT::v2i64, Custom);
780 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2f64, Custom);
781 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v2i64, Custom);
782 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f64, Custom);
783 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
785 if (Subtarget->is64Bit()) {
786 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Custom);
787 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
790 // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
791 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v2i64; i++) {
792 MVT::SimpleValueType SVT = (MVT::SimpleValueType)i;
795 // Do not attempt to promote non-128-bit vectors
796 if (!VT.is128BitVector())
799 setOperationAction(ISD::AND, SVT, Promote);
800 AddPromotedToType (ISD::AND, SVT, MVT::v2i64);
801 setOperationAction(ISD::OR, SVT, Promote);
802 AddPromotedToType (ISD::OR, SVT, MVT::v2i64);
803 setOperationAction(ISD::XOR, SVT, Promote);
804 AddPromotedToType (ISD::XOR, SVT, MVT::v2i64);
805 setOperationAction(ISD::LOAD, SVT, Promote);
806 AddPromotedToType (ISD::LOAD, SVT, MVT::v2i64);
807 setOperationAction(ISD::SELECT, SVT, Promote);
808 AddPromotedToType (ISD::SELECT, SVT, MVT::v2i64);
811 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
813 // Custom lower v2i64 and v2f64 selects.
814 setOperationAction(ISD::LOAD, MVT::v2f64, Legal);
815 setOperationAction(ISD::LOAD, MVT::v2i64, Legal);
816 setOperationAction(ISD::SELECT, MVT::v2f64, Custom);
817 setOperationAction(ISD::SELECT, MVT::v2i64, Custom);
819 setOperationAction(ISD::FP_TO_SINT, MVT::v4i32, Legal);
820 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Legal);
821 if (!DisableMMX && Subtarget->hasMMX()) {
822 setOperationAction(ISD::FP_TO_SINT, MVT::v2i32, Custom);
823 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
827 if (Subtarget->hasSSE41()) {
828 setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
829 setOperationAction(ISD::FCEIL, MVT::f32, Legal);
830 setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
831 setOperationAction(ISD::FRINT, MVT::f32, Legal);
832 setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
833 setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
834 setOperationAction(ISD::FCEIL, MVT::f64, Legal);
835 setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
836 setOperationAction(ISD::FRINT, MVT::f64, Legal);
837 setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
839 // FIXME: Do we need to handle scalar-to-vector here?
840 setOperationAction(ISD::MUL, MVT::v4i32, Legal);
842 // i8 and i16 vectors are custom , because the source register and source
843 // source memory operand types are not the same width. f32 vectors are
844 // custom since the immediate controlling the insert encodes additional
846 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i8, Custom);
847 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i16, Custom);
848 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i32, Custom);
849 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f32, Custom);
851 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
852 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
853 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
854 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
856 if (Subtarget->is64Bit()) {
857 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i64, Legal);
858 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Legal);
862 if (Subtarget->hasSSE42()) {
863 setOperationAction(ISD::VSETCC, MVT::v2i64, Custom);
866 if (!UseSoftFloat && Subtarget->hasAVX()) {
867 addRegisterClass(MVT::v8f32, X86::VR256RegisterClass);
868 addRegisterClass(MVT::v4f64, X86::VR256RegisterClass);
869 addRegisterClass(MVT::v8i32, X86::VR256RegisterClass);
870 addRegisterClass(MVT::v4i64, X86::VR256RegisterClass);
872 setOperationAction(ISD::LOAD, MVT::v8f32, Legal);
873 setOperationAction(ISD::LOAD, MVT::v8i32, Legal);
874 setOperationAction(ISD::LOAD, MVT::v4f64, Legal);
875 setOperationAction(ISD::LOAD, MVT::v4i64, Legal);
876 setOperationAction(ISD::FADD, MVT::v8f32, Legal);
877 setOperationAction(ISD::FSUB, MVT::v8f32, Legal);
878 setOperationAction(ISD::FMUL, MVT::v8f32, Legal);
879 setOperationAction(ISD::FDIV, MVT::v8f32, Legal);
880 setOperationAction(ISD::FSQRT, MVT::v8f32, Legal);
881 setOperationAction(ISD::FNEG, MVT::v8f32, Custom);
882 //setOperationAction(ISD::BUILD_VECTOR, MVT::v8f32, Custom);
883 //setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Custom);
884 //setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8f32, Custom);
885 //setOperationAction(ISD::SELECT, MVT::v8f32, Custom);
886 //setOperationAction(ISD::VSETCC, MVT::v8f32, Custom);
888 // Operations to consider commented out -v16i16 v32i8
889 //setOperationAction(ISD::ADD, MVT::v16i16, Legal);
890 setOperationAction(ISD::ADD, MVT::v8i32, Custom);
891 setOperationAction(ISD::ADD, MVT::v4i64, Custom);
892 //setOperationAction(ISD::SUB, MVT::v32i8, Legal);
893 //setOperationAction(ISD::SUB, MVT::v16i16, Legal);
894 setOperationAction(ISD::SUB, MVT::v8i32, Custom);
895 setOperationAction(ISD::SUB, MVT::v4i64, Custom);
896 //setOperationAction(ISD::MUL, MVT::v16i16, Legal);
897 setOperationAction(ISD::FADD, MVT::v4f64, Legal);
898 setOperationAction(ISD::FSUB, MVT::v4f64, Legal);
899 setOperationAction(ISD::FMUL, MVT::v4f64, Legal);
900 setOperationAction(ISD::FDIV, MVT::v4f64, Legal);
901 setOperationAction(ISD::FSQRT, MVT::v4f64, Legal);
902 setOperationAction(ISD::FNEG, MVT::v4f64, Custom);
904 setOperationAction(ISD::VSETCC, MVT::v4f64, Custom);
905 // setOperationAction(ISD::VSETCC, MVT::v32i8, Custom);
906 // setOperationAction(ISD::VSETCC, MVT::v16i16, Custom);
907 setOperationAction(ISD::VSETCC, MVT::v8i32, Custom);
909 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v32i8, Custom);
910 // setOperationAction(ISD::SCALAR_TO_VECTOR, MVT::v16i16, Custom);
911 // setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v16i16, Custom);
912 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i32, Custom);
913 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8f32, Custom);
915 setOperationAction(ISD::BUILD_VECTOR, MVT::v4f64, Custom);
916 setOperationAction(ISD::BUILD_VECTOR, MVT::v4i64, Custom);
917 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f64, Custom);
918 setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i64, Custom);
919 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f64, Custom);
920 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f64, Custom);
923 // Not sure we want to do this since there are no 256-bit integer
926 // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
927 // This includes 256-bit vectors
928 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; ++i) {
929 EVT VT = (MVT::SimpleValueType)i;
931 // Do not attempt to custom lower non-power-of-2 vectors
932 if (!isPowerOf2_32(VT.getVectorNumElements()))
935 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
936 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
937 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
940 if (Subtarget->is64Bit()) {
941 setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i64, Custom);
942 setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i64, Custom);
947 // Not sure we want to do this since there are no 256-bit integer
950 // Promote v32i8, v16i16, v8i32 load, select, and, or, xor to v4i64.
951 // Including 256-bit vectors
952 for (unsigned i = (unsigned)MVT::v16i8; i != (unsigned)MVT::v4i64; i++) {
953 EVT VT = (MVT::SimpleValueType)i;
955 if (!VT.is256BitVector()) {
958 setOperationAction(ISD::AND, VT, Promote);
959 AddPromotedToType (ISD::AND, VT, MVT::v4i64);
960 setOperationAction(ISD::OR, VT, Promote);
961 AddPromotedToType (ISD::OR, VT, MVT::v4i64);
962 setOperationAction(ISD::XOR, VT, Promote);
963 AddPromotedToType (ISD::XOR, VT, MVT::v4i64);
964 setOperationAction(ISD::LOAD, VT, Promote);
965 AddPromotedToType (ISD::LOAD, VT, MVT::v4i64);
966 setOperationAction(ISD::SELECT, VT, Promote);
967 AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
970 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
974 // We want to custom lower some of our intrinsics.
975 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
977 // Add/Sub/Mul with overflow operations are custom lowered.
978 setOperationAction(ISD::SADDO, MVT::i32, Custom);
979 setOperationAction(ISD::UADDO, MVT::i32, Custom);
980 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
981 setOperationAction(ISD::USUBO, MVT::i32, Custom);
982 setOperationAction(ISD::SMULO, MVT::i32, Custom);
984 // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
985 // handle type legalization for these operations here.
987 // FIXME: We really should do custom legalization for addition and
988 // subtraction on x86-32 once PR3203 is fixed. We really can't do much better
989 // than generic legalization for 64-bit multiplication-with-overflow, though.
990 if (Subtarget->is64Bit()) {
991 setOperationAction(ISD::SADDO, MVT::i64, Custom);
992 setOperationAction(ISD::UADDO, MVT::i64, Custom);
993 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
994 setOperationAction(ISD::USUBO, MVT::i64, Custom);
995 setOperationAction(ISD::SMULO, MVT::i64, Custom);
998 if (!Subtarget->is64Bit()) {
999 // These libcalls are not available in 32-bit.
1000 setLibcallName(RTLIB::SHL_I128, 0);
1001 setLibcallName(RTLIB::SRL_I128, 0);
1002 setLibcallName(RTLIB::SRA_I128, 0);
1005 // We have target-specific dag combine patterns for the following nodes:
1006 setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1007 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1008 setTargetDAGCombine(ISD::BUILD_VECTOR);
1009 setTargetDAGCombine(ISD::SELECT);
1010 setTargetDAGCombine(ISD::SHL);
1011 setTargetDAGCombine(ISD::SRA);
1012 setTargetDAGCombine(ISD::SRL);
1013 setTargetDAGCombine(ISD::OR);
1014 setTargetDAGCombine(ISD::STORE);
1015 setTargetDAGCombine(ISD::ZERO_EXTEND);
1016 if (Subtarget->is64Bit())
1017 setTargetDAGCombine(ISD::MUL);
1019 computeRegisterProperties();
1021 // FIXME: These should be based on subtarget info. Plus, the values should
1022 // be smaller when we are in optimizing for size mode.
1023 maxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1024 maxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1025 maxStoresPerMemmove = 3; // For @llvm.memmove -> sequence of stores
1026 setPrefLoopAlignment(16);
1027 benefitFromCodePlacementOpt = true;
1031 MVT::SimpleValueType X86TargetLowering::getSetCCResultType(EVT VT) const {
1036 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1037 /// the desired ByVal argument alignment.
1038 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1041 if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1042 if (VTy->getBitWidth() == 128)
1044 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1045 unsigned EltAlign = 0;
1046 getMaxByValAlign(ATy->getElementType(), EltAlign);
1047 if (EltAlign > MaxAlign)
1048 MaxAlign = EltAlign;
1049 } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1050 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1051 unsigned EltAlign = 0;
1052 getMaxByValAlign(STy->getElementType(i), EltAlign);
1053 if (EltAlign > MaxAlign)
1054 MaxAlign = EltAlign;
1062 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1063 /// function arguments in the caller parameter area. For X86, aggregates
1064 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1065 /// are at 4-byte boundaries.
1066 unsigned X86TargetLowering::getByValTypeAlignment(const Type *Ty) const {
1067 if (Subtarget->is64Bit()) {
1068 // Max of 8 and alignment of type.
1069 unsigned TyAlign = TD->getABITypeAlignment(Ty);
1076 if (Subtarget->hasSSE1())
1077 getMaxByValAlign(Ty, Align);
1081 /// getOptimalMemOpType - Returns the target specific optimal type for load
1082 /// and store operations as a result of memset, memcpy, and memmove
1083 /// lowering. If DstAlign is zero that means it's safe to destination
1084 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1085 /// means there isn't a need to check it against alignment requirement,
1086 /// probably because the source does not need to be loaded. If
1087 /// 'NonScalarIntSafe' is true, that means it's safe to return a
1088 /// non-scalar-integer type, e.g. empty string source, constant, or loaded
1089 /// from memory. 'MemcpyStrSrc' indicates whether the memcpy source is
1090 /// constant so it does not need to be loaded.
1091 /// It returns EVT::Other if the type should be determined using generic
1092 /// target-independent logic.
1094 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1095 unsigned DstAlign, unsigned SrcAlign,
1096 bool NonScalarIntSafe,
1098 MachineFunction &MF) const {
1099 // FIXME: This turns off use of xmm stores for memset/memcpy on targets like
1100 // linux. This is because the stack realignment code can't handle certain
1101 // cases like PR2962. This should be removed when PR2962 is fixed.
1102 const Function *F = MF.getFunction();
1103 if (NonScalarIntSafe &&
1104 !F->hasFnAttr(Attribute::NoImplicitFloat)) {
1106 (Subtarget->isUnalignedMemAccessFast() ||
1107 ((DstAlign == 0 || DstAlign >= 16) &&
1108 (SrcAlign == 0 || SrcAlign >= 16))) &&
1109 Subtarget->getStackAlignment() >= 16) {
1110 if (Subtarget->hasSSE2())
1112 if (Subtarget->hasSSE1())
1114 } else if (!MemcpyStrSrc && Size >= 8 &&
1115 !Subtarget->is64Bit() &&
1116 Subtarget->getStackAlignment() >= 8 &&
1117 Subtarget->hasSSE2()) {
1118 // Do not use f64 to lower memcpy if source is string constant. It's
1119 // better to use i32 to avoid the loads.
1123 if (Subtarget->is64Bit() && Size >= 8)
1128 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1129 /// current function. The returned value is a member of the
1130 /// MachineJumpTableInfo::JTEntryKind enum.
1131 unsigned X86TargetLowering::getJumpTableEncoding() const {
1132 // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1134 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1135 Subtarget->isPICStyleGOT())
1136 return MachineJumpTableInfo::EK_Custom32;
1138 // Otherwise, use the normal jump table encoding heuristics.
1139 return TargetLowering::getJumpTableEncoding();
1142 /// getPICBaseSymbol - Return the X86-32 PIC base.
1144 X86TargetLowering::getPICBaseSymbol(const MachineFunction *MF,
1145 MCContext &Ctx) const {
1146 const MCAsmInfo &MAI = *getTargetMachine().getMCAsmInfo();
1147 return Ctx.GetOrCreateSymbol(Twine(MAI.getPrivateGlobalPrefix())+
1148 Twine(MF->getFunctionNumber())+"$pb");
1153 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1154 const MachineBasicBlock *MBB,
1155 unsigned uid,MCContext &Ctx) const{
1156 assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1157 Subtarget->isPICStyleGOT());
1158 // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1160 return MCSymbolRefExpr::Create(MBB->getSymbol(),
1161 MCSymbolRefExpr::VK_GOTOFF, Ctx);
1164 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1166 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1167 SelectionDAG &DAG) const {
1168 if (!Subtarget->is64Bit())
1169 // This doesn't have DebugLoc associated with it, but is not really the
1170 // same as a Register.
1171 return DAG.getNode(X86ISD::GlobalBaseReg, DebugLoc(), getPointerTy());
1175 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1176 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1178 const MCExpr *X86TargetLowering::
1179 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1180 MCContext &Ctx) const {
1181 // X86-64 uses RIP relative addressing based on the jump table label.
1182 if (Subtarget->isPICStyleRIPRel())
1183 return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1185 // Otherwise, the reference is relative to the PIC base.
1186 return MCSymbolRefExpr::Create(getPICBaseSymbol(MF, Ctx), Ctx);
1189 /// getFunctionAlignment - Return the Log2 alignment of this function.
1190 unsigned X86TargetLowering::getFunctionAlignment(const Function *F) const {
1191 return F->hasFnAttr(Attribute::OptimizeForSize) ? 0 : 4;
1194 //===----------------------------------------------------------------------===//
1195 // Return Value Calling Convention Implementation
1196 //===----------------------------------------------------------------------===//
1198 #include "X86GenCallingConv.inc"
1201 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv, bool isVarArg,
1202 const SmallVectorImpl<EVT> &OutTys,
1203 const SmallVectorImpl<ISD::ArgFlagsTy> &ArgsFlags,
1204 SelectionDAG &DAG) const {
1205 SmallVector<CCValAssign, 16> RVLocs;
1206 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1207 RVLocs, *DAG.getContext());
1208 return CCInfo.CheckReturn(OutTys, ArgsFlags, RetCC_X86);
1212 X86TargetLowering::LowerReturn(SDValue Chain,
1213 CallingConv::ID CallConv, bool isVarArg,
1214 const SmallVectorImpl<ISD::OutputArg> &Outs,
1215 DebugLoc dl, SelectionDAG &DAG) const {
1216 MachineFunction &MF = DAG.getMachineFunction();
1217 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1219 SmallVector<CCValAssign, 16> RVLocs;
1220 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1221 RVLocs, *DAG.getContext());
1222 CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1224 // Add the regs to the liveout set for the function.
1225 MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1226 for (unsigned i = 0; i != RVLocs.size(); ++i)
1227 if (RVLocs[i].isRegLoc() && !MRI.isLiveOut(RVLocs[i].getLocReg()))
1228 MRI.addLiveOut(RVLocs[i].getLocReg());
1232 SmallVector<SDValue, 6> RetOps;
1233 RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1234 // Operand #1 = Bytes To Pop
1235 RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1238 // Copy the result values into the output registers.
1239 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1240 CCValAssign &VA = RVLocs[i];
1241 assert(VA.isRegLoc() && "Can only return in registers!");
1242 SDValue ValToCopy = Outs[i].Val;
1244 // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1245 // the RET instruction and handled by the FP Stackifier.
1246 if (VA.getLocReg() == X86::ST0 ||
1247 VA.getLocReg() == X86::ST1) {
1248 // If this is a copy from an xmm register to ST(0), use an FPExtend to
1249 // change the value to the FP stack register class.
1250 if (isScalarFPTypeInSSEReg(VA.getValVT()))
1251 ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1252 RetOps.push_back(ValToCopy);
1253 // Don't emit a copytoreg.
1257 // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1258 // which is returned in RAX / RDX.
1259 if (Subtarget->is64Bit()) {
1260 EVT ValVT = ValToCopy.getValueType();
1261 if (ValVT.isVector() && ValVT.getSizeInBits() == 64) {
1262 ValToCopy = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, ValToCopy);
1263 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1)
1264 ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, ValToCopy);
1268 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1269 Flag = Chain.getValue(1);
1272 // The x86-64 ABI for returning structs by value requires that we copy
1273 // the sret argument into %rax for the return. We saved the argument into
1274 // a virtual register in the entry block, so now we copy the value out
1276 if (Subtarget->is64Bit() &&
1277 DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
1278 MachineFunction &MF = DAG.getMachineFunction();
1279 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1280 unsigned Reg = FuncInfo->getSRetReturnReg();
1282 "SRetReturnReg should have been set in LowerFormalArguments().");
1283 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1285 Chain = DAG.getCopyToReg(Chain, dl, X86::RAX, Val, Flag);
1286 Flag = Chain.getValue(1);
1288 // RAX now acts like a return value.
1289 MRI.addLiveOut(X86::RAX);
1292 RetOps[0] = Chain; // Update chain.
1294 // Add the flag if we have it.
1296 RetOps.push_back(Flag);
1298 return DAG.getNode(X86ISD::RET_FLAG, dl,
1299 MVT::Other, &RetOps[0], RetOps.size());
1302 /// LowerCallResult - Lower the result values of a call into the
1303 /// appropriate copies out of appropriate physical registers.
1306 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
1307 CallingConv::ID CallConv, bool isVarArg,
1308 const SmallVectorImpl<ISD::InputArg> &Ins,
1309 DebugLoc dl, SelectionDAG &DAG,
1310 SmallVectorImpl<SDValue> &InVals) const {
1312 // Assign locations to each value returned by this call.
1313 SmallVector<CCValAssign, 16> RVLocs;
1314 bool Is64Bit = Subtarget->is64Bit();
1315 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1316 RVLocs, *DAG.getContext());
1317 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
1319 // Copy all of the result registers out of their specified physreg.
1320 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1321 CCValAssign &VA = RVLocs[i];
1322 EVT CopyVT = VA.getValVT();
1324 // If this is x86-64, and we disabled SSE, we can't return FP values
1325 if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
1326 ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
1327 report_fatal_error("SSE register return with SSE disabled");
1330 // If this is a call to a function that returns an fp value on the floating
1331 // point stack, but where we prefer to use the value in xmm registers, copy
1332 // it out as F80 and use a truncate to move it from fp stack reg to xmm reg.
1333 if ((VA.getLocReg() == X86::ST0 ||
1334 VA.getLocReg() == X86::ST1) &&
1335 isScalarFPTypeInSSEReg(VA.getValVT())) {
1340 if (Is64Bit && CopyVT.isVector() && CopyVT.getSizeInBits() == 64) {
1341 // For x86-64, MMX values are returned in XMM0 / XMM1 except for v1i64.
1342 if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1343 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1344 MVT::v2i64, InFlag).getValue(1);
1345 Val = Chain.getValue(0);
1346 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1347 Val, DAG.getConstant(0, MVT::i64));
1349 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1350 MVT::i64, InFlag).getValue(1);
1351 Val = Chain.getValue(0);
1353 Val = DAG.getNode(ISD::BIT_CONVERT, dl, CopyVT, Val);
1355 Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
1356 CopyVT, InFlag).getValue(1);
1357 Val = Chain.getValue(0);
1359 InFlag = Chain.getValue(2);
1361 if (CopyVT != VA.getValVT()) {
1362 // Round the F80 the right size, which also moves to the appropriate xmm
1364 Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
1365 // This truncation won't change the value.
1366 DAG.getIntPtrConstant(1));
1369 InVals.push_back(Val);
1376 //===----------------------------------------------------------------------===//
1377 // C & StdCall & Fast Calling Convention implementation
1378 //===----------------------------------------------------------------------===//
1379 // StdCall calling convention seems to be standard for many Windows' API
1380 // routines and around. It differs from C calling convention just a little:
1381 // callee should clean up the stack, not caller. Symbols should be also
1382 // decorated in some fancy way :) It doesn't support any vector arguments.
1383 // For info on fast calling convention see Fast Calling Convention (tail call)
1384 // implementation LowerX86_32FastCCCallTo.
1386 /// CallIsStructReturn - Determines whether a call uses struct return
1388 static bool CallIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
1392 return Outs[0].Flags.isSRet();
1395 /// ArgsAreStructReturn - Determines whether a function uses struct
1396 /// return semantics.
1398 ArgsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
1402 return Ins[0].Flags.isSRet();
1405 /// CCAssignFnForNode - Selects the correct CCAssignFn for a the
1406 /// given CallingConvention value.
1407 CCAssignFn *X86TargetLowering::CCAssignFnForNode(CallingConv::ID CC) const {
1408 if (Subtarget->is64Bit()) {
1409 if (CC == CallingConv::GHC)
1410 return CC_X86_64_GHC;
1411 else if (Subtarget->isTargetWin64())
1412 return CC_X86_Win64_C;
1417 if (CC == CallingConv::X86_FastCall)
1418 return CC_X86_32_FastCall;
1419 else if (CC == CallingConv::X86_ThisCall)
1420 return CC_X86_32_ThisCall;
1421 else if (CC == CallingConv::Fast)
1422 return CC_X86_32_FastCC;
1423 else if (CC == CallingConv::GHC)
1424 return CC_X86_32_GHC;
1429 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
1430 /// by "Src" to address "Dst" with size and alignment information specified by
1431 /// the specific parameter attribute. The copy will be passed as a byval
1432 /// function parameter.
1434 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
1435 ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
1437 SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
1438 return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
1439 /*isVolatile*/false, /*AlwaysInline=*/true,
1443 /// IsTailCallConvention - Return true if the calling convention is one that
1444 /// supports tail call optimization.
1445 static bool IsTailCallConvention(CallingConv::ID CC) {
1446 return (CC == CallingConv::Fast || CC == CallingConv::GHC);
1449 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
1450 /// a tailcall target by changing its ABI.
1451 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC) {
1452 return GuaranteedTailCallOpt && IsTailCallConvention(CC);
1456 X86TargetLowering::LowerMemArgument(SDValue Chain,
1457 CallingConv::ID CallConv,
1458 const SmallVectorImpl<ISD::InputArg> &Ins,
1459 DebugLoc dl, SelectionDAG &DAG,
1460 const CCValAssign &VA,
1461 MachineFrameInfo *MFI,
1463 // Create the nodes corresponding to a load from this parameter slot.
1464 ISD::ArgFlagsTy Flags = Ins[i].Flags;
1465 bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv);
1466 bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
1469 // If value is passed by pointer we have address passed instead of the value
1471 if (VA.getLocInfo() == CCValAssign::Indirect)
1472 ValVT = VA.getLocVT();
1474 ValVT = VA.getValVT();
1476 // FIXME: For now, all byval parameter objects are marked mutable. This can be
1477 // changed with more analysis.
1478 // In case of tail call optimization mark all arguments mutable. Since they
1479 // could be overwritten by lowering of arguments in case of a tail call.
1480 if (Flags.isByVal()) {
1481 int FI = MFI->CreateFixedObject(Flags.getByValSize(),
1482 VA.getLocMemOffset(), isImmutable);
1483 return DAG.getFrameIndex(FI, getPointerTy());
1485 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
1486 VA.getLocMemOffset(), isImmutable);
1487 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1488 return DAG.getLoad(ValVT, dl, Chain, FIN,
1489 PseudoSourceValue::getFixedStack(FI), 0,
1495 X86TargetLowering::LowerFormalArguments(SDValue Chain,
1496 CallingConv::ID CallConv,
1498 const SmallVectorImpl<ISD::InputArg> &Ins,
1501 SmallVectorImpl<SDValue> &InVals)
1503 MachineFunction &MF = DAG.getMachineFunction();
1504 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1506 const Function* Fn = MF.getFunction();
1507 if (Fn->hasExternalLinkage() &&
1508 Subtarget->isTargetCygMing() &&
1509 Fn->getName() == "main")
1510 FuncInfo->setForceFramePointer(true);
1512 MachineFrameInfo *MFI = MF.getFrameInfo();
1513 bool Is64Bit = Subtarget->is64Bit();
1514 bool IsWin64 = Subtarget->isTargetWin64();
1516 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1517 "Var args not supported with calling convention fastcc or ghc");
1519 // Assign locations to all of the incoming arguments.
1520 SmallVector<CCValAssign, 16> ArgLocs;
1521 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1522 ArgLocs, *DAG.getContext());
1523 CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForNode(CallConv));
1525 unsigned LastVal = ~0U;
1527 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1528 CCValAssign &VA = ArgLocs[i];
1529 // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
1531 assert(VA.getValNo() != LastVal &&
1532 "Don't support value assigned to multiple locs yet");
1533 LastVal = VA.getValNo();
1535 if (VA.isRegLoc()) {
1536 EVT RegVT = VA.getLocVT();
1537 TargetRegisterClass *RC = NULL;
1538 if (RegVT == MVT::i32)
1539 RC = X86::GR32RegisterClass;
1540 else if (Is64Bit && RegVT == MVT::i64)
1541 RC = X86::GR64RegisterClass;
1542 else if (RegVT == MVT::f32)
1543 RC = X86::FR32RegisterClass;
1544 else if (RegVT == MVT::f64)
1545 RC = X86::FR64RegisterClass;
1546 else if (RegVT.isVector() && RegVT.getSizeInBits() == 128)
1547 RC = X86::VR128RegisterClass;
1548 else if (RegVT.isVector() && RegVT.getSizeInBits() == 64)
1549 RC = X86::VR64RegisterClass;
1551 llvm_unreachable("Unknown argument type!");
1553 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1554 ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
1556 // If this is an 8 or 16-bit value, it is really passed promoted to 32
1557 // bits. Insert an assert[sz]ext to capture this, then truncate to the
1559 if (VA.getLocInfo() == CCValAssign::SExt)
1560 ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
1561 DAG.getValueType(VA.getValVT()));
1562 else if (VA.getLocInfo() == CCValAssign::ZExt)
1563 ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
1564 DAG.getValueType(VA.getValVT()));
1565 else if (VA.getLocInfo() == CCValAssign::BCvt)
1566 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1568 if (VA.isExtInLoc()) {
1569 // Handle MMX values passed in XMM regs.
1570 if (RegVT.isVector()) {
1571 ArgValue = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64,
1572 ArgValue, DAG.getConstant(0, MVT::i64));
1573 ArgValue = DAG.getNode(ISD::BIT_CONVERT, dl, VA.getValVT(), ArgValue);
1575 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
1578 assert(VA.isMemLoc());
1579 ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
1582 // If value is passed via pointer - do a load.
1583 if (VA.getLocInfo() == CCValAssign::Indirect)
1584 ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue, NULL, 0,
1587 InVals.push_back(ArgValue);
1590 // The x86-64 ABI for returning structs by value requires that we copy
1591 // the sret argument into %rax for the return. Save the argument into
1592 // a virtual register so that we can access it from the return points.
1593 if (Is64Bit && MF.getFunction()->hasStructRetAttr()) {
1594 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1595 unsigned Reg = FuncInfo->getSRetReturnReg();
1597 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i64));
1598 FuncInfo->setSRetReturnReg(Reg);
1600 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
1601 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
1604 unsigned StackSize = CCInfo.getNextStackOffset();
1605 // Align stack specially for tail calls.
1606 if (FuncIsMadeTailCallSafe(CallConv))
1607 StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
1609 // If the function takes variable number of arguments, make a frame index for
1610 // the start of the first vararg value... for expansion of llvm.va_start.
1612 if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
1613 CallConv != CallingConv::X86_ThisCall)) {
1614 FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
1617 unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
1619 // FIXME: We should really autogenerate these arrays
1620 static const unsigned GPR64ArgRegsWin64[] = {
1621 X86::RCX, X86::RDX, X86::R8, X86::R9
1623 static const unsigned XMMArgRegsWin64[] = {
1624 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3
1626 static const unsigned GPR64ArgRegs64Bit[] = {
1627 X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
1629 static const unsigned XMMArgRegs64Bit[] = {
1630 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1631 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1633 const unsigned *GPR64ArgRegs, *XMMArgRegs;
1636 TotalNumIntRegs = 4; TotalNumXMMRegs = 4;
1637 GPR64ArgRegs = GPR64ArgRegsWin64;
1638 XMMArgRegs = XMMArgRegsWin64;
1640 TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
1641 GPR64ArgRegs = GPR64ArgRegs64Bit;
1642 XMMArgRegs = XMMArgRegs64Bit;
1644 unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
1646 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs,
1649 bool NoImplicitFloatOps = Fn->hasFnAttr(Attribute::NoImplicitFloat);
1650 assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
1651 "SSE register cannot be used when SSE is disabled!");
1652 assert(!(NumXMMRegs && UseSoftFloat && NoImplicitFloatOps) &&
1653 "SSE register cannot be used when SSE is disabled!");
1654 if (UseSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
1655 // Kernel mode asks for SSE to be disabled, so don't push them
1657 TotalNumXMMRegs = 0;
1659 // For X86-64, if there are vararg parameters that are passed via
1660 // registers, then we must store them to their spots on the stack so they
1661 // may be loaded by deferencing the result of va_next.
1662 FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
1663 FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
1664 FuncInfo->setRegSaveFrameIndex(
1665 MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
1668 // Store the integer parameter registers.
1669 SmallVector<SDValue, 8> MemOps;
1670 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
1672 unsigned Offset = FuncInfo->getVarArgsGPOffset();
1673 for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
1674 SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
1675 DAG.getIntPtrConstant(Offset));
1676 unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
1677 X86::GR64RegisterClass);
1678 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
1680 DAG.getStore(Val.getValue(1), dl, Val, FIN,
1681 PseudoSourceValue::getFixedStack(
1682 FuncInfo->getRegSaveFrameIndex()),
1683 Offset, false, false, 0);
1684 MemOps.push_back(Store);
1688 if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
1689 // Now store the XMM (fp + vector) parameter registers.
1690 SmallVector<SDValue, 11> SaveXMMOps;
1691 SaveXMMOps.push_back(Chain);
1693 unsigned AL = MF.addLiveIn(X86::AL, X86::GR8RegisterClass);
1694 SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
1695 SaveXMMOps.push_back(ALVal);
1697 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1698 FuncInfo->getRegSaveFrameIndex()));
1699 SaveXMMOps.push_back(DAG.getIntPtrConstant(
1700 FuncInfo->getVarArgsFPOffset()));
1702 for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
1703 unsigned VReg = MF.addLiveIn(XMMArgRegs[NumXMMRegs],
1704 X86::VR128RegisterClass);
1705 SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
1706 SaveXMMOps.push_back(Val);
1708 MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
1710 &SaveXMMOps[0], SaveXMMOps.size()));
1713 if (!MemOps.empty())
1714 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1715 &MemOps[0], MemOps.size());
1719 // Some CCs need callee pop.
1720 if (Subtarget->IsCalleePop(isVarArg, CallConv)) {
1721 FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
1723 FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
1724 // If this is an sret function, the return should pop the hidden pointer.
1725 if (!Is64Bit && !IsTailCallConvention(CallConv) && ArgsAreStructReturn(Ins))
1726 FuncInfo->setBytesToPopOnReturn(4);
1730 // RegSaveFrameIndex is X86-64 only.
1731 FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
1732 if (CallConv == CallingConv::X86_FastCall ||
1733 CallConv == CallingConv::X86_ThisCall)
1734 // fastcc functions can't have varargs.
1735 FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
1742 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
1743 SDValue StackPtr, SDValue Arg,
1744 DebugLoc dl, SelectionDAG &DAG,
1745 const CCValAssign &VA,
1746 ISD::ArgFlagsTy Flags) const {
1747 const unsigned FirstStackArgOffset = (Subtarget->isTargetWin64() ? 32 : 0);
1748 unsigned LocMemOffset = FirstStackArgOffset + VA.getLocMemOffset();
1749 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
1750 PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
1751 if (Flags.isByVal()) {
1752 return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
1754 return DAG.getStore(Chain, dl, Arg, PtrOff,
1755 PseudoSourceValue::getStack(), LocMemOffset,
1759 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
1760 /// optimization is performed and it is required.
1762 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
1763 SDValue &OutRetAddr, SDValue Chain,
1764 bool IsTailCall, bool Is64Bit,
1765 int FPDiff, DebugLoc dl) const {
1766 // Adjust the Return address stack slot.
1767 EVT VT = getPointerTy();
1768 OutRetAddr = getReturnAddressFrameIndex(DAG);
1770 // Load the "old" Return address.
1771 OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, NULL, 0, false, false, 0);
1772 return SDValue(OutRetAddr.getNode(), 1);
1775 /// EmitTailCallStoreRetAddr - Emit a store of the return adress if tail call
1776 /// optimization is performed and it is required (FPDiff!=0).
1778 EmitTailCallStoreRetAddr(SelectionDAG & DAG, MachineFunction &MF,
1779 SDValue Chain, SDValue RetAddrFrIdx,
1780 bool Is64Bit, int FPDiff, DebugLoc dl) {
1781 // Store the return address to the appropriate stack slot.
1782 if (!FPDiff) return Chain;
1783 // Calculate the new stack slot for the return address.
1784 int SlotSize = Is64Bit ? 8 : 4;
1785 int NewReturnAddrFI =
1786 MF.getFrameInfo()->CreateFixedObject(SlotSize, FPDiff-SlotSize, false);
1787 EVT VT = Is64Bit ? MVT::i64 : MVT::i32;
1788 SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, VT);
1789 Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
1790 PseudoSourceValue::getFixedStack(NewReturnAddrFI), 0,
1796 X86TargetLowering::LowerCall(SDValue Chain, SDValue Callee,
1797 CallingConv::ID CallConv, bool isVarArg,
1799 const SmallVectorImpl<ISD::OutputArg> &Outs,
1800 const SmallVectorImpl<ISD::InputArg> &Ins,
1801 DebugLoc dl, SelectionDAG &DAG,
1802 SmallVectorImpl<SDValue> &InVals) const {
1803 MachineFunction &MF = DAG.getMachineFunction();
1804 bool Is64Bit = Subtarget->is64Bit();
1805 bool IsStructRet = CallIsStructReturn(Outs);
1806 bool IsSibcall = false;
1809 // Check if it's really possible to do a tail call.
1810 isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1811 isVarArg, IsStructRet, MF.getFunction()->hasStructRetAttr(),
1814 // Sibcalls are automatically detected tailcalls which do not require
1816 if (!GuaranteedTailCallOpt && isTailCall)
1823 assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
1824 "Var args not supported with calling convention fastcc or ghc");
1826 // Analyze operands of the call, assigning locations to each operand.
1827 SmallVector<CCValAssign, 16> ArgLocs;
1828 CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
1829 ArgLocs, *DAG.getContext());
1830 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CallConv));
1832 // Get a count of how many bytes are to be pushed on the stack.
1833 unsigned NumBytes = CCInfo.getNextStackOffset();
1835 // This is a sibcall. The memory operands are available in caller's
1836 // own caller's stack.
1838 else if (GuaranteedTailCallOpt && IsTailCallConvention(CallConv))
1839 NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
1842 if (isTailCall && !IsSibcall) {
1843 // Lower arguments at fp - stackoffset + fpdiff.
1844 unsigned NumBytesCallerPushed =
1845 MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn();
1846 FPDiff = NumBytesCallerPushed - NumBytes;
1848 // Set the delta of movement of the returnaddr stackslot.
1849 // But only set if delta is greater than previous delta.
1850 if (FPDiff < (MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta()))
1851 MF.getInfo<X86MachineFunctionInfo>()->setTCReturnAddrDelta(FPDiff);
1855 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true));
1857 SDValue RetAddrFrIdx;
1858 // Load return adress for tail calls.
1859 if (isTailCall && FPDiff)
1860 Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
1861 Is64Bit, FPDiff, dl);
1863 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1864 SmallVector<SDValue, 8> MemOpChains;
1867 // Walk the register/memloc assignments, inserting copies/loads. In the case
1868 // of tail call optimization arguments are handle later.
1869 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1870 CCValAssign &VA = ArgLocs[i];
1871 EVT RegVT = VA.getLocVT();
1872 SDValue Arg = Outs[i].Val;
1873 ISD::ArgFlagsTy Flags = Outs[i].Flags;
1874 bool isByVal = Flags.isByVal();
1876 // Promote the value if needed.
1877 switch (VA.getLocInfo()) {
1878 default: llvm_unreachable("Unknown loc info!");
1879 case CCValAssign::Full: break;
1880 case CCValAssign::SExt:
1881 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
1883 case CCValAssign::ZExt:
1884 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
1886 case CCValAssign::AExt:
1887 if (RegVT.isVector() && RegVT.getSizeInBits() == 128) {
1888 // Special case: passing MMX values in XMM registers.
1889 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i64, Arg);
1890 Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
1891 Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
1893 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
1895 case CCValAssign::BCvt:
1896 Arg = DAG.getNode(ISD::BIT_CONVERT, dl, RegVT, Arg);
1898 case CCValAssign::Indirect: {
1899 // Store the argument.
1900 SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
1901 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
1902 Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
1903 PseudoSourceValue::getFixedStack(FI), 0,
1910 if (VA.isRegLoc()) {
1911 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1912 } else if (!IsSibcall && (!isTailCall || isByVal)) {
1913 assert(VA.isMemLoc());
1914 if (StackPtr.getNode() == 0)
1915 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr, getPointerTy());
1916 MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1917 dl, DAG, VA, Flags));
1921 if (!MemOpChains.empty())
1922 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1923 &MemOpChains[0], MemOpChains.size());
1925 // Build a sequence of copy-to-reg nodes chained together with token chain
1926 // and flag operands which copy the outgoing args into registers.
1928 // Tail call byval lowering might overwrite argument registers so in case of
1929 // tail call optimization the copies to registers are lowered later.
1931 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1932 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1933 RegsToPass[i].second, InFlag);
1934 InFlag = Chain.getValue(1);
1937 if (Subtarget->isPICStyleGOT()) {
1938 // ELF / PIC requires GOT in the EBX register before function calls via PLT
1941 Chain = DAG.getCopyToReg(Chain, dl, X86::EBX,
1942 DAG.getNode(X86ISD::GlobalBaseReg,
1943 DebugLoc(), getPointerTy()),
1945 InFlag = Chain.getValue(1);
1947 // If we are tail calling and generating PIC/GOT style code load the
1948 // address of the callee into ECX. The value in ecx is used as target of
1949 // the tail jump. This is done to circumvent the ebx/callee-saved problem
1950 // for tail calls on PIC/GOT architectures. Normally we would just put the
1951 // address of GOT into ebx and then call target@PLT. But for tail calls
1952 // ebx would be restored (since ebx is callee saved) before jumping to the
1955 // Note: The actual moving to ECX is done further down.
1956 GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
1957 if (G && !G->getGlobal()->hasHiddenVisibility() &&
1958 !G->getGlobal()->hasProtectedVisibility())
1959 Callee = LowerGlobalAddress(Callee, DAG);
1960 else if (isa<ExternalSymbolSDNode>(Callee))
1961 Callee = LowerExternalSymbol(Callee, DAG);
1965 if (Is64Bit && isVarArg) {
1966 // From AMD64 ABI document:
1967 // For calls that may call functions that use varargs or stdargs
1968 // (prototype-less calls or calls to functions containing ellipsis (...) in
1969 // the declaration) %al is used as hidden argument to specify the number
1970 // of SSE registers used. The contents of %al do not need to match exactly
1971 // the number of registers, but must be an ubound on the number of SSE
1972 // registers used and is in the range 0 - 8 inclusive.
1974 // FIXME: Verify this on Win64
1975 // Count the number of XMM registers allocated.
1976 static const unsigned XMMArgRegs[] = {
1977 X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
1978 X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
1980 unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
1981 assert((Subtarget->hasSSE1() || !NumXMMRegs)
1982 && "SSE registers cannot be used when SSE is disabled");
1984 Chain = DAG.getCopyToReg(Chain, dl, X86::AL,
1985 DAG.getConstant(NumXMMRegs, MVT::i8), InFlag);
1986 InFlag = Chain.getValue(1);
1990 // For tail calls lower the arguments to the 'real' stack slot.
1992 // Force all the incoming stack arguments to be loaded from the stack
1993 // before any new outgoing arguments are stored to the stack, because the
1994 // outgoing stack slots may alias the incoming argument stack slots, and
1995 // the alias isn't otherwise explicit. This is slightly more conservative
1996 // than necessary, because it means that each store effectively depends
1997 // on every argument instead of just those arguments it would clobber.
1998 SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2000 SmallVector<SDValue, 8> MemOpChains2;
2003 // Do not flag preceeding copytoreg stuff together with the following stuff.
2005 if (GuaranteedTailCallOpt) {
2006 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2007 CCValAssign &VA = ArgLocs[i];
2010 assert(VA.isMemLoc());
2011 SDValue Arg = Outs[i].Val;
2012 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2013 // Create frame index.
2014 int32_t Offset = VA.getLocMemOffset()+FPDiff;
2015 uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2016 FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2017 FIN = DAG.getFrameIndex(FI, getPointerTy());
2019 if (Flags.isByVal()) {
2020 // Copy relative to framepointer.
2021 SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2022 if (StackPtr.getNode() == 0)
2023 StackPtr = DAG.getCopyFromReg(Chain, dl, X86StackPtr,
2025 Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2027 MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2031 // Store relative to framepointer.
2032 MemOpChains2.push_back(
2033 DAG.getStore(ArgChain, dl, Arg, FIN,
2034 PseudoSourceValue::getFixedStack(FI), 0,
2040 if (!MemOpChains2.empty())
2041 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2042 &MemOpChains2[0], MemOpChains2.size());
2044 // Copy arguments to their registers.
2045 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2046 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2047 RegsToPass[i].second, InFlag);
2048 InFlag = Chain.getValue(1);
2052 // Store the return address to the appropriate stack slot.
2053 Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx, Is64Bit,
2057 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2058 assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2059 // In the 64-bit large code model, we have to make all calls
2060 // through a register, since the call instruction's 32-bit
2061 // pc-relative offset may not be large enough to hold the whole
2063 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2064 // If the callee is a GlobalAddress node (quite common, every direct call
2065 // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2068 // We should use extra load for direct calls to dllimported functions in
2070 const GlobalValue *GV = G->getGlobal();
2071 if (!GV->hasDLLImportLinkage()) {
2072 unsigned char OpFlags = 0;
2074 // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2075 // external symbols most go through the PLT in PIC mode. If the symbol
2076 // has hidden or protected visibility, or if it is static or local, then
2077 // we don't need to use the PLT - we can directly call it.
2078 if (Subtarget->isTargetELF() &&
2079 getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2080 GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2081 OpFlags = X86II::MO_PLT;
2082 } else if (Subtarget->isPICStyleStubAny() &&
2083 (GV->isDeclaration() || GV->isWeakForLinker()) &&
2084 Subtarget->getDarwinVers() < 9) {
2085 // PC-relative references to external symbols should go through $stub,
2086 // unless we're building with the leopard linker or later, which
2087 // automatically synthesizes these stubs.
2088 OpFlags = X86II::MO_DARWIN_STUB;
2091 Callee = DAG.getTargetGlobalAddress(GV, getPointerTy(),
2092 G->getOffset(), OpFlags);
2094 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2095 unsigned char OpFlags = 0;
2097 // On ELF targets, in either X86-64 or X86-32 mode, direct calls to external
2098 // symbols should go through the PLT.
2099 if (Subtarget->isTargetELF() &&
2100 getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2101 OpFlags = X86II::MO_PLT;
2102 } else if (Subtarget->isPICStyleStubAny() &&
2103 Subtarget->getDarwinVers() < 9) {
2104 // PC-relative references to external symbols should go through $stub,
2105 // unless we're building with the leopard linker or later, which
2106 // automatically synthesizes these stubs.
2107 OpFlags = X86II::MO_DARWIN_STUB;
2110 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2114 // Returns a chain & a flag for retval copy to use.
2115 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
2116 SmallVector<SDValue, 8> Ops;
2118 if (!IsSibcall && isTailCall) {
2119 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2120 DAG.getIntPtrConstant(0, true), InFlag);
2121 InFlag = Chain.getValue(1);
2124 Ops.push_back(Chain);
2125 Ops.push_back(Callee);
2128 Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2130 // Add argument registers to the end of the list so that they are known live
2132 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2133 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2134 RegsToPass[i].second.getValueType()));
2136 // Add an implicit use GOT pointer in EBX.
2137 if (!isTailCall && Subtarget->isPICStyleGOT())
2138 Ops.push_back(DAG.getRegister(X86::EBX, getPointerTy()));
2140 // Add an implicit use of AL for x86 vararg functions.
2141 if (Is64Bit && isVarArg)
2142 Ops.push_back(DAG.getRegister(X86::AL, MVT::i8));
2144 if (InFlag.getNode())
2145 Ops.push_back(InFlag);
2149 //// If this is the first return lowered for this function, add the regs
2150 //// to the liveout set for the function.
2151 // This isn't right, although it's probably harmless on x86; liveouts
2152 // should be computed from returns not tail calls. Consider a void
2153 // function making a tail call to a function returning int.
2154 return DAG.getNode(X86ISD::TC_RETURN, dl,
2155 NodeTys, &Ops[0], Ops.size());
2158 Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
2159 InFlag = Chain.getValue(1);
2161 // Create the CALLSEQ_END node.
2162 unsigned NumBytesForCalleeToPush;
2163 if (Subtarget->IsCalleePop(isVarArg, CallConv))
2164 NumBytesForCalleeToPush = NumBytes; // Callee pops everything
2165 else if (!Is64Bit && !IsTailCallConvention(CallConv) && IsStructRet)
2166 // If this is a call to a struct-return function, the callee
2167 // pops the hidden struct pointer, so we have to push it back.
2168 // This is common for Darwin/X86, Linux & Mingw32 targets.
2169 NumBytesForCalleeToPush = 4;
2171 NumBytesForCalleeToPush = 0; // Callee pops nothing.
2173 // Returns a flag for retval copy to use.
2175 Chain = DAG.getCALLSEQ_END(Chain,
2176 DAG.getIntPtrConstant(NumBytes, true),
2177 DAG.getIntPtrConstant(NumBytesForCalleeToPush,
2180 InFlag = Chain.getValue(1);
2183 // Handle result values, copying them out of physregs into vregs that we
2185 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2186 Ins, dl, DAG, InVals);
2190 //===----------------------------------------------------------------------===//
2191 // Fast Calling Convention (tail call) implementation
2192 //===----------------------------------------------------------------------===//
2194 // Like std call, callee cleans arguments, convention except that ECX is
2195 // reserved for storing the tail called function address. Only 2 registers are
2196 // free for argument passing (inreg). Tail call optimization is performed
2198 // * tailcallopt is enabled
2199 // * caller/callee are fastcc
2200 // On X86_64 architecture with GOT-style position independent code only local
2201 // (within module) calls are supported at the moment.
2202 // To keep the stack aligned according to platform abi the function
2203 // GetAlignedArgumentStackSize ensures that argument delta is always multiples
2204 // of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
2205 // If a tail called function callee has more arguments than the caller the
2206 // caller needs to make sure that there is room to move the RETADDR to. This is
2207 // achieved by reserving an area the size of the argument delta right after the
2208 // original REtADDR, but before the saved framepointer or the spilled registers
2209 // e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
2221 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
2222 /// for a 16 byte align requirement.
2224 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
2225 SelectionDAG& DAG) const {
2226 MachineFunction &MF = DAG.getMachineFunction();
2227 const TargetMachine &TM = MF.getTarget();
2228 const TargetFrameInfo &TFI = *TM.getFrameInfo();
2229 unsigned StackAlignment = TFI.getStackAlignment();
2230 uint64_t AlignMask = StackAlignment - 1;
2231 int64_t Offset = StackSize;
2232 uint64_t SlotSize = TD->getPointerSize();
2233 if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
2234 // Number smaller than 12 so just add the difference.
2235 Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
2237 // Mask out lower bits, add stackalignment once plus the 12 bytes.
2238 Offset = ((~AlignMask) & Offset) + StackAlignment +
2239 (StackAlignment-SlotSize);
2244 /// MatchingStackOffset - Return true if the given stack call argument is
2245 /// already available in the same position (relatively) of the caller's
2246 /// incoming argument stack.
2248 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2249 MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
2250 const X86InstrInfo *TII) {
2251 unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
2253 if (Arg.getOpcode() == ISD::CopyFromReg) {
2254 unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2255 if (!VR || TargetRegisterInfo::isPhysicalRegister(VR))
2257 MachineInstr *Def = MRI->getVRegDef(VR);
2260 if (!Flags.isByVal()) {
2261 if (!TII->isLoadFromStackSlot(Def, FI))
2264 unsigned Opcode = Def->getOpcode();
2265 if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
2266 Def->getOperand(1).isFI()) {
2267 FI = Def->getOperand(1).getIndex();
2268 Bytes = Flags.getByValSize();
2272 } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2273 if (Flags.isByVal())
2274 // ByVal argument is passed in as a pointer but it's now being
2275 // dereferenced. e.g.
2276 // define @foo(%struct.X* %A) {
2277 // tail call @bar(%struct.X* byval %A)
2280 SDValue Ptr = Ld->getBasePtr();
2281 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2284 FI = FINode->getIndex();
2288 assert(FI != INT_MAX);
2289 if (!MFI->isFixedObjectIndex(FI))
2291 return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
2294 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2295 /// for tail call optimization. Targets which want to do tail call
2296 /// optimization should implement this function.
2298 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2299 CallingConv::ID CalleeCC,
2301 bool isCalleeStructRet,
2302 bool isCallerStructRet,
2303 const SmallVectorImpl<ISD::OutputArg> &Outs,
2304 const SmallVectorImpl<ISD::InputArg> &Ins,
2305 SelectionDAG& DAG) const {
2306 if (!IsTailCallConvention(CalleeCC) &&
2307 CalleeCC != CallingConv::C)
2310 // If -tailcallopt is specified, make fastcc functions tail-callable.
2311 const MachineFunction &MF = DAG.getMachineFunction();
2312 const Function *CallerF = DAG.getMachineFunction().getFunction();
2313 CallingConv::ID CallerCC = CallerF->getCallingConv();
2314 bool CCMatch = CallerCC == CalleeCC;
2316 if (GuaranteedTailCallOpt) {
2317 if (IsTailCallConvention(CalleeCC) && CCMatch)
2322 // Look for obvious safe cases to perform tail call optimization that do not
2323 // require ABI changes. This is what gcc calls sibcall.
2325 // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
2326 // emit a special epilogue.
2327 if (RegInfo->needsStackRealignment(MF))
2330 // Do not sibcall optimize vararg calls unless the call site is not passing any
2332 if (isVarArg && !Outs.empty())
2335 // Also avoid sibcall optimization if either caller or callee uses struct
2336 // return semantics.
2337 if (isCalleeStructRet || isCallerStructRet)
2340 // If the call result is in ST0 / ST1, it needs to be popped off the x87 stack.
2341 // Therefore if it's not used by the call it is not safe to optimize this into
2343 bool Unused = false;
2344 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
2351 SmallVector<CCValAssign, 16> RVLocs;
2352 CCState CCInfo(CalleeCC, false, getTargetMachine(),
2353 RVLocs, *DAG.getContext());
2354 CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2355 for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2356 CCValAssign &VA = RVLocs[i];
2357 if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
2362 // If the calling conventions do not match, then we'd better make sure the
2363 // results are returned in the same way as what the caller expects.
2365 SmallVector<CCValAssign, 16> RVLocs1;
2366 CCState CCInfo1(CalleeCC, false, getTargetMachine(),
2367 RVLocs1, *DAG.getContext());
2368 CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
2370 SmallVector<CCValAssign, 16> RVLocs2;
2371 CCState CCInfo2(CallerCC, false, getTargetMachine(),
2372 RVLocs2, *DAG.getContext());
2373 CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
2375 if (RVLocs1.size() != RVLocs2.size())
2377 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2378 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2380 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2382 if (RVLocs1[i].isRegLoc()) {
2383 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2386 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2392 // If the callee takes no arguments then go on to check the results of the
2394 if (!Outs.empty()) {
2395 // Check if stack adjustment is needed. For now, do not do this if any
2396 // argument is passed on the stack.
2397 SmallVector<CCValAssign, 16> ArgLocs;
2398 CCState CCInfo(CalleeCC, isVarArg, getTargetMachine(),
2399 ArgLocs, *DAG.getContext());
2400 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForNode(CalleeCC));
2401 if (CCInfo.getNextStackOffset()) {
2402 MachineFunction &MF = DAG.getMachineFunction();
2403 if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
2405 if (Subtarget->isTargetWin64())
2406 // Win64 ABI has additional complications.
2409 // Check if the arguments are already laid out in the right way as
2410 // the caller's fixed stack objects.
2411 MachineFrameInfo *MFI = MF.getFrameInfo();
2412 const MachineRegisterInfo *MRI = &MF.getRegInfo();
2413 const X86InstrInfo *TII =
2414 ((X86TargetMachine&)getTargetMachine()).getInstrInfo();
2415 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2416 CCValAssign &VA = ArgLocs[i];
2417 SDValue Arg = Outs[i].Val;
2418 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2419 if (VA.getLocInfo() == CCValAssign::Indirect)
2421 if (!VA.isRegLoc()) {
2422 if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2429 // If the tailcall address may be in a register, then make sure it's
2430 // possible to register allocate for it. In 32-bit, the call address can
2431 // only target EAX, EDX, or ECX since the tail call must be scheduled after
2432 // callee-saved registers are restored. In 64-bit, it's RAX, RCX, RDX, RSI,
2433 // RDI, R8, R9, R11.
2434 if (!isa<GlobalAddressSDNode>(Callee) &&
2435 !isa<ExternalSymbolSDNode>(Callee)) {
2436 unsigned Limit = Subtarget->is64Bit() ? 8 : 3;
2437 unsigned NumInRegs = 0;
2438 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2439 CCValAssign &VA = ArgLocs[i];
2440 if (VA.isRegLoc()) {
2441 if (++NumInRegs == Limit)
2452 X86TargetLowering::createFastISel(MachineFunction &mf,
2453 DenseMap<const Value *, unsigned> &vm,
2454 DenseMap<const BasicBlock*, MachineBasicBlock*> &bm,
2455 DenseMap<const AllocaInst *, int> &am,
2456 std::vector<std::pair<MachineInstr*, unsigned> > &pn
2458 , SmallSet<const Instruction *, 8> &cil
2461 return X86::createFastISel(mf, vm, bm, am, pn
2469 //===----------------------------------------------------------------------===//
2470 // Other Lowering Hooks
2471 //===----------------------------------------------------------------------===//
2474 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
2475 MachineFunction &MF = DAG.getMachineFunction();
2476 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2477 int ReturnAddrIndex = FuncInfo->getRAIndex();
2479 if (ReturnAddrIndex == 0) {
2480 // Set up a frame object for the return address.
2481 uint64_t SlotSize = TD->getPointerSize();
2482 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize, -SlotSize,
2484 FuncInfo->setRAIndex(ReturnAddrIndex);
2487 return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
2491 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
2492 bool hasSymbolicDisplacement) {
2493 // Offset should fit into 32 bit immediate field.
2494 if (!isInt<32>(Offset))
2497 // If we don't have a symbolic displacement - we don't have any extra
2499 if (!hasSymbolicDisplacement)
2502 // FIXME: Some tweaks might be needed for medium code model.
2503 if (M != CodeModel::Small && M != CodeModel::Kernel)
2506 // For small code model we assume that latest object is 16MB before end of 31
2507 // bits boundary. We may also accept pretty large negative constants knowing
2508 // that all objects are in the positive half of address space.
2509 if (M == CodeModel::Small && Offset < 16*1024*1024)
2512 // For kernel code model we know that all object resist in the negative half
2513 // of 32bits address space. We may not accept negative offsets, since they may
2514 // be just off and we may accept pretty large positive ones.
2515 if (M == CodeModel::Kernel && Offset > 0)
2521 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
2522 /// specific condition code, returning the condition code and the LHS/RHS of the
2523 /// comparison to make.
2524 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
2525 SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
2527 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
2528 if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
2529 // X > -1 -> X == 0, jump !sign.
2530 RHS = DAG.getConstant(0, RHS.getValueType());
2531 return X86::COND_NS;
2532 } else if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
2533 // X < 0 -> X == 0, jump on sign.
2535 } else if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
2537 RHS = DAG.getConstant(0, RHS.getValueType());
2538 return X86::COND_LE;
2542 switch (SetCCOpcode) {
2543 default: llvm_unreachable("Invalid integer condition!");
2544 case ISD::SETEQ: return X86::COND_E;
2545 case ISD::SETGT: return X86::COND_G;
2546 case ISD::SETGE: return X86::COND_GE;
2547 case ISD::SETLT: return X86::COND_L;
2548 case ISD::SETLE: return X86::COND_LE;
2549 case ISD::SETNE: return X86::COND_NE;
2550 case ISD::SETULT: return X86::COND_B;
2551 case ISD::SETUGT: return X86::COND_A;
2552 case ISD::SETULE: return X86::COND_BE;
2553 case ISD::SETUGE: return X86::COND_AE;
2557 // First determine if it is required or is profitable to flip the operands.
2559 // If LHS is a foldable load, but RHS is not, flip the condition.
2560 if ((ISD::isNON_EXTLoad(LHS.getNode()) && LHS.hasOneUse()) &&
2561 !(ISD::isNON_EXTLoad(RHS.getNode()) && RHS.hasOneUse())) {
2562 SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
2563 std::swap(LHS, RHS);
2566 switch (SetCCOpcode) {
2572 std::swap(LHS, RHS);
2576 // On a floating point condition, the flags are set as follows:
2578 // 0 | 0 | 0 | X > Y
2579 // 0 | 0 | 1 | X < Y
2580 // 1 | 0 | 0 | X == Y
2581 // 1 | 1 | 1 | unordered
2582 switch (SetCCOpcode) {
2583 default: llvm_unreachable("Condcode should be pre-legalized away");
2585 case ISD::SETEQ: return X86::COND_E;
2586 case ISD::SETOLT: // flipped
2588 case ISD::SETGT: return X86::COND_A;
2589 case ISD::SETOLE: // flipped
2591 case ISD::SETGE: return X86::COND_AE;
2592 case ISD::SETUGT: // flipped
2594 case ISD::SETLT: return X86::COND_B;
2595 case ISD::SETUGE: // flipped
2597 case ISD::SETLE: return X86::COND_BE;
2599 case ISD::SETNE: return X86::COND_NE;
2600 case ISD::SETUO: return X86::COND_P;
2601 case ISD::SETO: return X86::COND_NP;
2603 case ISD::SETUNE: return X86::COND_INVALID;
2607 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
2608 /// code. Current x86 isa includes the following FP cmov instructions:
2609 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
2610 static bool hasFPCMov(unsigned X86CC) {
2626 /// isFPImmLegal - Returns true if the target can instruction select the
2627 /// specified FP immediate natively. If false, the legalizer will
2628 /// materialize the FP immediate as a load from a constant pool.
2629 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2630 for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
2631 if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
2637 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
2638 /// the specified range (L, H].
2639 static bool isUndefOrInRange(int Val, int Low, int Hi) {
2640 return (Val < 0) || (Val >= Low && Val < Hi);
2643 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
2644 /// specified value.
2645 static bool isUndefOrEqual(int Val, int CmpVal) {
2646 if (Val < 0 || Val == CmpVal)
2651 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
2652 /// is suitable for input to PSHUFD or PSHUFW. That is, it doesn't reference
2653 /// the second operand.
2654 static bool isPSHUFDMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2655 if (VT == MVT::v4f32 || VT == MVT::v4i32 || VT == MVT::v4i16)
2656 return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
2657 if (VT == MVT::v2f64 || VT == MVT::v2i64)
2658 return (Mask[0] < 2 && Mask[1] < 2);
2662 bool X86::isPSHUFDMask(ShuffleVectorSDNode *N) {
2663 SmallVector<int, 8> M;
2665 return ::isPSHUFDMask(M, N->getValueType(0));
2668 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
2669 /// is suitable for input to PSHUFHW.
2670 static bool isPSHUFHWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2671 if (VT != MVT::v8i16)
2674 // Lower quadword copied in order or undef.
2675 for (int i = 0; i != 4; ++i)
2676 if (Mask[i] >= 0 && Mask[i] != i)
2679 // Upper quadword shuffled.
2680 for (int i = 4; i != 8; ++i)
2681 if (Mask[i] >= 0 && (Mask[i] < 4 || Mask[i] > 7))
2687 bool X86::isPSHUFHWMask(ShuffleVectorSDNode *N) {
2688 SmallVector<int, 8> M;
2690 return ::isPSHUFHWMask(M, N->getValueType(0));
2693 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
2694 /// is suitable for input to PSHUFLW.
2695 static bool isPSHUFLWMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2696 if (VT != MVT::v8i16)
2699 // Upper quadword copied in order.
2700 for (int i = 4; i != 8; ++i)
2701 if (Mask[i] >= 0 && Mask[i] != i)
2704 // Lower quadword shuffled.
2705 for (int i = 0; i != 4; ++i)
2712 bool X86::isPSHUFLWMask(ShuffleVectorSDNode *N) {
2713 SmallVector<int, 8> M;
2715 return ::isPSHUFLWMask(M, N->getValueType(0));
2718 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
2719 /// is suitable for input to PALIGNR.
2720 static bool isPALIGNRMask(const SmallVectorImpl<int> &Mask, EVT VT,
2722 int i, e = VT.getVectorNumElements();
2724 // Do not handle v2i64 / v2f64 shuffles with palignr.
2725 if (e < 4 || !hasSSSE3)
2728 for (i = 0; i != e; ++i)
2732 // All undef, not a palignr.
2736 // Determine if it's ok to perform a palignr with only the LHS, since we
2737 // don't have access to the actual shuffle elements to see if RHS is undef.
2738 bool Unary = Mask[i] < (int)e;
2739 bool NeedsUnary = false;
2741 int s = Mask[i] - i;
2743 // Check the rest of the elements to see if they are consecutive.
2744 for (++i; i != e; ++i) {
2749 Unary = Unary && (m < (int)e);
2750 NeedsUnary = NeedsUnary || (m < s);
2752 if (NeedsUnary && !Unary)
2754 if (Unary && m != ((s+i) & (e-1)))
2756 if (!Unary && m != (s+i))
2762 bool X86::isPALIGNRMask(ShuffleVectorSDNode *N) {
2763 SmallVector<int, 8> M;
2765 return ::isPALIGNRMask(M, N->getValueType(0), true);
2768 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
2769 /// specifies a shuffle of elements that is suitable for input to SHUFP*.
2770 static bool isSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2771 int NumElems = VT.getVectorNumElements();
2772 if (NumElems != 2 && NumElems != 4)
2775 int Half = NumElems / 2;
2776 for (int i = 0; i < Half; ++i)
2777 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2779 for (int i = Half; i < NumElems; ++i)
2780 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2786 bool X86::isSHUFPMask(ShuffleVectorSDNode *N) {
2787 SmallVector<int, 8> M;
2789 return ::isSHUFPMask(M, N->getValueType(0));
2792 /// isCommutedSHUFP - Returns true if the shuffle mask is exactly
2793 /// the reverse of what x86 shuffles want. x86 shuffles requires the lower
2794 /// half elements to come from vector 1 (which would equal the dest.) and
2795 /// the upper half to come from vector 2.
2796 static bool isCommutedSHUFPMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2797 int NumElems = VT.getVectorNumElements();
2799 if (NumElems != 2 && NumElems != 4)
2802 int Half = NumElems / 2;
2803 for (int i = 0; i < Half; ++i)
2804 if (!isUndefOrInRange(Mask[i], NumElems, NumElems*2))
2806 for (int i = Half; i < NumElems; ++i)
2807 if (!isUndefOrInRange(Mask[i], 0, NumElems))
2812 static bool isCommutedSHUFP(ShuffleVectorSDNode *N) {
2813 SmallVector<int, 8> M;
2815 return isCommutedSHUFPMask(M, N->getValueType(0));
2818 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
2819 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
2820 bool X86::isMOVHLPSMask(ShuffleVectorSDNode *N) {
2821 if (N->getValueType(0).getVectorNumElements() != 4)
2824 // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
2825 return isUndefOrEqual(N->getMaskElt(0), 6) &&
2826 isUndefOrEqual(N->getMaskElt(1), 7) &&
2827 isUndefOrEqual(N->getMaskElt(2), 2) &&
2828 isUndefOrEqual(N->getMaskElt(3), 3);
2831 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
2832 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
2834 bool X86::isMOVHLPS_v_undef_Mask(ShuffleVectorSDNode *N) {
2835 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2840 return isUndefOrEqual(N->getMaskElt(0), 2) &&
2841 isUndefOrEqual(N->getMaskElt(1), 3) &&
2842 isUndefOrEqual(N->getMaskElt(2), 2) &&
2843 isUndefOrEqual(N->getMaskElt(3), 3);
2846 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
2847 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
2848 bool X86::isMOVLPMask(ShuffleVectorSDNode *N) {
2849 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2851 if (NumElems != 2 && NumElems != 4)
2854 for (unsigned i = 0; i < NumElems/2; ++i)
2855 if (!isUndefOrEqual(N->getMaskElt(i), i + NumElems))
2858 for (unsigned i = NumElems/2; i < NumElems; ++i)
2859 if (!isUndefOrEqual(N->getMaskElt(i), i))
2865 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
2866 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
2867 bool X86::isMOVLHPSMask(ShuffleVectorSDNode *N) {
2868 unsigned NumElems = N->getValueType(0).getVectorNumElements();
2870 if (NumElems != 2 && NumElems != 4)
2873 for (unsigned i = 0; i < NumElems/2; ++i)
2874 if (!isUndefOrEqual(N->getMaskElt(i), i))
2877 for (unsigned i = 0; i < NumElems/2; ++i)
2878 if (!isUndefOrEqual(N->getMaskElt(i + NumElems/2), i + NumElems))
2884 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
2885 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
2886 static bool isUNPCKLMask(const SmallVectorImpl<int> &Mask, EVT VT,
2887 bool V2IsSplat = false) {
2888 int NumElts = VT.getVectorNumElements();
2889 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2892 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2894 int BitI1 = Mask[i+1];
2895 if (!isUndefOrEqual(BitI, j))
2898 if (!isUndefOrEqual(BitI1, NumElts))
2901 if (!isUndefOrEqual(BitI1, j + NumElts))
2908 bool X86::isUNPCKLMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2909 SmallVector<int, 8> M;
2911 return ::isUNPCKLMask(M, N->getValueType(0), V2IsSplat);
2914 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
2915 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
2916 static bool isUNPCKHMask(const SmallVectorImpl<int> &Mask, EVT VT,
2917 bool V2IsSplat = false) {
2918 int NumElts = VT.getVectorNumElements();
2919 if (NumElts != 2 && NumElts != 4 && NumElts != 8 && NumElts != 16)
2922 for (int i = 0, j = 0; i != NumElts; i += 2, ++j) {
2924 int BitI1 = Mask[i+1];
2925 if (!isUndefOrEqual(BitI, j + NumElts/2))
2928 if (isUndefOrEqual(BitI1, NumElts))
2931 if (!isUndefOrEqual(BitI1, j + NumElts/2 + NumElts))
2938 bool X86::isUNPCKHMask(ShuffleVectorSDNode *N, bool V2IsSplat) {
2939 SmallVector<int, 8> M;
2941 return ::isUNPCKHMask(M, N->getValueType(0), V2IsSplat);
2944 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
2945 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
2947 static bool isUNPCKL_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2948 int NumElems = VT.getVectorNumElements();
2949 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2952 for (int i = 0, j = 0; i != NumElems; i += 2, ++j) {
2954 int BitI1 = Mask[i+1];
2955 if (!isUndefOrEqual(BitI, j))
2957 if (!isUndefOrEqual(BitI1, j))
2963 bool X86::isUNPCKL_v_undef_Mask(ShuffleVectorSDNode *N) {
2964 SmallVector<int, 8> M;
2966 return ::isUNPCKL_v_undef_Mask(M, N->getValueType(0));
2969 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
2970 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
2972 static bool isUNPCKH_v_undef_Mask(const SmallVectorImpl<int> &Mask, EVT VT) {
2973 int NumElems = VT.getVectorNumElements();
2974 if (NumElems != 2 && NumElems != 4 && NumElems != 8 && NumElems != 16)
2977 for (int i = 0, j = NumElems / 2; i != NumElems; i += 2, ++j) {
2979 int BitI1 = Mask[i+1];
2980 if (!isUndefOrEqual(BitI, j))
2982 if (!isUndefOrEqual(BitI1, j))
2988 bool X86::isUNPCKH_v_undef_Mask(ShuffleVectorSDNode *N) {
2989 SmallVector<int, 8> M;
2991 return ::isUNPCKH_v_undef_Mask(M, N->getValueType(0));
2994 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
2995 /// specifies a shuffle of elements that is suitable for input to MOVSS,
2996 /// MOVSD, and MOVD, i.e. setting the lowest element.
2997 static bool isMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT) {
2998 if (VT.getVectorElementType().getSizeInBits() < 32)
3001 int NumElts = VT.getVectorNumElements();
3003 if (!isUndefOrEqual(Mask[0], NumElts))
3006 for (int i = 1; i < NumElts; ++i)
3007 if (!isUndefOrEqual(Mask[i], i))
3013 bool X86::isMOVLMask(ShuffleVectorSDNode *N) {
3014 SmallVector<int, 8> M;
3016 return ::isMOVLMask(M, N->getValueType(0));
3019 /// isCommutedMOVL - Returns true if the shuffle mask is except the reverse
3020 /// of what x86 movss want. X86 movs requires the lowest element to be lowest
3021 /// element of vector 2 and the other elements to come from vector 1 in order.
3022 static bool isCommutedMOVLMask(const SmallVectorImpl<int> &Mask, EVT VT,
3023 bool V2IsSplat = false, bool V2IsUndef = false) {
3024 int NumOps = VT.getVectorNumElements();
3025 if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
3028 if (!isUndefOrEqual(Mask[0], 0))
3031 for (int i = 1; i < NumOps; ++i)
3032 if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
3033 (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
3034 (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
3040 static bool isCommutedMOVL(ShuffleVectorSDNode *N, bool V2IsSplat = false,
3041 bool V2IsUndef = false) {
3042 SmallVector<int, 8> M;
3044 return isCommutedMOVLMask(M, N->getValueType(0), V2IsSplat, V2IsUndef);
3047 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3048 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
3049 bool X86::isMOVSHDUPMask(ShuffleVectorSDNode *N) {
3050 if (N->getValueType(0).getVectorNumElements() != 4)
3053 // Expect 1, 1, 3, 3
3054 for (unsigned i = 0; i < 2; ++i) {
3055 int Elt = N->getMaskElt(i);
3056 if (Elt >= 0 && Elt != 1)
3061 for (unsigned i = 2; i < 4; ++i) {
3062 int Elt = N->getMaskElt(i);
3063 if (Elt >= 0 && Elt != 3)
3068 // Don't use movshdup if it can be done with a shufps.
3069 // FIXME: verify that matching u, u, 3, 3 is what we want.
3073 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3074 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
3075 bool X86::isMOVSLDUPMask(ShuffleVectorSDNode *N) {
3076 if (N->getValueType(0).getVectorNumElements() != 4)
3079 // Expect 0, 0, 2, 2
3080 for (unsigned i = 0; i < 2; ++i)
3081 if (N->getMaskElt(i) > 0)
3085 for (unsigned i = 2; i < 4; ++i) {
3086 int Elt = N->getMaskElt(i);
3087 if (Elt >= 0 && Elt != 2)
3092 // Don't use movsldup if it can be done with a shufps.
3096 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
3097 /// specifies a shuffle of elements that is suitable for input to MOVDDUP.
3098 bool X86::isMOVDDUPMask(ShuffleVectorSDNode *N) {
3099 int e = N->getValueType(0).getVectorNumElements() / 2;
3101 for (int i = 0; i < e; ++i)
3102 if (!isUndefOrEqual(N->getMaskElt(i), i))
3104 for (int i = 0; i < e; ++i)
3105 if (!isUndefOrEqual(N->getMaskElt(e+i), i))
3110 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
3111 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
3112 unsigned X86::getShuffleSHUFImmediate(SDNode *N) {
3113 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3114 int NumOperands = SVOp->getValueType(0).getVectorNumElements();
3116 unsigned Shift = (NumOperands == 4) ? 2 : 1;
3118 for (int i = 0; i < NumOperands; ++i) {
3119 int Val = SVOp->getMaskElt(NumOperands-i-1);
3120 if (Val < 0) Val = 0;
3121 if (Val >= NumOperands) Val -= NumOperands;
3123 if (i != NumOperands - 1)
3129 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
3130 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
3131 unsigned X86::getShufflePSHUFHWImmediate(SDNode *N) {
3132 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3134 // 8 nodes, but we only care about the last 4.
3135 for (unsigned i = 7; i >= 4; --i) {
3136 int Val = SVOp->getMaskElt(i);
3145 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
3146 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
3147 unsigned X86::getShufflePSHUFLWImmediate(SDNode *N) {
3148 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3150 // 8 nodes, but we only care about the first 4.
3151 for (int i = 3; i >= 0; --i) {
3152 int Val = SVOp->getMaskElt(i);
3161 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
3162 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
3163 unsigned X86::getShufflePALIGNRImmediate(SDNode *N) {
3164 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
3165 EVT VVT = N->getValueType(0);
3166 unsigned EltSize = VVT.getVectorElementType().getSizeInBits() >> 3;
3170 for (i = 0, e = VVT.getVectorNumElements(); i != e; ++i) {
3171 Val = SVOp->getMaskElt(i);
3175 return (Val - i) * EltSize;
3178 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
3180 bool X86::isZeroNode(SDValue Elt) {
3181 return ((isa<ConstantSDNode>(Elt) &&
3182 cast<ConstantSDNode>(Elt)->isNullValue()) ||
3183 (isa<ConstantFPSDNode>(Elt) &&
3184 cast<ConstantFPSDNode>(Elt)->getValueAPF().isPosZero()));
3187 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
3188 /// their permute mask.
3189 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
3190 SelectionDAG &DAG) {
3191 EVT VT = SVOp->getValueType(0);
3192 unsigned NumElems = VT.getVectorNumElements();
3193 SmallVector<int, 8> MaskVec;
3195 for (unsigned i = 0; i != NumElems; ++i) {
3196 int idx = SVOp->getMaskElt(i);
3198 MaskVec.push_back(idx);
3199 else if (idx < (int)NumElems)
3200 MaskVec.push_back(idx + NumElems);
3202 MaskVec.push_back(idx - NumElems);
3204 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(1),
3205 SVOp->getOperand(0), &MaskVec[0]);
3208 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3209 /// the two vector operands have swapped position.
3210 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask, EVT VT) {
3211 unsigned NumElems = VT.getVectorNumElements();
3212 for (unsigned i = 0; i != NumElems; ++i) {
3216 else if (idx < (int)NumElems)
3217 Mask[i] = idx + NumElems;
3219 Mask[i] = idx - NumElems;
3223 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
3224 /// match movhlps. The lower half elements should come from upper half of
3225 /// V1 (and in order), and the upper half elements should come from the upper
3226 /// half of V2 (and in order).
3227 static bool ShouldXformToMOVHLPS(ShuffleVectorSDNode *Op) {
3228 if (Op->getValueType(0).getVectorNumElements() != 4)
3230 for (unsigned i = 0, e = 2; i != e; ++i)
3231 if (!isUndefOrEqual(Op->getMaskElt(i), i+2))
3233 for (unsigned i = 2; i != 4; ++i)
3234 if (!isUndefOrEqual(Op->getMaskElt(i), i+4))
3239 /// isScalarLoadToVector - Returns true if the node is a scalar load that
3240 /// is promoted to a vector. It also returns the LoadSDNode by reference if
3242 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = NULL) {
3243 if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
3245 N = N->getOperand(0).getNode();
3246 if (!ISD::isNON_EXTLoad(N))
3249 *LD = cast<LoadSDNode>(N);
3253 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
3254 /// match movlp{s|d}. The lower half elements should come from lower half of
3255 /// V1 (and in order), and the upper half elements should come from the upper
3256 /// half of V2 (and in order). And since V1 will become the source of the
3257 /// MOVLP, it must be either a vector load or a scalar load to vector.
3258 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
3259 ShuffleVectorSDNode *Op) {
3260 if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
3262 // Is V2 is a vector load, don't do this transformation. We will try to use
3263 // load folding shufps op.
3264 if (ISD::isNON_EXTLoad(V2))
3267 unsigned NumElems = Op->getValueType(0).getVectorNumElements();
3269 if (NumElems != 2 && NumElems != 4)
3271 for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3272 if (!isUndefOrEqual(Op->getMaskElt(i), i))
3274 for (unsigned i = NumElems/2; i != NumElems; ++i)
3275 if (!isUndefOrEqual(Op->getMaskElt(i), i+NumElems))
3280 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
3282 static bool isSplatVector(SDNode *N) {
3283 if (N->getOpcode() != ISD::BUILD_VECTOR)
3286 SDValue SplatValue = N->getOperand(0);
3287 for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
3288 if (N->getOperand(i) != SplatValue)
3293 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
3294 /// to an zero vector.
3295 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
3296 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
3297 SDValue V1 = N->getOperand(0);
3298 SDValue V2 = N->getOperand(1);
3299 unsigned NumElems = N->getValueType(0).getVectorNumElements();
3300 for (unsigned i = 0; i != NumElems; ++i) {
3301 int Idx = N->getMaskElt(i);
3302 if (Idx >= (int)NumElems) {
3303 unsigned Opc = V2.getOpcode();
3304 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
3306 if (Opc != ISD::BUILD_VECTOR ||
3307 !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
3309 } else if (Idx >= 0) {
3310 unsigned Opc = V1.getOpcode();
3311 if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
3313 if (Opc != ISD::BUILD_VECTOR ||
3314 !X86::isZeroNode(V1.getOperand(Idx)))
3321 /// getZeroVector - Returns a vector of specified type with all zero elements.
3323 static SDValue getZeroVector(EVT VT, bool HasSSE2, SelectionDAG &DAG,
3325 assert(VT.isVector() && "Expected a vector type");
3327 // Always build zero vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3328 // type. This ensures they get CSE'd.
3330 if (VT.getSizeInBits() == 64) { // MMX
3331 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3332 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3333 } else if (HasSSE2) { // SSE2
3334 SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
3335 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3337 SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
3338 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
3340 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3343 /// getOnesVector - Returns a vector of specified type with all bits set.
3345 static SDValue getOnesVector(EVT VT, SelectionDAG &DAG, DebugLoc dl) {
3346 assert(VT.isVector() && "Expected a vector type");
3348 // Always build ones vectors as <4 x i32> or <2 x i32> bitcasted to their dest
3349 // type. This ensures they get CSE'd.
3350 SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
3352 if (VT.getSizeInBits() == 64) // MMX
3353 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2i32, Cst, Cst);
3355 Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
3356 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Vec);
3360 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
3361 /// that point to V2 points to its first element.
3362 static SDValue NormalizeMask(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
3363 EVT VT = SVOp->getValueType(0);
3364 unsigned NumElems = VT.getVectorNumElements();
3366 bool Changed = false;
3367 SmallVector<int, 8> MaskVec;
3368 SVOp->getMask(MaskVec);
3370 for (unsigned i = 0; i != NumElems; ++i) {
3371 if (MaskVec[i] > (int)NumElems) {
3372 MaskVec[i] = NumElems;
3377 return DAG.getVectorShuffle(VT, SVOp->getDebugLoc(), SVOp->getOperand(0),
3378 SVOp->getOperand(1), &MaskVec[0]);
3379 return SDValue(SVOp, 0);
3382 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
3383 /// operation of specified width.
3384 static SDValue getMOVL(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3386 unsigned NumElems = VT.getVectorNumElements();
3387 SmallVector<int, 8> Mask;
3388 Mask.push_back(NumElems);
3389 for (unsigned i = 1; i != NumElems; ++i)
3391 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3394 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
3395 static SDValue getUnpackl(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3397 unsigned NumElems = VT.getVectorNumElements();
3398 SmallVector<int, 8> Mask;
3399 for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
3401 Mask.push_back(i + NumElems);
3403 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3406 /// getUnpackhMask - Returns a vector_shuffle node for an unpackh operation.
3407 static SDValue getUnpackh(SelectionDAG &DAG, DebugLoc dl, EVT VT, SDValue V1,
3409 unsigned NumElems = VT.getVectorNumElements();
3410 unsigned Half = NumElems/2;
3411 SmallVector<int, 8> Mask;
3412 for (unsigned i = 0; i != Half; ++i) {
3413 Mask.push_back(i + Half);
3414 Mask.push_back(i + NumElems + Half);
3416 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
3419 /// PromoteSplat - Promote a splat of v4f32, v8i16 or v16i8 to v4i32.
3420 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG,
3422 if (SV->getValueType(0).getVectorNumElements() <= 4)
3423 return SDValue(SV, 0);
3425 EVT PVT = MVT::v4f32;
3426 EVT VT = SV->getValueType(0);
3427 DebugLoc dl = SV->getDebugLoc();
3428 SDValue V1 = SV->getOperand(0);
3429 int NumElems = VT.getVectorNumElements();
3430 int EltNo = SV->getSplatIndex();
3432 // unpack elements to the correct location
3433 while (NumElems > 4) {
3434 if (EltNo < NumElems/2) {
3435 V1 = getUnpackl(DAG, dl, VT, V1, V1);
3437 V1 = getUnpackh(DAG, dl, VT, V1, V1);
3438 EltNo -= NumElems/2;
3443 // Perform the splat.
3444 int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
3445 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, PVT, V1);
3446 V1 = DAG.getVectorShuffle(PVT, dl, V1, DAG.getUNDEF(PVT), &SplatMask[0]);
3447 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, V1);
3450 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
3451 /// vector of zero or undef vector. This produces a shuffle where the low
3452 /// element of V2 is swizzled into the zero/undef vector, landing at element
3453 /// Idx. This produces a shuffle mask like 4,1,2,3 (idx=0) or 0,1,2,4 (idx=3).
3454 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
3455 bool isZero, bool HasSSE2,
3456 SelectionDAG &DAG) {
3457 EVT VT = V2.getValueType();
3459 ? getZeroVector(VT, HasSSE2, DAG, V2.getDebugLoc()) : DAG.getUNDEF(VT);
3460 unsigned NumElems = VT.getVectorNumElements();
3461 SmallVector<int, 16> MaskVec;
3462 for (unsigned i = 0; i != NumElems; ++i)
3463 // If this is the insertion idx, put the low elt of V2 here.
3464 MaskVec.push_back(i == Idx ? NumElems : i);
3465 return DAG.getVectorShuffle(VT, V2.getDebugLoc(), V1, V2, &MaskVec[0]);
3468 /// getNumOfConsecutiveZeros - Return the number of elements in a result of
3469 /// a shuffle that is zero.
3471 unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp, int NumElems,
3472 bool Low, SelectionDAG &DAG) {
3473 unsigned NumZeros = 0;
3474 for (int i = 0; i < NumElems; ++i) {
3475 unsigned Index = Low ? i : NumElems-i-1;
3476 int Idx = SVOp->getMaskElt(Index);
3481 SDValue Elt = DAG.getShuffleScalarElt(SVOp, Index);
3482 if (Elt.getNode() && X86::isZeroNode(Elt))
3490 /// isVectorShift - Returns true if the shuffle can be implemented as a
3491 /// logical left or right shift of a vector.
3492 /// FIXME: split into pslldqi, psrldqi, palignr variants.
3493 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
3494 bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
3495 unsigned NumElems = SVOp->getValueType(0).getVectorNumElements();
3498 unsigned NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, true, DAG);
3501 NumZeros = getNumOfConsecutiveZeros(SVOp, NumElems, false, DAG);
3505 bool SeenV1 = false;
3506 bool SeenV2 = false;
3507 for (unsigned i = NumZeros; i < NumElems; ++i) {
3508 unsigned Val = isLeft ? (i - NumZeros) : i;
3509 int Idx_ = SVOp->getMaskElt(isLeft ? i : (i - NumZeros));
3512 unsigned Idx = (unsigned) Idx_;
3522 if (SeenV1 && SeenV2)
3525 ShVal = SeenV1 ? SVOp->getOperand(0) : SVOp->getOperand(1);
3531 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
3533 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
3534 unsigned NumNonZero, unsigned NumZero,
3536 const TargetLowering &TLI) {
3540 DebugLoc dl = Op.getDebugLoc();
3543 for (unsigned i = 0; i < 16; ++i) {
3544 bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
3545 if (ThisIsNonZero && First) {
3547 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3549 V = DAG.getUNDEF(MVT::v8i16);
3554 SDValue ThisElt(0, 0), LastElt(0, 0);
3555 bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
3556 if (LastIsNonZero) {
3557 LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
3558 MVT::i16, Op.getOperand(i-1));
3560 if (ThisIsNonZero) {
3561 ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
3562 ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
3563 ThisElt, DAG.getConstant(8, MVT::i8));
3565 ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
3569 if (ThisElt.getNode())
3570 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
3571 DAG.getIntPtrConstant(i/2));
3575 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V);
3578 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
3580 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
3581 unsigned NumNonZero, unsigned NumZero,
3583 const TargetLowering &TLI) {
3587 DebugLoc dl = Op.getDebugLoc();
3590 for (unsigned i = 0; i < 8; ++i) {
3591 bool isNonZero = (NonZeros & (1 << i)) != 0;
3595 V = getZeroVector(MVT::v8i16, true, DAG, dl);
3597 V = DAG.getUNDEF(MVT::v8i16);
3600 V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
3601 MVT::v8i16, V, Op.getOperand(i),
3602 DAG.getIntPtrConstant(i));
3609 /// getVShift - Return a vector logical shift node.
3611 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
3612 unsigned NumBits, SelectionDAG &DAG,
3613 const TargetLowering &TLI, DebugLoc dl) {
3614 bool isMMX = VT.getSizeInBits() == 64;
3615 EVT ShVT = isMMX ? MVT::v1i64 : MVT::v2i64;
3616 unsigned Opc = isLeft ? X86ISD::VSHL : X86ISD::VSRL;
3617 SrcOp = DAG.getNode(ISD::BIT_CONVERT, dl, ShVT, SrcOp);
3618 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3619 DAG.getNode(Opc, dl, ShVT, SrcOp,
3620 DAG.getConstant(NumBits, TLI.getShiftAmountTy())));
3624 X86TargetLowering::LowerAsSplatVectorLoad(SDValue SrcOp, EVT VT, DebugLoc dl,
3625 SelectionDAG &DAG) const {
3627 // Check if the scalar load can be widened into a vector load. And if
3628 // the address is "base + cst" see if the cst can be "absorbed" into
3629 // the shuffle mask.
3630 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
3631 SDValue Ptr = LD->getBasePtr();
3632 if (!ISD::isNormalLoad(LD) || LD->isVolatile())
3634 EVT PVT = LD->getValueType(0);
3635 if (PVT != MVT::i32 && PVT != MVT::f32)
3640 if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
3641 FI = FINode->getIndex();
3643 } else if (Ptr.getOpcode() == ISD::ADD &&
3644 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
3645 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
3646 FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
3647 Offset = Ptr.getConstantOperandVal(1);
3648 Ptr = Ptr.getOperand(0);
3653 SDValue Chain = LD->getChain();
3654 // Make sure the stack object alignment is at least 16.
3655 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3656 if (DAG.InferPtrAlignment(Ptr) < 16) {
3657 if (MFI->isFixedObjectIndex(FI)) {
3658 // Can't change the alignment. FIXME: It's possible to compute
3659 // the exact stack offset and reference FI + adjust offset instead.
3660 // If someone *really* cares about this. That's the way to implement it.
3663 MFI->setObjectAlignment(FI, 16);
3667 // (Offset % 16) must be multiple of 4. Then address is then
3668 // Ptr + (Offset & ~15).
3671 if ((Offset % 16) & 3)
3673 int64_t StartOffset = Offset & ~15;
3675 Ptr = DAG.getNode(ISD::ADD, Ptr.getDebugLoc(), Ptr.getValueType(),
3676 Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
3678 int EltNo = (Offset - StartOffset) >> 2;
3679 int Mask[4] = { EltNo, EltNo, EltNo, EltNo };
3680 EVT VT = (PVT == MVT::i32) ? MVT::v4i32 : MVT::v4f32;
3681 SDValue V1 = DAG.getLoad(VT, dl, Chain, Ptr,LD->getSrcValue(),0,
3683 // Canonicalize it to a v4i32 shuffle.
3684 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32, V1);
3685 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
3686 DAG.getVectorShuffle(MVT::v4i32, dl, V1,
3687 DAG.getUNDEF(MVT::v4i32), &Mask[0]));
3693 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
3694 /// vector of type 'VT', see if the elements can be replaced by a single large
3695 /// load which has the same value as a build_vector whose operands are 'elts'.
3697 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
3699 /// FIXME: we'd also like to handle the case where the last elements are zero
3700 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
3701 /// There's even a handy isZeroNode for that purpose.
3702 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
3703 DebugLoc &dl, SelectionDAG &DAG) {
3704 EVT EltVT = VT.getVectorElementType();
3705 unsigned NumElems = Elts.size();
3707 LoadSDNode *LDBase = NULL;
3708 unsigned LastLoadedElt = -1U;
3710 // For each element in the initializer, see if we've found a load or an undef.
3711 // If we don't find an initial load element, or later load elements are
3712 // non-consecutive, bail out.
3713 for (unsigned i = 0; i < NumElems; ++i) {
3714 SDValue Elt = Elts[i];
3716 if (!Elt.getNode() ||
3717 (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
3720 if (Elt.getNode()->getOpcode() == ISD::UNDEF)
3722 LDBase = cast<LoadSDNode>(Elt.getNode());
3726 if (Elt.getOpcode() == ISD::UNDEF)
3729 LoadSDNode *LD = cast<LoadSDNode>(Elt);
3730 if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
3735 // If we have found an entire vector of loads and undefs, then return a large
3736 // load of the entire vector width starting at the base pointer. If we found
3737 // consecutive loads for the low half, generate a vzext_load node.
3738 if (LastLoadedElt == NumElems - 1) {
3739 if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
3740 return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3741 LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3742 LDBase->isVolatile(), LDBase->isNonTemporal(), 0);
3743 return DAG.getLoad(VT, dl, LDBase->getChain(), LDBase->getBasePtr(),
3744 LDBase->getSrcValue(), LDBase->getSrcValueOffset(),
3745 LDBase->isVolatile(), LDBase->isNonTemporal(),
3746 LDBase->getAlignment());
3747 } else if (NumElems == 4 && LastLoadedElt == 1) {
3748 SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
3749 SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
3750 SDValue ResNode = DAG.getNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops, 2);
3751 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, ResNode);
3757 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
3758 DebugLoc dl = Op.getDebugLoc();
3759 // All zero's are handled with pxor, all one's are handled with pcmpeqd.
3760 if (ISD::isBuildVectorAllZeros(Op.getNode())
3761 || ISD::isBuildVectorAllOnes(Op.getNode())) {
3762 // Canonicalize this to either <4 x i32> or <2 x i32> (SSE vs MMX) to
3763 // 1) ensure the zero vectors are CSE'd, and 2) ensure that i64 scalars are
3764 // eliminated on x86-32 hosts.
3765 if (Op.getValueType() == MVT::v4i32 || Op.getValueType() == MVT::v2i32)
3768 if (ISD::isBuildVectorAllOnes(Op.getNode()))
3769 return getOnesVector(Op.getValueType(), DAG, dl);
3770 return getZeroVector(Op.getValueType(), Subtarget->hasSSE2(), DAG, dl);
3773 EVT VT = Op.getValueType();
3774 EVT ExtVT = VT.getVectorElementType();
3775 unsigned EVTBits = ExtVT.getSizeInBits();
3777 unsigned NumElems = Op.getNumOperands();
3778 unsigned NumZero = 0;
3779 unsigned NumNonZero = 0;
3780 unsigned NonZeros = 0;
3781 bool IsAllConstants = true;
3782 SmallSet<SDValue, 8> Values;
3783 for (unsigned i = 0; i < NumElems; ++i) {
3784 SDValue Elt = Op.getOperand(i);
3785 if (Elt.getOpcode() == ISD::UNDEF)
3788 if (Elt.getOpcode() != ISD::Constant &&
3789 Elt.getOpcode() != ISD::ConstantFP)
3790 IsAllConstants = false;
3791 if (X86::isZeroNode(Elt))
3794 NonZeros |= (1 << i);
3799 if (NumNonZero == 0) {
3800 // All undef vector. Return an UNDEF. All zero vectors were handled above.
3801 return DAG.getUNDEF(VT);
3804 // Special case for single non-zero, non-undef, element.
3805 if (NumNonZero == 1) {
3806 unsigned Idx = CountTrailingZeros_32(NonZeros);
3807 SDValue Item = Op.getOperand(Idx);
3809 // If this is an insertion of an i64 value on x86-32, and if the top bits of
3810 // the value are obviously zero, truncate the value to i32 and do the
3811 // insertion that way. Only do this if the value is non-constant or if the
3812 // value is a constant being inserted into element 0. It is cheaper to do
3813 // a constant pool load than it is to do a movd + shuffle.
3814 if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
3815 (!IsAllConstants || Idx == 0)) {
3816 if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
3817 // Handle MMX and SSE both.
3818 EVT VecVT = VT == MVT::v2i64 ? MVT::v4i32 : MVT::v2i32;
3819 unsigned VecElts = VT == MVT::v2i64 ? 4 : 2;
3821 // Truncate the value (which may itself be a constant) to i32, and
3822 // convert it to a vector with movd (S2V+shuffle to zero extend).
3823 Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
3824 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
3825 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3826 Subtarget->hasSSE2(), DAG);
3828 // Now we have our 32-bit value zero extended in the low element of
3829 // a vector. If Idx != 0, swizzle it into place.
3831 SmallVector<int, 4> Mask;
3832 Mask.push_back(Idx);
3833 for (unsigned i = 1; i != VecElts; ++i)
3835 Item = DAG.getVectorShuffle(VecVT, dl, Item,
3836 DAG.getUNDEF(Item.getValueType()),
3839 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(), Item);
3843 // If we have a constant or non-constant insertion into the low element of
3844 // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
3845 // the rest of the elements. This will be matched as movd/movq/movss/movsd
3846 // depending on what the source datatype is.
3849 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3850 } else if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
3851 (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
3852 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3853 // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
3854 return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget->hasSSE2(),
3856 } else if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
3857 Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
3858 EVT MiddleVT = VT.getSizeInBits() == 64 ? MVT::v2i32 : MVT::v4i32;
3859 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MiddleVT, Item);
3860 Item = getShuffleVectorZeroOrUndef(Item, 0, true,
3861 Subtarget->hasSSE2(), DAG);
3862 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Item);
3866 // Is it a vector logical left shift?
3867 if (NumElems == 2 && Idx == 1 &&
3868 X86::isZeroNode(Op.getOperand(0)) &&
3869 !X86::isZeroNode(Op.getOperand(1))) {
3870 unsigned NumBits = VT.getSizeInBits();
3871 return getVShift(true, VT,
3872 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
3873 VT, Op.getOperand(1)),
3874 NumBits/2, DAG, *this, dl);
3877 if (IsAllConstants) // Otherwise, it's better to do a constpool load.
3880 // Otherwise, if this is a vector with i32 or f32 elements, and the element
3881 // is a non-constant being inserted into an element other than the low one,
3882 // we can't use a constant pool load. Instead, use SCALAR_TO_VECTOR (aka
3883 // movd/movss) to move this into the low element, then shuffle it into
3885 if (EVTBits == 32) {
3886 Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
3888 // Turn it into a shuffle of zero and zero-extended scalar to vector.
3889 Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0,
3890 Subtarget->hasSSE2(), DAG);
3891 SmallVector<int, 8> MaskVec;
3892 for (unsigned i = 0; i < NumElems; i++)
3893 MaskVec.push_back(i == Idx ? 0 : 1);
3894 return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
3898 // Splat is obviously ok. Let legalizer expand it to a shuffle.
3899 if (Values.size() == 1) {
3900 if (EVTBits == 32) {
3901 // Instead of a shuffle like this:
3902 // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
3903 // Check if it's possible to issue this instead.
3904 // shuffle (vload ptr)), undef, <1, 1, 1, 1>
3905 unsigned Idx = CountTrailingZeros_32(NonZeros);
3906 SDValue Item = Op.getOperand(Idx);
3907 if (Op.getNode()->isOnlyUserOf(Item.getNode()))
3908 return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
3913 // A vector full of immediates; various special cases are already
3914 // handled, so this is best done with a single constant-pool load.
3918 // Let legalizer expand 2-wide build_vectors.
3919 if (EVTBits == 64) {
3920 if (NumNonZero == 1) {
3921 // One half is zero or undef.
3922 unsigned Idx = CountTrailingZeros_32(NonZeros);
3923 SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
3924 Op.getOperand(Idx));
3925 return getShuffleVectorZeroOrUndef(V2, Idx, true,
3926 Subtarget->hasSSE2(), DAG);
3931 // If element VT is < 32 bits, convert it to inserts into a zero vector.
3932 if (EVTBits == 8 && NumElems == 16) {
3933 SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
3935 if (V.getNode()) return V;
3938 if (EVTBits == 16 && NumElems == 8) {
3939 SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
3941 if (V.getNode()) return V;
3944 // If element VT is == 32 bits, turn it into a number of shuffles.
3945 SmallVector<SDValue, 8> V;
3947 if (NumElems == 4 && NumZero > 0) {
3948 for (unsigned i = 0; i < 4; ++i) {
3949 bool isZero = !(NonZeros & (1 << i));
3951 V[i] = getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
3953 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
3956 for (unsigned i = 0; i < 2; ++i) {
3957 switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
3960 V[i] = V[i*2]; // Must be a zero vector.
3963 V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
3966 V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
3969 V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
3974 SmallVector<int, 8> MaskVec;
3975 bool Reverse = (NonZeros & 0x3) == 2;
3976 for (unsigned i = 0; i < 2; ++i)
3977 MaskVec.push_back(Reverse ? 1-i : i);
3978 Reverse = ((NonZeros & (0x3 << 2)) >> 2) == 2;
3979 for (unsigned i = 0; i < 2; ++i)
3980 MaskVec.push_back(Reverse ? 1-i+NumElems : i+NumElems);
3981 return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
3984 if (Values.size() > 1 && VT.getSizeInBits() == 128) {
3985 // Check for a build vector of consecutive loads.
3986 for (unsigned i = 0; i < NumElems; ++i)
3987 V[i] = Op.getOperand(i);
3989 // Check for elements which are consecutive loads.
3990 SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG);
3994 // For SSE 4.1, use inserts into undef.
3995 if (getSubtarget()->hasSSE41()) {
3996 V[0] = DAG.getUNDEF(VT);
3997 for (unsigned i = 0; i < NumElems; ++i)
3998 if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
3999 V[0] = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, V[0],
4000 Op.getOperand(i), DAG.getIntPtrConstant(i));
4004 // Otherwise, expand into a number of unpckl*
4006 // Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
4007 // : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
4008 // Step 2: unpcklps X, Y ==> <3, 2, 1, 0>
4009 for (unsigned i = 0; i < NumElems; ++i)
4010 V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
4012 while (NumElems != 0) {
4013 for (unsigned i = 0; i < NumElems; ++i)
4014 V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + NumElems]);
4023 X86TargetLowering::LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) const {
4024 // We support concatenate two MMX registers and place them in a MMX
4025 // register. This is better than doing a stack convert.
4026 DebugLoc dl = Op.getDebugLoc();
4027 EVT ResVT = Op.getValueType();
4028 assert(Op.getNumOperands() == 2);
4029 assert(ResVT == MVT::v2i64 || ResVT == MVT::v4i32 ||
4030 ResVT == MVT::v8i16 || ResVT == MVT::v16i8);
4032 SDValue InVec = DAG.getNode(ISD::BIT_CONVERT,dl, MVT::v1i64, Op.getOperand(0));
4033 SDValue VecOp = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4034 InVec = Op.getOperand(1);
4035 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
4036 unsigned NumElts = ResVT.getVectorNumElements();
4037 VecOp = DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4038 VecOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ResVT, VecOp,
4039 InVec.getOperand(0), DAG.getIntPtrConstant(NumElts/2+1));
4041 InVec = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v1i64, InVec);
4042 SDValue VecOp2 = DAG.getNode(X86ISD::MOVQ2DQ, dl, MVT::v2i64, InVec);
4043 Mask[0] = 0; Mask[1] = 2;
4044 VecOp = DAG.getVectorShuffle(MVT::v2i64, dl, VecOp, VecOp2, Mask);
4046 return DAG.getNode(ISD::BIT_CONVERT, dl, ResVT, VecOp);
4049 // v8i16 shuffles - Prefer shuffles in the following order:
4050 // 1. [all] pshuflw, pshufhw, optional move
4051 // 2. [ssse3] 1 x pshufb
4052 // 3. [ssse3] 2 x pshufb + 1 x por
4053 // 4. [all] mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
4055 SDValue LowerVECTOR_SHUFFLEv8i16(ShuffleVectorSDNode *SVOp,
4057 const X86TargetLowering &TLI) {
4058 SDValue V1 = SVOp->getOperand(0);
4059 SDValue V2 = SVOp->getOperand(1);
4060 DebugLoc dl = SVOp->getDebugLoc();
4061 SmallVector<int, 8> MaskVals;
4063 // Determine if more than 1 of the words in each of the low and high quadwords
4064 // of the result come from the same quadword of one of the two inputs. Undef
4065 // mask values count as coming from any quadword, for better codegen.
4066 SmallVector<unsigned, 4> LoQuad(4);
4067 SmallVector<unsigned, 4> HiQuad(4);
4068 BitVector InputQuads(4);
4069 for (unsigned i = 0; i < 8; ++i) {
4070 SmallVectorImpl<unsigned> &Quad = i < 4 ? LoQuad : HiQuad;
4071 int EltIdx = SVOp->getMaskElt(i);
4072 MaskVals.push_back(EltIdx);
4081 InputQuads.set(EltIdx / 4);
4084 int BestLoQuad = -1;
4085 unsigned MaxQuad = 1;
4086 for (unsigned i = 0; i < 4; ++i) {
4087 if (LoQuad[i] > MaxQuad) {
4089 MaxQuad = LoQuad[i];
4093 int BestHiQuad = -1;
4095 for (unsigned i = 0; i < 4; ++i) {
4096 if (HiQuad[i] > MaxQuad) {
4098 MaxQuad = HiQuad[i];
4102 // For SSSE3, If all 8 words of the result come from only 1 quadword of each
4103 // of the two input vectors, shuffle them into one input vector so only a
4104 // single pshufb instruction is necessary. If There are more than 2 input
4105 // quads, disable the next transformation since it does not help SSSE3.
4106 bool V1Used = InputQuads[0] || InputQuads[1];
4107 bool V2Used = InputQuads[2] || InputQuads[3];
4108 if (TLI.getSubtarget()->hasSSSE3()) {
4109 if (InputQuads.count() == 2 && V1Used && V2Used) {
4110 BestLoQuad = InputQuads.find_first();
4111 BestHiQuad = InputQuads.find_next(BestLoQuad);
4113 if (InputQuads.count() > 2) {
4119 // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
4120 // the shuffle mask. If a quad is scored as -1, that means that it contains
4121 // words from all 4 input quadwords.
4123 if (BestLoQuad >= 0 || BestHiQuad >= 0) {
4124 SmallVector<int, 8> MaskV;
4125 MaskV.push_back(BestLoQuad < 0 ? 0 : BestLoQuad);
4126 MaskV.push_back(BestHiQuad < 0 ? 1 : BestHiQuad);
4127 NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
4128 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V1),
4129 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, V2), &MaskV[0]);
4130 NewV = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, NewV);
4132 // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
4133 // source words for the shuffle, to aid later transformations.
4134 bool AllWordsInNewV = true;
4135 bool InOrder[2] = { true, true };
4136 for (unsigned i = 0; i != 8; ++i) {
4137 int idx = MaskVals[i];
4139 InOrder[i/4] = false;
4140 if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
4142 AllWordsInNewV = false;
4146 bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
4147 if (AllWordsInNewV) {
4148 for (int i = 0; i != 8; ++i) {
4149 int idx = MaskVals[i];
4152 idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
4153 if ((idx != i) && idx < 4)
4155 if ((idx != i) && idx > 3)
4164 // If we've eliminated the use of V2, and the new mask is a pshuflw or
4165 // pshufhw, that's as cheap as it gets. Return the new shuffle.
4166 if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
4167 return DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
4168 DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
4172 // If we have SSSE3, and all words of the result are from 1 input vector,
4173 // case 2 is generated, otherwise case 3 is generated. If no SSSE3
4174 // is present, fall back to case 4.
4175 if (TLI.getSubtarget()->hasSSSE3()) {
4176 SmallVector<SDValue,16> pshufbMask;
4178 // If we have elements from both input vectors, set the high bit of the
4179 // shuffle mask element to zero out elements that come from V2 in the V1
4180 // mask, and elements that come from V1 in the V2 mask, so that the two
4181 // results can be OR'd together.
4182 bool TwoInputs = V1Used && V2Used;
4183 for (unsigned i = 0; i != 8; ++i) {
4184 int EltIdx = MaskVals[i] * 2;
4185 if (TwoInputs && (EltIdx >= 16)) {
4186 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4187 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4190 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4191 pshufbMask.push_back(DAG.getConstant(EltIdx+1, MVT::i8));
4193 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V1);
4194 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4195 DAG.getNode(ISD::BUILD_VECTOR, dl,
4196 MVT::v16i8, &pshufbMask[0], 16));
4198 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4200 // Calculate the shuffle mask for the second input, shuffle it, and
4201 // OR it with the first shuffled input.
4203 for (unsigned i = 0; i != 8; ++i) {
4204 int EltIdx = MaskVals[i] * 2;
4206 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4207 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4210 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4211 pshufbMask.push_back(DAG.getConstant(EltIdx - 15, MVT::i8));
4213 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, V2);
4214 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4215 DAG.getNode(ISD::BUILD_VECTOR, dl,
4216 MVT::v16i8, &pshufbMask[0], 16));
4217 V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4218 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4221 // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
4222 // and update MaskVals with new element order.
4223 BitVector InOrder(8);
4224 if (BestLoQuad >= 0) {
4225 SmallVector<int, 8> MaskV;
4226 for (int i = 0; i != 4; ++i) {
4227 int idx = MaskVals[i];
4229 MaskV.push_back(-1);
4231 } else if ((idx / 4) == BestLoQuad) {
4232 MaskV.push_back(idx & 3);
4235 MaskV.push_back(-1);
4238 for (unsigned i = 4; i != 8; ++i)
4240 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4244 // If BestHi >= 0, generate a pshufhw to put the high elements in order,
4245 // and update MaskVals with the new element order.
4246 if (BestHiQuad >= 0) {
4247 SmallVector<int, 8> MaskV;
4248 for (unsigned i = 0; i != 4; ++i)
4250 for (unsigned i = 4; i != 8; ++i) {
4251 int idx = MaskVals[i];
4253 MaskV.push_back(-1);
4255 } else if ((idx / 4) == BestHiQuad) {
4256 MaskV.push_back((idx & 3) + 4);
4259 MaskV.push_back(-1);
4262 NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
4266 // In case BestHi & BestLo were both -1, which means each quadword has a word
4267 // from each of the four input quadwords, calculate the InOrder bitvector now
4268 // before falling through to the insert/extract cleanup.
4269 if (BestLoQuad == -1 && BestHiQuad == -1) {
4271 for (int i = 0; i != 8; ++i)
4272 if (MaskVals[i] < 0 || MaskVals[i] == i)
4276 // The other elements are put in the right place using pextrw and pinsrw.
4277 for (unsigned i = 0; i != 8; ++i) {
4280 int EltIdx = MaskVals[i];
4283 SDValue ExtOp = (EltIdx < 8)
4284 ? DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
4285 DAG.getIntPtrConstant(EltIdx))
4286 : DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
4287 DAG.getIntPtrConstant(EltIdx - 8));
4288 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
4289 DAG.getIntPtrConstant(i));
4294 // v16i8 shuffles - Prefer shuffles in the following order:
4295 // 1. [ssse3] 1 x pshufb
4296 // 2. [ssse3] 2 x pshufb + 1 x por
4297 // 3. [all] v8i16 shuffle + N x pextrw + rotate + pinsrw
4299 SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
4301 const X86TargetLowering &TLI) {
4302 SDValue V1 = SVOp->getOperand(0);
4303 SDValue V2 = SVOp->getOperand(1);
4304 DebugLoc dl = SVOp->getDebugLoc();
4305 SmallVector<int, 16> MaskVals;
4306 SVOp->getMask(MaskVals);
4308 // If we have SSSE3, case 1 is generated when all result bytes come from
4309 // one of the inputs. Otherwise, case 2 is generated. If no SSSE3 is
4310 // present, fall back to case 3.
4311 // FIXME: kill V2Only once shuffles are canonizalized by getNode.
4314 for (unsigned i = 0; i < 16; ++i) {
4315 int EltIdx = MaskVals[i];
4324 // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
4325 if (TLI.getSubtarget()->hasSSSE3()) {
4326 SmallVector<SDValue,16> pshufbMask;
4328 // If all result elements are from one input vector, then only translate
4329 // undef mask values to 0x80 (zero out result) in the pshufb mask.
4331 // Otherwise, we have elements from both input vectors, and must zero out
4332 // elements that come from V2 in the first mask, and V1 in the second mask
4333 // so that we can OR them together.
4334 bool TwoInputs = !(V1Only || V2Only);
4335 for (unsigned i = 0; i != 16; ++i) {
4336 int EltIdx = MaskVals[i];
4337 if (EltIdx < 0 || (TwoInputs && EltIdx >= 16)) {
4338 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4341 pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
4343 // If all the elements are from V2, assign it to V1 and return after
4344 // building the first pshufb.
4347 V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
4348 DAG.getNode(ISD::BUILD_VECTOR, dl,
4349 MVT::v16i8, &pshufbMask[0], 16));
4353 // Calculate the shuffle mask for the second input, shuffle it, and
4354 // OR it with the first shuffled input.
4356 for (unsigned i = 0; i != 16; ++i) {
4357 int EltIdx = MaskVals[i];
4359 pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
4362 pshufbMask.push_back(DAG.getConstant(EltIdx - 16, MVT::i8));
4364 V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
4365 DAG.getNode(ISD::BUILD_VECTOR, dl,
4366 MVT::v16i8, &pshufbMask[0], 16));
4367 return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
4370 // No SSSE3 - Calculate in place words and then fix all out of place words
4371 // With 0-16 extracts & inserts. Worst case is 16 bytes out of order from
4372 // the 16 different words that comprise the two doublequadword input vectors.
4373 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V1);
4374 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v8i16, V2);
4375 SDValue NewV = V2Only ? V2 : V1;
4376 for (int i = 0; i != 8; ++i) {
4377 int Elt0 = MaskVals[i*2];
4378 int Elt1 = MaskVals[i*2+1];
4380 // This word of the result is all undef, skip it.
4381 if (Elt0 < 0 && Elt1 < 0)
4384 // This word of the result is already in the correct place, skip it.
4385 if (V1Only && (Elt0 == i*2) && (Elt1 == i*2+1))
4387 if (V2Only && (Elt0 == i*2+16) && (Elt1 == i*2+17))
4390 SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
4391 SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
4394 // If Elt0 and Elt1 are defined, are consecutive, and can be load
4395 // using a single extract together, load it and store it.
4396 if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
4397 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4398 DAG.getIntPtrConstant(Elt1 / 2));
4399 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4400 DAG.getIntPtrConstant(i));
4404 // If Elt1 is defined, extract it from the appropriate source. If the
4405 // source byte is not also odd, shift the extracted word left 8 bits
4406 // otherwise clear the bottom 8 bits if we need to do an or.
4408 InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
4409 DAG.getIntPtrConstant(Elt1 / 2));
4410 if ((Elt1 & 1) == 0)
4411 InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
4412 DAG.getConstant(8, TLI.getShiftAmountTy()));
4414 InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
4415 DAG.getConstant(0xFF00, MVT::i16));
4417 // If Elt0 is defined, extract it from the appropriate source. If the
4418 // source byte is not also even, shift the extracted word right 8 bits. If
4419 // Elt1 was also defined, OR the extracted values together before
4420 // inserting them in the result.
4422 SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
4423 Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
4424 if ((Elt0 & 1) != 0)
4425 InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
4426 DAG.getConstant(8, TLI.getShiftAmountTy()));
4428 InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
4429 DAG.getConstant(0x00FF, MVT::i16));
4430 InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
4433 NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
4434 DAG.getIntPtrConstant(i));
4436 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v16i8, NewV);
4439 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
4440 /// ones, or rewriting v4i32 / v2i32 as 2 wide ones if possible. This can be
4441 /// done when every pair / quad of shuffle mask elements point to elements in
4442 /// the right sequence. e.g.
4443 /// vector_shuffle <>, <>, < 3, 4, | 10, 11, | 0, 1, | 14, 15>
4445 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
4447 const TargetLowering &TLI, DebugLoc dl) {
4448 EVT VT = SVOp->getValueType(0);
4449 SDValue V1 = SVOp->getOperand(0);
4450 SDValue V2 = SVOp->getOperand(1);
4451 unsigned NumElems = VT.getVectorNumElements();
4452 unsigned NewWidth = (NumElems == 4) ? 2 : 4;
4453 EVT MaskVT = MVT::getIntVectorWithNumElements(NewWidth);
4455 switch (VT.getSimpleVT().SimpleTy) {
4456 default: assert(false && "Unexpected!");
4457 case MVT::v4f32: NewVT = MVT::v2f64; break;
4458 case MVT::v4i32: NewVT = MVT::v2i64; break;
4459 case MVT::v8i16: NewVT = MVT::v4i32; break;
4460 case MVT::v16i8: NewVT = MVT::v4i32; break;
4463 if (NewWidth == 2) {
4469 int Scale = NumElems / NewWidth;
4470 SmallVector<int, 8> MaskVec;
4471 for (unsigned i = 0; i < NumElems; i += Scale) {
4473 for (int j = 0; j < Scale; ++j) {
4474 int EltIdx = SVOp->getMaskElt(i+j);
4478 StartIdx = EltIdx - (EltIdx % Scale);
4479 if (EltIdx != StartIdx + j)
4483 MaskVec.push_back(-1);
4485 MaskVec.push_back(StartIdx / Scale);
4488 V1 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V1);
4489 V2 = DAG.getNode(ISD::BIT_CONVERT, dl, NewVT, V2);
4490 return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
4493 /// getVZextMovL - Return a zero-extending vector move low node.
4495 static SDValue getVZextMovL(EVT VT, EVT OpVT,
4496 SDValue SrcOp, SelectionDAG &DAG,
4497 const X86Subtarget *Subtarget, DebugLoc dl) {
4498 if (VT == MVT::v2f64 || VT == MVT::v4f32) {
4499 LoadSDNode *LD = NULL;
4500 if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
4501 LD = dyn_cast<LoadSDNode>(SrcOp);
4503 // movssrr and movsdrr do not clear top bits. Try to use movd, movq
4505 MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
4506 if ((ExtVT.SimpleTy != MVT::i64 || Subtarget->is64Bit()) &&
4507 SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4508 SrcOp.getOperand(0).getOpcode() == ISD::BIT_CONVERT &&
4509 SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
4511 OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
4512 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4513 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4514 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
4522 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4523 DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
4524 DAG.getNode(ISD::BIT_CONVERT, dl,
4528 /// LowerVECTOR_SHUFFLE_4wide - Handle all 4 wide cases with a number of
4531 LowerVECTOR_SHUFFLE_4wide(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
4532 SDValue V1 = SVOp->getOperand(0);
4533 SDValue V2 = SVOp->getOperand(1);
4534 DebugLoc dl = SVOp->getDebugLoc();
4535 EVT VT = SVOp->getValueType(0);
4537 SmallVector<std::pair<int, int>, 8> Locs;
4539 SmallVector<int, 8> Mask1(4U, -1);
4540 SmallVector<int, 8> PermMask;
4541 SVOp->getMask(PermMask);
4545 for (unsigned i = 0; i != 4; ++i) {
4546 int Idx = PermMask[i];
4548 Locs[i] = std::make_pair(-1, -1);
4550 assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
4552 Locs[i] = std::make_pair(0, NumLo);
4556 Locs[i] = std::make_pair(1, NumHi);
4558 Mask1[2+NumHi] = Idx;
4564 if (NumLo <= 2 && NumHi <= 2) {
4565 // If no more than two elements come from either vector. This can be
4566 // implemented with two shuffles. First shuffle gather the elements.
4567 // The second shuffle, which takes the first shuffle as both of its
4568 // vector operands, put the elements into the right order.
4569 V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4571 SmallVector<int, 8> Mask2(4U, -1);
4573 for (unsigned i = 0; i != 4; ++i) {
4574 if (Locs[i].first == -1)
4577 unsigned Idx = (i < 2) ? 0 : 4;
4578 Idx += Locs[i].first * 2 + Locs[i].second;
4583 return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
4584 } else if (NumLo == 3 || NumHi == 3) {
4585 // Otherwise, we must have three elements from one vector, call it X, and
4586 // one element from the other, call it Y. First, use a shufps to build an
4587 // intermediate vector with the one element from Y and the element from X
4588 // that will be in the same half in the final destination (the indexes don't
4589 // matter). Then, use a shufps to build the final vector, taking the half
4590 // containing the element from Y from the intermediate, and the other half
4593 // Normalize it so the 3 elements come from V1.
4594 CommuteVectorShuffleMask(PermMask, VT);
4598 // Find the element from V2.
4600 for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
4601 int Val = PermMask[HiIndex];
4608 Mask1[0] = PermMask[HiIndex];
4610 Mask1[2] = PermMask[HiIndex^1];
4612 V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4615 Mask1[0] = PermMask[0];
4616 Mask1[1] = PermMask[1];
4617 Mask1[2] = HiIndex & 1 ? 6 : 4;
4618 Mask1[3] = HiIndex & 1 ? 4 : 6;
4619 return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
4621 Mask1[0] = HiIndex & 1 ? 2 : 0;
4622 Mask1[1] = HiIndex & 1 ? 0 : 2;
4623 Mask1[2] = PermMask[2];
4624 Mask1[3] = PermMask[3];
4629 return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
4633 // Break it into (shuffle shuffle_hi, shuffle_lo).
4635 SmallVector<int,8> LoMask(4U, -1);
4636 SmallVector<int,8> HiMask(4U, -1);
4638 SmallVector<int,8> *MaskPtr = &LoMask;
4639 unsigned MaskIdx = 0;
4642 for (unsigned i = 0; i != 4; ++i) {
4649 int Idx = PermMask[i];
4651 Locs[i] = std::make_pair(-1, -1);
4652 } else if (Idx < 4) {
4653 Locs[i] = std::make_pair(MaskIdx, LoIdx);
4654 (*MaskPtr)[LoIdx] = Idx;
4657 Locs[i] = std::make_pair(MaskIdx, HiIdx);
4658 (*MaskPtr)[HiIdx] = Idx;
4663 SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
4664 SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
4665 SmallVector<int, 8> MaskOps;
4666 for (unsigned i = 0; i != 4; ++i) {
4667 if (Locs[i].first == -1) {
4668 MaskOps.push_back(-1);
4670 unsigned Idx = Locs[i].first * 4 + Locs[i].second;
4671 MaskOps.push_back(Idx);
4674 return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
4678 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
4679 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
4680 SDValue V1 = Op.getOperand(0);
4681 SDValue V2 = Op.getOperand(1);
4682 EVT VT = Op.getValueType();
4683 DebugLoc dl = Op.getDebugLoc();
4684 unsigned NumElems = VT.getVectorNumElements();
4685 bool isMMX = VT.getSizeInBits() == 64;
4686 bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
4687 bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
4688 bool V1IsSplat = false;
4689 bool V2IsSplat = false;
4691 if (isZeroShuffle(SVOp))
4692 return getZeroVector(VT, Subtarget->hasSSE2(), DAG, dl);
4694 // Promote splats to v4f32.
4695 if (SVOp->isSplat()) {
4696 if (isMMX || NumElems < 4)
4698 return PromoteSplat(SVOp, DAG, Subtarget->hasSSE2());
4701 // If the shuffle can be profitably rewritten as a narrower shuffle, then
4703 if (VT == MVT::v8i16 || VT == MVT::v16i8) {
4704 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4705 if (NewOp.getNode())
4706 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
4707 LowerVECTOR_SHUFFLE(NewOp, DAG));
4708 } else if ((VT == MVT::v4i32 || (VT == MVT::v4f32 && Subtarget->hasSSE2()))) {
4709 // FIXME: Figure out a cleaner way to do this.
4710 // Try to make use of movq to zero out the top part.
4711 if (ISD::isBuildVectorAllZeros(V2.getNode())) {
4712 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4713 if (NewOp.getNode()) {
4714 if (isCommutedMOVL(cast<ShuffleVectorSDNode>(NewOp), true, false))
4715 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(0),
4716 DAG, Subtarget, dl);
4718 } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
4719 SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG, *this, dl);
4720 if (NewOp.getNode() && X86::isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)))
4721 return getVZextMovL(VT, NewOp.getValueType(), NewOp.getOperand(1),
4722 DAG, Subtarget, dl);
4726 if (X86::isPSHUFDMask(SVOp))
4729 // Check if this can be converted into a logical shift.
4730 bool isLeft = false;
4733 bool isShift = getSubtarget()->hasSSE2() &&
4734 isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
4735 if (isShift && ShVal.hasOneUse()) {
4736 // If the shifted value has multiple uses, it may be cheaper to use
4737 // v_set0 + movlhps or movhlps, etc.
4738 EVT EltVT = VT.getVectorElementType();
4739 ShAmt *= EltVT.getSizeInBits();
4740 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4743 if (X86::isMOVLMask(SVOp)) {
4746 if (ISD::isBuildVectorAllZeros(V1.getNode()))
4747 return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
4752 // FIXME: fold these into legal mask.
4753 if (!isMMX && (X86::isMOVSHDUPMask(SVOp) ||
4754 X86::isMOVSLDUPMask(SVOp) ||
4755 X86::isMOVHLPSMask(SVOp) ||
4756 X86::isMOVLHPSMask(SVOp) ||
4757 X86::isMOVLPMask(SVOp)))
4760 if (ShouldXformToMOVHLPS(SVOp) ||
4761 ShouldXformToMOVLP(V1.getNode(), V2.getNode(), SVOp))
4762 return CommuteVectorShuffle(SVOp, DAG);
4765 // No better options. Use a vshl / vsrl.
4766 EVT EltVT = VT.getVectorElementType();
4767 ShAmt *= EltVT.getSizeInBits();
4768 return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
4771 bool Commuted = false;
4772 // FIXME: This should also accept a bitcast of a splat? Be careful, not
4773 // 1,1,1,1 -> v8i16 though.
4774 V1IsSplat = isSplatVector(V1.getNode());
4775 V2IsSplat = isSplatVector(V2.getNode());
4777 // Canonicalize the splat or undef, if present, to be on the RHS.
4778 if ((V1IsSplat || V1IsUndef) && !(V2IsSplat || V2IsUndef)) {
4779 Op = CommuteVectorShuffle(SVOp, DAG);
4780 SVOp = cast<ShuffleVectorSDNode>(Op);
4781 V1 = SVOp->getOperand(0);
4782 V2 = SVOp->getOperand(1);
4783 std::swap(V1IsSplat, V2IsSplat);
4784 std::swap(V1IsUndef, V2IsUndef);
4788 if (isCommutedMOVL(SVOp, V2IsSplat, V2IsUndef)) {
4789 // Shuffling low element of v1 into undef, just return v1.
4792 // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
4793 // the instruction selector will not match, so get a canonical MOVL with
4794 // swapped operands to undo the commute.
4795 return getMOVL(DAG, dl, VT, V2, V1);
4798 if (X86::isUNPCKL_v_undef_Mask(SVOp) ||
4799 X86::isUNPCKH_v_undef_Mask(SVOp) ||
4800 X86::isUNPCKLMask(SVOp) ||
4801 X86::isUNPCKHMask(SVOp))
4805 // Normalize mask so all entries that point to V2 points to its first
4806 // element then try to match unpck{h|l} again. If match, return a
4807 // new vector_shuffle with the corrected mask.
4808 SDValue NewMask = NormalizeMask(SVOp, DAG);
4809 ShuffleVectorSDNode *NSVOp = cast<ShuffleVectorSDNode>(NewMask);
4810 if (NSVOp != SVOp) {
4811 if (X86::isUNPCKLMask(NSVOp, true)) {
4813 } else if (X86::isUNPCKHMask(NSVOp, true)) {
4820 // Commute is back and try unpck* again.
4821 // FIXME: this seems wrong.
4822 SDValue NewOp = CommuteVectorShuffle(SVOp, DAG);
4823 ShuffleVectorSDNode *NewSVOp = cast<ShuffleVectorSDNode>(NewOp);
4824 if (X86::isUNPCKL_v_undef_Mask(NewSVOp) ||
4825 X86::isUNPCKH_v_undef_Mask(NewSVOp) ||
4826 X86::isUNPCKLMask(NewSVOp) ||
4827 X86::isUNPCKHMask(NewSVOp))
4831 // FIXME: for mmx, bitcast v2i32 to v4i16 for shuffle.
4833 // Normalize the node to match x86 shuffle ops if needed
4834 if (!isMMX && V2.getOpcode() != ISD::UNDEF && isCommutedSHUFP(SVOp))
4835 return CommuteVectorShuffle(SVOp, DAG);
4837 // Check for legal shuffle and return?
4838 SmallVector<int, 16> PermMask;
4839 SVOp->getMask(PermMask);
4840 if (isShuffleMaskLegal(PermMask, VT))
4843 // Handle v8i16 specifically since SSE can do byte extraction and insertion.
4844 if (VT == MVT::v8i16) {
4845 SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(SVOp, DAG, *this);
4846 if (NewOp.getNode())
4850 if (VT == MVT::v16i8) {
4851 SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, DAG, *this);
4852 if (NewOp.getNode())
4856 // Handle all 4 wide cases with a number of shuffles except for MMX.
4857 if (NumElems == 4 && !isMMX)
4858 return LowerVECTOR_SHUFFLE_4wide(SVOp, DAG);
4864 X86TargetLowering::LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op,
4865 SelectionDAG &DAG) const {
4866 EVT VT = Op.getValueType();
4867 DebugLoc dl = Op.getDebugLoc();
4868 if (VT.getSizeInBits() == 8) {
4869 SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
4870 Op.getOperand(0), Op.getOperand(1));
4871 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4872 DAG.getValueType(VT));
4873 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4874 } else if (VT.getSizeInBits() == 16) {
4875 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4876 // If Idx is 0, it's cheaper to do a move instead of a pextrw.
4878 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4879 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4880 DAG.getNode(ISD::BIT_CONVERT, dl,
4884 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
4885 Op.getOperand(0), Op.getOperand(1));
4886 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
4887 DAG.getValueType(VT));
4888 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4889 } else if (VT == MVT::f32) {
4890 // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
4891 // the result back to FR32 register. It's only worth matching if the
4892 // result has a single use which is a store or a bitcast to i32. And in
4893 // the case of a store, it's not worth it if the index is a constant 0,
4894 // because a MOVSSmr can be used instead, which is smaller and faster.
4895 if (!Op.hasOneUse())
4897 SDNode *User = *Op.getNode()->use_begin();
4898 if ((User->getOpcode() != ISD::STORE ||
4899 (isa<ConstantSDNode>(Op.getOperand(1)) &&
4900 cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
4901 (User->getOpcode() != ISD::BIT_CONVERT ||
4902 User->getValueType(0) != MVT::i32))
4904 SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4905 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4i32,
4908 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, Extract);
4909 } else if (VT == MVT::i32) {
4910 // ExtractPS works with constant index.
4911 if (isa<ConstantSDNode>(Op.getOperand(1)))
4919 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
4920 SelectionDAG &DAG) const {
4921 if (!isa<ConstantSDNode>(Op.getOperand(1)))
4924 if (Subtarget->hasSSE41()) {
4925 SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
4930 EVT VT = Op.getValueType();
4931 DebugLoc dl = Op.getDebugLoc();
4932 // TODO: handle v16i8.
4933 if (VT.getSizeInBits() == 16) {
4934 SDValue Vec = Op.getOperand(0);
4935 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4937 return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
4938 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
4939 DAG.getNode(ISD::BIT_CONVERT, dl,
4942 // Transform it so it match pextrw which produces a 32-bit result.
4943 EVT EltVT = MVT::i32;
4944 SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
4945 Op.getOperand(0), Op.getOperand(1));
4946 SDValue Assert = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
4947 DAG.getValueType(VT));
4948 return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
4949 } else if (VT.getSizeInBits() == 32) {
4950 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4954 // SHUFPS the element to the lowest double word, then movss.
4955 int Mask[4] = { Idx, -1, -1, -1 };
4956 EVT VVT = Op.getOperand(0).getValueType();
4957 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4958 DAG.getUNDEF(VVT), Mask);
4959 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4960 DAG.getIntPtrConstant(0));
4961 } else if (VT.getSizeInBits() == 64) {
4962 // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
4963 // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
4964 // to match extract_elt for f64.
4965 unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4969 // UNPCKHPD the element to the lowest double word, then movsd.
4970 // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
4971 // to a f64mem, the whole operation is folded into a single MOVHPDmr.
4972 int Mask[2] = { 1, -1 };
4973 EVT VVT = Op.getOperand(0).getValueType();
4974 SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
4975 DAG.getUNDEF(VVT), Mask);
4976 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
4977 DAG.getIntPtrConstant(0));
4984 X86TargetLowering::LowerINSERT_VECTOR_ELT_SSE4(SDValue Op,
4985 SelectionDAG &DAG) const {
4986 EVT VT = Op.getValueType();
4987 EVT EltVT = VT.getVectorElementType();
4988 DebugLoc dl = Op.getDebugLoc();
4990 SDValue N0 = Op.getOperand(0);
4991 SDValue N1 = Op.getOperand(1);
4992 SDValue N2 = Op.getOperand(2);
4994 if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
4995 isa<ConstantSDNode>(N2)) {
4997 if (VT == MVT::v8i16)
4998 Opc = X86ISD::PINSRW;
4999 else if (VT == MVT::v4i16)
5000 Opc = X86ISD::MMX_PINSRW;
5001 else if (VT == MVT::v16i8)
5002 Opc = X86ISD::PINSRB;
5004 Opc = X86ISD::PINSRB;
5006 // Transform it so it match pinsr{b,w} which expects a GR32 as its second
5008 if (N1.getValueType() != MVT::i32)
5009 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5010 if (N2.getValueType() != MVT::i32)
5011 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5012 return DAG.getNode(Opc, dl, VT, N0, N1, N2);
5013 } else if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
5014 // Bits [7:6] of the constant are the source select. This will always be
5015 // zero here. The DAG Combiner may combine an extract_elt index into these
5016 // bits. For example (insert (extract, 3), 2) could be matched by putting
5017 // the '3' into bits [7:6] of X86ISD::INSERTPS.
5018 // Bits [5:4] of the constant are the destination select. This is the
5019 // value of the incoming immediate.
5020 // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
5021 // combine either bitwise AND or insert of float 0.0 to set these bits.
5022 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
5023 // Create this as a scalar to vector..
5024 N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
5025 return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
5026 } else if (EltVT == MVT::i32 && isa<ConstantSDNode>(N2)) {
5027 // PINSR* works with constant index.
5034 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
5035 EVT VT = Op.getValueType();
5036 EVT EltVT = VT.getVectorElementType();
5038 if (Subtarget->hasSSE41())
5039 return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
5041 if (EltVT == MVT::i8)
5044 DebugLoc dl = Op.getDebugLoc();
5045 SDValue N0 = Op.getOperand(0);
5046 SDValue N1 = Op.getOperand(1);
5047 SDValue N2 = Op.getOperand(2);
5049 if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
5050 // Transform it so it match pinsrw which expects a 16-bit value in a GR32
5051 // as its second argument.
5052 if (N1.getValueType() != MVT::i32)
5053 N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
5054 if (N2.getValueType() != MVT::i32)
5055 N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
5056 return DAG.getNode(VT == MVT::v8i16 ? X86ISD::PINSRW : X86ISD::MMX_PINSRW,
5057 dl, VT, N0, N1, N2);
5063 X86TargetLowering::LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5064 DebugLoc dl = Op.getDebugLoc();
5066 if (Op.getValueType() == MVT::v1i64 &&
5067 Op.getOperand(0).getValueType() == MVT::i64)
5068 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
5070 SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
5071 EVT VT = MVT::v2i32;
5072 switch (Op.getValueType().getSimpleVT().SimpleTy) {
5079 return DAG.getNode(ISD::BIT_CONVERT, dl, Op.getValueType(),
5080 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, AnyExt));
5083 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
5084 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
5085 // one of the above mentioned nodes. It has to be wrapped because otherwise
5086 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
5087 // be used to form addressing mode. These wrapped nodes will be selected
5090 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
5091 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
5093 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5095 unsigned char OpFlag = 0;
5096 unsigned WrapperKind = X86ISD::Wrapper;
5097 CodeModel::Model M = getTargetMachine().getCodeModel();
5099 if (Subtarget->isPICStyleRIPRel() &&
5100 (M == CodeModel::Small || M == CodeModel::Kernel))
5101 WrapperKind = X86ISD::WrapperRIP;
5102 else if (Subtarget->isPICStyleGOT())
5103 OpFlag = X86II::MO_GOTOFF;
5104 else if (Subtarget->isPICStyleStubPIC())
5105 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5107 SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
5109 CP->getOffset(), OpFlag);
5110 DebugLoc DL = CP->getDebugLoc();
5111 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5112 // With PIC, the address is actually $g + Offset.
5114 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5115 DAG.getNode(X86ISD::GlobalBaseReg,
5116 DebugLoc(), getPointerTy()),
5123 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
5124 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
5126 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5128 unsigned char OpFlag = 0;
5129 unsigned WrapperKind = X86ISD::Wrapper;
5130 CodeModel::Model M = getTargetMachine().getCodeModel();
5132 if (Subtarget->isPICStyleRIPRel() &&
5133 (M == CodeModel::Small || M == CodeModel::Kernel))
5134 WrapperKind = X86ISD::WrapperRIP;
5135 else if (Subtarget->isPICStyleGOT())
5136 OpFlag = X86II::MO_GOTOFF;
5137 else if (Subtarget->isPICStyleStubPIC())
5138 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5140 SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
5142 DebugLoc DL = JT->getDebugLoc();
5143 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5145 // With PIC, the address is actually $g + Offset.
5147 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5148 DAG.getNode(X86ISD::GlobalBaseReg,
5149 DebugLoc(), getPointerTy()),
5157 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
5158 const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
5160 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5162 unsigned char OpFlag = 0;
5163 unsigned WrapperKind = X86ISD::Wrapper;
5164 CodeModel::Model M = getTargetMachine().getCodeModel();
5166 if (Subtarget->isPICStyleRIPRel() &&
5167 (M == CodeModel::Small || M == CodeModel::Kernel))
5168 WrapperKind = X86ISD::WrapperRIP;
5169 else if (Subtarget->isPICStyleGOT())
5170 OpFlag = X86II::MO_GOTOFF;
5171 else if (Subtarget->isPICStyleStubPIC())
5172 OpFlag = X86II::MO_PIC_BASE_OFFSET;
5174 SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
5176 DebugLoc DL = Op.getDebugLoc();
5177 Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5180 // With PIC, the address is actually $g + Offset.
5181 if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
5182 !Subtarget->is64Bit()) {
5183 Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5184 DAG.getNode(X86ISD::GlobalBaseReg,
5185 DebugLoc(), getPointerTy()),
5193 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
5194 // Create the TargetBlockAddressAddress node.
5195 unsigned char OpFlags =
5196 Subtarget->ClassifyBlockAddressReference();
5197 CodeModel::Model M = getTargetMachine().getCodeModel();
5198 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
5199 DebugLoc dl = Op.getDebugLoc();
5200 SDValue Result = DAG.getBlockAddress(BA, getPointerTy(),
5201 /*isTarget=*/true, OpFlags);
5203 if (Subtarget->isPICStyleRIPRel() &&
5204 (M == CodeModel::Small || M == CodeModel::Kernel))
5205 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5207 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5209 // With PIC, the address is actually $g + Offset.
5210 if (isGlobalRelativeToPICBase(OpFlags)) {
5211 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5212 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5220 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, DebugLoc dl,
5222 SelectionDAG &DAG) const {
5223 // Create the TargetGlobalAddress node, folding in the constant
5224 // offset if it is legal.
5225 unsigned char OpFlags =
5226 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
5227 CodeModel::Model M = getTargetMachine().getCodeModel();
5229 if (OpFlags == X86II::MO_NO_FLAG &&
5230 X86::isOffsetSuitableForCodeModel(Offset, M)) {
5231 // A direct static reference to a global.
5232 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), Offset);
5235 Result = DAG.getTargetGlobalAddress(GV, getPointerTy(), 0, OpFlags);
5238 if (Subtarget->isPICStyleRIPRel() &&
5239 (M == CodeModel::Small || M == CodeModel::Kernel))
5240 Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
5242 Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
5244 // With PIC, the address is actually $g + Offset.
5245 if (isGlobalRelativeToPICBase(OpFlags)) {
5246 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
5247 DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
5251 // For globals that require a load from a stub to get the address, emit the
5253 if (isGlobalStubReference(OpFlags))
5254 Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
5255 PseudoSourceValue::getGOT(), 0, false, false, 0);
5257 // If there was a non-zero offset that we didn't fold, create an explicit
5260 Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
5261 DAG.getConstant(Offset, getPointerTy()));
5267 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
5268 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
5269 int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
5270 return LowerGlobalAddress(GV, Op.getDebugLoc(), Offset, DAG);
5274 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
5275 SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
5276 unsigned char OperandFlags) {
5277 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5278 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
5279 DebugLoc dl = GA->getDebugLoc();
5280 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(),
5281 GA->getValueType(0),
5285 SDValue Ops[] = { Chain, TGA, *InFlag };
5286 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 3);
5288 SDValue Ops[] = { Chain, TGA };
5289 Chain = DAG.getNode(X86ISD::TLSADDR, dl, NodeTys, Ops, 2);
5292 // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
5293 MFI->setAdjustsStack(true);
5295 SDValue Flag = Chain.getValue(1);
5296 return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
5299 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
5301 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5304 DebugLoc dl = GA->getDebugLoc(); // ? function entry point might be better
5305 SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
5306 DAG.getNode(X86ISD::GlobalBaseReg,
5307 DebugLoc(), PtrVT), InFlag);
5308 InFlag = Chain.getValue(1);
5310 return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
5313 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
5315 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5317 return GetTLSADDR(DAG, DAG.getEntryNode(), GA, NULL, PtrVT,
5318 X86::RAX, X86II::MO_TLSGD);
5321 // Lower ISD::GlobalTLSAddress using the "initial exec" (for no-pic) or
5322 // "local exec" model.
5323 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
5324 const EVT PtrVT, TLSModel::Model model,
5326 DebugLoc dl = GA->getDebugLoc();
5327 // Get the Thread Pointer
5328 SDValue Base = DAG.getNode(X86ISD::SegmentBaseAddress,
5330 DAG.getRegister(is64Bit? X86::FS : X86::GS,
5333 SDValue ThreadPointer = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Base,
5334 NULL, 0, false, false, 0);
5336 unsigned char OperandFlags = 0;
5337 // Most TLS accesses are not RIP relative, even on x86-64. One exception is
5339 unsigned WrapperKind = X86ISD::Wrapper;
5340 if (model == TLSModel::LocalExec) {
5341 OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
5342 } else if (is64Bit) {
5343 assert(model == TLSModel::InitialExec);
5344 OperandFlags = X86II::MO_GOTTPOFF;
5345 WrapperKind = X86ISD::WrapperRIP;
5347 assert(model == TLSModel::InitialExec);
5348 OperandFlags = X86II::MO_INDNTPOFF;
5351 // emit "addl x@ntpoff,%eax" (local exec) or "addl x@indntpoff,%eax" (initial
5353 SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), GA->getValueType(0),
5354 GA->getOffset(), OperandFlags);
5355 SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
5357 if (model == TLSModel::InitialExec)
5358 Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
5359 PseudoSourceValue::getGOT(), 0, false, false, 0);
5361 // The address of the thread local variable is the add of the thread
5362 // pointer with the offset of the variable.
5363 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
5367 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
5369 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
5370 const GlobalValue *GV = GA->getGlobal();
5372 if (Subtarget->isTargetELF()) {
5373 // TODO: implement the "local dynamic" model
5374 // TODO: implement the "initial exec"model for pic executables
5376 // If GV is an alias then use the aliasee for determining
5377 // thread-localness.
5378 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
5379 GV = GA->resolveAliasedGlobal(false);
5381 TLSModel::Model model
5382 = getTLSModel(GV, getTargetMachine().getRelocationModel());
5385 case TLSModel::GeneralDynamic:
5386 case TLSModel::LocalDynamic: // not implemented
5387 if (Subtarget->is64Bit())
5388 return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
5389 return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
5391 case TLSModel::InitialExec:
5392 case TLSModel::LocalExec:
5393 return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
5394 Subtarget->is64Bit());
5396 } else if (Subtarget->isTargetDarwin()) {
5397 // Darwin only has one model of TLS. Lower to that.
5398 unsigned char OpFlag = 0;
5399 unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
5400 X86ISD::WrapperRIP : X86ISD::Wrapper;
5402 // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
5404 bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
5405 !Subtarget->is64Bit();
5407 OpFlag = X86II::MO_TLVP_PIC_BASE;
5409 OpFlag = X86II::MO_TLVP;
5411 SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(),
5413 GA->getOffset(), OpFlag);
5415 DebugLoc DL = Op.getDebugLoc();
5416 SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
5418 // With PIC32, the address is actually $g + Offset.
5420 Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
5421 DAG.getNode(X86ISD::GlobalBaseReg,
5422 DebugLoc(), getPointerTy()),
5425 // Lowering the machine isd will make sure everything is in the right
5427 SDValue Args[] = { Offset };
5428 SDValue Chain = DAG.getNode(X86ISD::TLSCALL, DL, MVT::Other, Args, 1);
5430 // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
5431 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5432 MFI->setAdjustsStack(true);
5434 // And our return value (tls address) is in the standard call return value
5436 unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
5437 return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
5441 "TLS not implemented for this target.");
5443 llvm_unreachable("Unreachable");
5448 /// LowerShift - Lower SRA_PARTS and friends, which return two i32 values and
5449 /// take a 2 x i32 value to shift plus a shift amount.
5450 SDValue X86TargetLowering::LowerShift(SDValue Op, SelectionDAG &DAG) const {
5451 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5452 EVT VT = Op.getValueType();
5453 unsigned VTBits = VT.getSizeInBits();
5454 DebugLoc dl = Op.getDebugLoc();
5455 bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
5456 SDValue ShOpLo = Op.getOperand(0);
5457 SDValue ShOpHi = Op.getOperand(1);
5458 SDValue ShAmt = Op.getOperand(2);
5459 SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
5460 DAG.getConstant(VTBits - 1, MVT::i8))
5461 : DAG.getConstant(0, VT);
5464 if (Op.getOpcode() == ISD::SHL_PARTS) {
5465 Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
5466 Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5468 Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
5469 Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, ShAmt);
5472 SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
5473 DAG.getConstant(VTBits, MVT::i8));
5474 SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
5475 AndNode, DAG.getConstant(0, MVT::i8));
5478 SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
5479 SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
5480 SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
5482 if (Op.getOpcode() == ISD::SHL_PARTS) {
5483 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5484 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5486 Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0, 4);
5487 Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1, 4);
5490 SDValue Ops[2] = { Lo, Hi };
5491 return DAG.getMergeValues(Ops, 2, dl);
5494 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
5495 SelectionDAG &DAG) const {
5496 EVT SrcVT = Op.getOperand(0).getValueType();
5498 if (SrcVT.isVector()) {
5499 if (SrcVT == MVT::v2i32 && Op.getValueType() == MVT::v2f64) {
5505 assert(SrcVT.getSimpleVT() <= MVT::i64 && SrcVT.getSimpleVT() >= MVT::i16 &&
5506 "Unknown SINT_TO_FP to lower!");
5508 // These are really Legal; return the operand so the caller accepts it as
5510 if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
5512 if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
5513 Subtarget->is64Bit()) {
5517 DebugLoc dl = Op.getDebugLoc();
5518 unsigned Size = SrcVT.getSizeInBits()/8;
5519 MachineFunction &MF = DAG.getMachineFunction();
5520 int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
5521 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5522 SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5524 PseudoSourceValue::getFixedStack(SSFI), 0,
5526 return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
5529 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
5531 SelectionDAG &DAG) const {
5533 DebugLoc dl = Op.getDebugLoc();
5535 bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
5537 Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Flag);
5539 Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
5540 SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
5541 SDValue Result = DAG.getNode(useSSE ? X86ISD::FILD_FLAG : X86ISD::FILD, dl,
5542 Tys, Ops, array_lengthof(Ops));
5545 Chain = Result.getValue(1);
5546 SDValue InFlag = Result.getValue(2);
5548 // FIXME: Currently the FST is flagged to the FILD_FLAG. This
5549 // shouldn't be necessary except that RFP cannot be live across
5550 // multiple blocks. When stackifier is fixed, they can be uncoupled.
5551 MachineFunction &MF = DAG.getMachineFunction();
5552 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8, false);
5553 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5554 Tys = DAG.getVTList(MVT::Other);
5556 Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
5558 Chain = DAG.getNode(X86ISD::FST, dl, Tys, Ops, array_lengthof(Ops));
5559 Result = DAG.getLoad(Op.getValueType(), dl, Chain, StackSlot,
5560 PseudoSourceValue::getFixedStack(SSFI), 0,
5567 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
5568 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
5569 SelectionDAG &DAG) const {
5570 // This algorithm is not obvious. Here it is in C code, more or less:
5572 double uint64_to_double( uint32_t hi, uint32_t lo ) {
5573 static const __m128i exp = { 0x4330000045300000ULL, 0 };
5574 static const __m128d bias = { 0x1.0p84, 0x1.0p52 };
5576 // Copy ints to xmm registers.
5577 __m128i xh = _mm_cvtsi32_si128( hi );
5578 __m128i xl = _mm_cvtsi32_si128( lo );
5580 // Combine into low half of a single xmm register.
5581 __m128i x = _mm_unpacklo_epi32( xh, xl );
5585 // Merge in appropriate exponents to give the integer bits the right
5587 x = _mm_unpacklo_epi32( x, exp );
5589 // Subtract away the biases to deal with the IEEE-754 double precision
5591 d = _mm_sub_pd( (__m128d) x, bias );
5593 // All conversions up to here are exact. The correctly rounded result is
5594 // calculated using the current rounding mode using the following
5596 d = _mm_add_sd( d, _mm_unpackhi_pd( d, d ) );
5597 _mm_store_sd( &sd, d ); // Because we are returning doubles in XMM, this
5598 // store doesn't really need to be here (except
5599 // maybe to zero the other double)
5604 DebugLoc dl = Op.getDebugLoc();
5605 LLVMContext *Context = DAG.getContext();
5607 // Build some magic constants.
5608 std::vector<Constant*> CV0;
5609 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x45300000)));
5610 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0x43300000)));
5611 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5612 CV0.push_back(ConstantInt::get(*Context, APInt(32, 0)));
5613 Constant *C0 = ConstantVector::get(CV0);
5614 SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
5616 std::vector<Constant*> CV1;
5618 ConstantFP::get(*Context, APFloat(APInt(64, 0x4530000000000000ULL))));
5620 ConstantFP::get(*Context, APFloat(APInt(64, 0x4330000000000000ULL))));
5621 Constant *C1 = ConstantVector::get(CV1);
5622 SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
5624 SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5625 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5627 DAG.getIntPtrConstant(1)));
5628 SDValue XR2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5629 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5631 DAG.getIntPtrConstant(0)));
5632 SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32, XR1, XR2);
5633 SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
5634 PseudoSourceValue::getConstantPool(), 0,
5636 SDValue Unpck2 = getUnpackl(DAG, dl, MVT::v4i32, Unpck1, CLod0);
5637 SDValue XR2F = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Unpck2);
5638 SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
5639 PseudoSourceValue::getConstantPool(), 0,
5641 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
5643 // Add the halves; easiest way is to swap them into another reg first.
5644 int ShufMask[2] = { 1, -1 };
5645 SDValue Shuf = DAG.getVectorShuffle(MVT::v2f64, dl, Sub,
5646 DAG.getUNDEF(MVT::v2f64), ShufMask);
5647 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::v2f64, Shuf, Sub);
5648 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Add,
5649 DAG.getIntPtrConstant(0));
5652 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
5653 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
5654 SelectionDAG &DAG) const {
5655 DebugLoc dl = Op.getDebugLoc();
5656 // FP constant to bias correct the final result.
5657 SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
5660 // Load the 32-bit value into an XMM register.
5661 SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
5662 DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
5664 DAG.getIntPtrConstant(0)));
5666 Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5667 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Load),
5668 DAG.getIntPtrConstant(0));
5670 // Or the load with the bias.
5671 SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
5672 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5673 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5675 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5676 DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5677 MVT::v2f64, Bias)));
5678 Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
5679 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2f64, Or),
5680 DAG.getIntPtrConstant(0));
5682 // Subtract the bias.
5683 SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
5685 // Handle final rounding.
5686 EVT DestVT = Op.getValueType();
5688 if (DestVT.bitsLT(MVT::f64)) {
5689 return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
5690 DAG.getIntPtrConstant(0));
5691 } else if (DestVT.bitsGT(MVT::f64)) {
5692 return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
5695 // Handle final rounding.
5699 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
5700 SelectionDAG &DAG) const {
5701 SDValue N0 = Op.getOperand(0);
5702 DebugLoc dl = Op.getDebugLoc();
5704 // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
5705 // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
5706 // the optimization here.
5707 if (DAG.SignBitIsZero(N0))
5708 return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
5710 EVT SrcVT = N0.getValueType();
5711 EVT DstVT = Op.getValueType();
5712 if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
5713 return LowerUINT_TO_FP_i64(Op, DAG);
5714 else if (SrcVT == MVT::i32 && X86ScalarSSEf64)
5715 return LowerUINT_TO_FP_i32(Op, DAG);
5717 // Make a 64-bit buffer, and use it to build an FILD.
5718 SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
5719 if (SrcVT == MVT::i32) {
5720 SDValue WordOff = DAG.getConstant(4, getPointerTy());
5721 SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
5722 getPointerTy(), StackSlot, WordOff);
5723 SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5724 StackSlot, NULL, 0, false, false, 0);
5725 SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
5726 OffsetSlot, NULL, 0, false, false, 0);
5727 SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
5731 assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
5732 SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
5733 StackSlot, NULL, 0, false, false, 0);
5734 // For i64 source, we need to add the appropriate power of 2 if the input
5735 // was negative. This is the same as the optimization in
5736 // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
5737 // we must be careful to do the computation in x87 extended precision, not
5738 // in SSE. (The generic code can't know it's OK to do this, or how to.)
5739 SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
5740 SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
5741 SDValue Fild = DAG.getNode(X86ISD::FILD, dl, Tys, Ops, 3);
5743 APInt FF(32, 0x5F800000ULL);
5745 // Check whether the sign bit is set.
5746 SDValue SignSet = DAG.getSetCC(dl, getSetCCResultType(MVT::i64),
5747 Op.getOperand(0), DAG.getConstant(0, MVT::i64),
5750 // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
5751 SDValue FudgePtr = DAG.getConstantPool(
5752 ConstantInt::get(*DAG.getContext(), FF.zext(64)),
5755 // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
5756 SDValue Zero = DAG.getIntPtrConstant(0);
5757 SDValue Four = DAG.getIntPtrConstant(4);
5758 SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
5760 FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
5762 // Load the value out, extending it from f32 to f80.
5763 // FIXME: Avoid the extend by constructing the right constant pool?
5764 SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
5765 FudgePtr, PseudoSourceValue::getConstantPool(),
5766 0, MVT::f32, false, false, 4);
5767 // Extend everything to 80 bits to force it to be done on x87.
5768 SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
5769 return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
5772 std::pair<SDValue,SDValue> X86TargetLowering::
5773 FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG, bool IsSigned) const {
5774 DebugLoc dl = Op.getDebugLoc();
5776 EVT DstTy = Op.getValueType();
5779 assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
5783 assert(DstTy.getSimpleVT() <= MVT::i64 &&
5784 DstTy.getSimpleVT() >= MVT::i16 &&
5785 "Unknown FP_TO_SINT to lower!");
5787 // These are really Legal.
5788 if (DstTy == MVT::i32 &&
5789 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5790 return std::make_pair(SDValue(), SDValue());
5791 if (Subtarget->is64Bit() &&
5792 DstTy == MVT::i64 &&
5793 isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
5794 return std::make_pair(SDValue(), SDValue());
5796 // We lower FP->sint64 into FISTP64, followed by a load, all to a temporary
5798 MachineFunction &MF = DAG.getMachineFunction();
5799 unsigned MemSize = DstTy.getSizeInBits()/8;
5800 int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5801 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5804 switch (DstTy.getSimpleVT().SimpleTy) {
5805 default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
5806 case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
5807 case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
5808 case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
5811 SDValue Chain = DAG.getEntryNode();
5812 SDValue Value = Op.getOperand(0);
5813 if (isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType())) {
5814 assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
5815 Chain = DAG.getStore(Chain, dl, Value, StackSlot,
5816 PseudoSourceValue::getFixedStack(SSFI), 0,
5818 SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
5820 Chain, StackSlot, DAG.getValueType(Op.getOperand(0).getValueType())
5822 Value = DAG.getNode(X86ISD::FLD, dl, Tys, Ops, 3);
5823 Chain = Value.getValue(1);
5824 SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
5825 StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
5828 // Build the FP_TO_INT*_IN_MEM
5829 SDValue Ops[] = { Chain, Value, StackSlot };
5830 SDValue FIST = DAG.getNode(Opc, dl, MVT::Other, Ops, 3);
5832 return std::make_pair(FIST, StackSlot);
5835 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
5836 SelectionDAG &DAG) const {
5837 if (Op.getValueType().isVector()) {
5838 if (Op.getValueType() == MVT::v2i32 &&
5839 Op.getOperand(0).getValueType() == MVT::v2f64) {
5845 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, true);
5846 SDValue FIST = Vals.first, StackSlot = Vals.second;
5847 // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
5848 if (FIST.getNode() == 0) return Op;
5851 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5852 FIST, StackSlot, NULL, 0, false, false, 0);
5855 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
5856 SelectionDAG &DAG) const {
5857 std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG, false);
5858 SDValue FIST = Vals.first, StackSlot = Vals.second;
5859 assert(FIST.getNode() && "Unexpected failure");
5862 return DAG.getLoad(Op.getValueType(), Op.getDebugLoc(),
5863 FIST, StackSlot, NULL, 0, false, false, 0);
5866 SDValue X86TargetLowering::LowerFABS(SDValue Op,
5867 SelectionDAG &DAG) const {
5868 LLVMContext *Context = DAG.getContext();
5869 DebugLoc dl = Op.getDebugLoc();
5870 EVT VT = Op.getValueType();
5873 EltVT = VT.getVectorElementType();
5874 std::vector<Constant*> CV;
5875 if (EltVT == MVT::f64) {
5876 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63))));
5880 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31))));
5886 Constant *C = ConstantVector::get(CV);
5887 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5888 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5889 PseudoSourceValue::getConstantPool(), 0,
5891 return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
5894 SDValue X86TargetLowering::LowerFNEG(SDValue Op, SelectionDAG &DAG) const {
5895 LLVMContext *Context = DAG.getContext();
5896 DebugLoc dl = Op.getDebugLoc();
5897 EVT VT = Op.getValueType();
5900 EltVT = VT.getVectorElementType();
5901 std::vector<Constant*> CV;
5902 if (EltVT == MVT::f64) {
5903 Constant *C = ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63)));
5907 Constant *C = ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31)));
5913 Constant *C = ConstantVector::get(CV);
5914 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5915 SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5916 PseudoSourceValue::getConstantPool(), 0,
5918 if (VT.isVector()) {
5919 return DAG.getNode(ISD::BIT_CONVERT, dl, VT,
5920 DAG.getNode(ISD::XOR, dl, MVT::v2i64,
5921 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64,
5923 DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v2i64, Mask)));
5925 return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
5929 SDValue X86TargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
5930 LLVMContext *Context = DAG.getContext();
5931 SDValue Op0 = Op.getOperand(0);
5932 SDValue Op1 = Op.getOperand(1);
5933 DebugLoc dl = Op.getDebugLoc();
5934 EVT VT = Op.getValueType();
5935 EVT SrcVT = Op1.getValueType();
5937 // If second operand is smaller, extend it first.
5938 if (SrcVT.bitsLT(VT)) {
5939 Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
5942 // And if it is bigger, shrink it first.
5943 if (SrcVT.bitsGT(VT)) {
5944 Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
5948 // At this point the operands and the result should have the same
5949 // type, and that won't be f80 since that is not custom lowered.
5951 // First get the sign bit of second operand.
5952 std::vector<Constant*> CV;
5953 if (SrcVT == MVT::f64) {
5954 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 1ULL << 63))));
5955 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5957 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 1U << 31))));
5958 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5959 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5960 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5962 Constant *C = ConstantVector::get(CV);
5963 SDValue CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5964 SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
5965 PseudoSourceValue::getConstantPool(), 0,
5967 SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
5969 // Shift sign bit right or left if the two operands have different types.
5970 if (SrcVT.bitsGT(VT)) {
5971 // Op0 is MVT::f32, Op1 is MVT::f64.
5972 SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
5973 SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
5974 DAG.getConstant(32, MVT::i32));
5975 SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::v4f32, SignBit);
5976 SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
5977 DAG.getIntPtrConstant(0));
5980 // Clear first operand sign bit.
5982 if (VT == MVT::f64) {
5983 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, ~(1ULL << 63)))));
5984 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(64, 0))));
5986 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, ~(1U << 31)))));
5987 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5988 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5989 CV.push_back(ConstantFP::get(*Context, APFloat(APInt(32, 0))));
5991 C = ConstantVector::get(CV);
5992 CPIdx = DAG.getConstantPool(C, getPointerTy(), 16);
5993 SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
5994 PseudoSourceValue::getConstantPool(), 0,
5996 SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
5998 // Or the value with the sign bit.
5999 return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
6002 /// Emit nodes that will be selected as "test Op0,Op0", or something
6004 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC,
6005 SelectionDAG &DAG) const {
6006 DebugLoc dl = Op.getDebugLoc();
6008 // CF and OF aren't always set the way we want. Determine which
6009 // of these we need.
6010 bool NeedCF = false;
6011 bool NeedOF = false;
6014 case X86::COND_A: case X86::COND_AE:
6015 case X86::COND_B: case X86::COND_BE:
6018 case X86::COND_G: case X86::COND_GE:
6019 case X86::COND_L: case X86::COND_LE:
6020 case X86::COND_O: case X86::COND_NO:
6025 // See if we can use the EFLAGS value from the operand instead of
6026 // doing a separate TEST. TEST always sets OF and CF to 0, so unless
6027 // we prove that the arithmetic won't overflow, we can't use OF or CF.
6028 if (Op.getResNo() != 0 || NeedOF || NeedCF)
6029 // Emit a CMP with 0, which is the TEST pattern.
6030 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6031 DAG.getConstant(0, Op.getValueType()));
6033 unsigned Opcode = 0;
6034 unsigned NumOperands = 0;
6035 switch (Op.getNode()->getOpcode()) {
6037 // Due to an isel shortcoming, be conservative if this add is likely to be
6038 // selected as part of a load-modify-store instruction. When the root node
6039 // in a match is a store, isel doesn't know how to remap non-chain non-flag
6040 // uses of other nodes in the match, such as the ADD in this case. This
6041 // leads to the ADD being left around and reselected, with the result being
6042 // two adds in the output. Alas, even if none our users are stores, that
6043 // doesn't prove we're O.K. Ergo, if we have any parents that aren't
6044 // CopyToReg or SETCC, eschew INC/DEC. A better fix seems to require
6045 // climbing the DAG back to the root, and it doesn't seem to be worth the
6047 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6048 UE = Op.getNode()->use_end(); UI != UE; ++UI)
6049 if (UI->getOpcode() != ISD::CopyToReg && UI->getOpcode() != ISD::SETCC)
6052 if (ConstantSDNode *C =
6053 dyn_cast<ConstantSDNode>(Op.getNode()->getOperand(1))) {
6054 // An add of one will be selected as an INC.
6055 if (C->getAPIntValue() == 1) {
6056 Opcode = X86ISD::INC;
6061 // An add of negative one (subtract of one) will be selected as a DEC.
6062 if (C->getAPIntValue().isAllOnesValue()) {
6063 Opcode = X86ISD::DEC;
6069 // Otherwise use a regular EFLAGS-setting add.
6070 Opcode = X86ISD::ADD;
6074 // If the primary and result isn't used, don't bother using X86ISD::AND,
6075 // because a TEST instruction will be better.
6076 bool NonFlagUse = false;
6077 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6078 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
6080 unsigned UOpNo = UI.getOperandNo();
6081 if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
6082 // Look pass truncate.
6083 UOpNo = User->use_begin().getOperandNo();
6084 User = *User->use_begin();
6087 if (User->getOpcode() != ISD::BRCOND &&
6088 User->getOpcode() != ISD::SETCC &&
6089 (User->getOpcode() != ISD::SELECT || UOpNo != 0)) {
6102 // Due to the ISEL shortcoming noted above, be conservative if this op is
6103 // likely to be selected as part of a load-modify-store instruction.
6104 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
6105 UE = Op.getNode()->use_end(); UI != UE; ++UI)
6106 if (UI->getOpcode() == ISD::STORE)
6109 // Otherwise use a regular EFLAGS-setting instruction.
6110 switch (Op.getNode()->getOpcode()) {
6111 default: llvm_unreachable("unexpected operator!");
6112 case ISD::SUB: Opcode = X86ISD::SUB; break;
6113 case ISD::OR: Opcode = X86ISD::OR; break;
6114 case ISD::XOR: Opcode = X86ISD::XOR; break;
6115 case ISD::AND: Opcode = X86ISD::AND; break;
6127 return SDValue(Op.getNode(), 1);
6134 // Emit a CMP with 0, which is the TEST pattern.
6135 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
6136 DAG.getConstant(0, Op.getValueType()));
6138 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
6139 SmallVector<SDValue, 4> Ops;
6140 for (unsigned i = 0; i != NumOperands; ++i)
6141 Ops.push_back(Op.getOperand(i));
6143 SDValue New = DAG.getNode(Opcode, dl, VTs, &Ops[0], NumOperands);
6144 DAG.ReplaceAllUsesWith(Op, New);
6145 return SDValue(New.getNode(), 1);
6148 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
6150 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
6151 SelectionDAG &DAG) const {
6152 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1))
6153 if (C->getAPIntValue() == 0)
6154 return EmitTest(Op0, X86CC, DAG);
6156 DebugLoc dl = Op0.getDebugLoc();
6157 return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
6160 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
6161 /// if it's possible.
6162 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
6163 DebugLoc dl, SelectionDAG &DAG) const {
6164 SDValue Op0 = And.getOperand(0);
6165 SDValue Op1 = And.getOperand(1);
6166 if (Op0.getOpcode() == ISD::TRUNCATE)
6167 Op0 = Op0.getOperand(0);
6168 if (Op1.getOpcode() == ISD::TRUNCATE)
6169 Op1 = Op1.getOperand(0);
6172 if (Op1.getOpcode() == ISD::SHL)
6173 std::swap(Op0, Op1);
6174 if (Op0.getOpcode() == ISD::SHL) {
6175 if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
6176 if (And00C->getZExtValue() == 1) {
6177 // If we looked past a truncate, check that it's only truncating away
6179 unsigned BitWidth = Op0.getValueSizeInBits();
6180 unsigned AndBitWidth = And.getValueSizeInBits();
6181 if (BitWidth > AndBitWidth) {
6182 APInt Mask = APInt::getAllOnesValue(BitWidth), Zeros, Ones;
6183 DAG.ComputeMaskedBits(Op0, Mask, Zeros, Ones);
6184 if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
6188 RHS = Op0.getOperand(1);
6190 } else if (Op1.getOpcode() == ISD::Constant) {
6191 ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
6192 SDValue AndLHS = Op0;
6193 if (AndRHS->getZExtValue() == 1 && AndLHS.getOpcode() == ISD::SRL) {
6194 LHS = AndLHS.getOperand(0);
6195 RHS = AndLHS.getOperand(1);
6199 if (LHS.getNode()) {
6200 // If LHS is i8, promote it to i32 with any_extend. There is no i8 BT
6201 // instruction. Since the shift amount is in-range-or-undefined, we know
6202 // that doing a bittest on the i32 value is ok. We extend to i32 because
6203 // the encoding for the i16 version is larger than the i32 version.
6204 // Also promote i16 to i32 for performance / code size reason.
6205 if (LHS.getValueType() == MVT::i8 ||
6206 LHS.getValueType() == MVT::i16)
6207 LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
6209 // If the operand types disagree, extend the shift amount to match. Since
6210 // BT ignores high bits (like shifts) we can use anyextend.
6211 if (LHS.getValueType() != RHS.getValueType())
6212 RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
6214 SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
6215 unsigned Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
6216 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6217 DAG.getConstant(Cond, MVT::i8), BT);
6223 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
6224 assert(Op.getValueType() == MVT::i8 && "SetCC type must be 8-bit integer");
6225 SDValue Op0 = Op.getOperand(0);
6226 SDValue Op1 = Op.getOperand(1);
6227 DebugLoc dl = Op.getDebugLoc();
6228 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6230 // Optimize to BT if possible.
6231 // Lower (X & (1 << N)) == 0 to BT(X, N).
6232 // Lower ((X >>u N) & 1) != 0 to BT(X, N).
6233 // Lower ((X >>s N) & 1) != 0 to BT(X, N).
6234 if (Op0.getOpcode() == ISD::AND &&
6236 Op1.getOpcode() == ISD::Constant &&
6237 cast<ConstantSDNode>(Op1)->isNullValue() &&
6238 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6239 SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
6240 if (NewSetCC.getNode())
6244 // Look for "(setcc) == / != 1" to avoid unncessary setcc.
6245 if (Op0.getOpcode() == X86ISD::SETCC &&
6246 Op1.getOpcode() == ISD::Constant &&
6247 (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
6248 cast<ConstantSDNode>(Op1)->isNullValue()) &&
6249 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
6250 X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
6251 bool Invert = (CC == ISD::SETNE) ^
6252 cast<ConstantSDNode>(Op1)->isNullValue();
6254 CCode = X86::GetOppositeBranchCondition(CCode);
6255 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6256 DAG.getConstant(CCode, MVT::i8), Op0.getOperand(1));
6259 bool isFP = Op1.getValueType().isFloatingPoint();
6260 unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
6261 if (X86CC == X86::COND_INVALID)
6264 SDValue Cond = EmitCmp(Op0, Op1, X86CC, DAG);
6266 // Use sbb x, x to materialize carry bit into a GPR.
6267 if (X86CC == X86::COND_B)
6268 return DAG.getNode(ISD::AND, dl, MVT::i8,
6269 DAG.getNode(X86ISD::SETCC_CARRY, dl, MVT::i8,
6270 DAG.getConstant(X86CC, MVT::i8), Cond),
6271 DAG.getConstant(1, MVT::i8));
6273 return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6274 DAG.getConstant(X86CC, MVT::i8), Cond);
6277 SDValue X86TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
6279 SDValue Op0 = Op.getOperand(0);
6280 SDValue Op1 = Op.getOperand(1);
6281 SDValue CC = Op.getOperand(2);
6282 EVT VT = Op.getValueType();
6283 ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
6284 bool isFP = Op.getOperand(1).getValueType().isFloatingPoint();
6285 DebugLoc dl = Op.getDebugLoc();
6289 EVT VT0 = Op0.getValueType();
6290 assert(VT0 == MVT::v4f32 || VT0 == MVT::v2f64);
6291 unsigned Opc = VT0 == MVT::v4f32 ? X86ISD::CMPPS : X86ISD::CMPPD;
6294 switch (SetCCOpcode) {
6297 case ISD::SETEQ: SSECC = 0; break;
6299 case ISD::SETGT: Swap = true; // Fallthrough
6301 case ISD::SETOLT: SSECC = 1; break;
6303 case ISD::SETGE: Swap = true; // Fallthrough
6305 case ISD::SETOLE: SSECC = 2; break;
6306 case ISD::SETUO: SSECC = 3; break;
6308 case ISD::SETNE: SSECC = 4; break;
6309 case ISD::SETULE: Swap = true;
6310 case ISD::SETUGE: SSECC = 5; break;
6311 case ISD::SETULT: Swap = true;
6312 case ISD::SETUGT: SSECC = 6; break;
6313 case ISD::SETO: SSECC = 7; break;
6316 std::swap(Op0, Op1);
6318 // In the two special cases we can't handle, emit two comparisons.
6320 if (SetCCOpcode == ISD::SETUEQ) {
6322 UNORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(3, MVT::i8));
6323 EQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(0, MVT::i8));
6324 return DAG.getNode(ISD::OR, dl, VT, UNORD, EQ);
6326 else if (SetCCOpcode == ISD::SETONE) {
6328 ORD = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(7, MVT::i8));
6329 NEQ = DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(4, MVT::i8));
6330 return DAG.getNode(ISD::AND, dl, VT, ORD, NEQ);
6332 llvm_unreachable("Illegal FP comparison");
6334 // Handle all other FP comparisons here.
6335 return DAG.getNode(Opc, dl, VT, Op0, Op1, DAG.getConstant(SSECC, MVT::i8));
6338 // We are handling one of the integer comparisons here. Since SSE only has
6339 // GT and EQ comparisons for integer, swapping operands and multiple
6340 // operations may be required for some comparisons.
6341 unsigned Opc = 0, EQOpc = 0, GTOpc = 0;
6342 bool Swap = false, Invert = false, FlipSigns = false;
6344 switch (VT.getSimpleVT().SimpleTy) {
6347 case MVT::v16i8: EQOpc = X86ISD::PCMPEQB; GTOpc = X86ISD::PCMPGTB; break;
6349 case MVT::v8i16: EQOpc = X86ISD::PCMPEQW; GTOpc = X86ISD::PCMPGTW; break;
6351 case MVT::v4i32: EQOpc = X86ISD::PCMPEQD; GTOpc = X86ISD::PCMPGTD; break;
6352 case MVT::v2i64: EQOpc = X86ISD::PCMPEQQ; GTOpc = X86ISD::PCMPGTQ; break;
6355 switch (SetCCOpcode) {
6357 case ISD::SETNE: Invert = true;
6358 case ISD::SETEQ: Opc = EQOpc; break;
6359 case ISD::SETLT: Swap = true;
6360 case ISD::SETGT: Opc = GTOpc; break;
6361 case ISD::SETGE: Swap = true;
6362 case ISD::SETLE: Opc = GTOpc; Invert = true; break;
6363 case ISD::SETULT: Swap = true;
6364 case ISD::SETUGT: Opc = GTOpc; FlipSigns = true; break;
6365 case ISD::SETUGE: Swap = true;
6366 case ISD::SETULE: Opc = GTOpc; FlipSigns = true; Invert = true; break;
6369 std::swap(Op0, Op1);
6371 // Since SSE has no unsigned integer comparisons, we need to flip the sign
6372 // bits of the inputs before performing those operations.
6374 EVT EltVT = VT.getVectorElementType();
6375 SDValue SignBit = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()),
6377 std::vector<SDValue> SignBits(VT.getVectorNumElements(), SignBit);
6378 SDValue SignVec = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &SignBits[0],
6380 Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SignVec);
6381 Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SignVec);
6384 SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
6386 // If the logical-not of the result is required, perform that now.
6388 Result = DAG.getNOT(dl, Result, VT);
6393 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
6394 static bool isX86LogicalCmp(SDValue Op) {
6395 unsigned Opc = Op.getNode()->getOpcode();
6396 if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI)
6398 if (Op.getResNo() == 1 &&
6399 (Opc == X86ISD::ADD ||
6400 Opc == X86ISD::SUB ||
6401 Opc == X86ISD::SMUL ||
6402 Opc == X86ISD::UMUL ||
6403 Opc == X86ISD::INC ||
6404 Opc == X86ISD::DEC ||
6405 Opc == X86ISD::OR ||
6406 Opc == X86ISD::XOR ||
6407 Opc == X86ISD::AND))
6413 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
6414 bool addTest = true;
6415 SDValue Cond = Op.getOperand(0);
6416 DebugLoc dl = Op.getDebugLoc();
6419 if (Cond.getOpcode() == ISD::SETCC) {
6420 SDValue NewCond = LowerSETCC(Cond, DAG);
6421 if (NewCond.getNode())
6425 // (select (x == 0), -1, 0) -> (sign_bit (x - 1))
6426 SDValue Op1 = Op.getOperand(1);
6427 SDValue Op2 = Op.getOperand(2);
6428 if (Cond.getOpcode() == X86ISD::SETCC &&
6429 cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue() == X86::COND_E) {
6430 SDValue Cmp = Cond.getOperand(1);
6431 if (Cmp.getOpcode() == X86ISD::CMP) {
6432 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op1);
6433 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
6434 ConstantSDNode *RHSC =
6435 dyn_cast<ConstantSDNode>(Cmp.getOperand(1).getNode());
6436 if (N1C && N1C->isAllOnesValue() &&
6437 N2C && N2C->isNullValue() &&
6438 RHSC && RHSC->isNullValue()) {
6439 SDValue CmpOp0 = Cmp.getOperand(0);
6440 Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
6441 CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
6442 return DAG.getNode(X86ISD::SETCC_CARRY, dl, Op.getValueType(),
6443 DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
6448 // Look pass (and (setcc_carry (cmp ...)), 1).
6449 if (Cond.getOpcode() == ISD::AND &&
6450 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6451 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6452 if (C && C->getAPIntValue() == 1)
6453 Cond = Cond.getOperand(0);
6456 // If condition flag is set by a X86ISD::CMP, then use it as the condition
6457 // setting operand in place of the X86ISD::SETCC.
6458 if (Cond.getOpcode() == X86ISD::SETCC ||
6459 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6460 CC = Cond.getOperand(0);
6462 SDValue Cmp = Cond.getOperand(1);
6463 unsigned Opc = Cmp.getOpcode();
6464 EVT VT = Op.getValueType();
6466 bool IllegalFPCMov = false;
6467 if (VT.isFloatingPoint() && !VT.isVector() &&
6468 !isScalarFPTypeInSSEReg(VT)) // FPStack?
6469 IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
6471 if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
6472 Opc == X86ISD::BT) { // FIXME
6479 // Look pass the truncate.
6480 if (Cond.getOpcode() == ISD::TRUNCATE)
6481 Cond = Cond.getOperand(0);
6483 // We know the result of AND is compared against zero. Try to match
6485 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
6486 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6487 if (NewSetCC.getNode()) {
6488 CC = NewSetCC.getOperand(0);
6489 Cond = NewSetCC.getOperand(1);
6496 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6497 Cond = EmitTest(Cond, X86::COND_NE, DAG);
6500 // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
6501 // condition is true.
6502 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Flag);
6503 SDValue Ops[] = { Op2, Op1, CC, Cond };
6504 return DAG.getNode(X86ISD::CMOV, dl, VTs, Ops, array_lengthof(Ops));
6507 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
6508 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
6509 // from the AND / OR.
6510 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
6511 Opc = Op.getOpcode();
6512 if (Opc != ISD::OR && Opc != ISD::AND)
6514 return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6515 Op.getOperand(0).hasOneUse() &&
6516 Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
6517 Op.getOperand(1).hasOneUse());
6520 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
6521 // 1 and that the SETCC node has a single use.
6522 static bool isXor1OfSetCC(SDValue Op) {
6523 if (Op.getOpcode() != ISD::XOR)
6525 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6526 if (N1C && N1C->getAPIntValue() == 1) {
6527 return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
6528 Op.getOperand(0).hasOneUse();
6533 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
6534 bool addTest = true;
6535 SDValue Chain = Op.getOperand(0);
6536 SDValue Cond = Op.getOperand(1);
6537 SDValue Dest = Op.getOperand(2);
6538 DebugLoc dl = Op.getDebugLoc();
6541 if (Cond.getOpcode() == ISD::SETCC) {
6542 SDValue NewCond = LowerSETCC(Cond, DAG);
6543 if (NewCond.getNode())
6547 // FIXME: LowerXALUO doesn't handle these!!
6548 else if (Cond.getOpcode() == X86ISD::ADD ||
6549 Cond.getOpcode() == X86ISD::SUB ||
6550 Cond.getOpcode() == X86ISD::SMUL ||
6551 Cond.getOpcode() == X86ISD::UMUL)
6552 Cond = LowerXALUO(Cond, DAG);
6555 // Look pass (and (setcc_carry (cmp ...)), 1).
6556 if (Cond.getOpcode() == ISD::AND &&
6557 Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
6558 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
6559 if (C && C->getAPIntValue() == 1)
6560 Cond = Cond.getOperand(0);
6563 // If condition flag is set by a X86ISD::CMP, then use it as the condition
6564 // setting operand in place of the X86ISD::SETCC.
6565 if (Cond.getOpcode() == X86ISD::SETCC ||
6566 Cond.getOpcode() == X86ISD::SETCC_CARRY) {
6567 CC = Cond.getOperand(0);
6569 SDValue Cmp = Cond.getOperand(1);
6570 unsigned Opc = Cmp.getOpcode();
6571 // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
6572 if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
6576 switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
6580 // These can only come from an arithmetic instruction with overflow,
6581 // e.g. SADDO, UADDO.
6582 Cond = Cond.getNode()->getOperand(1);
6589 if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
6590 SDValue Cmp = Cond.getOperand(0).getOperand(1);
6591 if (CondOpc == ISD::OR) {
6592 // Also, recognize the pattern generated by an FCMP_UNE. We can emit
6593 // two branches instead of an explicit OR instruction with a
6595 if (Cmp == Cond.getOperand(1).getOperand(1) &&
6596 isX86LogicalCmp(Cmp)) {
6597 CC = Cond.getOperand(0).getOperand(0);
6598 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6599 Chain, Dest, CC, Cmp);
6600 CC = Cond.getOperand(1).getOperand(0);
6604 } else { // ISD::AND
6605 // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
6606 // two branches instead of an explicit AND instruction with a
6607 // separate test. However, we only do this if this block doesn't
6608 // have a fall-through edge, because this requires an explicit
6609 // jmp when the condition is false.
6610 if (Cmp == Cond.getOperand(1).getOperand(1) &&
6611 isX86LogicalCmp(Cmp) &&
6612 Op.getNode()->hasOneUse()) {
6613 X86::CondCode CCode =
6614 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6615 CCode = X86::GetOppositeBranchCondition(CCode);
6616 CC = DAG.getConstant(CCode, MVT::i8);
6617 SDNode *User = *Op.getNode()->use_begin();
6618 // Look for an unconditional branch following this conditional branch.
6619 // We need this because we need to reverse the successors in order
6620 // to implement FCMP_OEQ.
6621 if (User->getOpcode() == ISD::BR) {
6622 SDValue FalseBB = User->getOperand(1);
6624 DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
6625 assert(NewBR == User);
6629 Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6630 Chain, Dest, CC, Cmp);
6631 X86::CondCode CCode =
6632 (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
6633 CCode = X86::GetOppositeBranchCondition(CCode);
6634 CC = DAG.getConstant(CCode, MVT::i8);
6640 } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
6641 // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
6642 // It should be transformed during dag combiner except when the condition
6643 // is set by a arithmetics with overflow node.
6644 X86::CondCode CCode =
6645 (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
6646 CCode = X86::GetOppositeBranchCondition(CCode);
6647 CC = DAG.getConstant(CCode, MVT::i8);
6648 Cond = Cond.getOperand(0).getOperand(1);
6654 // Look pass the truncate.
6655 if (Cond.getOpcode() == ISD::TRUNCATE)
6656 Cond = Cond.getOperand(0);
6658 // We know the result of AND is compared against zero. Try to match
6660 if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
6661 SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
6662 if (NewSetCC.getNode()) {
6663 CC = NewSetCC.getOperand(0);
6664 Cond = NewSetCC.getOperand(1);
6671 CC = DAG.getConstant(X86::COND_NE, MVT::i8);
6672 Cond = EmitTest(Cond, X86::COND_NE, DAG);
6674 return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
6675 Chain, Dest, CC, Cond);
6679 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
6680 // Calls to _alloca is needed to probe the stack when allocating more than 4k
6681 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
6682 // that the guard pages used by the OS virtual memory manager are allocated in
6683 // correct sequence.
6685 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
6686 SelectionDAG &DAG) const {
6687 assert(Subtarget->isTargetCygMing() &&
6688 "This should be used only on Cygwin/Mingw targets");
6689 DebugLoc dl = Op.getDebugLoc();
6692 SDValue Chain = Op.getOperand(0);
6693 SDValue Size = Op.getOperand(1);
6694 // FIXME: Ensure alignment here
6698 EVT SPTy = Subtarget->is64Bit() ? MVT::i64 : MVT::i32;
6700 Chain = DAG.getCopyToReg(Chain, dl, X86::EAX, Size, Flag);
6701 Flag = Chain.getValue(1);
6703 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Flag);
6705 Chain = DAG.getNode(X86ISD::MINGW_ALLOCA, dl, NodeTys, Chain, Flag);
6706 Flag = Chain.getValue(1);
6708 Chain = DAG.getCopyFromReg(Chain, dl, X86StackPtr, SPTy).getValue(1);
6710 SDValue Ops1[2] = { Chain.getValue(0), Chain };
6711 return DAG.getMergeValues(Ops1, 2, dl);
6714 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
6715 MachineFunction &MF = DAG.getMachineFunction();
6716 X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
6718 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
6719 DebugLoc dl = Op.getDebugLoc();
6721 if (!Subtarget->is64Bit()) {
6722 // vastart just stores the address of the VarArgsFrameIndex slot into the
6723 // memory location argument.
6724 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
6726 return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1), SV, 0,
6731 // gp_offset (0 - 6 * 8)
6732 // fp_offset (48 - 48 + 8 * 16)
6733 // overflow_arg_area (point to parameters coming in memory).
6735 SmallVector<SDValue, 8> MemOps;
6736 SDValue FIN = Op.getOperand(1);
6738 SDValue Store = DAG.getStore(Op.getOperand(0), dl,
6739 DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
6741 FIN, SV, 0, false, false, 0);
6742 MemOps.push_back(Store);
6745 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6746 FIN, DAG.getIntPtrConstant(4));
6747 Store = DAG.getStore(Op.getOperand(0), dl,
6748 DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
6750 FIN, SV, 0, false, false, 0);
6751 MemOps.push_back(Store);
6753 // Store ptr to overflow_arg_area
6754 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6755 FIN, DAG.getIntPtrConstant(4));
6756 SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
6758 Store = DAG.getStore(Op.getOperand(0), dl, OVFIN, FIN, SV, 0,
6760 MemOps.push_back(Store);
6762 // Store ptr to reg_save_area.
6763 FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(),
6764 FIN, DAG.getIntPtrConstant(8));
6765 SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
6767 Store = DAG.getStore(Op.getOperand(0), dl, RSFIN, FIN, SV, 0,
6769 MemOps.push_back(Store);
6770 return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6771 &MemOps[0], MemOps.size());
6774 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
6775 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6776 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_arg!");
6778 report_fatal_error("VAArgInst is not yet implemented for x86-64!");
6782 SDValue X86TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
6783 // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
6784 assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
6785 SDValue Chain = Op.getOperand(0);
6786 SDValue DstPtr = Op.getOperand(1);
6787 SDValue SrcPtr = Op.getOperand(2);
6788 const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
6789 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
6790 DebugLoc dl = Op.getDebugLoc();
6792 return DAG.getMemcpy(Chain, dl, DstPtr, SrcPtr,
6793 DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
6794 false, DstSV, 0, SrcSV, 0);
6798 X86TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) const {
6799 DebugLoc dl = Op.getDebugLoc();
6800 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6802 default: return SDValue(); // Don't custom lower most intrinsics.
6803 // Comparison intrinsics.
6804 case Intrinsic::x86_sse_comieq_ss:
6805 case Intrinsic::x86_sse_comilt_ss:
6806 case Intrinsic::x86_sse_comile_ss:
6807 case Intrinsic::x86_sse_comigt_ss:
6808 case Intrinsic::x86_sse_comige_ss:
6809 case Intrinsic::x86_sse_comineq_ss:
6810 case Intrinsic::x86_sse_ucomieq_ss:
6811 case Intrinsic::x86_sse_ucomilt_ss:
6812 case Intrinsic::x86_sse_ucomile_ss:
6813 case Intrinsic::x86_sse_ucomigt_ss:
6814 case Intrinsic::x86_sse_ucomige_ss:
6815 case Intrinsic::x86_sse_ucomineq_ss:
6816 case Intrinsic::x86_sse2_comieq_sd:
6817 case Intrinsic::x86_sse2_comilt_sd:
6818 case Intrinsic::x86_sse2_comile_sd:
6819 case Intrinsic::x86_sse2_comigt_sd:
6820 case Intrinsic::x86_sse2_comige_sd:
6821 case Intrinsic::x86_sse2_comineq_sd:
6822 case Intrinsic::x86_sse2_ucomieq_sd:
6823 case Intrinsic::x86_sse2_ucomilt_sd:
6824 case Intrinsic::x86_sse2_ucomile_sd:
6825 case Intrinsic::x86_sse2_ucomigt_sd:
6826 case Intrinsic::x86_sse2_ucomige_sd:
6827 case Intrinsic::x86_sse2_ucomineq_sd: {
6829 ISD::CondCode CC = ISD::SETCC_INVALID;
6832 case Intrinsic::x86_sse_comieq_ss:
6833 case Intrinsic::x86_sse2_comieq_sd:
6837 case Intrinsic::x86_sse_comilt_ss:
6838 case Intrinsic::x86_sse2_comilt_sd:
6842 case Intrinsic::x86_sse_comile_ss:
6843 case Intrinsic::x86_sse2_comile_sd:
6847 case Intrinsic::x86_sse_comigt_ss:
6848 case Intrinsic::x86_sse2_comigt_sd:
6852 case Intrinsic::x86_sse_comige_ss:
6853 case Intrinsic::x86_sse2_comige_sd:
6857 case Intrinsic::x86_sse_comineq_ss:
6858 case Intrinsic::x86_sse2_comineq_sd:
6862 case Intrinsic::x86_sse_ucomieq_ss:
6863 case Intrinsic::x86_sse2_ucomieq_sd:
6864 Opc = X86ISD::UCOMI;
6867 case Intrinsic::x86_sse_ucomilt_ss:
6868 case Intrinsic::x86_sse2_ucomilt_sd:
6869 Opc = X86ISD::UCOMI;
6872 case Intrinsic::x86_sse_ucomile_ss:
6873 case Intrinsic::x86_sse2_ucomile_sd:
6874 Opc = X86ISD::UCOMI;
6877 case Intrinsic::x86_sse_ucomigt_ss:
6878 case Intrinsic::x86_sse2_ucomigt_sd:
6879 Opc = X86ISD::UCOMI;
6882 case Intrinsic::x86_sse_ucomige_ss:
6883 case Intrinsic::x86_sse2_ucomige_sd:
6884 Opc = X86ISD::UCOMI;
6887 case Intrinsic::x86_sse_ucomineq_ss:
6888 case Intrinsic::x86_sse2_ucomineq_sd:
6889 Opc = X86ISD::UCOMI;
6894 SDValue LHS = Op.getOperand(1);
6895 SDValue RHS = Op.getOperand(2);
6896 unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
6897 assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
6898 SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
6899 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
6900 DAG.getConstant(X86CC, MVT::i8), Cond);
6901 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6903 // ptest intrinsics. The intrinsic these come from are designed to return
6904 // an integer value, not just an instruction so lower it to the ptest
6905 // pattern and a setcc for the result.
6906 case Intrinsic::x86_sse41_ptestz:
6907 case Intrinsic::x86_sse41_ptestc:
6908 case Intrinsic::x86_sse41_ptestnzc:{
6911 default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
6912 case Intrinsic::x86_sse41_ptestz:
6914 X86CC = X86::COND_E;
6916 case Intrinsic::x86_sse41_ptestc:
6918 X86CC = X86::COND_B;
6920 case Intrinsic::x86_sse41_ptestnzc:
6922 X86CC = X86::COND_A;
6926 SDValue LHS = Op.getOperand(1);
6927 SDValue RHS = Op.getOperand(2);
6928 SDValue Test = DAG.getNode(X86ISD::PTEST, dl, MVT::i32, LHS, RHS);
6929 SDValue CC = DAG.getConstant(X86CC, MVT::i8);
6930 SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
6931 return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
6934 // Fix vector shift instructions where the last operand is a non-immediate
6936 case Intrinsic::x86_sse2_pslli_w:
6937 case Intrinsic::x86_sse2_pslli_d:
6938 case Intrinsic::x86_sse2_pslli_q:
6939 case Intrinsic::x86_sse2_psrli_w:
6940 case Intrinsic::x86_sse2_psrli_d:
6941 case Intrinsic::x86_sse2_psrli_q:
6942 case Intrinsic::x86_sse2_psrai_w:
6943 case Intrinsic::x86_sse2_psrai_d:
6944 case Intrinsic::x86_mmx_pslli_w:
6945 case Intrinsic::x86_mmx_pslli_d:
6946 case Intrinsic::x86_mmx_pslli_q:
6947 case Intrinsic::x86_mmx_psrli_w:
6948 case Intrinsic::x86_mmx_psrli_d:
6949 case Intrinsic::x86_mmx_psrli_q:
6950 case Intrinsic::x86_mmx_psrai_w:
6951 case Intrinsic::x86_mmx_psrai_d: {
6952 SDValue ShAmt = Op.getOperand(2);
6953 if (isa<ConstantSDNode>(ShAmt))
6956 unsigned NewIntNo = 0;
6957 EVT ShAmtVT = MVT::v4i32;
6959 case Intrinsic::x86_sse2_pslli_w:
6960 NewIntNo = Intrinsic::x86_sse2_psll_w;
6962 case Intrinsic::x86_sse2_pslli_d:
6963 NewIntNo = Intrinsic::x86_sse2_psll_d;
6965 case Intrinsic::x86_sse2_pslli_q:
6966 NewIntNo = Intrinsic::x86_sse2_psll_q;
6968 case Intrinsic::x86_sse2_psrli_w:
6969 NewIntNo = Intrinsic::x86_sse2_psrl_w;
6971 case Intrinsic::x86_sse2_psrli_d:
6972 NewIntNo = Intrinsic::x86_sse2_psrl_d;
6974 case Intrinsic::x86_sse2_psrli_q:
6975 NewIntNo = Intrinsic::x86_sse2_psrl_q;
6977 case Intrinsic::x86_sse2_psrai_w:
6978 NewIntNo = Intrinsic::x86_sse2_psra_w;
6980 case Intrinsic::x86_sse2_psrai_d:
6981 NewIntNo = Intrinsic::x86_sse2_psra_d;
6984 ShAmtVT = MVT::v2i32;
6986 case Intrinsic::x86_mmx_pslli_w:
6987 NewIntNo = Intrinsic::x86_mmx_psll_w;
6989 case Intrinsic::x86_mmx_pslli_d:
6990 NewIntNo = Intrinsic::x86_mmx_psll_d;
6992 case Intrinsic::x86_mmx_pslli_q:
6993 NewIntNo = Intrinsic::x86_mmx_psll_q;
6995 case Intrinsic::x86_mmx_psrli_w:
6996 NewIntNo = Intrinsic::x86_mmx_psrl_w;
6998 case Intrinsic::x86_mmx_psrli_d:
6999 NewIntNo = Intrinsic::x86_mmx_psrl_d;
7001 case Intrinsic::x86_mmx_psrli_q:
7002 NewIntNo = Intrinsic::x86_mmx_psrl_q;
7004 case Intrinsic::x86_mmx_psrai_w:
7005 NewIntNo = Intrinsic::x86_mmx_psra_w;
7007 case Intrinsic::x86_mmx_psrai_d:
7008 NewIntNo = Intrinsic::x86_mmx_psra_d;
7010 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
7016 // The vector shift intrinsics with scalars uses 32b shift amounts but
7017 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
7021 ShOps[1] = DAG.getConstant(0, MVT::i32);
7022 if (ShAmtVT == MVT::v4i32) {
7023 ShOps[2] = DAG.getUNDEF(MVT::i32);
7024 ShOps[3] = DAG.getUNDEF(MVT::i32);
7025 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 4);
7027 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
7030 EVT VT = Op.getValueType();
7031 ShAmt = DAG.getNode(ISD::BIT_CONVERT, dl, VT, ShAmt);
7032 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7033 DAG.getConstant(NewIntNo, MVT::i32),
7034 Op.getOperand(1), ShAmt);
7039 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
7040 SelectionDAG &DAG) const {
7041 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7042 MFI->setReturnAddressIsTaken(true);
7044 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7045 DebugLoc dl = Op.getDebugLoc();
7048 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
7050 DAG.getConstant(TD->getPointerSize(),
7051 Subtarget->is64Bit() ? MVT::i64 : MVT::i32);
7052 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7053 DAG.getNode(ISD::ADD, dl, getPointerTy(),
7055 NULL, 0, false, false, 0);
7058 // Just load the return address.
7059 SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
7060 return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
7061 RetAddrFI, NULL, 0, false, false, 0);
7064 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
7065 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7066 MFI->setFrameAddressIsTaken(true);
7068 EVT VT = Op.getValueType();
7069 DebugLoc dl = Op.getDebugLoc(); // FIXME probably not meaningful
7070 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
7071 unsigned FrameReg = Subtarget->is64Bit() ? X86::RBP : X86::EBP;
7072 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
7074 FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr, NULL, 0,
7079 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
7080 SelectionDAG &DAG) const {
7081 return DAG.getIntPtrConstant(2*TD->getPointerSize());
7084 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
7085 MachineFunction &MF = DAG.getMachineFunction();
7086 SDValue Chain = Op.getOperand(0);
7087 SDValue Offset = Op.getOperand(1);
7088 SDValue Handler = Op.getOperand(2);
7089 DebugLoc dl = Op.getDebugLoc();
7091 SDValue Frame = DAG.getRegister(Subtarget->is64Bit() ? X86::RBP : X86::EBP,
7093 unsigned StoreAddrReg = (Subtarget->is64Bit() ? X86::RCX : X86::ECX);
7095 SDValue StoreAddr = DAG.getNode(ISD::SUB, dl, getPointerTy(), Frame,
7096 DAG.getIntPtrConstant(-TD->getPointerSize()));
7097 StoreAddr = DAG.getNode(ISD::ADD, dl, getPointerTy(), StoreAddr, Offset);
7098 Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, NULL, 0, false, false, 0);
7099 Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
7100 MF.getRegInfo().addLiveOut(StoreAddrReg);
7102 return DAG.getNode(X86ISD::EH_RETURN, dl,
7104 Chain, DAG.getRegister(StoreAddrReg, getPointerTy()));
7107 SDValue X86TargetLowering::LowerTRAMPOLINE(SDValue Op,
7108 SelectionDAG &DAG) const {
7109 SDValue Root = Op.getOperand(0);
7110 SDValue Trmp = Op.getOperand(1); // trampoline
7111 SDValue FPtr = Op.getOperand(2); // nested function
7112 SDValue Nest = Op.getOperand(3); // 'nest' parameter value
7113 DebugLoc dl = Op.getDebugLoc();
7115 const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
7117 if (Subtarget->is64Bit()) {
7118 SDValue OutChains[6];
7120 // Large code-model.
7121 const unsigned char JMP64r = 0xFF; // 64-bit jmp through register opcode.
7122 const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
7124 const unsigned char N86R10 = RegInfo->getX86RegNum(X86::R10);
7125 const unsigned char N86R11 = RegInfo->getX86RegNum(X86::R11);
7127 const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
7129 // Load the pointer to the nested function into R11.
7130 unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
7131 SDValue Addr = Trmp;
7132 OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7133 Addr, TrmpAddr, 0, false, false, 0);
7135 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7136 DAG.getConstant(2, MVT::i64));
7137 OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr, TrmpAddr, 2,
7140 // Load the 'nest' parameter value into R10.
7141 // R10 is specified in X86CallingConv.td
7142 OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
7143 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7144 DAG.getConstant(10, MVT::i64));
7145 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7146 Addr, TrmpAddr, 10, false, false, 0);
7148 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7149 DAG.getConstant(12, MVT::i64));
7150 OutChains[3] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 12,
7153 // Jump to the nested function.
7154 OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
7155 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7156 DAG.getConstant(20, MVT::i64));
7157 OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
7158 Addr, TrmpAddr, 20, false, false, 0);
7160 unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
7161 Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
7162 DAG.getConstant(22, MVT::i64));
7163 OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
7164 TrmpAddr, 22, false, false, 0);
7167 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 6) };
7168 return DAG.getMergeValues(Ops, 2, dl);
7170 const Function *Func =
7171 cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
7172 CallingConv::ID CC = Func->getCallingConv();
7177 llvm_unreachable("Unsupported calling convention");
7178 case CallingConv::C:
7179 case CallingConv::X86_StdCall: {
7180 // Pass 'nest' parameter in ECX.
7181 // Must be kept in sync with X86CallingConv.td
7184 // Check that ECX wasn't needed by an 'inreg' parameter.
7185 const FunctionType *FTy = Func->getFunctionType();
7186 const AttrListPtr &Attrs = Func->getAttributes();
7188 if (!Attrs.isEmpty() && !Func->isVarArg()) {
7189 unsigned InRegCount = 0;
7192 for (FunctionType::param_iterator I = FTy->param_begin(),
7193 E = FTy->param_end(); I != E; ++I, ++Idx)
7194 if (Attrs.paramHasAttr(Idx, Attribute::InReg))
7195 // FIXME: should only count parameters that are lowered to integers.
7196 InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
7198 if (InRegCount > 2) {
7199 report_fatal_error("Nest register in use - reduce number of inreg parameters!");
7204 case CallingConv::X86_FastCall:
7205 case CallingConv::X86_ThisCall:
7206 case CallingConv::Fast:
7207 // Pass 'nest' parameter in EAX.
7208 // Must be kept in sync with X86CallingConv.td
7213 SDValue OutChains[4];
7216 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7217 DAG.getConstant(10, MVT::i32));
7218 Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
7220 // This is storing the opcode for MOV32ri.
7221 const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
7222 const unsigned char N86Reg = RegInfo->getX86RegNum(NestReg);
7223 OutChains[0] = DAG.getStore(Root, dl,
7224 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
7225 Trmp, TrmpAddr, 0, false, false, 0);
7227 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7228 DAG.getConstant(1, MVT::i32));
7229 OutChains[1] = DAG.getStore(Root, dl, Nest, Addr, TrmpAddr, 1,
7232 const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
7233 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7234 DAG.getConstant(5, MVT::i32));
7235 OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
7236 TrmpAddr, 5, false, false, 1);
7238 Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
7239 DAG.getConstant(6, MVT::i32));
7240 OutChains[3] = DAG.getStore(Root, dl, Disp, Addr, TrmpAddr, 6,
7244 { Trmp, DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains, 4) };
7245 return DAG.getMergeValues(Ops, 2, dl);
7249 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
7250 SelectionDAG &DAG) const {
7252 The rounding mode is in bits 11:10 of FPSR, and has the following
7259 FLT_ROUNDS, on the other hand, expects the following:
7266 To perform the conversion, we do:
7267 (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
7270 MachineFunction &MF = DAG.getMachineFunction();
7271 const TargetMachine &TM = MF.getTarget();
7272 const TargetFrameInfo &TFI = *TM.getFrameInfo();
7273 unsigned StackAlignment = TFI.getStackAlignment();
7274 EVT VT = Op.getValueType();
7275 DebugLoc dl = Op.getDebugLoc();
7277 // Save FP Control Word to stack slot
7278 int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
7279 SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
7281 SDValue Chain = DAG.getNode(X86ISD::FNSTCW16m, dl, MVT::Other,
7282 DAG.getEntryNode(), StackSlot);
7284 // Load FP Control Word from stack slot
7285 SDValue CWD = DAG.getLoad(MVT::i16, dl, Chain, StackSlot, NULL, 0,
7288 // Transform as necessary
7290 DAG.getNode(ISD::SRL, dl, MVT::i16,
7291 DAG.getNode(ISD::AND, dl, MVT::i16,
7292 CWD, DAG.getConstant(0x800, MVT::i16)),
7293 DAG.getConstant(11, MVT::i8));
7295 DAG.getNode(ISD::SRL, dl, MVT::i16,
7296 DAG.getNode(ISD::AND, dl, MVT::i16,
7297 CWD, DAG.getConstant(0x400, MVT::i16)),
7298 DAG.getConstant(9, MVT::i8));
7301 DAG.getNode(ISD::AND, dl, MVT::i16,
7302 DAG.getNode(ISD::ADD, dl, MVT::i16,
7303 DAG.getNode(ISD::OR, dl, MVT::i16, CWD1, CWD2),
7304 DAG.getConstant(1, MVT::i16)),
7305 DAG.getConstant(3, MVT::i16));
7308 return DAG.getNode((VT.getSizeInBits() < 16 ?
7309 ISD::TRUNCATE : ISD::ZERO_EXTEND), dl, VT, RetVal);
7312 SDValue X86TargetLowering::LowerCTLZ(SDValue Op, SelectionDAG &DAG) const {
7313 EVT VT = Op.getValueType();
7315 unsigned NumBits = VT.getSizeInBits();
7316 DebugLoc dl = Op.getDebugLoc();
7318 Op = Op.getOperand(0);
7319 if (VT == MVT::i8) {
7320 // Zero extend to i32 since there is not an i8 bsr.
7322 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7325 // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
7326 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7327 Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
7329 // If src is zero (i.e. bsr sets ZF), returns NumBits.
7332 DAG.getConstant(NumBits+NumBits-1, OpVT),
7333 DAG.getConstant(X86::COND_E, MVT::i8),
7336 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7338 // Finally xor with NumBits-1.
7339 Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
7342 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7346 SDValue X86TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
7347 EVT VT = Op.getValueType();
7349 unsigned NumBits = VT.getSizeInBits();
7350 DebugLoc dl = Op.getDebugLoc();
7352 Op = Op.getOperand(0);
7353 if (VT == MVT::i8) {
7355 Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
7358 // Issue a bsf (scan bits forward) which also sets EFLAGS.
7359 SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
7360 Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
7362 // If src is zero (i.e. bsf sets ZF), returns NumBits.
7365 DAG.getConstant(NumBits, OpVT),
7366 DAG.getConstant(X86::COND_E, MVT::i8),
7369 Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops, array_lengthof(Ops));
7372 Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
7376 SDValue X86TargetLowering::LowerMUL_V2I64(SDValue Op, SelectionDAG &DAG) const {
7377 EVT VT = Op.getValueType();
7378 assert(VT == MVT::v2i64 && "Only know how to lower V2I64 multiply");
7379 DebugLoc dl = Op.getDebugLoc();
7381 // ulong2 Ahi = __builtin_ia32_psrlqi128( a, 32);
7382 // ulong2 Bhi = __builtin_ia32_psrlqi128( b, 32);
7383 // ulong2 AloBlo = __builtin_ia32_pmuludq128( a, b );
7384 // ulong2 AloBhi = __builtin_ia32_pmuludq128( a, Bhi );
7385 // ulong2 AhiBlo = __builtin_ia32_pmuludq128( Ahi, b );
7387 // AloBhi = __builtin_ia32_psllqi128( AloBhi, 32 );
7388 // AhiBlo = __builtin_ia32_psllqi128( AhiBlo, 32 );
7389 // return AloBlo + AloBhi + AhiBlo;
7391 SDValue A = Op.getOperand(0);
7392 SDValue B = Op.getOperand(1);
7394 SDValue Ahi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7395 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7396 A, DAG.getConstant(32, MVT::i32));
7397 SDValue Bhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7398 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
7399 B, DAG.getConstant(32, MVT::i32));
7400 SDValue AloBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7401 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7403 SDValue AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7404 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7406 SDValue AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7407 DAG.getConstant(Intrinsic::x86_sse2_pmulu_dq, MVT::i32),
7409 AloBhi = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7410 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7411 AloBhi, DAG.getConstant(32, MVT::i32));
7412 AhiBlo = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
7413 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
7414 AhiBlo, DAG.getConstant(32, MVT::i32));
7415 SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
7416 Res = DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
7421 SDValue X86TargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
7422 // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
7423 // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
7424 // looks for this combo and may remove the "setcc" instruction if the "setcc"
7425 // has only one use.
7426 SDNode *N = Op.getNode();
7427 SDValue LHS = N->getOperand(0);
7428 SDValue RHS = N->getOperand(1);
7429 unsigned BaseOp = 0;
7431 DebugLoc dl = Op.getDebugLoc();
7433 switch (Op.getOpcode()) {
7434 default: llvm_unreachable("Unknown ovf instruction!");
7436 // A subtract of one will be selected as a INC. Note that INC doesn't
7437 // set CF, so we can't do this for UADDO.
7438 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7439 if (C->getAPIntValue() == 1) {
7440 BaseOp = X86ISD::INC;
7444 BaseOp = X86ISD::ADD;
7448 BaseOp = X86ISD::ADD;
7452 // A subtract of one will be selected as a DEC. Note that DEC doesn't
7453 // set CF, so we can't do this for USUBO.
7454 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
7455 if (C->getAPIntValue() == 1) {
7456 BaseOp = X86ISD::DEC;
7460 BaseOp = X86ISD::SUB;
7464 BaseOp = X86ISD::SUB;
7468 BaseOp = X86ISD::SMUL;
7472 BaseOp = X86ISD::UMUL;
7477 // Also sets EFLAGS.
7478 SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
7479 SDValue Sum = DAG.getNode(BaseOp, dl, VTs, LHS, RHS);
7482 DAG.getNode(X86ISD::SETCC, dl, N->getValueType(1),
7483 DAG.getConstant(Cond, MVT::i32), SDValue(Sum.getNode(), 1));
7485 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SetCC);
7489 SDValue X86TargetLowering::LowerCMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
7490 EVT T = Op.getValueType();
7491 DebugLoc dl = Op.getDebugLoc();
7494 switch(T.getSimpleVT().SimpleTy) {
7496 assert(false && "Invalid value type!");
7497 case MVT::i8: Reg = X86::AL; size = 1; break;
7498 case MVT::i16: Reg = X86::AX; size = 2; break;
7499 case MVT::i32: Reg = X86::EAX; size = 4; break;
7501 assert(Subtarget->is64Bit() && "Node not type legal!");
7502 Reg = X86::RAX; size = 8;
7505 SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), dl, Reg,
7506 Op.getOperand(2), SDValue());
7507 SDValue Ops[] = { cpIn.getValue(0),
7510 DAG.getTargetConstant(size, MVT::i8),
7512 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7513 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG_DAG, dl, Tys, Ops, 5);
7515 DAG.getCopyFromReg(Result.getValue(0), dl, Reg, T, Result.getValue(1));
7519 SDValue X86TargetLowering::LowerREADCYCLECOUNTER(SDValue Op,
7520 SelectionDAG &DAG) const {
7521 assert(Subtarget->is64Bit() && "Result not type legalized?");
7522 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7523 SDValue TheChain = Op.getOperand(0);
7524 DebugLoc dl = Op.getDebugLoc();
7525 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7526 SDValue rax = DAG.getCopyFromReg(rd, dl, X86::RAX, MVT::i64, rd.getValue(1));
7527 SDValue rdx = DAG.getCopyFromReg(rax.getValue(1), dl, X86::RDX, MVT::i64,
7529 SDValue Tmp = DAG.getNode(ISD::SHL, dl, MVT::i64, rdx,
7530 DAG.getConstant(32, MVT::i8));
7532 DAG.getNode(ISD::OR, dl, MVT::i64, rax, Tmp),
7535 return DAG.getMergeValues(Ops, 2, dl);
7538 SDValue X86TargetLowering::LowerBIT_CONVERT(SDValue Op,
7539 SelectionDAG &DAG) const {
7540 EVT SrcVT = Op.getOperand(0).getValueType();
7541 EVT DstVT = Op.getValueType();
7542 assert((Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
7543 Subtarget->hasMMX() && !DisableMMX) &&
7544 "Unexpected custom BIT_CONVERT");
7545 assert((DstVT == MVT::i64 ||
7546 (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
7547 "Unexpected custom BIT_CONVERT");
7548 // i64 <=> MMX conversions are Legal.
7549 if (SrcVT==MVT::i64 && DstVT.isVector())
7551 if (DstVT==MVT::i64 && SrcVT.isVector())
7553 // MMX <=> MMX conversions are Legal.
7554 if (SrcVT.isVector() && DstVT.isVector())
7556 // All other conversions need to be expanded.
7559 SDValue X86TargetLowering::LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) const {
7560 SDNode *Node = Op.getNode();
7561 DebugLoc dl = Node->getDebugLoc();
7562 EVT T = Node->getValueType(0);
7563 SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
7564 DAG.getConstant(0, T), Node->getOperand(2));
7565 return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
7566 cast<AtomicSDNode>(Node)->getMemoryVT(),
7567 Node->getOperand(0),
7568 Node->getOperand(1), negOp,
7569 cast<AtomicSDNode>(Node)->getSrcValue(),
7570 cast<AtomicSDNode>(Node)->getAlignment());
7573 /// LowerOperation - Provide custom lowering hooks for some operations.
7575 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7576 switch (Op.getOpcode()) {
7577 default: llvm_unreachable("Should not custom lower this!");
7578 case ISD::ATOMIC_CMP_SWAP: return LowerCMP_SWAP(Op,DAG);
7579 case ISD::ATOMIC_LOAD_SUB: return LowerLOAD_SUB(Op,DAG);
7580 case ISD::BUILD_VECTOR: return LowerBUILD_VECTOR(Op, DAG);
7581 case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
7582 case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7583 case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7584 case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7585 case ISD::SCALAR_TO_VECTOR: return LowerSCALAR_TO_VECTOR(Op, DAG);
7586 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
7587 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
7588 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7589 case ISD::ExternalSymbol: return LowerExternalSymbol(Op, DAG);
7590 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
7591 case ISD::SHL_PARTS:
7592 case ISD::SRA_PARTS:
7593 case ISD::SRL_PARTS: return LowerShift(Op, DAG);
7594 case ISD::SINT_TO_FP: return LowerSINT_TO_FP(Op, DAG);
7595 case ISD::UINT_TO_FP: return LowerUINT_TO_FP(Op, DAG);
7596 case ISD::FP_TO_SINT: return LowerFP_TO_SINT(Op, DAG);
7597 case ISD::FP_TO_UINT: return LowerFP_TO_UINT(Op, DAG);
7598 case ISD::FABS: return LowerFABS(Op, DAG);
7599 case ISD::FNEG: return LowerFNEG(Op, DAG);
7600 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
7601 case ISD::SETCC: return LowerSETCC(Op, DAG);
7602 case ISD::VSETCC: return LowerVSETCC(Op, DAG);
7603 case ISD::SELECT: return LowerSELECT(Op, DAG);
7604 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
7605 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
7606 case ISD::VASTART: return LowerVASTART(Op, DAG);
7607 case ISD::VAARG: return LowerVAARG(Op, DAG);
7608 case ISD::VACOPY: return LowerVACOPY(Op, DAG);
7609 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
7610 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
7611 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
7612 case ISD::FRAME_TO_ARGS_OFFSET:
7613 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
7614 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
7615 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
7616 case ISD::TRAMPOLINE: return LowerTRAMPOLINE(Op, DAG);
7617 case ISD::FLT_ROUNDS_: return LowerFLT_ROUNDS_(Op, DAG);
7618 case ISD::CTLZ: return LowerCTLZ(Op, DAG);
7619 case ISD::CTTZ: return LowerCTTZ(Op, DAG);
7620 case ISD::MUL: return LowerMUL_V2I64(Op, DAG);
7626 case ISD::UMULO: return LowerXALUO(Op, DAG);
7627 case ISD::READCYCLECOUNTER: return LowerREADCYCLECOUNTER(Op, DAG);
7628 case ISD::BIT_CONVERT: return LowerBIT_CONVERT(Op, DAG);
7632 void X86TargetLowering::
7633 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
7634 SelectionDAG &DAG, unsigned NewOp) const {
7635 EVT T = Node->getValueType(0);
7636 DebugLoc dl = Node->getDebugLoc();
7637 assert (T == MVT::i64 && "Only know how to expand i64 atomics");
7639 SDValue Chain = Node->getOperand(0);
7640 SDValue In1 = Node->getOperand(1);
7641 SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7642 Node->getOperand(2), DAG.getIntPtrConstant(0));
7643 SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7644 Node->getOperand(2), DAG.getIntPtrConstant(1));
7645 SDValue Ops[] = { Chain, In1, In2L, In2H };
7646 SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
7648 DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, 4, MVT::i64,
7649 cast<MemSDNode>(Node)->getMemOperand());
7650 SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
7651 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7652 Results.push_back(Result.getValue(2));
7655 /// ReplaceNodeResults - Replace a node with an illegal result type
7656 /// with a new node built out of custom code.
7657 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
7658 SmallVectorImpl<SDValue>&Results,
7659 SelectionDAG &DAG) const {
7660 DebugLoc dl = N->getDebugLoc();
7661 switch (N->getOpcode()) {
7663 assert(false && "Do not know how to custom type legalize this operation!");
7665 case ISD::FP_TO_SINT: {
7666 std::pair<SDValue,SDValue> Vals =
7667 FP_TO_INTHelper(SDValue(N, 0), DAG, true);
7668 SDValue FIST = Vals.first, StackSlot = Vals.second;
7669 if (FIST.getNode() != 0) {
7670 EVT VT = N->getValueType(0);
7671 // Return a load from the stack slot.
7672 Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot, NULL, 0,
7677 case ISD::READCYCLECOUNTER: {
7678 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7679 SDValue TheChain = N->getOperand(0);
7680 SDValue rd = DAG.getNode(X86ISD::RDTSC_DAG, dl, Tys, &TheChain, 1);
7681 SDValue eax = DAG.getCopyFromReg(rd, dl, X86::EAX, MVT::i32,
7683 SDValue edx = DAG.getCopyFromReg(eax.getValue(1), dl, X86::EDX, MVT::i32,
7685 // Use a buildpair to merge the two 32-bit values into a 64-bit one.
7686 SDValue Ops[] = { eax, edx };
7687 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Ops, 2));
7688 Results.push_back(edx.getValue(1));
7691 case ISD::ATOMIC_CMP_SWAP: {
7692 EVT T = N->getValueType(0);
7693 assert (T == MVT::i64 && "Only know how to expand i64 Cmp and Swap");
7694 SDValue cpInL, cpInH;
7695 cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7696 DAG.getConstant(0, MVT::i32));
7697 cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(2),
7698 DAG.getConstant(1, MVT::i32));
7699 cpInL = DAG.getCopyToReg(N->getOperand(0), dl, X86::EAX, cpInL, SDValue());
7700 cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl, X86::EDX, cpInH,
7702 SDValue swapInL, swapInH;
7703 swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7704 DAG.getConstant(0, MVT::i32));
7705 swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(3),
7706 DAG.getConstant(1, MVT::i32));
7707 swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl, X86::EBX, swapInL,
7709 swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl, X86::ECX, swapInH,
7710 swapInL.getValue(1));
7711 SDValue Ops[] = { swapInH.getValue(0),
7713 swapInH.getValue(1) };
7714 SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Flag);
7715 SDValue Result = DAG.getNode(X86ISD::LCMPXCHG8_DAG, dl, Tys, Ops, 3);
7716 SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl, X86::EAX,
7717 MVT::i32, Result.getValue(1));
7718 SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl, X86::EDX,
7719 MVT::i32, cpOutL.getValue(2));
7720 SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
7721 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF, 2));
7722 Results.push_back(cpOutH.getValue(1));
7725 case ISD::ATOMIC_LOAD_ADD:
7726 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMADD64_DAG);
7728 case ISD::ATOMIC_LOAD_AND:
7729 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMAND64_DAG);
7731 case ISD::ATOMIC_LOAD_NAND:
7732 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMNAND64_DAG);
7734 case ISD::ATOMIC_LOAD_OR:
7735 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMOR64_DAG);
7737 case ISD::ATOMIC_LOAD_SUB:
7738 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSUB64_DAG);
7740 case ISD::ATOMIC_LOAD_XOR:
7741 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMXOR64_DAG);
7743 case ISD::ATOMIC_SWAP:
7744 ReplaceATOMIC_BINARY_64(N, Results, DAG, X86ISD::ATOMSWAP64_DAG);
7749 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
7751 default: return NULL;
7752 case X86ISD::BSF: return "X86ISD::BSF";
7753 case X86ISD::BSR: return "X86ISD::BSR";
7754 case X86ISD::SHLD: return "X86ISD::SHLD";
7755 case X86ISD::SHRD: return "X86ISD::SHRD";
7756 case X86ISD::FAND: return "X86ISD::FAND";
7757 case X86ISD::FOR: return "X86ISD::FOR";
7758 case X86ISD::FXOR: return "X86ISD::FXOR";
7759 case X86ISD::FSRL: return "X86ISD::FSRL";
7760 case X86ISD::FILD: return "X86ISD::FILD";
7761 case X86ISD::FILD_FLAG: return "X86ISD::FILD_FLAG";
7762 case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
7763 case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
7764 case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
7765 case X86ISD::FLD: return "X86ISD::FLD";
7766 case X86ISD::FST: return "X86ISD::FST";
7767 case X86ISD::CALL: return "X86ISD::CALL";
7768 case X86ISD::RDTSC_DAG: return "X86ISD::RDTSC_DAG";
7769 case X86ISD::BT: return "X86ISD::BT";
7770 case X86ISD::CMP: return "X86ISD::CMP";
7771 case X86ISD::COMI: return "X86ISD::COMI";
7772 case X86ISD::UCOMI: return "X86ISD::UCOMI";
7773 case X86ISD::SETCC: return "X86ISD::SETCC";
7774 case X86ISD::SETCC_CARRY: return "X86ISD::SETCC_CARRY";
7775 case X86ISD::CMOV: return "X86ISD::CMOV";
7776 case X86ISD::BRCOND: return "X86ISD::BRCOND";
7777 case X86ISD::RET_FLAG: return "X86ISD::RET_FLAG";
7778 case X86ISD::REP_STOS: return "X86ISD::REP_STOS";
7779 case X86ISD::REP_MOVS: return "X86ISD::REP_MOVS";
7780 case X86ISD::GlobalBaseReg: return "X86ISD::GlobalBaseReg";
7781 case X86ISD::Wrapper: return "X86ISD::Wrapper";
7782 case X86ISD::WrapperRIP: return "X86ISD::WrapperRIP";
7783 case X86ISD::PEXTRB: return "X86ISD::PEXTRB";
7784 case X86ISD::PEXTRW: return "X86ISD::PEXTRW";
7785 case X86ISD::INSERTPS: return "X86ISD::INSERTPS";
7786 case X86ISD::PINSRB: return "X86ISD::PINSRB";
7787 case X86ISD::PINSRW: return "X86ISD::PINSRW";
7788 case X86ISD::MMX_PINSRW: return "X86ISD::MMX_PINSRW";
7789 case X86ISD::PSHUFB: return "X86ISD::PSHUFB";
7790 case X86ISD::FMAX: return "X86ISD::FMAX";
7791 case X86ISD::FMIN: return "X86ISD::FMIN";
7792 case X86ISD::FRSQRT: return "X86ISD::FRSQRT";
7793 case X86ISD::FRCP: return "X86ISD::FRCP";
7794 case X86ISD::TLSADDR: return "X86ISD::TLSADDR";
7795 case X86ISD::TLSCALL: return "X86ISD::TLSCALL";
7796 case X86ISD::SegmentBaseAddress: return "X86ISD::SegmentBaseAddress";
7797 case X86ISD::EH_RETURN: return "X86ISD::EH_RETURN";
7798 case X86ISD::TC_RETURN: return "X86ISD::TC_RETURN";
7799 case X86ISD::FNSTCW16m: return "X86ISD::FNSTCW16m";
7800 case X86ISD::LCMPXCHG_DAG: return "X86ISD::LCMPXCHG_DAG";
7801 case X86ISD::LCMPXCHG8_DAG: return "X86ISD::LCMPXCHG8_DAG";
7802 case X86ISD::ATOMADD64_DAG: return "X86ISD::ATOMADD64_DAG";
7803 case X86ISD::ATOMSUB64_DAG: return "X86ISD::ATOMSUB64_DAG";
7804 case X86ISD::ATOMOR64_DAG: return "X86ISD::ATOMOR64_DAG";
7805 case X86ISD::ATOMXOR64_DAG: return "X86ISD::ATOMXOR64_DAG";
7806 case X86ISD::ATOMAND64_DAG: return "X86ISD::ATOMAND64_DAG";
7807 case X86ISD::ATOMNAND64_DAG: return "X86ISD::ATOMNAND64_DAG";
7808 case X86ISD::VZEXT_MOVL: return "X86ISD::VZEXT_MOVL";
7809 case X86ISD::VZEXT_LOAD: return "X86ISD::VZEXT_LOAD";
7810 case X86ISD::VSHL: return "X86ISD::VSHL";
7811 case X86ISD::VSRL: return "X86ISD::VSRL";
7812 case X86ISD::CMPPD: return "X86ISD::CMPPD";
7813 case X86ISD::CMPPS: return "X86ISD::CMPPS";
7814 case X86ISD::PCMPEQB: return "X86ISD::PCMPEQB";
7815 case X86ISD::PCMPEQW: return "X86ISD::PCMPEQW";
7816 case X86ISD::PCMPEQD: return "X86ISD::PCMPEQD";
7817 case X86ISD::PCMPEQQ: return "X86ISD::PCMPEQQ";
7818 case X86ISD::PCMPGTB: return "X86ISD::PCMPGTB";
7819 case X86ISD::PCMPGTW: return "X86ISD::PCMPGTW";
7820 case X86ISD::PCMPGTD: return "X86ISD::PCMPGTD";
7821 case X86ISD::PCMPGTQ: return "X86ISD::PCMPGTQ";
7822 case X86ISD::ADD: return "X86ISD::ADD";
7823 case X86ISD::SUB: return "X86ISD::SUB";
7824 case X86ISD::SMUL: return "X86ISD::SMUL";
7825 case X86ISD::UMUL: return "X86ISD::UMUL";
7826 case X86ISD::INC: return "X86ISD::INC";
7827 case X86ISD::DEC: return "X86ISD::DEC";
7828 case X86ISD::OR: return "X86ISD::OR";
7829 case X86ISD::XOR: return "X86ISD::XOR";
7830 case X86ISD::AND: return "X86ISD::AND";
7831 case X86ISD::MUL_IMM: return "X86ISD::MUL_IMM";
7832 case X86ISD::PTEST: return "X86ISD::PTEST";
7833 case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
7834 case X86ISD::MINGW_ALLOCA: return "X86ISD::MINGW_ALLOCA";
7838 // isLegalAddressingMode - Return true if the addressing mode represented
7839 // by AM is legal for this target, for a load/store of the specified type.
7840 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
7841 const Type *Ty) const {
7842 // X86 supports extremely general addressing modes.
7843 CodeModel::Model M = getTargetMachine().getCodeModel();
7845 // X86 allows a sign-extended 32-bit immediate field as a displacement.
7846 if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != NULL))
7851 Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
7853 // If a reference to this global requires an extra load, we can't fold it.
7854 if (isGlobalStubReference(GVFlags))
7857 // If BaseGV requires a register for the PIC base, we cannot also have a
7858 // BaseReg specified.
7859 if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
7862 // If lower 4G is not available, then we must use rip-relative addressing.
7863 if (Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
7873 // These scales always work.
7878 // These scales are formed with basereg+scalereg. Only accept if there is
7883 default: // Other stuff never works.
7891 bool X86TargetLowering::isTruncateFree(const Type *Ty1, const Type *Ty2) const {
7892 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7894 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7895 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7896 if (NumBits1 <= NumBits2)
7901 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7902 if (!VT1.isInteger() || !VT2.isInteger())
7904 unsigned NumBits1 = VT1.getSizeInBits();
7905 unsigned NumBits2 = VT2.getSizeInBits();
7906 if (NumBits1 <= NumBits2)
7911 bool X86TargetLowering::isZExtFree(const Type *Ty1, const Type *Ty2) const {
7912 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7913 return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
7916 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7917 // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
7918 return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
7921 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
7922 // i16 instructions are longer (0x66 prefix) and potentially slower.
7923 return !(VT1 == MVT::i32 && VT2 == MVT::i16);
7926 /// isShuffleMaskLegal - Targets can use this to indicate that they only
7927 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
7928 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
7929 /// are assumed to be legal.
7931 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
7933 // Very little shuffling can be done for 64-bit vectors right now.
7934 if (VT.getSizeInBits() == 64)
7935 return isPALIGNRMask(M, VT, Subtarget->hasSSSE3());
7937 // FIXME: pshufb, blends, shifts.
7938 return (VT.getVectorNumElements() == 2 ||
7939 ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
7940 isMOVLMask(M, VT) ||
7941 isSHUFPMask(M, VT) ||
7942 isPSHUFDMask(M, VT) ||
7943 isPSHUFHWMask(M, VT) ||
7944 isPSHUFLWMask(M, VT) ||
7945 isPALIGNRMask(M, VT, Subtarget->hasSSSE3()) ||
7946 isUNPCKLMask(M, VT) ||
7947 isUNPCKHMask(M, VT) ||
7948 isUNPCKL_v_undef_Mask(M, VT) ||
7949 isUNPCKH_v_undef_Mask(M, VT));
7953 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
7955 unsigned NumElts = VT.getVectorNumElements();
7956 // FIXME: This collection of masks seems suspect.
7959 if (NumElts == 4 && VT.getSizeInBits() == 128) {
7960 return (isMOVLMask(Mask, VT) ||
7961 isCommutedMOVLMask(Mask, VT, true) ||
7962 isSHUFPMask(Mask, VT) ||
7963 isCommutedSHUFPMask(Mask, VT));
7968 //===----------------------------------------------------------------------===//
7969 // X86 Scheduler Hooks
7970 //===----------------------------------------------------------------------===//
7972 // private utility function
7974 X86TargetLowering::EmitAtomicBitwiseWithCustomInserter(MachineInstr *bInstr,
7975 MachineBasicBlock *MBB,
7983 TargetRegisterClass *RC,
7984 bool invSrc) const {
7985 // For the atomic bitwise operator, we generate
7988 // ld t1 = [bitinstr.addr]
7989 // op t2 = t1, [bitinstr.val]
7991 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
7993 // fallthrough -->nextMBB
7994 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
7995 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
7996 MachineFunction::iterator MBBIter = MBB;
7999 /// First build the CFG
8000 MachineFunction *F = MBB->getParent();
8001 MachineBasicBlock *thisMBB = MBB;
8002 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8003 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8004 F->insert(MBBIter, newMBB);
8005 F->insert(MBBIter, nextMBB);
8007 // Move all successors to thisMBB to nextMBB
8008 nextMBB->transferSuccessors(thisMBB);
8010 // Update thisMBB to fall through to newMBB
8011 thisMBB->addSuccessor(newMBB);
8013 // newMBB jumps to itself and fall through to nextMBB
8014 newMBB->addSuccessor(nextMBB);
8015 newMBB->addSuccessor(newMBB);
8017 // Insert instructions into newMBB based on incoming instruction
8018 assert(bInstr->getNumOperands() < X86AddrNumOperands + 4 &&
8019 "unexpected number of operands");
8020 DebugLoc dl = bInstr->getDebugLoc();
8021 MachineOperand& destOper = bInstr->getOperand(0);
8022 MachineOperand* argOpers[2 + X86AddrNumOperands];
8023 int numArgs = bInstr->getNumOperands() - 1;
8024 for (int i=0; i < numArgs; ++i)
8025 argOpers[i] = &bInstr->getOperand(i+1);
8027 // x86 address has 4 operands: base, index, scale, and displacement
8028 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8029 int valArgIndx = lastAddrIndx + 1;
8031 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
8032 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(LoadOpc), t1);
8033 for (int i=0; i <= lastAddrIndx; ++i)
8034 (*MIB).addOperand(*argOpers[i]);
8036 unsigned tt = F->getRegInfo().createVirtualRegister(RC);
8038 MIB = BuildMI(newMBB, dl, TII->get(notOpc), tt).addReg(t1);
8043 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8044 assert((argOpers[valArgIndx]->isReg() ||
8045 argOpers[valArgIndx]->isImm()) &&
8047 if (argOpers[valArgIndx]->isReg())
8048 MIB = BuildMI(newMBB, dl, TII->get(regOpc), t2);
8050 MIB = BuildMI(newMBB, dl, TII->get(immOpc), t2);
8052 (*MIB).addOperand(*argOpers[valArgIndx]);
8054 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), EAXreg);
8057 MIB = BuildMI(newMBB, dl, TII->get(CXchgOpc));
8058 for (int i=0; i <= lastAddrIndx; ++i)
8059 (*MIB).addOperand(*argOpers[i]);
8061 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8062 (*MIB).setMemRefs(bInstr->memoperands_begin(),
8063 bInstr->memoperands_end());
8065 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), destOper.getReg());
8069 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8071 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
8075 // private utility function: 64 bit atomics on 32 bit host.
8077 X86TargetLowering::EmitAtomicBit6432WithCustomInserter(MachineInstr *bInstr,
8078 MachineBasicBlock *MBB,
8083 bool invSrc) const {
8084 // For the atomic bitwise operator, we generate
8085 // thisMBB (instructions are in pairs, except cmpxchg8b)
8086 // ld t1,t2 = [bitinstr.addr]
8088 // out1, out2 = phi (thisMBB, t1/t2) (newMBB, t3/t4)
8089 // op t5, t6 <- out1, out2, [bitinstr.val]
8090 // (for SWAP, substitute: mov t5, t6 <- [bitinstr.val])
8091 // mov ECX, EBX <- t5, t6
8092 // mov EAX, EDX <- t1, t2
8093 // cmpxchg8b [bitinstr.addr] [EAX, EDX, EBX, ECX implicit]
8094 // mov t3, t4 <- EAX, EDX
8096 // result in out1, out2
8097 // fallthrough -->nextMBB
8099 const TargetRegisterClass *RC = X86::GR32RegisterClass;
8100 const unsigned LoadOpc = X86::MOV32rm;
8101 const unsigned copyOpc = X86::MOV32rr;
8102 const unsigned NotOpc = X86::NOT32r;
8103 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8104 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8105 MachineFunction::iterator MBBIter = MBB;
8108 /// First build the CFG
8109 MachineFunction *F = MBB->getParent();
8110 MachineBasicBlock *thisMBB = MBB;
8111 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8112 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8113 F->insert(MBBIter, newMBB);
8114 F->insert(MBBIter, nextMBB);
8116 // Move all successors to thisMBB to nextMBB
8117 nextMBB->transferSuccessors(thisMBB);
8119 // Update thisMBB to fall through to newMBB
8120 thisMBB->addSuccessor(newMBB);
8122 // newMBB jumps to itself and fall through to nextMBB
8123 newMBB->addSuccessor(nextMBB);
8124 newMBB->addSuccessor(newMBB);
8126 DebugLoc dl = bInstr->getDebugLoc();
8127 // Insert instructions into newMBB based on incoming instruction
8128 // There are 8 "real" operands plus 9 implicit def/uses, ignored here.
8129 assert(bInstr->getNumOperands() < X86AddrNumOperands + 14 &&
8130 "unexpected number of operands");
8131 MachineOperand& dest1Oper = bInstr->getOperand(0);
8132 MachineOperand& dest2Oper = bInstr->getOperand(1);
8133 MachineOperand* argOpers[2 + X86AddrNumOperands];
8134 for (int i=0; i < 2 + X86AddrNumOperands; ++i) {
8135 argOpers[i] = &bInstr->getOperand(i+2);
8137 // We use some of the operands multiple times, so conservatively just
8138 // clear any kill flags that might be present.
8139 if (argOpers[i]->isReg() && argOpers[i]->isUse())
8140 argOpers[i]->setIsKill(false);
8143 // x86 address has 5 operands: base, index, scale, displacement, and segment.
8144 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8146 unsigned t1 = F->getRegInfo().createVirtualRegister(RC);
8147 MachineInstrBuilder MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t1);
8148 for (int i=0; i <= lastAddrIndx; ++i)
8149 (*MIB).addOperand(*argOpers[i]);
8150 unsigned t2 = F->getRegInfo().createVirtualRegister(RC);
8151 MIB = BuildMI(thisMBB, dl, TII->get(LoadOpc), t2);
8152 // add 4 to displacement.
8153 for (int i=0; i <= lastAddrIndx-2; ++i)
8154 (*MIB).addOperand(*argOpers[i]);
8155 MachineOperand newOp3 = *(argOpers[3]);
8157 newOp3.setImm(newOp3.getImm()+4);
8159 newOp3.setOffset(newOp3.getOffset()+4);
8160 (*MIB).addOperand(newOp3);
8161 (*MIB).addOperand(*argOpers[lastAddrIndx]);
8163 // t3/4 are defined later, at the bottom of the loop
8164 unsigned t3 = F->getRegInfo().createVirtualRegister(RC);
8165 unsigned t4 = F->getRegInfo().createVirtualRegister(RC);
8166 BuildMI(newMBB, dl, TII->get(X86::PHI), dest1Oper.getReg())
8167 .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(newMBB);
8168 BuildMI(newMBB, dl, TII->get(X86::PHI), dest2Oper.getReg())
8169 .addReg(t2).addMBB(thisMBB).addReg(t4).addMBB(newMBB);
8171 // The subsequent operations should be using the destination registers of
8172 //the PHI instructions.
8174 t1 = F->getRegInfo().createVirtualRegister(RC);
8175 t2 = F->getRegInfo().createVirtualRegister(RC);
8176 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t1).addReg(dest1Oper.getReg());
8177 MIB = BuildMI(newMBB, dl, TII->get(NotOpc), t2).addReg(dest2Oper.getReg());
8179 t1 = dest1Oper.getReg();
8180 t2 = dest2Oper.getReg();
8183 int valArgIndx = lastAddrIndx + 1;
8184 assert((argOpers[valArgIndx]->isReg() ||
8185 argOpers[valArgIndx]->isImm()) &&
8187 unsigned t5 = F->getRegInfo().createVirtualRegister(RC);
8188 unsigned t6 = F->getRegInfo().createVirtualRegister(RC);
8189 if (argOpers[valArgIndx]->isReg())
8190 MIB = BuildMI(newMBB, dl, TII->get(regOpcL), t5);
8192 MIB = BuildMI(newMBB, dl, TII->get(immOpcL), t5);
8193 if (regOpcL != X86::MOV32rr)
8195 (*MIB).addOperand(*argOpers[valArgIndx]);
8196 assert(argOpers[valArgIndx + 1]->isReg() ==
8197 argOpers[valArgIndx]->isReg());
8198 assert(argOpers[valArgIndx + 1]->isImm() ==
8199 argOpers[valArgIndx]->isImm());
8200 if (argOpers[valArgIndx + 1]->isReg())
8201 MIB = BuildMI(newMBB, dl, TII->get(regOpcH), t6);
8203 MIB = BuildMI(newMBB, dl, TII->get(immOpcH), t6);
8204 if (regOpcH != X86::MOV32rr)
8206 (*MIB).addOperand(*argOpers[valArgIndx + 1]);
8208 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EAX);
8210 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EDX);
8213 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::EBX);
8215 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), X86::ECX);
8218 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG8B));
8219 for (int i=0; i <= lastAddrIndx; ++i)
8220 (*MIB).addOperand(*argOpers[i]);
8222 assert(bInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8223 (*MIB).setMemRefs(bInstr->memoperands_begin(),
8224 bInstr->memoperands_end());
8226 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t3);
8227 MIB.addReg(X86::EAX);
8228 MIB = BuildMI(newMBB, dl, TII->get(copyOpc), t4);
8229 MIB.addReg(X86::EDX);
8232 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8234 F->DeleteMachineInstr(bInstr); // The pseudo instruction is gone now.
8238 // private utility function
8240 X86TargetLowering::EmitAtomicMinMaxWithCustomInserter(MachineInstr *mInstr,
8241 MachineBasicBlock *MBB,
8242 unsigned cmovOpc) const {
8243 // For the atomic min/max operator, we generate
8246 // ld t1 = [min/max.addr]
8247 // mov t2 = [min/max.val]
8249 // cmov[cond] t2 = t1
8251 // lcs dest = [bitinstr.addr], t2 [EAX is implicit]
8253 // fallthrough -->nextMBB
8255 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8256 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8257 MachineFunction::iterator MBBIter = MBB;
8260 /// First build the CFG
8261 MachineFunction *F = MBB->getParent();
8262 MachineBasicBlock *thisMBB = MBB;
8263 MachineBasicBlock *newMBB = F->CreateMachineBasicBlock(LLVM_BB);
8264 MachineBasicBlock *nextMBB = F->CreateMachineBasicBlock(LLVM_BB);
8265 F->insert(MBBIter, newMBB);
8266 F->insert(MBBIter, nextMBB);
8268 // Move all successors of thisMBB to nextMBB
8269 nextMBB->transferSuccessors(thisMBB);
8271 // Update thisMBB to fall through to newMBB
8272 thisMBB->addSuccessor(newMBB);
8274 // newMBB jumps to newMBB and fall through to nextMBB
8275 newMBB->addSuccessor(nextMBB);
8276 newMBB->addSuccessor(newMBB);
8278 DebugLoc dl = mInstr->getDebugLoc();
8279 // Insert instructions into newMBB based on incoming instruction
8280 assert(mInstr->getNumOperands() < X86AddrNumOperands + 4 &&
8281 "unexpected number of operands");
8282 MachineOperand& destOper = mInstr->getOperand(0);
8283 MachineOperand* argOpers[2 + X86AddrNumOperands];
8284 int numArgs = mInstr->getNumOperands() - 1;
8285 for (int i=0; i < numArgs; ++i)
8286 argOpers[i] = &mInstr->getOperand(i+1);
8288 // x86 address has 4 operands: base, index, scale, and displacement
8289 int lastAddrIndx = X86AddrNumOperands - 1; // [0,3]
8290 int valArgIndx = lastAddrIndx + 1;
8292 unsigned t1 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8293 MachineInstrBuilder MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rm), t1);
8294 for (int i=0; i <= lastAddrIndx; ++i)
8295 (*MIB).addOperand(*argOpers[i]);
8297 // We only support register and immediate values
8298 assert((argOpers[valArgIndx]->isReg() ||
8299 argOpers[valArgIndx]->isImm()) &&
8302 unsigned t2 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8303 if (argOpers[valArgIndx]->isReg())
8304 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8306 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), t2);
8307 (*MIB).addOperand(*argOpers[valArgIndx]);
8309 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), X86::EAX);
8312 MIB = BuildMI(newMBB, dl, TII->get(X86::CMP32rr));
8317 unsigned t3 = F->getRegInfo().createVirtualRegister(X86::GR32RegisterClass);
8318 MIB = BuildMI(newMBB, dl, TII->get(cmovOpc),t3);
8322 // Cmp and exchange if none has modified the memory location
8323 MIB = BuildMI(newMBB, dl, TII->get(X86::LCMPXCHG32));
8324 for (int i=0; i <= lastAddrIndx; ++i)
8325 (*MIB).addOperand(*argOpers[i]);
8327 assert(mInstr->hasOneMemOperand() && "Unexpected number of memoperand");
8328 (*MIB).setMemRefs(mInstr->memoperands_begin(),
8329 mInstr->memoperands_end());
8331 MIB = BuildMI(newMBB, dl, TII->get(X86::MOV32rr), destOper.getReg());
8332 MIB.addReg(X86::EAX);
8335 BuildMI(newMBB, dl, TII->get(X86::JNE_4)).addMBB(newMBB);
8337 F->DeleteMachineInstr(mInstr); // The pseudo instruction is gone now.
8341 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
8342 // all of this code can be replaced with that in the .td file.
8344 X86TargetLowering::EmitPCMP(MachineInstr *MI, MachineBasicBlock *BB,
8345 unsigned numArgs, bool memArg) const {
8347 MachineFunction *F = BB->getParent();
8348 DebugLoc dl = MI->getDebugLoc();
8349 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8353 Opc = numArgs == 3 ? X86::PCMPISTRM128rm : X86::PCMPESTRM128rm;
8355 Opc = numArgs == 3 ? X86::PCMPISTRM128rr : X86::PCMPESTRM128rr;
8357 MachineInstrBuilder MIB = BuildMI(BB, dl, TII->get(Opc));
8359 for (unsigned i = 0; i < numArgs; ++i) {
8360 MachineOperand &Op = MI->getOperand(i+1);
8362 if (!(Op.isReg() && Op.isImplicit()))
8366 BuildMI(BB, dl, TII->get(X86::MOVAPSrr), MI->getOperand(0).getReg())
8369 F->DeleteMachineInstr(MI);
8375 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
8377 MachineBasicBlock *MBB) const {
8378 // Emit code to save XMM registers to the stack. The ABI says that the
8379 // number of registers to save is given in %al, so it's theoretically
8380 // possible to do an indirect jump trick to avoid saving all of them,
8381 // however this code takes a simpler approach and just executes all
8382 // of the stores if %al is non-zero. It's less code, and it's probably
8383 // easier on the hardware branch predictor, and stores aren't all that
8384 // expensive anyway.
8386 // Create the new basic blocks. One block contains all the XMM stores,
8387 // and one block is the final destination regardless of whether any
8388 // stores were performed.
8389 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
8390 MachineFunction *F = MBB->getParent();
8391 MachineFunction::iterator MBBIter = MBB;
8393 MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
8394 MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
8395 F->insert(MBBIter, XMMSaveMBB);
8396 F->insert(MBBIter, EndMBB);
8399 // Move any original successors of MBB to the end block.
8400 EndMBB->transferSuccessors(MBB);
8401 // The original block will now fall through to the XMM save block.
8402 MBB->addSuccessor(XMMSaveMBB);
8403 // The XMMSaveMBB will fall through to the end block.
8404 XMMSaveMBB->addSuccessor(EndMBB);
8406 // Now add the instructions.
8407 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8408 DebugLoc DL = MI->getDebugLoc();
8410 unsigned CountReg = MI->getOperand(0).getReg();
8411 int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
8412 int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
8414 if (!Subtarget->isTargetWin64()) {
8415 // If %al is 0, branch around the XMM save block.
8416 BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
8417 BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
8418 MBB->addSuccessor(EndMBB);
8421 // In the XMM save block, save all the XMM argument registers.
8422 for (int i = 3, e = MI->getNumOperands(); i != e; ++i) {
8423 int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
8424 MachineMemOperand *MMO =
8425 F->getMachineMemOperand(
8426 PseudoSourceValue::getFixedStack(RegSaveFrameIndex),
8427 MachineMemOperand::MOStore, Offset,
8428 /*Size=*/16, /*Align=*/16);
8429 BuildMI(XMMSaveMBB, DL, TII->get(X86::MOVAPSmr))
8430 .addFrameIndex(RegSaveFrameIndex)
8431 .addImm(/*Scale=*/1)
8432 .addReg(/*IndexReg=*/0)
8433 .addImm(/*Disp=*/Offset)
8434 .addReg(/*Segment=*/0)
8435 .addReg(MI->getOperand(i).getReg())
8436 .addMemOperand(MMO);
8439 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8445 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
8446 MachineBasicBlock *BB) const {
8447 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8448 DebugLoc DL = MI->getDebugLoc();
8450 // To "insert" a SELECT_CC instruction, we actually have to insert the
8451 // diamond control-flow pattern. The incoming instruction knows the
8452 // destination vreg to set, the condition code register to branch on, the
8453 // true/false values to select between, and a branch opcode to use.
8454 const BasicBlock *LLVM_BB = BB->getBasicBlock();
8455 MachineFunction::iterator It = BB;
8461 // cmpTY ccX, r1, r2
8463 // fallthrough --> copy0MBB
8464 MachineBasicBlock *thisMBB = BB;
8465 MachineFunction *F = BB->getParent();
8466 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8467 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
8469 X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
8471 BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
8472 F->insert(It, copy0MBB);
8473 F->insert(It, sinkMBB);
8475 // Update machine-CFG edges by first adding all successors of the current
8476 // block to the new block which will contain the Phi node for the select.
8477 for (MachineBasicBlock::succ_iterator I = BB->succ_begin(),
8478 E = BB->succ_end(); I != E; ++I)
8479 sinkMBB->addSuccessor(*I);
8481 // Next, remove all successors of the current block, and add the true
8482 // and fallthrough blocks as its successors.
8483 while (!BB->succ_empty())
8484 BB->removeSuccessor(BB->succ_begin());
8486 // Add the true and fallthrough blocks as its successors.
8487 BB->addSuccessor(copy0MBB);
8488 BB->addSuccessor(sinkMBB);
8490 // If the EFLAGS register isn't dead in the terminator, then claim that it's
8491 // live into the sink and copy blocks.
8492 const MachineFunction *MF = BB->getParent();
8493 const TargetRegisterInfo *TRI = MF->getTarget().getRegisterInfo();
8494 BitVector ReservedRegs = TRI->getReservedRegs(*MF);
8495 const MachineInstr *Term = BB->getFirstTerminator();
8497 for (unsigned I = 0, E = Term->getNumOperands(); I != E; ++I) {
8498 const MachineOperand &MO = Term->getOperand(I);
8499 if (!MO.isReg() || MO.isKill() || MO.isDead()) continue;
8500 unsigned Reg = MO.getReg();
8501 if (Reg != X86::EFLAGS) continue;
8502 copy0MBB->addLiveIn(Reg);
8503 sinkMBB->addLiveIn(Reg);
8507 // %FalseValue = ...
8508 // # fallthrough to sinkMBB
8509 copy0MBB->addSuccessor(sinkMBB);
8512 // %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8514 BuildMI(sinkMBB, DL, TII->get(X86::PHI), MI->getOperand(0).getReg())
8515 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
8516 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
8518 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8523 X86TargetLowering::EmitLoweredMingwAlloca(MachineInstr *MI,
8524 MachineBasicBlock *BB) const {
8525 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8526 DebugLoc DL = MI->getDebugLoc();
8527 MachineFunction *F = BB->getParent();
8529 // The lowering is pretty easy: we're just emitting the call to _alloca. The
8530 // non-trivial part is impdef of ESP.
8531 // FIXME: The code should be tweaked as soon as we'll try to do codegen for
8534 BuildMI(BB, DL, TII->get(X86::CALLpcrel32))
8535 .addExternalSymbol("_alloca")
8536 .addReg(X86::EAX, RegState::Implicit)
8537 .addReg(X86::ESP, RegState::Implicit)
8538 .addReg(X86::EAX, RegState::Define | RegState::Implicit)
8539 .addReg(X86::ESP, RegState::Define | RegState::Implicit);
8541 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8546 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
8547 MachineBasicBlock *BB) const {
8548 // This is pretty easy. We're taking the value that we received from
8549 // our load from the relocation, sticking it in either RDI (x86-64)
8550 // or EAX and doing an indirect call. The return value will then
8551 // be in the normal return register.
8552 const X86InstrInfo *TII
8553 = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
8554 DebugLoc DL = MI->getDebugLoc();
8555 MachineFunction *F = BB->getParent();
8557 assert(MI->getOperand(3).isGlobal() && "This should be a global");
8559 if (Subtarget->is64Bit()) {
8560 MachineInstrBuilder MIB = BuildMI(BB, DL, TII->get(X86::MOV64rm), X86::RDI)
8562 .addImm(0).addReg(0)
8563 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
8564 MI->getOperand(3).getTargetFlags())
8566 MIB = BuildMI(BB, DL, TII->get(X86::CALL64m));
8567 addDirectMem(MIB, X86::RDI).addReg(0);
8568 } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
8569 MachineInstrBuilder MIB = BuildMI(BB, DL, TII->get(X86::MOV32rm), X86::EAX)
8571 .addImm(0).addReg(0)
8572 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
8573 MI->getOperand(3).getTargetFlags())
8575 MIB = BuildMI(BB, DL, TII->get(X86::CALL32m));
8576 addDirectMem(MIB, X86::EAX).addReg(0);
8578 MachineInstrBuilder MIB = BuildMI(BB, DL, TII->get(X86::MOV32rm), X86::EAX)
8579 .addReg(TII->getGlobalBaseReg(F))
8580 .addImm(0).addReg(0)
8581 .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
8582 MI->getOperand(3).getTargetFlags())
8584 MIB = BuildMI(BB, DL, TII->get(X86::CALL32m));
8585 addDirectMem(MIB, X86::EAX).addReg(0);
8588 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8593 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
8594 MachineBasicBlock *BB) const {
8595 switch (MI->getOpcode()) {
8596 default: assert(false && "Unexpected instr type to insert");
8597 case X86::MINGW_ALLOCA:
8598 return EmitLoweredMingwAlloca(MI, BB);
8599 case X86::TLSCall_32:
8600 case X86::TLSCall_64:
8601 return EmitLoweredTLSCall(MI, BB);
8603 case X86::CMOV_V1I64:
8604 case X86::CMOV_FR32:
8605 case X86::CMOV_FR64:
8606 case X86::CMOV_V4F32:
8607 case X86::CMOV_V2F64:
8608 case X86::CMOV_V2I64:
8609 case X86::CMOV_GR16:
8610 case X86::CMOV_GR32:
8611 case X86::CMOV_RFP32:
8612 case X86::CMOV_RFP64:
8613 case X86::CMOV_RFP80:
8614 return EmitLoweredSelect(MI, BB);
8616 case X86::FP32_TO_INT16_IN_MEM:
8617 case X86::FP32_TO_INT32_IN_MEM:
8618 case X86::FP32_TO_INT64_IN_MEM:
8619 case X86::FP64_TO_INT16_IN_MEM:
8620 case X86::FP64_TO_INT32_IN_MEM:
8621 case X86::FP64_TO_INT64_IN_MEM:
8622 case X86::FP80_TO_INT16_IN_MEM:
8623 case X86::FP80_TO_INT32_IN_MEM:
8624 case X86::FP80_TO_INT64_IN_MEM: {
8625 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
8626 DebugLoc DL = MI->getDebugLoc();
8628 // Change the floating point control register to use "round towards zero"
8629 // mode when truncating to an integer value.
8630 MachineFunction *F = BB->getParent();
8631 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
8632 addFrameReference(BuildMI(BB, DL, TII->get(X86::FNSTCW16m)), CWFrameIdx);
8634 // Load the old value of the high byte of the control word...
8636 F->getRegInfo().createVirtualRegister(X86::GR16RegisterClass);
8637 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16rm), OldCW),
8640 // Set the high part to be round to zero...
8641 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
8644 // Reload the modified control word now...
8645 addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8647 // Restore the memory image of control word to original value
8648 addFrameReference(BuildMI(BB, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
8651 // Get the X86 opcode to use.
8653 switch (MI->getOpcode()) {
8654 default: llvm_unreachable("illegal opcode!");
8655 case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
8656 case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
8657 case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
8658 case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
8659 case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
8660 case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
8661 case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
8662 case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
8663 case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
8667 MachineOperand &Op = MI->getOperand(0);
8669 AM.BaseType = X86AddressMode::RegBase;
8670 AM.Base.Reg = Op.getReg();
8672 AM.BaseType = X86AddressMode::FrameIndexBase;
8673 AM.Base.FrameIndex = Op.getIndex();
8675 Op = MI->getOperand(1);
8677 AM.Scale = Op.getImm();
8678 Op = MI->getOperand(2);
8680 AM.IndexReg = Op.getImm();
8681 Op = MI->getOperand(3);
8682 if (Op.isGlobal()) {
8683 AM.GV = Op.getGlobal();
8685 AM.Disp = Op.getImm();
8687 addFullAddress(BuildMI(BB, DL, TII->get(Opc)), AM)
8688 .addReg(MI->getOperand(X86AddrNumOperands).getReg());
8690 // Reload the original control word now.
8691 addFrameReference(BuildMI(BB, DL, TII->get(X86::FLDCW16m)), CWFrameIdx);
8693 F->DeleteMachineInstr(MI); // The pseudo instruction is gone now.
8696 // String/text processing lowering.
8697 case X86::PCMPISTRM128REG:
8698 return EmitPCMP(MI, BB, 3, false /* in-mem */);
8699 case X86::PCMPISTRM128MEM:
8700 return EmitPCMP(MI, BB, 3, true /* in-mem */);
8701 case X86::PCMPESTRM128REG:
8702 return EmitPCMP(MI, BB, 5, false /* in mem */);
8703 case X86::PCMPESTRM128MEM:
8704 return EmitPCMP(MI, BB, 5, true /* in mem */);
8707 case X86::ATOMAND32:
8708 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8709 X86::AND32ri, X86::MOV32rm,
8710 X86::LCMPXCHG32, X86::MOV32rr,
8711 X86::NOT32r, X86::EAX,
8712 X86::GR32RegisterClass);
8714 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR32rr,
8715 X86::OR32ri, X86::MOV32rm,
8716 X86::LCMPXCHG32, X86::MOV32rr,
8717 X86::NOT32r, X86::EAX,
8718 X86::GR32RegisterClass);
8719 case X86::ATOMXOR32:
8720 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR32rr,
8721 X86::XOR32ri, X86::MOV32rm,
8722 X86::LCMPXCHG32, X86::MOV32rr,
8723 X86::NOT32r, X86::EAX,
8724 X86::GR32RegisterClass);
8725 case X86::ATOMNAND32:
8726 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND32rr,
8727 X86::AND32ri, X86::MOV32rm,
8728 X86::LCMPXCHG32, X86::MOV32rr,
8729 X86::NOT32r, X86::EAX,
8730 X86::GR32RegisterClass, true);
8731 case X86::ATOMMIN32:
8732 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL32rr);
8733 case X86::ATOMMAX32:
8734 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG32rr);
8735 case X86::ATOMUMIN32:
8736 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB32rr);
8737 case X86::ATOMUMAX32:
8738 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA32rr);
8740 case X86::ATOMAND16:
8741 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8742 X86::AND16ri, X86::MOV16rm,
8743 X86::LCMPXCHG16, X86::MOV16rr,
8744 X86::NOT16r, X86::AX,
8745 X86::GR16RegisterClass);
8747 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR16rr,
8748 X86::OR16ri, X86::MOV16rm,
8749 X86::LCMPXCHG16, X86::MOV16rr,
8750 X86::NOT16r, X86::AX,
8751 X86::GR16RegisterClass);
8752 case X86::ATOMXOR16:
8753 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR16rr,
8754 X86::XOR16ri, X86::MOV16rm,
8755 X86::LCMPXCHG16, X86::MOV16rr,
8756 X86::NOT16r, X86::AX,
8757 X86::GR16RegisterClass);
8758 case X86::ATOMNAND16:
8759 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND16rr,
8760 X86::AND16ri, X86::MOV16rm,
8761 X86::LCMPXCHG16, X86::MOV16rr,
8762 X86::NOT16r, X86::AX,
8763 X86::GR16RegisterClass, true);
8764 case X86::ATOMMIN16:
8765 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL16rr);
8766 case X86::ATOMMAX16:
8767 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG16rr);
8768 case X86::ATOMUMIN16:
8769 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB16rr);
8770 case X86::ATOMUMAX16:
8771 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA16rr);
8774 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8775 X86::AND8ri, X86::MOV8rm,
8776 X86::LCMPXCHG8, X86::MOV8rr,
8777 X86::NOT8r, X86::AL,
8778 X86::GR8RegisterClass);
8780 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR8rr,
8781 X86::OR8ri, X86::MOV8rm,
8782 X86::LCMPXCHG8, X86::MOV8rr,
8783 X86::NOT8r, X86::AL,
8784 X86::GR8RegisterClass);
8786 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR8rr,
8787 X86::XOR8ri, X86::MOV8rm,
8788 X86::LCMPXCHG8, X86::MOV8rr,
8789 X86::NOT8r, X86::AL,
8790 X86::GR8RegisterClass);
8791 case X86::ATOMNAND8:
8792 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND8rr,
8793 X86::AND8ri, X86::MOV8rm,
8794 X86::LCMPXCHG8, X86::MOV8rr,
8795 X86::NOT8r, X86::AL,
8796 X86::GR8RegisterClass, true);
8797 // FIXME: There are no CMOV8 instructions; MIN/MAX need some other way.
8798 // This group is for 64-bit host.
8799 case X86::ATOMAND64:
8800 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8801 X86::AND64ri32, X86::MOV64rm,
8802 X86::LCMPXCHG64, X86::MOV64rr,
8803 X86::NOT64r, X86::RAX,
8804 X86::GR64RegisterClass);
8806 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::OR64rr,
8807 X86::OR64ri32, X86::MOV64rm,
8808 X86::LCMPXCHG64, X86::MOV64rr,
8809 X86::NOT64r, X86::RAX,
8810 X86::GR64RegisterClass);
8811 case X86::ATOMXOR64:
8812 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::XOR64rr,
8813 X86::XOR64ri32, X86::MOV64rm,
8814 X86::LCMPXCHG64, X86::MOV64rr,
8815 X86::NOT64r, X86::RAX,
8816 X86::GR64RegisterClass);
8817 case X86::ATOMNAND64:
8818 return EmitAtomicBitwiseWithCustomInserter(MI, BB, X86::AND64rr,
8819 X86::AND64ri32, X86::MOV64rm,
8820 X86::LCMPXCHG64, X86::MOV64rr,
8821 X86::NOT64r, X86::RAX,
8822 X86::GR64RegisterClass, true);
8823 case X86::ATOMMIN64:
8824 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVL64rr);
8825 case X86::ATOMMAX64:
8826 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVG64rr);
8827 case X86::ATOMUMIN64:
8828 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVB64rr);
8829 case X86::ATOMUMAX64:
8830 return EmitAtomicMinMaxWithCustomInserter(MI, BB, X86::CMOVA64rr);
8832 // This group does 64-bit operations on a 32-bit host.
8833 case X86::ATOMAND6432:
8834 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8835 X86::AND32rr, X86::AND32rr,
8836 X86::AND32ri, X86::AND32ri,
8838 case X86::ATOMOR6432:
8839 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8840 X86::OR32rr, X86::OR32rr,
8841 X86::OR32ri, X86::OR32ri,
8843 case X86::ATOMXOR6432:
8844 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8845 X86::XOR32rr, X86::XOR32rr,
8846 X86::XOR32ri, X86::XOR32ri,
8848 case X86::ATOMNAND6432:
8849 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8850 X86::AND32rr, X86::AND32rr,
8851 X86::AND32ri, X86::AND32ri,
8853 case X86::ATOMADD6432:
8854 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8855 X86::ADD32rr, X86::ADC32rr,
8856 X86::ADD32ri, X86::ADC32ri,
8858 case X86::ATOMSUB6432:
8859 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8860 X86::SUB32rr, X86::SBB32rr,
8861 X86::SUB32ri, X86::SBB32ri,
8863 case X86::ATOMSWAP6432:
8864 return EmitAtomicBit6432WithCustomInserter(MI, BB,
8865 X86::MOV32rr, X86::MOV32rr,
8866 X86::MOV32ri, X86::MOV32ri,
8868 case X86::VASTART_SAVE_XMM_REGS:
8869 return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
8873 //===----------------------------------------------------------------------===//
8874 // X86 Optimization Hooks
8875 //===----------------------------------------------------------------------===//
8877 void X86TargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
8881 const SelectionDAG &DAG,
8882 unsigned Depth) const {
8883 unsigned Opc = Op.getOpcode();
8884 assert((Opc >= ISD::BUILTIN_OP_END ||
8885 Opc == ISD::INTRINSIC_WO_CHAIN ||
8886 Opc == ISD::INTRINSIC_W_CHAIN ||
8887 Opc == ISD::INTRINSIC_VOID) &&
8888 "Should use MaskedValueIsZero if you don't know whether Op"
8889 " is a target node!");
8891 KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0); // Don't know anything.
8903 // These nodes' second result is a boolean.
8904 if (Op.getResNo() == 0)
8908 KnownZero |= APInt::getHighBitsSet(Mask.getBitWidth(),
8909 Mask.getBitWidth() - 1);
8914 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
8915 /// node is a GlobalAddress + offset.
8916 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
8917 const GlobalValue* &GA,
8918 int64_t &Offset) const {
8919 if (N->getOpcode() == X86ISD::Wrapper) {
8920 if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
8921 GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
8922 Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
8926 return TargetLowering::isGAPlusOffset(N, GA, Offset);
8929 /// PerformShuffleCombine - Combine a vector_shuffle that is equal to
8930 /// build_vector load1, load2, load3, load4, <0, 1, 2, 3> into a 128-bit load
8931 /// if the load addresses are consecutive, non-overlapping, and in the right
8933 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
8934 const TargetLowering &TLI) {
8935 DebugLoc dl = N->getDebugLoc();
8936 EVT VT = N->getValueType(0);
8937 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
8939 if (VT.getSizeInBits() != 128)
8942 SmallVector<SDValue, 16> Elts;
8943 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
8944 Elts.push_back(DAG.getShuffleScalarElt(SVN, i));
8946 return EltsFromConsecutiveLoads(VT, Elts, dl, DAG);
8949 /// PerformShuffleCombine - Detect vector gather/scatter index generation
8950 /// and convert it from being a bunch of shuffles and extracts to a simple
8951 /// store and scalar loads to extract the elements.
8952 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
8953 const TargetLowering &TLI) {
8954 SDValue InputVector = N->getOperand(0);
8956 // Only operate on vectors of 4 elements, where the alternative shuffling
8957 // gets to be more expensive.
8958 if (InputVector.getValueType() != MVT::v4i32)
8961 // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
8962 // single use which is a sign-extend or zero-extend, and all elements are
8964 SmallVector<SDNode *, 4> Uses;
8965 unsigned ExtractedElements = 0;
8966 for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
8967 UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
8968 if (UI.getUse().getResNo() != InputVector.getResNo())
8971 SDNode *Extract = *UI;
8972 if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8975 if (Extract->getValueType(0) != MVT::i32)
8977 if (!Extract->hasOneUse())
8979 if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
8980 Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
8982 if (!isa<ConstantSDNode>(Extract->getOperand(1)))
8985 // Record which element was extracted.
8986 ExtractedElements |=
8987 1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
8989 Uses.push_back(Extract);
8992 // If not all the elements were used, this may not be worthwhile.
8993 if (ExtractedElements != 15)
8996 // Ok, we've now decided to do the transformation.
8997 DebugLoc dl = InputVector.getDebugLoc();
8999 // Store the value to a temporary stack slot.
9000 SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
9001 SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr, NULL, 0,
9004 // Replace each use (extract) with a load of the appropriate element.
9005 for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
9006 UE = Uses.end(); UI != UE; ++UI) {
9007 SDNode *Extract = *UI;
9009 // Compute the element's address.
9010 SDValue Idx = Extract->getOperand(1);
9012 InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
9013 uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
9014 SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
9016 SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), OffsetVal, StackPtr);
9019 SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch, ScalarAddr,
9020 NULL, 0, false, false, 0);
9022 // Replace the exact with the load.
9023 DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
9026 // The replacement was made in place; don't return anything.
9030 /// PerformSELECTCombine - Do target-specific dag combines on SELECT nodes.
9031 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
9032 const X86Subtarget *Subtarget) {
9033 DebugLoc DL = N->getDebugLoc();
9034 SDValue Cond = N->getOperand(0);
9035 // Get the LHS/RHS of the select.
9036 SDValue LHS = N->getOperand(1);
9037 SDValue RHS = N->getOperand(2);
9039 // If we have SSE[12] support, try to form min/max nodes. SSE min/max
9040 // instructions match the semantics of the common C idiom x<y?x:y but not
9041 // x<=y?x:y, because of how they handle negative zero (which can be
9042 // ignored in unsafe-math mode).
9043 if (Subtarget->hasSSE2() &&
9044 (LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64) &&
9045 Cond.getOpcode() == ISD::SETCC) {
9046 ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
9048 unsigned Opcode = 0;
9049 // Check for x CC y ? x : y.
9050 if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
9051 DAG.isEqualTo(RHS, Cond.getOperand(1))) {
9055 // Converting this to a min would handle NaNs incorrectly, and swapping
9056 // the operands would cause it to handle comparisons between positive
9057 // and negative zero incorrectly.
9058 if (!FiniteOnlyFPMath() &&
9059 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
9060 if (!UnsafeFPMath &&
9061 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9063 std::swap(LHS, RHS);
9065 Opcode = X86ISD::FMIN;
9068 // Converting this to a min would handle comparisons between positive
9069 // and negative zero incorrectly.
9070 if (!UnsafeFPMath &&
9071 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
9073 Opcode = X86ISD::FMIN;
9076 // Converting this to a min would handle both negative zeros and NaNs
9077 // incorrectly, but we can swap the operands to fix both.
9078 std::swap(LHS, RHS);
9082 Opcode = X86ISD::FMIN;
9086 // Converting this to a max would handle comparisons between positive
9087 // and negative zero incorrectly.
9088 if (!UnsafeFPMath &&
9089 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(LHS))
9091 Opcode = X86ISD::FMAX;
9094 // Converting this to a max would handle NaNs incorrectly, and swapping
9095 // the operands would cause it to handle comparisons between positive
9096 // and negative zero incorrectly.
9097 if (!FiniteOnlyFPMath() &&
9098 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))) {
9099 if (!UnsafeFPMath &&
9100 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9102 std::swap(LHS, RHS);
9104 Opcode = X86ISD::FMAX;
9107 // Converting this to a max would handle both negative zeros and NaNs
9108 // incorrectly, but we can swap the operands to fix both.
9109 std::swap(LHS, RHS);
9113 Opcode = X86ISD::FMAX;
9116 // Check for x CC y ? y : x -- a min/max with reversed arms.
9117 } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
9118 DAG.isEqualTo(RHS, Cond.getOperand(0))) {
9122 // Converting this to a min would handle comparisons between positive
9123 // and negative zero incorrectly, and swapping the operands would
9124 // cause it to handle NaNs incorrectly.
9125 if (!UnsafeFPMath &&
9126 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
9127 if (!FiniteOnlyFPMath() &&
9128 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9130 std::swap(LHS, RHS);
9132 Opcode = X86ISD::FMIN;
9135 // Converting this to a min would handle NaNs incorrectly.
9136 if (!UnsafeFPMath &&
9137 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9139 Opcode = X86ISD::FMIN;
9142 // Converting this to a min would handle both negative zeros and NaNs
9143 // incorrectly, but we can swap the operands to fix both.
9144 std::swap(LHS, RHS);
9148 Opcode = X86ISD::FMIN;
9152 // Converting this to a max would handle NaNs incorrectly.
9153 if (!FiniteOnlyFPMath() &&
9154 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9156 Opcode = X86ISD::FMAX;
9159 // Converting this to a max would handle comparisons between positive
9160 // and negative zero incorrectly, and swapping the operands would
9161 // cause it to handle NaNs incorrectly.
9162 if (!UnsafeFPMath &&
9163 !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
9164 if (!FiniteOnlyFPMath() &&
9165 (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
9167 std::swap(LHS, RHS);
9169 Opcode = X86ISD::FMAX;
9172 // Converting this to a max would handle both negative zeros and NaNs
9173 // incorrectly, but we can swap the operands to fix both.
9174 std::swap(LHS, RHS);
9178 Opcode = X86ISD::FMAX;
9184 return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
9187 // If this is a select between two integer constants, try to do some
9189 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
9190 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
9191 // Don't do this for crazy integer types.
9192 if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
9193 // If this is efficiently invertible, canonicalize the LHSC/RHSC values
9194 // so that TrueC (the true value) is larger than FalseC.
9195 bool NeedsCondInvert = false;
9197 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
9198 // Efficiently invertible.
9199 (Cond.getOpcode() == ISD::SETCC || // setcc -> invertible.
9200 (Cond.getOpcode() == ISD::XOR && // xor(X, C) -> invertible.
9201 isa<ConstantSDNode>(Cond.getOperand(1))))) {
9202 NeedsCondInvert = true;
9203 std::swap(TrueC, FalseC);
9206 // Optimize C ? 8 : 0 -> zext(C) << 3. Likewise for any pow2/0.
9207 if (FalseC->getAPIntValue() == 0 &&
9208 TrueC->getAPIntValue().isPowerOf2()) {
9209 if (NeedsCondInvert) // Invert the condition if needed.
9210 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9211 DAG.getConstant(1, Cond.getValueType()));
9213 // Zero extend the condition if needed.
9214 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
9216 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9217 return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
9218 DAG.getConstant(ShAmt, MVT::i8));
9221 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
9222 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9223 if (NeedsCondInvert) // Invert the condition if needed.
9224 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9225 DAG.getConstant(1, Cond.getValueType()));
9227 // Zero extend the condition if needed.
9228 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9229 FalseC->getValueType(0), Cond);
9230 return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9231 SDValue(FalseC, 0));
9234 // Optimize cases that will turn into an LEA instruction. This requires
9235 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9236 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9237 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9238 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9240 bool isFastMultiplier = false;
9242 switch ((unsigned char)Diff) {
9244 case 1: // result = add base, cond
9245 case 2: // result = lea base( , cond*2)
9246 case 3: // result = lea base(cond, cond*2)
9247 case 4: // result = lea base( , cond*4)
9248 case 5: // result = lea base(cond, cond*4)
9249 case 8: // result = lea base( , cond*8)
9250 case 9: // result = lea base(cond, cond*8)
9251 isFastMultiplier = true;
9256 if (isFastMultiplier) {
9257 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9258 if (NeedsCondInvert) // Invert the condition if needed.
9259 Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
9260 DAG.getConstant(1, Cond.getValueType()));
9262 // Zero extend the condition if needed.
9263 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9265 // Scale the condition by the difference.
9267 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9268 DAG.getConstant(Diff, Cond.getValueType()));
9270 // Add the base if non-zero.
9271 if (FalseC->getAPIntValue() != 0)
9272 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9273 SDValue(FalseC, 0));
9283 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
9284 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
9285 TargetLowering::DAGCombinerInfo &DCI) {
9286 DebugLoc DL = N->getDebugLoc();
9288 // If the flag operand isn't dead, don't touch this CMOV.
9289 if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
9292 // If this is a select between two integer constants, try to do some
9293 // optimizations. Note that the operands are ordered the opposite of SELECT
9295 if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
9296 if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(N->getOperand(0))) {
9297 // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
9298 // larger than FalseC (the false value).
9299 X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
9301 if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
9302 CC = X86::GetOppositeBranchCondition(CC);
9303 std::swap(TrueC, FalseC);
9306 // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3. Likewise for any pow2/0.
9307 // This is efficient for any integer data type (including i8/i16) and
9309 if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
9310 SDValue Cond = N->getOperand(3);
9311 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9312 DAG.getConstant(CC, MVT::i8), Cond);
9314 // Zero extend the condition if needed.
9315 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
9317 unsigned ShAmt = TrueC->getAPIntValue().logBase2();
9318 Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
9319 DAG.getConstant(ShAmt, MVT::i8));
9320 if (N->getNumValues() == 2) // Dead flag value?
9321 return DCI.CombineTo(N, Cond, SDValue());
9325 // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst. This is efficient
9326 // for any integer data type, including i8/i16.
9327 if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
9328 SDValue Cond = N->getOperand(3);
9329 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9330 DAG.getConstant(CC, MVT::i8), Cond);
9332 // Zero extend the condition if needed.
9333 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
9334 FalseC->getValueType(0), Cond);
9335 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9336 SDValue(FalseC, 0));
9338 if (N->getNumValues() == 2) // Dead flag value?
9339 return DCI.CombineTo(N, Cond, SDValue());
9343 // Optimize cases that will turn into an LEA instruction. This requires
9344 // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
9345 if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
9346 uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
9347 if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
9349 bool isFastMultiplier = false;
9351 switch ((unsigned char)Diff) {
9353 case 1: // result = add base, cond
9354 case 2: // result = lea base( , cond*2)
9355 case 3: // result = lea base(cond, cond*2)
9356 case 4: // result = lea base( , cond*4)
9357 case 5: // result = lea base(cond, cond*4)
9358 case 8: // result = lea base( , cond*8)
9359 case 9: // result = lea base(cond, cond*8)
9360 isFastMultiplier = true;
9365 if (isFastMultiplier) {
9366 APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
9367 SDValue Cond = N->getOperand(3);
9368 Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
9369 DAG.getConstant(CC, MVT::i8), Cond);
9370 // Zero extend the condition if needed.
9371 Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
9373 // Scale the condition by the difference.
9375 Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
9376 DAG.getConstant(Diff, Cond.getValueType()));
9378 // Add the base if non-zero.
9379 if (FalseC->getAPIntValue() != 0)
9380 Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
9381 SDValue(FalseC, 0));
9382 if (N->getNumValues() == 2) // Dead flag value?
9383 return DCI.CombineTo(N, Cond, SDValue());
9393 /// PerformMulCombine - Optimize a single multiply with constant into two
9394 /// in order to implement it with two cheaper instructions, e.g.
9395 /// LEA + SHL, LEA + LEA.
9396 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
9397 TargetLowering::DAGCombinerInfo &DCI) {
9398 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9401 EVT VT = N->getValueType(0);
9405 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9408 uint64_t MulAmt = C->getZExtValue();
9409 if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
9412 uint64_t MulAmt1 = 0;
9413 uint64_t MulAmt2 = 0;
9414 if ((MulAmt % 9) == 0) {
9416 MulAmt2 = MulAmt / 9;
9417 } else if ((MulAmt % 5) == 0) {
9419 MulAmt2 = MulAmt / 5;
9420 } else if ((MulAmt % 3) == 0) {
9422 MulAmt2 = MulAmt / 3;
9425 (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
9426 DebugLoc DL = N->getDebugLoc();
9428 if (isPowerOf2_64(MulAmt2) &&
9429 !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
9430 // If second multiplifer is pow2, issue it first. We want the multiply by
9431 // 3, 5, or 9 to be folded into the addressing mode unless the lone use
9433 std::swap(MulAmt1, MulAmt2);
9436 if (isPowerOf2_64(MulAmt1))
9437 NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
9438 DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
9440 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
9441 DAG.getConstant(MulAmt1, VT));
9443 if (isPowerOf2_64(MulAmt2))
9444 NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
9445 DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
9447 NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
9448 DAG.getConstant(MulAmt2, VT));
9450 // Do not add new nodes to DAG combiner worklist.
9451 DCI.CombineTo(N, NewMul, false);
9456 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
9457 SDValue N0 = N->getOperand(0);
9458 SDValue N1 = N->getOperand(1);
9459 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
9460 EVT VT = N0.getValueType();
9462 // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
9463 // since the result of setcc_c is all zero's or all ones.
9464 if (N1C && N0.getOpcode() == ISD::AND &&
9465 N0.getOperand(1).getOpcode() == ISD::Constant) {
9466 SDValue N00 = N0.getOperand(0);
9467 if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
9468 ((N00.getOpcode() == ISD::ANY_EXTEND ||
9469 N00.getOpcode() == ISD::ZERO_EXTEND) &&
9470 N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
9471 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
9472 APInt ShAmt = N1C->getAPIntValue();
9473 Mask = Mask.shl(ShAmt);
9475 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
9476 N00, DAG.getConstant(Mask, VT));
9483 /// PerformShiftCombine - Transforms vector shift nodes to use vector shifts
9485 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
9486 const X86Subtarget *Subtarget) {
9487 EVT VT = N->getValueType(0);
9488 if (!VT.isVector() && VT.isInteger() &&
9489 N->getOpcode() == ISD::SHL)
9490 return PerformSHLCombine(N, DAG);
9492 // On X86 with SSE2 support, we can transform this to a vector shift if
9493 // all elements are shifted by the same amount. We can't do this in legalize
9494 // because the a constant vector is typically transformed to a constant pool
9495 // so we have no knowledge of the shift amount.
9496 if (!Subtarget->hasSSE2())
9499 if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
9502 SDValue ShAmtOp = N->getOperand(1);
9503 EVT EltVT = VT.getVectorElementType();
9504 DebugLoc DL = N->getDebugLoc();
9505 SDValue BaseShAmt = SDValue();
9506 if (ShAmtOp.getOpcode() == ISD::BUILD_VECTOR) {
9507 unsigned NumElts = VT.getVectorNumElements();
9509 for (; i != NumElts; ++i) {
9510 SDValue Arg = ShAmtOp.getOperand(i);
9511 if (Arg.getOpcode() == ISD::UNDEF) continue;
9515 for (; i != NumElts; ++i) {
9516 SDValue Arg = ShAmtOp.getOperand(i);
9517 if (Arg.getOpcode() == ISD::UNDEF) continue;
9518 if (Arg != BaseShAmt) {
9522 } else if (ShAmtOp.getOpcode() == ISD::VECTOR_SHUFFLE &&
9523 cast<ShuffleVectorSDNode>(ShAmtOp)->isSplat()) {
9524 SDValue InVec = ShAmtOp.getOperand(0);
9525 if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
9526 unsigned NumElts = InVec.getValueType().getVectorNumElements();
9528 for (; i != NumElts; ++i) {
9529 SDValue Arg = InVec.getOperand(i);
9530 if (Arg.getOpcode() == ISD::UNDEF) continue;
9534 } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
9535 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
9536 unsigned SplatIdx= cast<ShuffleVectorSDNode>(ShAmtOp)->getSplatIndex();
9537 if (C->getZExtValue() == SplatIdx)
9538 BaseShAmt = InVec.getOperand(1);
9541 if (BaseShAmt.getNode() == 0)
9542 BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, ShAmtOp,
9543 DAG.getIntPtrConstant(0));
9547 // The shift amount is an i32.
9548 if (EltVT.bitsGT(MVT::i32))
9549 BaseShAmt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, BaseShAmt);
9550 else if (EltVT.bitsLT(MVT::i32))
9551 BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, BaseShAmt);
9553 // The shift amount is identical so we can do a vector shift.
9554 SDValue ValOp = N->getOperand(0);
9555 switch (N->getOpcode()) {
9557 llvm_unreachable("Unknown shift opcode!");
9560 if (VT == MVT::v2i64)
9561 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9562 DAG.getConstant(Intrinsic::x86_sse2_pslli_q, MVT::i32),
9564 if (VT == MVT::v4i32)
9565 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9566 DAG.getConstant(Intrinsic::x86_sse2_pslli_d, MVT::i32),
9568 if (VT == MVT::v8i16)
9569 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9570 DAG.getConstant(Intrinsic::x86_sse2_pslli_w, MVT::i32),
9574 if (VT == MVT::v4i32)
9575 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9576 DAG.getConstant(Intrinsic::x86_sse2_psrai_d, MVT::i32),
9578 if (VT == MVT::v8i16)
9579 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9580 DAG.getConstant(Intrinsic::x86_sse2_psrai_w, MVT::i32),
9584 if (VT == MVT::v2i64)
9585 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9586 DAG.getConstant(Intrinsic::x86_sse2_psrli_q, MVT::i32),
9588 if (VT == MVT::v4i32)
9589 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9590 DAG.getConstant(Intrinsic::x86_sse2_psrli_d, MVT::i32),
9592 if (VT == MVT::v8i16)
9593 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
9594 DAG.getConstant(Intrinsic::x86_sse2_psrli_w, MVT::i32),
9601 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
9602 TargetLowering::DAGCombinerInfo &DCI,
9603 const X86Subtarget *Subtarget) {
9604 if (DCI.isBeforeLegalizeOps())
9607 EVT VT = N->getValueType(0);
9608 if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
9611 // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
9612 SDValue N0 = N->getOperand(0);
9613 SDValue N1 = N->getOperand(1);
9614 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
9616 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
9618 if (!N0.hasOneUse() || !N1.hasOneUse())
9621 SDValue ShAmt0 = N0.getOperand(1);
9622 if (ShAmt0.getValueType() != MVT::i8)
9624 SDValue ShAmt1 = N1.getOperand(1);
9625 if (ShAmt1.getValueType() != MVT::i8)
9627 if (ShAmt0.getOpcode() == ISD::TRUNCATE)
9628 ShAmt0 = ShAmt0.getOperand(0);
9629 if (ShAmt1.getOpcode() == ISD::TRUNCATE)
9630 ShAmt1 = ShAmt1.getOperand(0);
9632 DebugLoc DL = N->getDebugLoc();
9633 unsigned Opc = X86ISD::SHLD;
9634 SDValue Op0 = N0.getOperand(0);
9635 SDValue Op1 = N1.getOperand(0);
9636 if (ShAmt0.getOpcode() == ISD::SUB) {
9638 std::swap(Op0, Op1);
9639 std::swap(ShAmt0, ShAmt1);
9642 unsigned Bits = VT.getSizeInBits();
9643 if (ShAmt1.getOpcode() == ISD::SUB) {
9644 SDValue Sum = ShAmt1.getOperand(0);
9645 if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
9646 SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
9647 if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
9648 ShAmt1Op1 = ShAmt1Op1.getOperand(0);
9649 if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
9650 return DAG.getNode(Opc, DL, VT,
9652 DAG.getNode(ISD::TRUNCATE, DL,
9655 } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
9656 ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
9658 ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
9659 return DAG.getNode(Opc, DL, VT,
9660 N0.getOperand(0), N1.getOperand(0),
9661 DAG.getNode(ISD::TRUNCATE, DL,
9668 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
9669 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
9670 const X86Subtarget *Subtarget) {
9671 // Turn load->store of MMX types into GPR load/stores. This avoids clobbering
9672 // the FP state in cases where an emms may be missing.
9673 // A preferable solution to the general problem is to figure out the right
9674 // places to insert EMMS. This qualifies as a quick hack.
9676 // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
9677 StoreSDNode *St = cast<StoreSDNode>(N);
9678 EVT VT = St->getValue().getValueType();
9679 if (VT.getSizeInBits() != 64)
9682 const Function *F = DAG.getMachineFunction().getFunction();
9683 bool NoImplicitFloatOps = F->hasFnAttr(Attribute::NoImplicitFloat);
9684 bool F64IsLegal = !UseSoftFloat && !NoImplicitFloatOps
9685 && Subtarget->hasSSE2();
9686 if ((VT.isVector() ||
9687 (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
9688 isa<LoadSDNode>(St->getValue()) &&
9689 !cast<LoadSDNode>(St->getValue())->isVolatile() &&
9690 St->getChain().hasOneUse() && !St->isVolatile()) {
9691 SDNode* LdVal = St->getValue().getNode();
9693 int TokenFactorIndex = -1;
9694 SmallVector<SDValue, 8> Ops;
9695 SDNode* ChainVal = St->getChain().getNode();
9696 // Must be a store of a load. We currently handle two cases: the load
9697 // is a direct child, and it's under an intervening TokenFactor. It is
9698 // possible to dig deeper under nested TokenFactors.
9699 if (ChainVal == LdVal)
9700 Ld = cast<LoadSDNode>(St->getChain());
9701 else if (St->getValue().hasOneUse() &&
9702 ChainVal->getOpcode() == ISD::TokenFactor) {
9703 for (unsigned i=0, e = ChainVal->getNumOperands(); i != e; ++i) {
9704 if (ChainVal->getOperand(i).getNode() == LdVal) {
9705 TokenFactorIndex = i;
9706 Ld = cast<LoadSDNode>(St->getValue());
9708 Ops.push_back(ChainVal->getOperand(i));
9712 if (!Ld || !ISD::isNormalLoad(Ld))
9715 // If this is not the MMX case, i.e. we are just turning i64 load/store
9716 // into f64 load/store, avoid the transformation if there are multiple
9717 // uses of the loaded value.
9718 if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
9721 DebugLoc LdDL = Ld->getDebugLoc();
9722 DebugLoc StDL = N->getDebugLoc();
9723 // If we are a 64-bit capable x86, lower to a single movq load/store pair.
9724 // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
9726 if (Subtarget->is64Bit() || F64IsLegal) {
9727 EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
9728 SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(),
9729 Ld->getBasePtr(), Ld->getSrcValue(),
9730 Ld->getSrcValueOffset(), Ld->isVolatile(),
9731 Ld->isNonTemporal(), Ld->getAlignment());
9732 SDValue NewChain = NewLd.getValue(1);
9733 if (TokenFactorIndex != -1) {
9734 Ops.push_back(NewChain);
9735 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9738 return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
9739 St->getSrcValue(), St->getSrcValueOffset(),
9740 St->isVolatile(), St->isNonTemporal(),
9741 St->getAlignment());
9744 // Otherwise, lower to two pairs of 32-bit loads / stores.
9745 SDValue LoAddr = Ld->getBasePtr();
9746 SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
9747 DAG.getConstant(4, MVT::i32));
9749 SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
9750 Ld->getSrcValue(), Ld->getSrcValueOffset(),
9751 Ld->isVolatile(), Ld->isNonTemporal(),
9752 Ld->getAlignment());
9753 SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
9754 Ld->getSrcValue(), Ld->getSrcValueOffset()+4,
9755 Ld->isVolatile(), Ld->isNonTemporal(),
9756 MinAlign(Ld->getAlignment(), 4));
9758 SDValue NewChain = LoLd.getValue(1);
9759 if (TokenFactorIndex != -1) {
9760 Ops.push_back(LoLd);
9761 Ops.push_back(HiLd);
9762 NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, &Ops[0],
9766 LoAddr = St->getBasePtr();
9767 HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
9768 DAG.getConstant(4, MVT::i32));
9770 SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
9771 St->getSrcValue(), St->getSrcValueOffset(),
9772 St->isVolatile(), St->isNonTemporal(),
9773 St->getAlignment());
9774 SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
9776 St->getSrcValueOffset() + 4,
9778 St->isNonTemporal(),
9779 MinAlign(St->getAlignment(), 4));
9780 return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
9785 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
9786 /// X86ISD::FXOR nodes.
9787 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
9788 assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
9789 // F[X]OR(0.0, x) -> x
9790 // F[X]OR(x, 0.0) -> x
9791 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9792 if (C->getValueAPF().isPosZero())
9793 return N->getOperand(1);
9794 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9795 if (C->getValueAPF().isPosZero())
9796 return N->getOperand(0);
9800 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
9801 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
9802 // FAND(0.0, x) -> 0.0
9803 // FAND(x, 0.0) -> 0.0
9804 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
9805 if (C->getValueAPF().isPosZero())
9806 return N->getOperand(0);
9807 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
9808 if (C->getValueAPF().isPosZero())
9809 return N->getOperand(1);
9813 static SDValue PerformBTCombine(SDNode *N,
9815 TargetLowering::DAGCombinerInfo &DCI) {
9816 // BT ignores high bits in the bit index operand.
9817 SDValue Op1 = N->getOperand(1);
9818 if (Op1.hasOneUse()) {
9819 unsigned BitWidth = Op1.getValueSizeInBits();
9820 APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
9821 APInt KnownZero, KnownOne;
9822 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
9823 !DCI.isBeforeLegalizeOps());
9824 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9825 if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
9826 TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
9827 DCI.CommitTargetLoweringOpt(TLO);
9832 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
9833 SDValue Op = N->getOperand(0);
9834 if (Op.getOpcode() == ISD::BIT_CONVERT)
9835 Op = Op.getOperand(0);
9836 EVT VT = N->getValueType(0), OpVT = Op.getValueType();
9837 if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
9838 VT.getVectorElementType().getSizeInBits() ==
9839 OpVT.getVectorElementType().getSizeInBits()) {
9840 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, Op);
9845 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG) {
9846 // (i32 zext (and (i8 x86isd::setcc_carry), 1)) ->
9847 // (and (i32 x86isd::setcc_carry), 1)
9848 // This eliminates the zext. This transformation is necessary because
9849 // ISD::SETCC is always legalized to i8.
9850 DebugLoc dl = N->getDebugLoc();
9851 SDValue N0 = N->getOperand(0);
9852 EVT VT = N->getValueType(0);
9853 if (N0.getOpcode() == ISD::AND &&
9855 N0.getOperand(0).hasOneUse()) {
9856 SDValue N00 = N0.getOperand(0);
9857 if (N00.getOpcode() != X86ISD::SETCC_CARRY)
9859 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
9860 if (!C || C->getZExtValue() != 1)
9862 return DAG.getNode(ISD::AND, dl, VT,
9863 DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
9864 N00.getOperand(0), N00.getOperand(1)),
9865 DAG.getConstant(1, VT));
9871 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
9872 DAGCombinerInfo &DCI) const {
9873 SelectionDAG &DAG = DCI.DAG;
9874 switch (N->getOpcode()) {
9876 case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, *this);
9877 case ISD::EXTRACT_VECTOR_ELT:
9878 return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, *this);
9879 case ISD::SELECT: return PerformSELECTCombine(N, DAG, Subtarget);
9880 case X86ISD::CMOV: return PerformCMOVCombine(N, DAG, DCI);
9881 case ISD::MUL: return PerformMulCombine(N, DAG, DCI);
9884 case ISD::SRL: return PerformShiftCombine(N, DAG, Subtarget);
9885 case ISD::OR: return PerformOrCombine(N, DAG, DCI, Subtarget);
9886 case ISD::STORE: return PerformSTORECombine(N, DAG, Subtarget);
9888 case X86ISD::FOR: return PerformFORCombine(N, DAG);
9889 case X86ISD::FAND: return PerformFANDCombine(N, DAG);
9890 case X86ISD::BT: return PerformBTCombine(N, DAG, DCI);
9891 case X86ISD::VZEXT_MOVL: return PerformVZEXT_MOVLCombine(N, DAG);
9892 case ISD::ZERO_EXTEND: return PerformZExtCombine(N, DAG);
9898 /// isTypeDesirableForOp - Return true if the target has native support for
9899 /// the specified value type and it is 'desirable' to use the type for the
9900 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
9901 /// instruction encodings are longer and some i16 instructions are slow.
9902 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
9903 if (!isTypeLegal(VT))
9912 case ISD::SIGN_EXTEND:
9913 case ISD::ZERO_EXTEND:
9914 case ISD::ANY_EXTEND:
9927 static bool MayFoldLoad(SDValue Op) {
9928 return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
9931 static bool MayFoldIntoStore(SDValue Op) {
9932 return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
9935 /// IsDesirableToPromoteOp - This method query the target whether it is
9936 /// beneficial for dag combiner to promote the specified node. If true, it
9937 /// should return the desired promotion type by reference.
9938 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
9939 EVT VT = Op.getValueType();
9943 bool Promote = false;
9944 bool Commute = false;
9945 switch (Op.getOpcode()) {
9948 LoadSDNode *LD = cast<LoadSDNode>(Op);
9949 // If the non-extending load has a single use and it's not live out, then it
9951 if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
9953 for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
9954 UE = Op.getNode()->use_end(); UI != UE; ++UI) {
9955 // The only case where we'd want to promote LOAD (rather then it being
9956 // promoted as an operand is when it's only use is liveout.
9957 if (UI->getOpcode() != ISD::CopyToReg)
9964 case ISD::SIGN_EXTEND:
9965 case ISD::ZERO_EXTEND:
9966 case ISD::ANY_EXTEND:
9971 SDValue N0 = Op.getOperand(0);
9972 // Look out for (store (shl (load), x)).
9973 if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
9986 SDValue N0 = Op.getOperand(0);
9987 SDValue N1 = Op.getOperand(1);
9988 if (!Commute && MayFoldLoad(N1))
9990 // Avoid disabling potential load folding opportunities.
9991 if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
9993 if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
10003 //===----------------------------------------------------------------------===//
10004 // X86 Inline Assembly Support
10005 //===----------------------------------------------------------------------===//
10007 static bool LowerToBSwap(CallInst *CI) {
10008 // FIXME: this should verify that we are targetting a 486 or better. If not,
10009 // we will turn this bswap into something that will be lowered to logical ops
10010 // instead of emitting the bswap asm. For now, we don't support 486 or lower
10011 // so don't worry about this.
10013 // Verify this is a simple bswap.
10014 if (CI->getNumArgOperands() != 1 ||
10015 CI->getType() != CI->getArgOperand(0)->getType() ||
10016 !CI->getType()->isIntegerTy())
10019 const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
10020 if (!Ty || Ty->getBitWidth() % 16 != 0)
10023 // Okay, we can do this xform, do so now.
10024 const Type *Tys[] = { Ty };
10025 Module *M = CI->getParent()->getParent()->getParent();
10026 Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
10028 Value *Op = CI->getArgOperand(0);
10029 Op = CallInst::Create(Int, Op, CI->getName(), CI);
10031 CI->replaceAllUsesWith(Op);
10032 CI->eraseFromParent();
10036 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
10037 InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
10038 std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
10040 std::string AsmStr = IA->getAsmString();
10042 // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
10043 SmallVector<StringRef, 4> AsmPieces;
10044 SplitString(AsmStr, AsmPieces, "\n"); // ; as separator?
10046 switch (AsmPieces.size()) {
10047 default: return false;
10049 AsmStr = AsmPieces[0];
10051 SplitString(AsmStr, AsmPieces, " \t"); // Split with whitespace.
10054 if (AsmPieces.size() == 2 &&
10055 (AsmPieces[0] == "bswap" ||
10056 AsmPieces[0] == "bswapq" ||
10057 AsmPieces[0] == "bswapl") &&
10058 (AsmPieces[1] == "$0" ||
10059 AsmPieces[1] == "${0:q}")) {
10060 // No need to check constraints, nothing other than the equivalent of
10061 // "=r,0" would be valid here.
10062 return LowerToBSwap(CI);
10064 // rorw $$8, ${0:w} --> llvm.bswap.i16
10065 if (CI->getType()->isIntegerTy(16) &&
10066 AsmPieces.size() == 3 &&
10067 (AsmPieces[0] == "rorw" || AsmPieces[0] == "rolw") &&
10068 AsmPieces[1] == "$$8," &&
10069 AsmPieces[2] == "${0:w}" &&
10070 IA->getConstraintString().compare(0, 5, "=r,0,") == 0) {
10072 const std::string &Constraints = IA->getConstraintString();
10073 SplitString(StringRef(Constraints).substr(5), AsmPieces, ",");
10074 std::sort(AsmPieces.begin(), AsmPieces.end());
10075 if (AsmPieces.size() == 4 &&
10076 AsmPieces[0] == "~{cc}" &&
10077 AsmPieces[1] == "~{dirflag}" &&
10078 AsmPieces[2] == "~{flags}" &&
10079 AsmPieces[3] == "~{fpsr}") {
10080 return LowerToBSwap(CI);
10085 if (CI->getType()->isIntegerTy(64) &&
10086 Constraints.size() >= 2 &&
10087 Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
10088 Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
10089 // bswap %eax / bswap %edx / xchgl %eax, %edx -> llvm.bswap.i64
10090 SmallVector<StringRef, 4> Words;
10091 SplitString(AsmPieces[0], Words, " \t");
10092 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
10094 SplitString(AsmPieces[1], Words, " \t");
10095 if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
10097 SplitString(AsmPieces[2], Words, " \t,");
10098 if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
10099 Words[2] == "%edx") {
10100 return LowerToBSwap(CI);
10112 /// getConstraintType - Given a constraint letter, return the type of
10113 /// constraint it is for this target.
10114 X86TargetLowering::ConstraintType
10115 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
10116 if (Constraint.size() == 1) {
10117 switch (Constraint[0]) {
10129 return C_RegisterClass;
10137 return TargetLowering::getConstraintType(Constraint);
10140 /// LowerXConstraint - try to replace an X constraint, which matches anything,
10141 /// with another that has more specific requirements based on the type of the
10142 /// corresponding operand.
10143 const char *X86TargetLowering::
10144 LowerXConstraint(EVT ConstraintVT) const {
10145 // FP X constraints get lowered to SSE1/2 registers if available, otherwise
10146 // 'f' like normal targets.
10147 if (ConstraintVT.isFloatingPoint()) {
10148 if (Subtarget->hasSSE2())
10150 if (Subtarget->hasSSE1())
10154 return TargetLowering::LowerXConstraint(ConstraintVT);
10157 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
10158 /// vector. If it is invalid, don't add anything to Ops.
10159 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
10161 std::vector<SDValue>&Ops,
10162 SelectionDAG &DAG) const {
10163 SDValue Result(0, 0);
10165 switch (Constraint) {
10168 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10169 if (C->getZExtValue() <= 31) {
10170 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10176 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10177 if (C->getZExtValue() <= 63) {
10178 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10184 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10185 if ((int8_t)C->getSExtValue() == C->getSExtValue()) {
10186 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10192 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10193 if (C->getZExtValue() <= 255) {
10194 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10200 // 32-bit signed value
10201 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10202 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10203 C->getSExtValue())) {
10204 // Widen to 64 bits here to get it sign extended.
10205 Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
10208 // FIXME gcc accepts some relocatable values here too, but only in certain
10209 // memory models; it's complicated.
10214 // 32-bit unsigned value
10215 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
10216 if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
10217 C->getZExtValue())) {
10218 Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
10222 // FIXME gcc accepts some relocatable values here too, but only in certain
10223 // memory models; it's complicated.
10227 // Literal immediates are always ok.
10228 if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
10229 // Widen to 64 bits here to get it sign extended.
10230 Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
10234 // In any sort of PIC mode addresses need to be computed at runtime by
10235 // adding in a register or some sort of table lookup. These can't
10236 // be used as immediates.
10237 if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC() ||
10238 Subtarget->isPICStyleRIPRel())
10241 // If we are in non-pic codegen mode, we allow the address of a global (with
10242 // an optional displacement) to be used with 'i'.
10243 GlobalAddressSDNode *GA = 0;
10244 int64_t Offset = 0;
10246 // Match either (GA), (GA+C), (GA+C1+C2), etc.
10248 if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
10249 Offset += GA->getOffset();
10251 } else if (Op.getOpcode() == ISD::ADD) {
10252 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10253 Offset += C->getZExtValue();
10254 Op = Op.getOperand(0);
10257 } else if (Op.getOpcode() == ISD::SUB) {
10258 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
10259 Offset += -C->getZExtValue();
10260 Op = Op.getOperand(0);
10265 // Otherwise, this isn't something we can handle, reject it.
10269 const GlobalValue *GV = GA->getGlobal();
10270 // If we require an extra load to get this address, as in PIC mode, we
10271 // can't accept it.
10272 if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
10273 getTargetMachine())))
10276 Result = DAG.getTargetGlobalAddress(GV, GA->getValueType(0), Offset);
10281 if (Result.getNode()) {
10282 Ops.push_back(Result);
10285 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
10288 std::vector<unsigned> X86TargetLowering::
10289 getRegClassForInlineAsmConstraint(const std::string &Constraint,
10291 if (Constraint.size() == 1) {
10292 // FIXME: not handling fp-stack yet!
10293 switch (Constraint[0]) { // GCC X86 Constraint Letters
10294 default: break; // Unknown constraint letter
10295 case 'q': // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
10296 if (Subtarget->is64Bit()) {
10297 if (VT == MVT::i32)
10298 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX,
10299 X86::ESI, X86::EDI, X86::R8D, X86::R9D,
10300 X86::R10D,X86::R11D,X86::R12D,
10301 X86::R13D,X86::R14D,X86::R15D,
10302 X86::EBP, X86::ESP, 0);
10303 else if (VT == MVT::i16)
10304 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX,
10305 X86::SI, X86::DI, X86::R8W,X86::R9W,
10306 X86::R10W,X86::R11W,X86::R12W,
10307 X86::R13W,X86::R14W,X86::R15W,
10308 X86::BP, X86::SP, 0);
10309 else if (VT == MVT::i8)
10310 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL,
10311 X86::SIL, X86::DIL, X86::R8B,X86::R9B,
10312 X86::R10B,X86::R11B,X86::R12B,
10313 X86::R13B,X86::R14B,X86::R15B,
10314 X86::BPL, X86::SPL, 0);
10316 else if (VT == MVT::i64)
10317 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX,
10318 X86::RSI, X86::RDI, X86::R8, X86::R9,
10319 X86::R10, X86::R11, X86::R12,
10320 X86::R13, X86::R14, X86::R15,
10321 X86::RBP, X86::RSP, 0);
10325 // 32-bit fallthrough
10326 case 'Q': // Q_REGS
10327 if (VT == MVT::i32)
10328 return make_vector<unsigned>(X86::EAX, X86::EDX, X86::ECX, X86::EBX, 0);
10329 else if (VT == MVT::i16)
10330 return make_vector<unsigned>(X86::AX, X86::DX, X86::CX, X86::BX, 0);
10331 else if (VT == MVT::i8)
10332 return make_vector<unsigned>(X86::AL, X86::DL, X86::CL, X86::BL, 0);
10333 else if (VT == MVT::i64)
10334 return make_vector<unsigned>(X86::RAX, X86::RDX, X86::RCX, X86::RBX, 0);
10339 return std::vector<unsigned>();
10342 std::pair<unsigned, const TargetRegisterClass*>
10343 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
10345 // First, see if this is a constraint that directly corresponds to an LLVM
10347 if (Constraint.size() == 1) {
10348 // GCC Constraint Letters
10349 switch (Constraint[0]) {
10351 case 'r': // GENERAL_REGS
10352 case 'l': // INDEX_REGS
10354 return std::make_pair(0U, X86::GR8RegisterClass);
10355 if (VT == MVT::i16)
10356 return std::make_pair(0U, X86::GR16RegisterClass);
10357 if (VT == MVT::i32 || !Subtarget->is64Bit())
10358 return std::make_pair(0U, X86::GR32RegisterClass);
10359 return std::make_pair(0U, X86::GR64RegisterClass);
10360 case 'R': // LEGACY_REGS
10362 return std::make_pair(0U, X86::GR8_NOREXRegisterClass);
10363 if (VT == MVT::i16)
10364 return std::make_pair(0U, X86::GR16_NOREXRegisterClass);
10365 if (VT == MVT::i32 || !Subtarget->is64Bit())
10366 return std::make_pair(0U, X86::GR32_NOREXRegisterClass);
10367 return std::make_pair(0U, X86::GR64_NOREXRegisterClass);
10368 case 'f': // FP Stack registers.
10369 // If SSE is enabled for this VT, use f80 to ensure the isel moves the
10370 // value to the correct fpstack register class.
10371 if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
10372 return std::make_pair(0U, X86::RFP32RegisterClass);
10373 if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
10374 return std::make_pair(0U, X86::RFP64RegisterClass);
10375 return std::make_pair(0U, X86::RFP80RegisterClass);
10376 case 'y': // MMX_REGS if MMX allowed.
10377 if (!Subtarget->hasMMX()) break;
10378 return std::make_pair(0U, X86::VR64RegisterClass);
10379 case 'Y': // SSE_REGS if SSE2 allowed
10380 if (!Subtarget->hasSSE2()) break;
10382 case 'x': // SSE_REGS if SSE1 allowed
10383 if (!Subtarget->hasSSE1()) break;
10385 switch (VT.getSimpleVT().SimpleTy) {
10387 // Scalar SSE types.
10390 return std::make_pair(0U, X86::FR32RegisterClass);
10393 return std::make_pair(0U, X86::FR64RegisterClass);
10401 return std::make_pair(0U, X86::VR128RegisterClass);
10407 // Use the default implementation in TargetLowering to convert the register
10408 // constraint into a member of a register class.
10409 std::pair<unsigned, const TargetRegisterClass*> Res;
10410 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
10412 // Not found as a standard register?
10413 if (Res.second == 0) {
10414 // Map st(0) -> st(7) -> ST0
10415 if (Constraint.size() == 7 && Constraint[0] == '{' &&
10416 tolower(Constraint[1]) == 's' &&
10417 tolower(Constraint[2]) == 't' &&
10418 Constraint[3] == '(' &&
10419 (Constraint[4] >= '0' && Constraint[4] <= '7') &&
10420 Constraint[5] == ')' &&
10421 Constraint[6] == '}') {
10423 Res.first = X86::ST0+Constraint[4]-'0';
10424 Res.second = X86::RFP80RegisterClass;
10428 // GCC allows "st(0)" to be called just plain "st".
10429 if (StringRef("{st}").equals_lower(Constraint)) {
10430 Res.first = X86::ST0;
10431 Res.second = X86::RFP80RegisterClass;
10436 if (StringRef("{flags}").equals_lower(Constraint)) {
10437 Res.first = X86::EFLAGS;
10438 Res.second = X86::CCRRegisterClass;
10442 // 'A' means EAX + EDX.
10443 if (Constraint == "A") {
10444 Res.first = X86::EAX;
10445 Res.second = X86::GR32_ADRegisterClass;
10451 // Otherwise, check to see if this is a register class of the wrong value
10452 // type. For example, we want to map "{ax},i32" -> {eax}, we don't want it to
10453 // turn into {ax},{dx}.
10454 if (Res.second->hasType(VT))
10455 return Res; // Correct type already, nothing to do.
10457 // All of the single-register GCC register classes map their values onto
10458 // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp". If we
10459 // really want an 8-bit or 32-bit register, map to the appropriate register
10460 // class and return the appropriate register.
10461 if (Res.second == X86::GR16RegisterClass) {
10462 if (VT == MVT::i8) {
10463 unsigned DestReg = 0;
10464 switch (Res.first) {
10466 case X86::AX: DestReg = X86::AL; break;
10467 case X86::DX: DestReg = X86::DL; break;
10468 case X86::CX: DestReg = X86::CL; break;
10469 case X86::BX: DestReg = X86::BL; break;
10472 Res.first = DestReg;
10473 Res.second = X86::GR8RegisterClass;
10475 } else if (VT == MVT::i32) {
10476 unsigned DestReg = 0;
10477 switch (Res.first) {
10479 case X86::AX: DestReg = X86::EAX; break;
10480 case X86::DX: DestReg = X86::EDX; break;
10481 case X86::CX: DestReg = X86::ECX; break;
10482 case X86::BX: DestReg = X86::EBX; break;
10483 case X86::SI: DestReg = X86::ESI; break;
10484 case X86::DI: DestReg = X86::EDI; break;
10485 case X86::BP: DestReg = X86::EBP; break;
10486 case X86::SP: DestReg = X86::ESP; break;
10489 Res.first = DestReg;
10490 Res.second = X86::GR32RegisterClass;
10492 } else if (VT == MVT::i64) {
10493 unsigned DestReg = 0;
10494 switch (Res.first) {
10496 case X86::AX: DestReg = X86::RAX; break;
10497 case X86::DX: DestReg = X86::RDX; break;
10498 case X86::CX: DestReg = X86::RCX; break;
10499 case X86::BX: DestReg = X86::RBX; break;
10500 case X86::SI: DestReg = X86::RSI; break;
10501 case X86::DI: DestReg = X86::RDI; break;
10502 case X86::BP: DestReg = X86::RBP; break;
10503 case X86::SP: DestReg = X86::RSP; break;
10506 Res.first = DestReg;
10507 Res.second = X86::GR64RegisterClass;
10510 } else if (Res.second == X86::FR32RegisterClass ||
10511 Res.second == X86::FR64RegisterClass ||
10512 Res.second == X86::VR128RegisterClass) {
10513 // Handle references to XMM physical registers that got mapped into the
10514 // wrong class. This can happen with constraints like {xmm0} where the
10515 // target independent register mapper will just pick the first match it can
10516 // find, ignoring the required type.
10517 if (VT == MVT::f32)
10518 Res.second = X86::FR32RegisterClass;
10519 else if (VT == MVT::f64)
10520 Res.second = X86::FR64RegisterClass;
10521 else if (X86::VR128RegisterClass->hasType(VT))
10522 Res.second = X86::VR128RegisterClass;